Modern Apps git

← Modern-Apps.git

arrows: add dependency-depth difficulty tiers to generation

Commit
b9fcde472b05d7f9764e2a5e0d1d076a6c03a2d6
Author
Vayun Mathur <[email protected]>
When
2026-12-06 03:58 UTC (9 hours ago)
Parents
6e5bafb
ArrowsGenerator already built boards in reverse removal order, so
boards were clearable, but difficulty came only from board size and
arrow count: nothing steered how deeply arrows block each other, and
generated boards were never re-checked with the solver.

Add ArrowsAnalysis with ArrowsDifficulty tiers (CASUAL/STANDARD/
EXPERT) and board metrics (open/blocked counts, mirror use, and
dependency depth: the longest chain of arrows whose cells lie on the
next arrow's exit route). The generator shapes boards per tier via
the opening cap divisor, a dependency-depth floor, maximum piece
length and depth-weighted candidate scoring, relaxes the depth floor
on late seeded rounds rather than returning no board, and verifies
every seeded board with ArrowsRules.solve before returning it.
ArrowsViewModel maps casual levels to tiers (CASUAL before mirrors,
STANDARD to level 40, EXPERT after); the puzzle format is unchanged.

Verified: :games:arrows:lint, :lintVitalRelease and
:testDevUnitTest pass, including solver-verified clearability,
determinism and tier depth ordering in ArrowsGenerationSystemTest.

Diff

games/arrows/AGENTS.md
diff --git a/games/arrows/AGENTS.md b/games/arrows/AGENTS.mdindex d9af66f222..808b98b910 100644--- a/games/arrows/AGENTS.md+++ b/games/arrows/AGENTS.md@@ -24,7 +24,8 @@ _Install: ./install games/arrows (dev by default)._ ### data/ + domain/ — progress + pure rules - com/vayunmathur/games/arrows/data/ArrowModels.kt - com/vayunmathur/games/arrows/data/ArrowsDataStore.kt-- com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt+- com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt — reverse-removal-order generator; accepts `ArrowsDifficulty` (opening cap, dependency-depth floor, piece length, depth-weighted candidate scoring) and verifies boards with `ArrowsRules.solve`+- com/vayunmathur/games/arrows/domain/ArrowsAnalysis.kt — `ArrowsDifficulty` tiers, `ArrowsBoardMetrics`/`dependencyDepth` analysis, and the level-to-difficulty mapping - com/vayunmathur/games/arrows/domain/ArrowsRules.kt ### platform/ — ViewModel + achievements - com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt
games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsAnalysis.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsAnalysis.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsAnalysis.ktnew file mode 100644index 0000000000..3277f3745e--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsAnalysis.kt@@ -0,0 +1,90 @@+package com.vayunmathur.games.arrows.domain++import com.vayunmathur.games.arrows.data.ArrowsGameState+import com.vayunmathur.games.arrows.data.ArrowsPuzzle+import com.vayunmathur.games.arrows.data.GameMode+import com.vayunmathur.games.arrows.data.STARTING_HEARTS++/** Difficulty tiers: dependency structure, not just board size, separates them. */+enum class ArrowsDifficulty(+    val openDivisor: Int,+    val minDependencyDepth: Int,+    val maxPieceLength: Int,+    val depthWeight: Int,+) {+    CASUAL(openDivisor = 3, minDependencyDepth = 1, maxPieceLength = 5, depthWeight = 0),+    STANDARD(openDivisor = 4, minDependencyDepth = 2, maxPieceLength = 5, depthWeight = 1),+    EXPERT(openDivisor = 5, minDependencyDepth = 3, maxPieceLength = 6, depthWeight = 3),+}++/** Structural facts about a board, derived from the game's own rules. */+data class ArrowsBoardMetrics(+    val pieceCount: Int,+    val openCount: Int,+    val blockedCount: Int,+    val dependencyDepth: Int,+    val mirrorUseCount: Int,+)++object ArrowsAnalysis {+    fun metrics(puzzle: ArrowsPuzzle): ArrowsBoardMetrics {+        val state =+            ArrowsGameState(+                puzzle = puzzle,+                removed = emptySet(),+                hearts = STARTING_HEARTS,+                level = 0,+                mode = GameMode.CASUAL,+            )+        val open = ArrowsRules.clearableNow(state).size+        val usedMirrors =+            puzzle.mirrors.keys.count { mirror ->+                puzzle.pieces.any { piece ->+                    ArrowsRules.exitPath(puzzle, piece.head, piece.direction)?.contains(mirror) == true+                }+            }+        return ArrowsBoardMetrics(+            pieceCount = puzzle.pieces.size,+            openCount = open,+            blockedCount = puzzle.pieces.size - open,+            dependencyDepth = dependencyDepth(puzzle),+            mirrorUseCount = usedMirrors,+        )+    }++    /**+     * Longest chain A -> B -> C ... where each arrow's cells lie on the next arrow's exit+     * route (so the next cannot leave until this one does). Cycles are cut by the visited set.+     */+    fun dependencyDepth(puzzle: ArrowsPuzzle): Int {+        if (puzzle.pieces.isEmpty()) return 0+        val blockers: Map<Int, Set<Int>> =+            puzzle.pieces.associate { piece ->+                val path = ArrowsRules.exitPath(puzzle, piece.head, piece.direction).orEmpty().toSet()+                piece.id to+                    puzzle.pieces+                        .filter { other -> other.id != piece.id && other.cells.any { it in path } }+                        .map { it.id }+                        .toSet()+            }++        fun depthFrom(+            id: Int,+            visiting: Set<Int>,+        ): Int {+            if (id in visiting) return 0+            val next = blockers[id].orEmpty()+            if (next.isEmpty()) return 1+            return 1 + next.maxOf { depthFrom(it, visiting + id) }+        }+        return puzzle.pieces.maxOf { depthFrom(it.id, emptySet()) }+    }++    /** Tier for a casual-ladder [level]; mirrors arrive at 11, depth ramps after that. */+    fun difficultyForLevel(level: Int): ArrowsDifficulty =+        when {+            level < 11 -> ArrowsDifficulty.CASUAL+            level < 40 -> ArrowsDifficulty.STANDARD+            else -> ArrowsDifficulty.EXPERT+        }+}
games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.ktindex af00cfc17c..dcf0fc634e 100644--- a/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt@@ -24,7 +24,6 @@ import kotlin.random.Random  * A generated board can still have many solutions; nothing here tries to make the order unique.  */ object ArrowsGenerator {-     /**      * A clearable board, or null if [attempts] rounds never reached [minPieces].      *@@ -43,9 +42,10 @@ object ArrowsGenerator {         minPieces: Int = (targetPieces * 2) / 3,         attempts: Int = DEFAULT_ATTEMPTS,         openSlack: Int = 0,+        difficulty: ArrowsDifficulty = ArrowsDifficulty.STANDARD,     ): ArrowsPuzzle? {         repeat(attempts) {-            build(cols, rows, targetPieces, mirrorCount, rng, openSlack)+            build(cols, rows, targetPieces, mirrorCount, rng, openSlack, difficulty)                 ?.takeIf { it.pieces.size >= minPieces }                 ?.let { return it }         }@@ -76,9 +76,28 @@ object ArrowsGenerator {         mirrorCount: Int,         seed: Long,         rounds: Int = DEFAULT_ROUNDS,+    ): ArrowsPuzzle? = generateSeeded(cols, rows, targetPieces, mirrorCount, seed, rounds, ArrowsDifficulty.STANDARD)++    /** Seeded board shaped by [difficulty]; verified clearable by [ArrowsRules.solve] before returning. */+    fun generateSeeded(+        cols: Int,+        rows: Int,+        targetPieces: Int,+        mirrorCount: Int,+        seed: Long,+        rounds: Int = DEFAULT_ROUNDS,+        difficulty: ArrowsDifficulty,     ): ArrowsPuzzle? {         for (round in 0 until rounds) {             val concession = CONCESSIONS[round.coerceAtMost(CONCESSIONS.lastIndex)]+            // Late rounds may relax the depth floor by one rather than return no board at all.+            val effective =+                if (round >= DEPTH_RELAX_ROUND && difficulty.minDependencyDepth > 1) {+                    ArrowsDifficulty.entries.firstOrNull { it.minDependencyDepth == difficulty.minDependencyDepth - 1 }+                        ?: difficulty+                } else {+                    difficulty+                }             generate(                 cols = cols,                 rows = rows,@@ -86,7 +105,8 @@ object ArrowsGenerator {                 mirrorCount = (mirrorCount - concession.fewerMirrors).coerceAtLeast(0),                 rng = Random(seed + round * SEED_STRIDE),                 openSlack = concession.openSlack,-            )?.let { return it }+                difficulty = effective,+            )?.takeIf { ArrowsRules.solve(it) != null }?.let { return it }         }         return null     }@@ -98,23 +118,27 @@ object ArrowsGenerator {     val MAX_MIRRORS_DROPPED: Int get() = CONCESSIONS.maxOf { it.fewerMirrors }      /** How much a given round is willing to give up. See [generateSeeded]. */-    private class Concession(val openSlack: Int, val fewerMirrors: Int)--    private val CONCESSIONS = listOf(-        // Four strict rounds before conceding anything: the cap is reachable on most shapes given enough-        // tries, and spending them here is what keeps the great majority of the ladder tight.-        Concession(openSlack = 0, fewerMirrors = 0),-        Concession(openSlack = 0, fewerMirrors = 0),-        Concession(openSlack = 0, fewerMirrors = 0),-        Concession(openSlack = 0, fewerMirrors = 0),-        Concession(openSlack = 1, fewerMirrors = 0),-        Concession(openSlack = 1, fewerMirrors = 0),-        Concession(openSlack = 2, fewerMirrors = 0),-        Concession(openSlack = 2, fewerMirrors = 1),-        Concession(openSlack = 3, fewerMirrors = 1),-        Concession(openSlack = 4, fewerMirrors = 2),+    private class Concession(+        val openSlack: Int,+        val fewerMirrors: Int,     ) +    private val CONCESSIONS =+        listOf(+            // Four strict rounds before conceding anything: the cap is reachable on most shapes given enough+            // tries, and spending them here is what keeps the great majority of the ladder tight.+            Concession(openSlack = 0, fewerMirrors = 0),+            Concession(openSlack = 0, fewerMirrors = 0),+            Concession(openSlack = 0, fewerMirrors = 0),+            Concession(openSlack = 0, fewerMirrors = 0),+            Concession(openSlack = 1, fewerMirrors = 0),+            Concession(openSlack = 1, fewerMirrors = 0),+            Concession(openSlack = 2, fewerMirrors = 0),+            Concession(openSlack = 2, fewerMirrors = 1),+            Concession(openSlack = 3, fewerMirrors = 1),+            Concession(openSlack = 4, fewerMirrors = 2),+        )+     private fun build(         cols: Int,         rows: Int,@@ -122,18 +146,22 @@ object ArrowsGenerator {         mirrorCount: Int,         rng: Random,         openSlack: Int,+        difficulty: ArrowsDifficulty = ArrowsDifficulty.STANDARD,     ): ArrowsPuzzle? {         val cellCount = cols * rows         // Mirrors are kept off the border: one on an edge cell mostly deflects arrows straight back         // out again, which reads as a decoration rather than an obstacle.-        val interior = (0 until cellCount).filter {-            val row = it / cols-            val col = it % cols-            row in 1 until rows - 1 && col in 1 until cols - 1-        }-        val mirrors = interior.shuffled(rng)-            .take(mirrorCount.coerceAtMost(interior.size))-            .associateWith { if (rng.nextBoolean()) Mirror.FORWARD else Mirror.BACK }+        val interior =+            (0 until cellCount).filter {+                val row = it / cols+                val col = it % cols+                row in 1 until rows - 1 && col in 1 until cols - 1+            }+        val mirrors =+            interior+                .shuffled(rng)+                .take(mirrorCount.coerceAtMost(interior.size))+                .associateWith { if (rng.nextBoolean()) Mirror.FORWARD else Mirror.BACK }          // Two different notions of "occupied", and conflating them is what made mirrors decorative: an         // arrow may not be *drawn* on a mirror, but a mirror does not *block* a route - it bends it.@@ -151,15 +179,18 @@ object ArrowsGenerator {          while (pieces.size < targetPieces && failures < MAX_CONSECUTIVE_FAILURES) {             val geometry = ArrowsPuzzle(cols, rows, pieces, mirrors)-            val chosen = chooseCandidate(-                geometry = geometry,-                undrawable = undrawable,-                blocking = blocking,-                paths = paths,-                unusedMirrors = unusedMirrors,-                id = pieces.size,-                rng = rng,-            )+            val chosen =+                chooseCandidate(+                    geometry = geometry,+                    undrawable = undrawable,+                    blocking = blocking,+                    paths = paths,+                    unusedMirrors = unusedMirrors,+                    id = pieces.size,+                    rng = rng,+                    maxLength = difficulty.maxPieceLength,+                    depthWeight = difficulty.depthWeight,+                )             if (chosen == null) {                 failures++                 continue@@ -176,11 +207,28 @@ object ArrowsGenerator {         // A mirror nothing routes through is scenery. Throwing the board away is cheap next to shipping a         // level whose one distinguishing feature does nothing.         if (unusedMirrors.isNotEmpty()) return null-        if (openCount(pieces, paths) > availabilityCapFor(pieces.size) + openSlack) return null-        return ArrowsPuzzle(cols, rows, pieces, mirrors)+        val tierCap = maxOf(MIN_AVAILABLE_FLOOR, (pieces.size + difficulty.openDivisor - 1) / difficulty.openDivisor)+        val cap =+            if (difficulty == ArrowsDifficulty.STANDARD) {+                availabilityCapFor(pieces.size)+            } else {+                tierCap+            }+        if (openCount(pieces, paths) > cap + openSlack) return null+        val puzzle = ArrowsPuzzle(cols, rows, pieces, mirrors)+        // Difficulty shaping: harder tiers must force a dependency chain, not just a bigger board.+        if (pieces.size >= MIN_PIECES_FOR_DEPTH &&+            ArrowsAnalysis.dependencyDepth(puzzle) < difficulty.minDependencyDepth+        ) {+            return null+        }+        return puzzle     } -    private class Candidate(val piece: ArrowPiece, val path: Set<Int>)+    private class Candidate(+        val piece: ArrowPiece,+        val path: Set<Int>,+    )      /**      * The most useful of several random candidates, or null if none was placeable.@@ -205,12 +253,15 @@ object ArrowsGenerator {         unusedMirrors: Set<Int>,         id: Int,         rng: Random,+        maxLength: Int = MAX_LENGTH,+        depthWeight: Int = 1,     ): Candidate? {         var best: Candidate? = null         var bestScore = Int.MIN_VALUE         repeat(CANDIDATES_PER_PIECE) {-            val piece = randomPiece(geometry.cols, geometry.rows, undrawable, id, rng)-                ?: return@repeat+            val piece =+                randomPiece(geometry.cols, geometry.rows, undrawable, id, rng, maxLength)+                    ?: return@repeat             val path = ArrowsRules.exitPath(geometry, piece.head, piece.direction) ?: return@repeat             // Must still be able to leave past everything already placed - that is what makes the             // insertion order a solution - and must not be turned back into itself, which a mirror can@@ -219,7 +270,7 @@ object ArrowsGenerator {              var score = 0             if (path.any { it in unusedMirrors }) score += MIRROR_SCORE-            score += paths.count { existing -> piece.cells.any { it in existing } }+            score += depthWeight * paths.count { existing -> piece.cells.any { it in existing } }             if (score > bestScore) {                 bestScore = score                 best = Candidate(piece, path.toSet())@@ -234,7 +285,10 @@ object ArrowsGenerator {      * Mirrors [ArrowsRules.travel]: an arrow is stopped by any arrow cell on its route, its own included,      * so the test is whether its path avoids every cell any arrow sits on.      */-    private fun openCount(pieces: List<ArrowPiece>, paths: List<Set<Int>>): Int {+    private fun openCount(+        pieces: List<ArrowPiece>,+        paths: List<Set<Int>>,+    ): Int {         val arrowCells = pieces.flatMapTo(mutableSetOf()) { it.cells }         return pieces.indices.count { index -> paths[index].none { it in arrowCells } }     }@@ -251,6 +305,7 @@ object ArrowsGenerator {         occupied: Set<Int>,         id: Int,         rng: Random,+        maxLength: Int = MAX_LENGTH,     ): ArrowPiece? {         val free = (0 until cols * rows).filterNot { it in occupied }         if (free.isEmpty()) return null@@ -258,19 +313,20 @@ object ArrowsGenerator {         val start = free.random(rng)         val cells = mutableListOf(start)         var heading = Direction.entries.random(rng)-        val targetLength = rng.nextInt(2, MAX_LENGTH + 1)+        val targetLength = rng.nextInt(2, maxLength + 1)          while (cells.size < targetLength) {             // Never immediately double back: that would put two cells of the piece on top of             // each other, and the "polyline" would stop being one.             val options = Direction.entries.filter { it != heading.opposite }.shuffled(rng)-            val step = options.firstNotNullOfOrNull { direction ->-                val row = cells.last() / cols + direction.dRow-                val col = cells.last() % cols + direction.dCol-                if (row !in 0 until rows || col !in 0 until cols) return@firstNotNullOfOrNull null-                val cell = row * cols + col-                if (cell in occupied || cell in cells) null else direction to cell-            } ?: break+            val step =+                options.firstNotNullOfOrNull { direction ->+                    val row = cells.last() / cols + direction.dRow+                    val col = cells.last() % cols + direction.dCol+                    if (row !in 0 until rows || col !in 0 until cols) return@firstNotNullOfOrNull null+                    val cell = row * cols + col+                    if (cell in occupied || cell in cells) null else direction to cell+                } ?: break              heading = step.first             cells += step.second@@ -299,6 +355,10 @@ object ArrowsGenerator {     /** Give up on a board once this many placement attempts in a row have failed. */     private const val MAX_CONSECUTIVE_FAILURES = 200 +    private const val MIN_AVAILABLE_FLOOR = 2+    private const val MIN_PIECES_FOR_DEPTH = 6+    private const val DEPTH_RELAX_ROUND = 7+     private const val DEFAULT_ATTEMPTS = 24     private const val DEFAULT_ROUNDS = 12 
games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.ktindex ff2d1cc041..a72529af83 100644--- a/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt@@ -15,6 +15,7 @@ import com.vayunmathur.games.arrows.data.TapOutcome import com.vayunmathur.games.arrows.data.arrowCountForLevel import com.vayunmathur.games.arrows.data.boardSizeForLevel import com.vayunmathur.games.arrows.data.mirrorCountForLevel+import com.vayunmathur.games.arrows.domain.ArrowsAnalysis import com.vayunmathur.games.arrows.domain.ArrowsGenerator import com.vayunmathur.games.arrows.domain.ArrowsRules import com.vayunmathur.library.util.AchievementsManager@@ -186,6 +187,7 @@ class ArrowsViewModel(application: Application) : AndroidViewModel(application),                 targetPieces = arrowCountForLevel(level),                 mirrorCount = mirrorCountForLevel(level),                 seed = level.toLong() + retries * RETRY_SEED_STRIDE,+                difficulty = ArrowsAnalysis.difficultyForLevel(level),             )         } 
games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsGenerationSystemTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsGenerationSystemTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsGenerationSystemTest.ktnew file mode 100644index 0000000000..7023ec878e--- /dev/null+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsGenerationSystemTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.games.arrows.domain++import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class ArrowsGenerationSystemTest {+    @Test+    fun seededBoardsAreSolverVerifiedAcrossTiers() {+        for (difficulty in ArrowsDifficulty.entries) {+            var emitted = 0+            for (seed in 0 until 8) {+                val puzzle =+                    ArrowsGenerator.generateSeeded(+                        cols = 7,+                        rows = 9,+                        targetPieces = 14,+                        mirrorCount = 2,+                        seed = 12_000L + seed * 733L,+                        difficulty = difficulty,+                    ) ?: continue+                emitted+++                val order = assertNotNull(ArrowsRules.solve(puzzle), "seed $seed $difficulty")+                assertEquals(puzzle.pieces.size, order.size)+                val metrics = ArrowsAnalysis.metrics(puzzle)+                assertTrue(metrics.openCount < metrics.pieceCount, "all open: $difficulty seed $seed")+                assertTrue(metrics.mirrorUseCount == puzzle.mirrors.size, "unused mirror")+            }+            assertTrue(emitted >= 4, "$difficulty emitted $emitted")+        }+    }++    @Test+    fun expertBoardsHaveDeeperDependenciesThanCasualOnAverage() {+        fun avgDepth(difficulty: ArrowsDifficulty): Double {+            val values =+                (0 until 8).mapNotNull { seed ->+                    ArrowsGenerator+                        .generateSeeded(+                            7,+                            9,+                            14,+                            2,+                            30_000L + seed * 991L,+                            difficulty = difficulty,+                        )?.let { ArrowsAnalysis.dependencyDepth(it) }+                }+            assertTrue(values.size >= 4, "$difficulty produced ${values.size}")+            return values.average()+        }+        assertTrue(avgDepth(ArrowsDifficulty.EXPERT) >= avgDepth(ArrowsDifficulty.CASUAL))+    }++    @Test+    fun sameSeedGivesSameBoard() {+        val a =+            assertNotNull(+                ArrowsGenerator.generateSeeded(6, 8, 12, 0, 4242L, difficulty = ArrowsDifficulty.STANDARD),+            )+        val b =+            assertNotNull(+                ArrowsGenerator.generateSeeded(6, 8, 12, 0, 4242L, difficulty = ArrowsDifficulty.STANDARD),+            )+        assertEquals(a.pieces, b.pieces)+        assertEquals(a.mirrors, b.mirrors)+    }++    @Test+    fun generateWithSeededRandomIsDeterministic() {+        val a = ArrowsGenerator.generate(6, 8, 12, 0, Random(99))+        val b = ArrowsGenerator.generate(6, 8, 12, 0, Random(99))+        assertEquals(a?.pieces, b?.pieces)+    }+}