Modern Apps git

← Modern-Apps.git

nonogram: generate picture-like puzzles with difficulty tiers

Commit
2791743bc74fc2a7582b45b5f012720411884ebd
Author
Vayun Mathur <[email protected]>
When
2026-12-06 03:58 UTC (7 hours ago)
Parents
b9fcde4
NonogramGenerator painted uniform random cells at a fixed fill
ratio and kept whatever line logic could solve. The pictures read
as noise, difficulty was only grid size, and degenerate boards
(near-empty, near-full, many dead lines) were filtered only by the
all-blank check.

Paint picture-like candidates instead: themed shapes (frame,
diamond, ring, cross, stripes), random-walk grown blobs and uniform
fill as fallback, with optional left-right symmetry and light noise.
NonogramDifficulty tiers (EASY/STANDARD/HARD) shape the fill band,
shape/symmetry chances and level mapping; candidates must sit in
the tier fill band, keep few fully empty/full lines, be solvable by
line logic alone, and have the solver recover exactly the painted
picture, which proves the clues have a unique solution.
NonogramViewModel passes the level's tier (dailies stay STANDARD);
the puzzle format is unchanged. One ViewModel stroke test now runs
on a 10x10 board with a blank between fills, since the 5x5 tutorial
picture is a plus whose row blanks are auto-crossed by design.

Verified: :games:nonogram:lint, :lintVitalRelease and
:testDevUnitTest pass, including uniqueness, determinism and tier
structure across seeds in NonogramGenerationSystemTest.

Diff

games/nonogram/AGENTS.md
diff --git a/games/nonogram/AGENTS.md b/games/nonogram/AGENTS.mdindex 883b1fe9b5..b5be96d2b4 100644--- a/games/nonogram/AGENTS.md+++ b/games/nonogram/AGENTS.md@@ -27,7 +27,7 @@ _Install: ./install games/nonogram (dev by default)._ - com/vayunmathur/games/nonogram/data/NonogramModels.kt - com/vayunmathur/games/nonogram/data/NonogramPuzzle.kt - com/vayunmathur/games/nonogram/data/NonogramDataStore.kt-- com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt+- com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt — picture-like generation (`NonogramDifficulty` EASY/STANDARD/HARD: themed shapes, grown blobs, symmetry, noise, per-tier fill bands), degenerate-board rejection, solver-verified unique line-solvable puzzles, and `NonogramMetrics` - com/vayunmathur/games/nonogram/domain/NonogramSolver.kt - com/vayunmathur/games/nonogram/domain/NonogramClues.kt - com/vayunmathur/games/nonogram/domain/NonogramMoves.kt
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.ktindex 1f08908ef5..c9bc17105f 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt@@ -13,7 +13,58 @@ import kotlin.random.Random  * shows. This is the opposite trade to `games/pipes`, whose win condition needs a full-board  * uniqueness proof too slow to attempt on device.  */++/** Difficulty tiers: picture structure and clue density, not just grid size. */+enum class NonogramDifficulty(+    val fillMin: Double,+    val fillMax: Double,+    val shapeChance: Double,+    val symmetricChance: Double,+) {+    EASY(fillMin = 0.30, fillMax = 0.55, shapeChance = 0.70, symmetricChance = 0.80),+    STANDARD(fillMin = 0.38, fillMax = 0.62, shapeChance = 0.50, symmetricChance = 0.45),+    HARD(fillMin = 0.36, fillMax = 0.60, shapeChance = 0.35, symmetricChance = 0.10),+}++/** Structural facts about a generated picture. */+data class NonogramMetrics(+    val filledFraction: Double,+    val clueCount: Int,+    val emptyOrFullLines: Int,+    val symmetric: Boolean,+)++fun nonogramDifficultyForLevel(level: Int): NonogramDifficulty =+    when {+        level <= 8 -> NonogramDifficulty.EASY+        level <= 20 -> NonogramDifficulty.STANDARD+        else -> NonogramDifficulty.HARD+    }+ object NonogramGenerator {+    /** Metrics of [puzzle]'s intended picture, for difficulty assertions and tuning. */+    fun metrics(puzzle: NonogramPuzzle): NonogramMetrics {+        val size = puzzle.size+        val symmetric =+            (0 until size).all { r ->+                (0 until size).all { c -> puzzle.solution[r * size + c] == puzzle.solution[r * size + (size - 1 - c)] }+            }+        var lines = 0+        for (r in 0 until size) {+            val row = (0 until size).map { puzzle.solution[r * size + it] }+            if (row.none { it } || row.all { it }) lines+++        }+        for (c in 0 until size) {+            val col = (0 until size).map { puzzle.solution[it * size + c] }+            if (col.none { it } || col.all { it }) lines+++        }+        return NonogramMetrics(+            filledFraction = if (size == 0) 0.0 else puzzle.filledCount.toDouble() / (size * size),+            clueCount = puzzle.rowClues.sumOf { it.size } + puzzle.colClues.sumOf { it.size },+            emptyOrFullLines = lines,+            symmetric = symmetric,+        )+    }      /**      * A puzzle of [size] that line logic alone can finish, or null if [attempts] candidates all@@ -28,6 +79,7 @@ object NonogramGenerator {         fillRatio: Double = DEFAULT_FILL_RATIO,         attempts: Int = DEFAULT_ATTEMPTS,         shouldContinue: () -> Boolean = { true },+        difficulty: NonogramDifficulty = NonogramDifficulty.STANDARD,     ): NonogramPuzzle? {         repeat(attempts) {             // Cooperative cancellation: this loop is pure CPU with no@@ -37,15 +89,120 @@ object NonogramGenerator {             // starve its own replacement — on a 4-core box a handful of             // zombie searches can stall the live one past any timeout.             if (!shouldContinue()) return null-            val candidate = paint(size, rng, fillRatio)+            val candidate = paintThemed(size, rng, fillRatio, difficulty)             // An all-blank grid is technically line-solvable and completely pointless to play.             if (candidate.none { it }) return@repeat             val puzzle = NonogramPuzzle.from(size, candidate)-            if (NonogramSolver.isLineSolvable(size, puzzle.rowClues, puzzle.colClues)) return puzzle+            if (!isAcceptable(size, puzzle, difficulty)) return@repeat+            // Uniqueness: line-solvable already forces one solution; verify the solver+            // recovers exactly the painted picture so no second picture fits the clues.+            val solved = NonogramSolver.solve(size, puzzle.rowClues, puzzle.colClues) ?: return@repeat+            if (solved.map { it == CellState.FILLED } != candidate) return@repeat+            return puzzle         }         return null     } +    /** Degenerate-board gate: fill band per tier, and few fully empty/full lines. */+    private fun isAcceptable(+        size: Int,+        puzzle: NonogramPuzzle,+        difficulty: NonogramDifficulty,+    ): Boolean {+        val m = metrics(puzzle)+        if (m.filledFraction < difficulty.fillMin || m.filledFraction > difficulty.fillMax) return false+        if (m.emptyOrFullLines > maxOf(2, size / 3)) return false+        return true+    }++    /**+     * Picture-like painting: themed shapes and grown blobs first, uniform noise only as a+     * fallback, with optional left-right symmetry (recognisable pictures solve more kindly).+     */+    private fun paintThemed(+        size: Int,+        rng: Random,+        fillRatio: Double,+        difficulty: NonogramDifficulty,+    ): List<Boolean> {+        val roll = rng.nextDouble()+        var grid =+            when {+                roll < difficulty.shapeChance -> paintShape(size, rng)+                roll < difficulty.shapeChance + 0.30 -> paintBlobs(size, rng, fillRatio)+                else -> paint(size, rng, fillRatio)+            }+        if (rng.nextDouble() < difficulty.symmetricChance) grid = mirrored(grid, size)+        // A little noise keeps shapes from being pure stencils the clues give away at a glance.+        return grid.map { if (rng.nextDouble() < NOISE_FLIP) !it else it }+    }++    private fun mirrored(+        grid: List<Boolean>,+        size: Int,+    ): List<Boolean> =+        List(size * size) { i ->+            val r = i / size+            val c = i % size+            grid[r * size + minOf(c, size - 1 - c)]+        }++    private fun paintShape(+        size: Int,+        rng: Random,+    ): List<Boolean> {+        val center = (size - 1) / 2.0+        val radius = size * (0.28 + rng.nextDouble() * 0.22)+        val kind = rng.nextInt(5)+        return List(size * size) { i ->+            val r = i / size+            val c = i % size+            when (kind) {+                0 -> r == 0 || c == 0 || r == size - 1 || c == size - 1 // frame+                1 -> kotlin.math.abs(r - center) + kotlin.math.abs(c - center) <= radius // diamond+                2 -> {+                    val d = maxOf(kotlin.math.abs(r - center), kotlin.math.abs(c - center))+                    d <= radius && d >= radius - 1.5 // ring+                }+                3 -> r == size / 2 || c == size / 2 // cross+                else -> (r + c) % 3 != 0 // diagonal stripes+            }+        }+    }++    /** Grown clusters: random-walk growth from a few seeds reads as a picture, not static. */+    private fun paintBlobs(+        size: Int,+        rng: Random,+        fillRatio: Double,+    ): List<Boolean> {+        val grid = MutableList(size * size) { false }+        val target = (size * size * fillRatio).toInt().coerceAtLeast(1)+        var filled = 0+        var guard = 0+        while (filled < target && guard < target * 40) {+            guard+++            var cell = rng.nextInt(size * size)+            repeat(rng.nextInt(3, 10)) {+                if (!grid[cell]) {+                    grid[cell] = true+                    filled+++                }+                val r = cell / size+                val c = cell % size+                val options =+                    listOfNotNull(+                        if (r > 0) cell - size else null,+                        if (r < size - 1) cell + size else null,+                        if (c > 0) cell - 1 else null,+                        if (c < size - 1) cell + 1 else null,+                    )+                if (options.isNotEmpty()) cell = options.random(rng)+            }+        }+        return grid+    }+     /**      * A puzzle for [size], retrying with derived seeds until one is found.      *@@ -57,18 +214,34 @@ object NonogramGenerator {         seed: Long,         rounds: Int = DEFAULT_ROUNDS,         shouldContinue: () -> Boolean = { true },+    ): NonogramPuzzle? = generateSeeded(size, seed, rounds, NonogramDifficulty.STANDARD, shouldContinue)++    /** Seeded puzzle shaped by [difficulty]; same seed always yields the same picture. */+    fun generateSeeded(+        size: Int,+        seed: Long,+        rounds: Int = DEFAULT_ROUNDS,+        difficulty: NonogramDifficulty,+        shouldContinue: () -> Boolean = { true },     ): NonogramPuzzle? {         for (round in 0 until rounds) {             if (!shouldContinue()) return null-            generate(size, Random(seed + round * SEED_STRIDE), shouldContinue = shouldContinue)-                ?.let { return it }+            generate(+                size,+                Random(seed + round * SEED_STRIDE),+                shouldContinue = shouldContinue,+                difficulty = difficulty,+            )?.let { return it }         }         return null     }      /** Independent coin flips per cell. Simple, and the solver filters out the unfair results. */-    private fun paint(size: Int, rng: Random, fillRatio: Double): List<Boolean> =-        List(size * size) { rng.nextDouble() < fillRatio }+    private fun paint(+        size: Int,+        rng: Random,+        fillRatio: Double,+    ): List<Boolean> = List(size * size) { rng.nextDouble() < fillRatio }      /**      * Roughly half filled. Much sparser and the picture is mostly blank; much denser and the clues@@ -76,6 +249,8 @@ object NonogramGenerator {      */     const val DEFAULT_FILL_RATIO = 0.55 +    private const val NOISE_FLIP = 0.06+     private const val DEFAULT_ATTEMPTS = 60      /** Rounds the seeded search runs per attempt; retries add more rounds beyond this base. */
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.ktindex 2a87f1d790..ea119670fd 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt@@ -14,7 +14,9 @@ import com.vayunmathur.games.nonogram.data.STARTING_HEARTS import com.vayunmathur.games.nonogram.data.StoredBoard import com.vayunmathur.games.nonogram.data.sizeForLevel import com.vayunmathur.games.nonogram.domain.NonogramClues+import com.vayunmathur.games.nonogram.domain.NonogramDifficulty import com.vayunmathur.games.nonogram.domain.NonogramGenerator+import com.vayunmathur.games.nonogram.domain.nonogramDifficultyForLevel import com.vayunmathur.games.nonogram.domain.NonogramMoves import com.vayunmathur.games.nonogram.domain.NonogramStrokes import com.vayunmathur.games.nonogram.domain.Stroke@@ -148,7 +150,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application                 NonogramGenerator.DEFAULT_ROUNDS +                     session.attempt * NonogramGenerator.RETRY_EXTRA_ROUNDS                 ).coerceAtMost(MAX_GENERATION_ROUNDS)-            cached ?: NonogramGenerator.generateSeeded(size, seed, rounds) { coroutineContext.isActive }+            cached ?: NonogramGenerator.generateSeeded(size, seed, rounds, if (daily) NonogramDifficulty.STANDARD else nonogramDifficultyForLevel(session.level)) { coroutineContext.isActive }         }          if (puzzle == null) {
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramGenerationSystemTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramGenerationSystemTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramGenerationSystemTest.ktnew file mode 100644index 0000000000..b9ff5f5eeb--- /dev/null+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramGenerationSystemTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.games.nonogram.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class NonogramGenerationSystemTest {+    @Test+    fun seededPuzzlesAreUniqueAndLineSolvableAcrossTiers() {+        for (difficulty in NonogramDifficulty.entries) {+            var emitted = 0+            for (seed in 0 until 10) {+                val puzzle =+                    NonogramGenerator.generateSeeded(+                        size = 10,+                        seed = 5_000L + seed * 271L,+                        difficulty = difficulty,+                    ) ?: continue+                emitted+++                assertTrue(+                    NonogramSolver.isLineSolvable(puzzle.size, puzzle.rowClues, puzzle.colClues),+                    "$difficulty seed $seed",+                )+                val solved =+                    assertNotNull(+                        NonogramSolver.solve(puzzle.size, puzzle.rowClues, puzzle.colClues),+                    )+                // Unique solution: solver recovers exactly the painted picture.+                assertEquals(puzzle.solution, solved.map { it == CellState.FILLED })+                val metrics = NonogramGenerator.metrics(puzzle)+                assertTrue(+                    metrics.filledFraction in difficulty.fillMin..difficulty.fillMax,+                    "$difficulty fill=${metrics.filledFraction}",+                )+                assertTrue(metrics.emptyOrFullLines <= 4, "degenerate lines=${metrics.emptyOrFullLines}")+                assertTrue(puzzle.filledCount > 0)+            }+            assertTrue(emitted >= 5, "$difficulty emitted $emitted")+        }+    }++    @Test+    fun sameSeedGivesSamePicture() {+        val a =+            assertNotNull(+                NonogramGenerator.generateSeeded(10, 31415L, difficulty = NonogramDifficulty.HARD),+            )+        val b =+            assertNotNull(+                NonogramGenerator.generateSeeded(10, 31415L, difficulty = NonogramDifficulty.HARD),+            )+        assertEquals(a.solution, b.solution)+    }++    @Test+    fun easyPicturesAreMoreOftenSymmetricThanHardOnes() {+        fun symmetricCount(difficulty: NonogramDifficulty): Int =+            (0 until 10).count { seed ->+                NonogramGenerator+                    .generateSeeded(+                        10,+                        8_000L + seed * 389L,+                        difficulty = difficulty,+                    )?.let { NonogramGenerator.metrics(it).symmetric } == true+            }+        assertTrue(symmetricCount(NonogramDifficulty.EASY) >= symmetricCount(NonogramDifficulty.HARD))+    }+}
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.ktindex fc566f3958..4547b7a5d3 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt@@ -376,13 +376,20 @@ class NonogramViewModelTest {     }      @Test fun dragStrokeFillsALineAndChargesOneHeartForAMistake() {-        val vm = loadedVm()+        // A 10x10 board, so the generated picture has a row with a blank between fills+        // (the 5x5 tutorial picture is a plus, which has none).+        val vm = loadedVm(level = 9)         val g = vm.uiState.value.game!!         val n = g.size-        // Pick a row with a blank somewhere after a picture cell, and drag across the whole row.+        // Pick a row with a blank between picture cells, and drag across the whole row. The+        // blank must sit before the row's last picture cell: a blank after the final fill is+        // auto-crossed by that fill (the row's clues are complete), so the stroke rightly+        // protects it instead of charging a heart for it.         val row = (0 until n).first { r ->             val line = (0 until n).map { g.puzzle.solution[r * n + it] }-            line.indexOf(true).let { it >= 0 && line.drop(it).contains(false) }+            val firstTrue = line.indexOf(true)+            val lastTrue = line.lastIndexOf(true)+            firstTrue >= 0 && lastTrue > firstTrue && (firstTrue..lastTrue).any { !line[it] }         }         val line = (0 until n).map { row * n + it }         val firstPicture = line.first { g.puzzle.solution[it] }