Modern Apps git

← Modern-Apps.git

pipes: only ship levels that force a full board, and draw dailies from them (#552)

Commit
39c4f4d4e39914b0e2835889283bcc5e3ff0968e
Author
vayun-mathur <[email protected]>
When
2026-08-18 18:18 UTC (3 months ago)
Parents
e734f63
A win needs every cell owned, so a level whose pairs can also be joined while leaving a
cell empty is a dead end: you connect everything and nothing happens. Daily levels were
generated on device with no solution check at all, which is where the reported levels came
from - the doc comment admitted it, since the ZDD solver the asset pipeline uses had no
Kotlin equivalent.

It does now. NumberlinkSolver is a port of scripts/pipes/numberlink_solver.cpp: it walks
cells diagonally and memoises on the frontier, which is what makes counting solutions
tractable. It agrees with the C++ solver on every shipped 8x8-11x11 level and with
brute-force enumeration on small boards.

Verifying a carve at runtime is not viable - a 9x9 candidate costs seconds and almost never
passes - so the daily now draws from the shipped packs, which the offline pipeline already
validated. Scanning them turned up 10 levels with the same bug (7 in 5x5, 3 in 6x6);
those are regenerated through LevelGenerator, which now gates on the solver, keeping their
IDs so per-level stats survive. ShippedPacksTest keeps them honest.

Note the daily pool is the 450 shipped levels, so dailies can now repeat and overlap the
campaign. A dedicated pool needs the offline pipeline (g++).

Diff

games/pipes/src/main/assets/packs/5x5.json
diff --git a/games/pipes/src/main/assets/packs/5x5.json b/games/pipes/src/main/assets/packs/5x5.jsonindex afec2dafc7..58e72c9ac7 100644--- a/games/pipes/src/main/assets/packs/5x5.json+++ b/games/pipes/src/main/assets/packs/5x5.json@@ -588,11 +588,11 @@           "color": 0,           "cells": [             [-              1,-              3+              4,+              2             ],             [-              4,+              1,               3             ]           ]@@ -601,11 +601,11 @@           "color": 1,           "cells": [             [-              4,+              1,               2             ],             [-              1,+              4,               1             ]           ]@@ -615,16 +615,29 @@           "cells": [             [               4,-              1+              3             ],             [               0,-              4+              0+            ]+          ]+        },+        {+          "color": 3,+          "cells": [+            [+              1,+              1+            ],+            [+              4,+              0             ]           ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 4     },     {       "id": "5\u00d75_014",@@ -695,12 +708,12 @@           "color": 0,           "cells": [             [-              0,-              3+              4,+              2             ],             [-              2,-              4+              1,+              3             ]           ]         },@@ -708,12 +721,12 @@           "color": 1,           "cells": [             [-              3,-              3+              1,+              2             ],             [               4,-              3+              1             ]           ]         },@@ -721,8 +734,21 @@           "color": 2,           "cells": [             [-              2,+              4,+              3+            ],+            [+              0,               0+            ]+          ]+        },+        {+          "color": 3,+          "cells": [+            [+              1,+              1             ],             [               4,@@ -731,7 +757,7 @@           ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 4     },     {       "id": "5\u00d75_016",@@ -909,12 +935,12 @@           "color": 0,           "cells": [             [-              2,+              0,               0             ],             [-              4,-              0+              2,+              3             ]           ]         },@@ -922,12 +948,12 @@           "color": 1,           "cells": [             [-              0,+              1,               1             ],             [-              1,-              2+              0,+              4             ]           ]         },@@ -935,17 +961,30 @@           "color": 2,           "cells": [             [-              0,-              2+              2,+              1             ],             [-              0,+              1,+              3+            ]+          ]+        },+        {+          "color": 3,+          "cells": [+            [+              1,               4+            ],+            [+              4,+              0             ]           ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 4     },     {       "id": "5\u00d75_020",@@ -956,12 +995,12 @@           "color": 0,           "cells": [             [-              4,-              2+              1,+              1             ],             [-              0,-              1+              2,+              2             ]           ]         },@@ -970,10 +1009,10 @@           "cells": [             [               3,-              4+              1             ],             [-              3,+              0,               3             ]           ]@@ -983,16 +1022,29 @@           "cells": [             [               3,-              1+              2             ],             [-              0,-              4+              1,+              3+            ]+          ]+        },+        {+          "color": 3,+          "cells": [+            [+              1,+              2+            ],+            [+              4,+              0             ]           ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 4     },     {       "id": "5\u00d75_021",@@ -1158,11 +1210,11 @@           "cells": [             [               1,-              2+              1             ],             [-              1,-              1+              2,+              2             ]           ]         },@@ -1170,21 +1222,34 @@           "color": 1,           "cells": [             [-              4,-              4+              3,+              1             ],             [-              3,-              2+              0,+              3             ]           ]         },         {           "color": 2,           "cells": [+            [+              3,+              2+            ],             [               1,               3+            ]+          ]+        },+        {+          "color": 3,+          "cells": [+            [+              1,+              2             ],             [               4,@@ -1193,7 +1258,7 @@           ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 4     },     {       "id": "5\u00d75_025",@@ -1298,12 +1363,12 @@           "color": 0,           "cells": [             [-              0,-              2+              1,+              1             ],             [-              1,-              0+              2,+              2             ]           ]         },@@ -1311,12 +1376,12 @@           "color": 1,           "cells": [             [-              1,+              3,               1             ],             [-              3,-              2+              0,+              3             ]           ]         },@@ -1324,17 +1389,30 @@           "color": 2,           "cells": [             [-              2,-              0+              3,+              2             ],             [-              2,+              1,+              3+            ]+          ]+        },+        {+          "color": 3,+          "cells": [+            [+              1,               2+            ],+            [+              4,+              0             ]           ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 4     },     {       "id": "5\u00d75_028",@@ -1344,35 +1422,48 @@         {           "color": 0,           "cells": [+            [+              1,+              1+            ],             [               2,               2-            ],+            ]+          ]+        },+        {+          "color": 1,+          "cells": [             [               3,-              0+              1+            ],+            [+              0,+              3             ]           ]         },         {-          "color": 1,+          "color": 2,           "cells": [             [-              1,+              3,               2             ],             [-              3,+              1,               3             ]           ]         },         {-          "color": 2,+          "color": 3,           "cells": [             [               1,-              1+              2             ],             [               4,@@ -1381,7 +1472,7 @@           ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 4     },     {       "id": "5\u00d75_029",@@ -1491,4 +1582,4 @@       "optimalMoves": 3     }   ]-}\ No newline at end of file+}
games/pipes/src/main/assets/packs/6x6.json
diff --git a/games/pipes/src/main/assets/packs/6x6.json b/games/pipes/src/main/assets/packs/6x6.jsonindex d085ea06ef..a52ca6c57c 100644--- a/games/pipes/src/main/assets/packs/6x6.json+++ b/games/pipes/src/main/assets/packs/6x6.json@@ -530,12 +530,12 @@           "color": 0,           "cells": [             [-              5,-              3+              0,+              4             ],             [-              4,-              4+              1,+              1             ]           ]         },@@ -543,12 +543,12 @@           "color": 1,           "cells": [             [-              3,-              2+              2,+              1             ],             [-              2,-              0+              1,+              4             ]           ]         },@@ -557,6 +557,32 @@           "cells": [             [               5,+              0+            ],+            [+              4,+              4+            ]+          ]+        },+        {+          "color": 3,+          "cells": [+            [+              5,+              1+            ],+            [+              5,+              4+            ]+          ]+        },+        {+          "color": 4,+          "cells": [+            [+              0,               2             ],             [@@ -564,9 +590,22 @@               4             ]           ]+        },+        {+          "color": 5,+          "cells": [+            [+              5,+              5+            ],+            [+              0,+              5+            ]+          ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 6     },     {       "id": "6\u00d76_010",@@ -1169,12 +1208,12 @@           "color": 0,           "cells": [             [-              5,-              3+              0,+              5             ],             [-              3,-              0+              1,+              1             ]           ]         },@@ -1182,11 +1221,11 @@           "color": 1,           "cells": [             [-              0,-              0+              3,+              2             ],             [-              2,+              1,               3             ]           ]@@ -1194,31 +1233,57 @@         {           "color": 2,           "cells": [+            [+              3,+              4+            ],             [               2,+              3+            ]+          ]+        },+        {+          "color": 3,+          "cells": [+            [+              0,               0             ],             [-              1,-              0+              5,+              1             ]           ]         },         {-          "color": 3,+          "color": 4,           "cells": [             [-              1,-              4+              5,+              5             ],             [-              0,+              4,+              1+            ]+          ]+        },+        {+          "color": 5,+          "cells": [+            [+              3,+              1+            ],+            [+              1,               2             ]           ]         }       ],-      "optimalMoves": 4+      "optimalMoves": 6     },     {       "id": "6\u00d76_020",@@ -1529,12 +1594,12 @@           "color": 0,           "cells": [             [-              3,-              0+              0,+              5             ],             [-              4,-              0+              1,+              1             ]           ]         },@@ -1542,12 +1607,12 @@           "color": 1,           "cells": [             [-              2,-              4+              3,+              2             ],             [-              4,-              4+              1,+              3             ]           ]         },@@ -1555,17 +1620,56 @@           "color": 2,           "cells": [             [-              5,-              0+              3,+              4             ],+            [+              2,+              3+            ]+          ]+        },+        {+          "color": 3,+          "cells": [             [               0,+              0+            ],+            [+              5,+              1+            ]+          ]+        },+        {+          "color": 4,+          "cells": [+            [+              5,               5+            ],+            [+              4,+              1+            ]+          ]+        },+        {+          "color": 5,+          "cells": [+            [+              3,+              1+            ],+            [+              1,+              2             ]           ]         }       ],-      "optimalMoves": 3+      "optimalMoves": 6     },     {       "id": "6\u00d76_026",@@ -1933,4 +2037,4 @@       "optimalMoves": 5     }   ]-}\ No newline at end of file+}
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.ktindex b6e64687cb..799cae8c4d 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.kt@@ -1,58 +1,41 @@ package com.vayunmathur.games.pipes.domain +import com.vayunmathur.games.pipes.data.LevelData import com.vayunmathur.games.pipes.data.LevelPack-import com.vayunmathur.games.pipes.data.computeAdjacency+import kotlin.random.Random  /**- * The five levels of a given day, generated from a seed derived purely from the epoch day, so- * every player on that date gets exactly the same pack without any server or shipped asset.+ * The five levels of a given day, drawn from the shipped packs by a seed derived purely from the+ * epoch day, so every player on that date gets exactly the same pack without any server call.  *- * Unlike the shipped packs these are not verified to have a unique solution — the ZDD solver the- * asset pipeline uses has no Kotlin equivalent — so some dailies admit more than one layout.+ * The levels are shipped rather than generated on the fly because the win condition needs every+ * cell owned, so a level whose pairs can be joined without filling the board is a dead end for the+ * player (issue #552). Ruling that out means proving the board has exactly one solution, which+ * [NumberlinkSolver] can do but which nothing can cheaply *generate* — the offline asset pipeline+ * throws away hundreds of candidates per keeper. The shipped packs already went through that, and+ * `ShippedPacksTest` holds them to it.  */ object DailyLevels {      const val LEVELS_PER_DAY = 5 -    /**-     * Board size and early-stop probability per level. A lower early stop yields fewer, longer-     * flows, which is the harder puzzle — so difficulty ramps on board size and flow length-     * together. The flow count itself falls out of the carve.-     */-    private val RAMP = listOf(-        6 to 0.10f,-        7 to 0.05f,-        8 to 0.0f,-        9 to 0.0f,-        10 to 0.0f,-    )-     fun levelId(day: Long, index: Int) = "daily_${day}_$index" -    /** Null only if generation somehow fails for a level, in which case the day has no daily. */-    fun packFor(day: Long): LevelPack? {-        val levels = RAMP.mapIndexedNotNull { index, (size, earlyStop) ->-            val cells = LevelGenerator.rectangularCells(size, size)-            val adjacency = computeAdjacency(cells)-            val baseSeed = SEED_OFFSET + day * 100 + index-            // generateLevel can fail outright for a given seed; bump it until a board comes back.-            (0 until MAX_SEED_BUMPS).firstNotNullOfOrNull { bump ->-                LevelGenerator.generateLevel(-                    cells = cells,-                    adjacency = adjacency,-                    maxFlows = LevelGenerator.flowCeiling(cells),-                    seed = baseSeed + bump * SEED_BUMP,-                    id = levelId(day, index),-                    earlyStopProb = earlyStop-                )-            }-        }-        return if (levels.size == RAMP.size) {-            LevelPack(name = "daily_$day", shape = "square", levels = levels)-        } else null+    /**+     * Null only when the shipped packs have not been loaded yet, or hold too few levels to fill a+     * day. Levels come back smallest first, so the day ramps up in difficulty.+     */+    fun packFor(day: Long, pool: List<LevelData> = defaultPool()): LevelPack? {+        if (pool.size < LEVELS_PER_DAY) return null+        val chosen = pool+            .shuffled(Random(SEED_OFFSET + day))+            .take(LEVELS_PER_DAY)+            .sortedBy { it.cells.size }+            .mapIndexed { index, level -> level.copy(id = levelId(day, index)) }+        return LevelPack(name = "daily_$day", shape = "square", levels = chosen)     } +    private fun defaultPool(): List<LevelData> = LevelPack.PACKS.flatMap { it.levels }+     private const val SEED_OFFSET = 500_000_000L-    private const val SEED_BUMP = 1_000_000L-    private const val MAX_SEED_BUMPS = 40 }
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.ktindex ede08cce5e..b0004072c1 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.kt@@ -8,6 +8,16 @@ import kotlin.math.roundToInt import kotlin.random.Random import java.util.Locale +/**+ * Builds levels by carving a board into pipe paths and keeping only their endpoints.+ *+ * Nothing at runtime uses this: the daily pack draws from the shipped assets instead, because+ * boards this produces only rarely force a full solution and proving that they do is far too slow+ * on a phone (a 9x9 candidate costs seconds). It stays as the tool that produced the replacement+ * 5x5 and 6x6 levels, and every board it returns is checked by [NumberlinkSolver] first, so it is+ * safe to point at an asset. For bulk pack generation use `scripts/pipes/generate_levels.py`, whose+ * meet-in-the-middle construction has a far better hit rate.+ */ object LevelGenerator {      fun rectangularCells(rows: Int, cols: Int): Set<CellPos> {@@ -18,7 +28,8 @@ object LevelGenerator {      /**      * Carves [cells] into pipe paths seeded by [seed], returning null if no attempt produced a-     * board with at most [maxFlows] flows that survives [shortPairViolation].+     * board with at most [maxFlows] flows that survives [shortPairViolation] and has the carve as+     * its only solution.      *      * [earlyStopProb] controls flow length: higher means more, shorter flows.      */@@ -34,9 +45,8 @@ object LevelGenerator {         val cols = cells.maxOf { it.col } + 1          for (attempt in 0 until 50) {-            val paths = carveCover(cells, adjacency, Random(seed + attempt), earlyStopProb) ?: continue-            if (paths.size > maxFlows) continue-            if (shortPairViolation(paths)) continue+            val carved = carveCover(cells, adjacency, Random(seed + attempt), earlyStopProb) ?: continue+            val paths = splitUntilUniquelySolvable(carved, cells, maxFlows) ?: continue             val endpoints = paths.mapIndexed { index, path ->                 EndpointPair(index, listOf(path.first(), path.last()))             }@@ -55,6 +65,53 @@ object LevelGenerator {         return null     } +    /**+     * A carve covers every cell, but only its endpoints survive into the level, and a long flow's+     * endpoints usually admit a shorter route. That leaves the board joinable without filling it,+     * which [com.vayunmathur.games.pipes.platform.PipesViewModel] refuses to score as a win — the+     * player connects everything and nothing happens. Bug #552.+     *+     * Cutting a flow in two pins down the middle of its route without disturbing the cover, so keep+     * cutting the longest flow until the endpoints admit only the carve. Returns null once the board+     * is out of room for more pairs, which means this carve cannot be salvaged.+     */+    private fun splitUntilUniquelySolvable(+        carved: List<List<CellPos>>,+        cells: Set<CellPos>,+        maxFlows: Int,+    ): List<List<CellPos>>? {+        var paths = carved+        while (paths.size <= maxFlows) {+            if (!shortPairViolation(paths)) {+                val endpoints = paths.mapIndexed { index, path ->+                    EndpointPair(index, listOf(path.first(), path.last()))+                }+                val verdict = NumberlinkSolver.classify(cells, endpoints)+                if (verdict == NumberlinkSolver.Verdict.UNIQUE) return paths+                // NONE is impossible (the carve is a solution) and UNDECIDED means the search gave+                // up, so in both cases splitting further is the only way forward.+            }+            paths = splitLongestFlow(paths) ?: return null+        }+        return null+    }++    /**+     * Halves the longest flow, or null if none is long enough to leave both halves above the+     * [shortPairViolation] floor.+     */+    private fun splitLongestFlow(paths: List<List<CellPos>>): List<List<CellPos>>? {+        val index = paths.indices+            .filter { paths[it].size >= 2 * MIN_SPLIT_LENGTH }+            .maxByOrNull { paths[it].size }+            ?: return null+        val path = paths[index]+        val half = path.size / 2+        return paths.subList(0, index) ++            listOf(path.subList(0, half), path.subList(half, path.size)) ++            paths.subList(index + 1, paths.size)+    }+     /**      * Path-cover with a dynamic number of flows: keep carving connectivity-preserving paths until      * every cell is used. A port of `carve_cover` in `scripts/pipes/generate_levels.py`, which is@@ -150,6 +207,9 @@ object LevelGenerator {     /** Max flows for a board of this size, keeping puzzles sparse with longer flows. */     fun flowCeiling(cells: Set<CellPos>): Int = maxOf(4, (cells.size / 5f).roundToInt()) +    /** Shortest flow [splitLongestFlow] will produce, so its output always clears length 4. */+    private const val MIN_SPLIT_LENGTH = 5+     fun generatePack(         name: String,         shape: String,
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.ktnew file mode 100644index 0000000000..f1f7d81f51--- /dev/null+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.kt@@ -0,0 +1,262 @@+package com.vayunmathur.games.pipes.domain++import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.EndpointPair++/**+ * Counts the ways a numberlink board can be solved.+ *+ * A Kotlin port of the ZDD counter in `scripts/pipes/numberlink_solver.cpp` (Kentaro Imajo, 2011)+ * that the offline asset pipeline runs, so runtime-generated levels clear the same bar as the+ * shipped packs. A solution is a set of grid edges where every cell has degree at most two, every+ * endpoint cell has degree exactly one, there are no cycles, and no two different colours are+ * joined — which leaves blank cells free to stay untouched. So a board whose pairs can be joined+ * without covering it counts as more than one solution.+ *+ * That is what makes [Verdict.UNIQUE] the property the generator wants: its carve already covers+ * every cell, so if that is the only solution then joining every pair necessarily fills the board,+ * which is what [com.vayunmathur.games.pipes.platform.PipesViewModel] demands for a win.+ *+ * Cells are walked along diagonals from the top-left, so the set of half-finished paths crossing the+ * diagonal — the "frontier" — stays about one row wide. Boards that differ before the frontier but+ * agree on it have the same number of completions, so memoising on the frontier collapses the search+ * from exponential in the cell count to exponential in the board width.+ */+internal object NumberlinkSolver {++    enum class Verdict {+        /** Exactly one solution, so a covering carve is the only way to join the pairs. */+        UNIQUE,++        /** At least two solutions, so at least one of them may leave cells empty. */+        MULTIPLE,++        /** No solution at all. Only reachable from a malformed board. */+        NONE,++        /** Gave up before deciding. Callers generating levels should treat this as a rejection. */+        UNDECIDED,+    }++    /**+     * Assumes the four-neighbour grid adjacency over [cells] that `computeAdjacency` produces;+     * boards with bridges or any other hand-written adjacency are out of scope.+     *+     * [stateBudget] caps the number of memoised frontier states, bounding both time and memory on a+     * board too wide for the frontier to stay small.+     */+    fun classify(+        cells: Set<CellPos>,+        endpoints: List<EndpointPair>,+        stateBudget: Int = DEFAULT_STATE_BUDGET,+    ): Verdict {+        if (cells.isEmpty() || endpoints.isEmpty()) return Verdict.NONE+        if (endpoints.any { pair -> pair.cells.size != 2 || pair.cells.any { it !in cells } }) {+            return Verdict.NONE+        }+        if (endpoints.flatMap { it.cells }.toSet().size != endpoints.size * 2) return Verdict.NONE++        val rows = cells.maxOf { it.row } + 1+        val cols = cells.maxOf { it.col } + 1+        val numbers = IntArray(rows * cols) { HOLE }+        for (cell in cells) numbers[cell.row * cols + cell.col] = BLANK+        endpoints.forEachIndexed { index, pair ->+            // Colours are numbered from one because zero means "blank".+            for (cell in pair.cells) numbers[cell.row * cols + cell.col] = index + 1+        }++        return Solver(rows, cols, numbers, stateBudget).classify()+    }++    const val DEFAULT_STATE_BUDGET = 2_000_000++    private const val HOLE = -1+    private const val BLANK = 0++    /** Mate value marking a cell that already has two incident edges and can take no more. */+    private const val INTERIOR = -1++    private class Solver(+        private val rows: Int,+        private val cols: Int,+        numbersByPosition: IntArray,+        private val stateBudget: Int,+    ) {+        private val size = rows * cols++        /** Diagonal walk order: [keys] maps a coordinate to its position in the order. */+        private val keys = IntArray(size)+        private val cellX = IntArray(size)+        private val cellY = IntArray(size)++        /** What is written in each cell, indexed by walk order: [HOLE], [BLANK] or a colour. */+        private val table = IntArray(size)++        /** Where the frontier for each step begins: the first cell not yet settled. */+        private val start = IntArray(size + 1)++        /**+         * Per cell: itself when untouched, the far end of its half-finished path when it has one+         * edge, or [INTERIOR] when it has two and is done.+         */+        private val mates = IntArray(size) { it }++        private val undoCell = IntArray(8 * size + 64)+        private val undoValue = IntArray(8 * size + 64)+        private var undoTop = 0++        /** Solution count per frontier state, saturated at two — nothing needs a finer answer. */+        private val memo = Array(size) { HashMap<String, Int>() }+        private var states = 0+        private var gaveUp = false++        init {+            var x = 0+            var y = 0+            var cellKey = 0+            while (true) {+                cellX[cellKey] = x+                cellY[cellKey] = y+                keys[y * cols + x] = cellKey+                cellKey+++                if (cellKey == size) break+                do {+                    x--+                    y+++                    if (x < 0) {+                        x = y+                        y = 0+                    }+                } while (x < 0 || x >= cols || y < 0 || y >= rows)+            }+            for (i in 0 until size) {+                val cx = cellX[i]+                val cy = cellY[i]+                // numbersByPosition is in row-major order; everything below indexes by walk order.+                table[i] = numbersByPosition[cy * cols + cx]+                start[i] = if (cy > 0) key(cx, cy - 1) else if (cx > 0) key(cx - 1, cy) else 0+            }+            start[size] = size+        }++        private fun key(x: Int, y: Int) = keys[y * cols + x]++        fun classify(): Verdict {+            for (k in 0 until size) if (table[k] == HOLE) mates[k] = INTERIOR+            val count = solve(0)+            return when {+                gaveUp -> Verdict.UNDECIDED+                count == 0 -> Verdict.NONE+                count == 1 -> Verdict.UNIQUE+                else -> Verdict.MULTIPLE+            }+        }++        /** Completions of the board from [cellKey] on, given the current frontier. */+        private fun solve(cellKey: Int): Int {+            if (cellKey > 0) {+                // Cells that just fell behind the frontier can never gain another edge, so their+                // degree is now final: a blank must be untouched or interior, a numbered cell must+                // have picked up its one line.+                for (settled in start[cellKey - 1] until start[cellKey]) {+                    when (table[settled]) {+                        HOLE -> continue+                        BLANK -> if (mates[settled] != INTERIOR && mates[settled] != settled) return 0+                        else -> if (mates[settled] == settled) return 0+                    }+                }+            }+            if (cellKey == size) return 1++            val frontier = frontierKey(cellKey)+            memo[cellKey][frontier]?.let { return it }+            if (states >= stateBudget) {+                gaveUp = true+                return 0+            }+            states+++            val count = connect(cellKey)+            memo[cellKey][frontier] = count+            return count+        }++        private fun frontierKey(cellKey: Int): String {+            val from = start[cellKey]+            val chars = CharArray(cellKey - from)+            for (i in chars.indices) chars[i] = (mates[from + i] + 1).toChar()+            return String(chars)+        }++        /** Sums the completions over the four ways this cell can join its left and upper neighbour. */+        private fun connect(cellKey: Int): Int {+            if (table[cellKey] == HOLE) return solve(cellKey + 1)++            val x = cellX[cellKey]+            val y = cellY[cellKey]+            var left = if (x > 0) key(x - 1, y) else -1+            var up = if (y > 0) key(x, y - 1) else -1+            if (left >= 0 && table[left] == HOLE) left = -1+            if (up >= 0 && table[up] == HOLE) up = -1++            val undoMark = undoTop+            var count = solve(cellKey + 1)+            if (up >= 0) {+                if (unite(cellKey, up)) count = saturate(count + solve(cellKey + 1))+                undo(undoMark)+            }+            if (left >= 0) {+                if (unite(cellKey, left)) {+                    count = saturate(count + solve(cellKey + 1))+                    if (up >= 0 && unite(cellKey, up)) {+                        count = saturate(count + solve(cellKey + 1))+                    }+                }+                undo(undoMark)+            }+            return count+        }++        /**+         * Joins the two cells with an edge, or returns false if that breaks a rule. Either way the+         * caller must [undo] back to its mark, because a rejected join still edited [mates].+         */+        private fun unite(cell1: Int, cell2: Int): Boolean {+            val end1 = mates[cell1]+            val end2 = mates[cell2]+            // A cell with two edges already cannot take a third.+            if (end1 == INTERIOR || end2 == INTERIOR) return false+            // Joining the two ends of one path would close a cycle.+            if (cell1 == end2 && cell2 == end1) return false++            setMate(cell1, INTERIOR)+            setMate(cell2, INTERIOR)+            setMate(end1, end2)+            setMate(end2, end1)++            // An endpoint cell carries exactly one line, so it must not have become interior.+            if (mates[cell1] == INTERIOR && table[cell1] > 0) return false+            if (mates[cell2] == INTERIOR && table[cell2] > 0) return false+            // The joined path must not run between two different colours.+            if (table[end1] > 0 && table[end2] > 0 && table[end1] != table[end2]) return false+            return true+        }++        private fun setMate(cell: Int, value: Int) {+            val previous = mates[cell]+            if (previous == value) return+            undoCell[undoTop] = cell+            undoValue[undoTop] = previous+            undoTop+++            mates[cell] = value+        }++        private fun undo(mark: Int) {+            while (undoTop > mark) {+                undoTop--+                mates[undoCell[undoTop]] = undoValue[undoTop]+            }+        }++        private fun saturate(count: Int) = if (count > 2) 2 else count+    }+}
games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.ktindex c911799474..4bbe971a62 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt@@ -104,9 +104,9 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),     }      /**-     * Generates the day's pack off the main thread — deliberately not in `LevelPack.init()`, which-     * runs synchronously in `onCreate`. Only runs when the player opens the daily; the pack-list-     * card derives its progress from the level IDs alone.+     * Picks the day's pack off the main thread — deliberately not in `LevelPack.init()`, which runs+     * synchronously in `onCreate`. Only runs when the player opens the daily; the pack-list card+     * derives its progress from the level IDs alone.      */     fun refreshDaily() {         viewModelScope.launch(Dispatchers.Default) {
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/DailyLevelsTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/DailyLevelsTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/DailyLevelsTest.ktindex d2e4ef269e..cfc6daf179 100644--- a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/DailyLevelsTest.kt+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/DailyLevelsTest.kt@@ -3,41 +3,41 @@ package com.vayunmathur.games.pipes.domain import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull+import kotlin.test.assertNull import kotlin.test.assertTrue  class DailyLevelsTest {      private val day = 20_300L+    private val pool = PackFixtures.allLevels()      @Test     fun sameDayGeneratesIdenticalPack() {-        val first = assertNotNull(DailyLevels.packFor(day))-        val second = assertNotNull(DailyLevels.packFor(day))-        assertEquals(first, second)+        assertEquals(DailyLevels.packFor(day, pool), DailyLevels.packFor(day, pool))     }      @Test     fun consecutiveDaysDiffer() {-        val today = assertNotNull(DailyLevels.packFor(day))-        val tomorrow = assertNotNull(DailyLevels.packFor(day + 1))+        val today = assertNotNull(DailyLevels.packFor(day, pool))+        val tomorrow = assertNotNull(DailyLevels.packFor(day + 1, pool))         assertTrue(today.levels.map { it.endpoints } != tomorrow.levels.map { it.endpoints })     }      @Test     fun packHasFiveLevelsOfRisingSize() {-        val pack = assertNotNull(DailyLevels.packFor(day))+        val pack = assertNotNull(DailyLevels.packFor(day, pool))         assertEquals(DailyLevels.LEVELS_PER_DAY, pack.levels.size)         var previousCells = 0         pack.levels.forEachIndexed { index, level ->             assertEquals(DailyLevels.levelId(day, index), level.id)-            assertTrue(level.cells.size > previousCells, "level $index is not bigger than the last")+            assertTrue(level.cells.size >= previousCells, "level $index is smaller than the last")             previousCells = level.cells.size         }     }      @Test     fun optimalMovesIsTheEndpointCount() {-        val pack = assertNotNull(DailyLevels.packFor(day))+        val pack = assertNotNull(DailyLevels.packFor(day, pool))         // cells.size here would make `bestScore <= optimalMoves` trivially true and hand out a         // star plus the optimal_win achievement for every daily win.         for (level in pack.levels) {@@ -47,7 +47,7 @@ class DailyLevelsTest {      @Test     fun endpointsAreDistinctCellsOnTheBoard() {-        val pack = assertNotNull(DailyLevels.packFor(day))+        val pack = assertNotNull(DailyLevels.packFor(day, pool))         for (level in pack.levels) {             val endpointCells = level.endpoints.flatMap { it.cells }             assertEquals(endpointCells.size, endpointCells.toSet().size, "${level.id} reuses a cell")@@ -57,18 +57,25 @@ class DailyLevelsTest {     }      @Test-    fun flowsAreLongEnoughToBeInteresting() {-        // The short-pair filter and the flow ceiling both exist to stop a board becoming a swarm-        // of tiny pairs. Note endpoints can still land next to each other on a U-shaped flow —-        // the shipped packs contain a handful of those too.-        val pack = assertNotNull(DailyLevels.packFor(day))-        for (level in pack.levels) {-            assertTrue(-                level.endpoints.size <= LevelGenerator.flowCeiling(level.cells),-                "${level.id} has ${level.endpoints.size} flows, over the ceiling"-            )-            val averageFlowLength = level.cells.size.toFloat() / level.endpoints.size-            assertTrue(averageFlowLength >= 4f, "${level.id} averages $averageFlowLength cells per flow")+    fun everyLevelForcesAFullBoard() {+        // PipesViewModel.checkWin only fires on a full board, so a level that can be "connected"+        // any other way is a dead end for the player. See issue #552.+        for (offset in 0 until 30) {+            val pack = assertNotNull(DailyLevels.packFor(day + offset, pool), "day ${day + offset}")+            for (level in pack.levels) {+                assertTrue(+                    NumberlinkSolver.classify(level.cells, level.endpoints)+                        != NumberlinkSolver.Verdict.MULTIPLE,+                    "${level.id} can be solved without filling the board",+                )+            }         }     }++    @Test+    fun noPackBeforeTheShippedLevelsAreLoaded() {+        // LevelPack.PACKS is empty until MainActivity calls LevelPack.init, and a day with four+        // levels in it would break the progress bookkeeping in PipesViewModel.+        assertNull(DailyLevels.packFor(day, pool.take(DailyLevels.LEVELS_PER_DAY - 1)))+    } }
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGeneratorTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGeneratorTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGeneratorTest.ktnew file mode 100644index 0000000000..eba0d0e483--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGeneratorTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.games.pipes.domain++import com.vayunmathur.games.pipes.data.computeAdjacency+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class LevelGeneratorTest {++    @Test+    fun everyGeneratedLevelForcesAFullBoard() {+        // The whole point of the uniqueness gate: an emitted level must not be solvable while+        // leaving cells empty, or PipesViewModel.checkWin will never fire. See issue #552.+        for (size in listOf(5, 6)) {+            val cells = LevelGenerator.rectangularCells(size, size)+            val adjacency = computeAdjacency(cells)+            var emitted = 0+            for (seed in 0 until 8) {+                val level = LevelGenerator.generateLevel(+                    cells = cells,+                    adjacency = adjacency,+                    maxFlows = LevelGenerator.flowCeiling(cells),+                    seed = 4_000L + seed * 97L,+                    id = "test_${size}_$seed",+                    earlyStopProb = 0.15f,+                ) ?: continue+                emitted+++                assertEquals(+                    NumberlinkSolver.Verdict.UNIQUE,+                    NumberlinkSolver.classify(level.cells, level.endpoints),+                    level.id,+                )+                assertEquals(level.endpoints.size, level.optimalMoves, level.id)+            }+            assertTrue(emitted > 0, "generated nothing at ${size}x$size")+        }+    }++    @Test+    fun generatedEndpointsAreDistinctCellsOnTheBoard() {+        val cells = LevelGenerator.rectangularCells(6, 6)+        val level = assertNotNull(+            LevelGenerator.generateLevel(+                cells = cells,+                adjacency = computeAdjacency(cells),+                maxFlows = LevelGenerator.flowCeiling(cells),+                seed = 4_000L,+                id = "test",+                earlyStopProb = 0.15f,+            )+        )+        val endpointCells = level.endpoints.flatMap { it.cells }+        assertEquals(endpointCells.size, endpointCells.toSet().size, "reuses a cell")+        assertTrue(endpointCells.all { it in level.cells }, "off-board endpoint")+        assertTrue(level.endpoints.all { it.cells.size == 2 }, "malformed pair")+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/NumberlinkSolverTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/NumberlinkSolverTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/NumberlinkSolverTest.ktnew file mode 100644index 0000000000..f4aeb70d35--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/NumberlinkSolverTest.kt@@ -0,0 +1,180 @@+package com.vayunmathur.games.pipes.domain++import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.EndpointPair+import kotlin.test.Test+import kotlin.test.assertEquals++class NumberlinkSolverTest {++    private fun rectangle(rows: Int, cols: Int) =+        buildSet { for (r in 0 until rows) for (c in 0 until cols) add(CellPos(r, c)) }++    private fun pairs(vararg ends: Pair<CellPos, CellPos>) =+        ends.mapIndexed { i, (a, b) -> EndpointPair(i, listOf(a, b)) }++    private fun verdict(rows: Int, cols: Int, vararg ends: Pair<CellPos, CellPos>) =+        NumberlinkSolver.classify(rectangle(rows, cols), pairs(*ends))++    @Test+    fun oneFlowDownEachColumnOfATwoByTwoIsUnique() {+        // A-B over A-B: each colour can only go straight down its own column.+        assertEquals(+            NumberlinkSolver.Verdict.UNIQUE,+            verdict(+                2, 2,+                CellPos(0, 0) to CellPos(1, 0),+                CellPos(0, 1) to CellPos(1, 1),+            ),+        )+    }++    @Test+    fun aSingleFlowAcrossAnOpenBoardHasManySolutions() {+        // Opposite corners of a 4x4 with nothing else on the board: every staircase works.+        assertEquals(+            NumberlinkSolver.Verdict.MULTIPLE,+            verdict(4, 4, CellPos(0, 0) to CellPos(3, 3)),+        )+    }++    @Test+    fun aFlowThatCannotReachItsPartnerIsUnsolvable() {+        // The row-1 pair walls off row 2 from row 0, so the vertical pair cannot get through.+        assertEquals(+            NumberlinkSolver.Verdict.NONE,+            verdict(+                3, 2,+                CellPos(1, 0) to CellPos(1, 1),+                CellPos(0, 0) to CellPos(2, 0),+            ),+        )+    }++    @Test+    fun anAdjacentPairLeavingTheBoardEmptyCountsAsAnExtraSolution() {+        // Bug #552 in miniature: the second pair's endpoints touch, so the board can be+        // "connected" with a two-cell line that strands (2,0) and (2,1). The intended full-board+        // solution exists too, which is what makes such a level look unwinnable.+        assertEquals(+            NumberlinkSolver.Verdict.MULTIPLE,+            verdict(+                3, 2,+                CellPos(0, 0) to CellPos(0, 1),+                CellPos(1, 0) to CellPos(1, 1),+            ),+        )+    }++    @Test+    fun budgetTooSmallToProveAnythingIsUndecided() {+        assertEquals(+            NumberlinkSolver.Verdict.UNDECIDED,+            NumberlinkSolver.classify(+                rectangle(6, 6),+                pairs(CellPos(0, 0) to CellPos(5, 5)),+                stateBudget = 0,+            ),+        )+    }++    /**+     * The solver walks cells diagonally and memoises on the frontier, which is easy to get subtly+     * wrong in a way that still looks plausible on square boards. These count the solutions by+     * enumerating every edge subset instead, which is only affordable on a handful of cells.+     */+    @Test+    fun agreesWithExhaustiveEnumerationOnSmallBoards() {+        val boards = listOf(+            // The worked example in the header of scripts/pipes/numberlink_solver.cpp.+            Triple(+                3 to 4,+                pairs(+                    CellPos(0, 0) to CellPos(1, 2),+                    CellPos(0, 3) to CellPos(2, 1),+                    CellPos(1, 1) to CellPos(2, 0),+                ),+                NumberlinkSolver.Verdict.UNIQUE,+            ),+            Triple(2 to 2, pairs(CellPos(0, 0) to CellPos(1, 1)), NumberlinkSolver.Verdict.MULTIPLE),+            Triple(2 to 3, pairs(CellPos(0, 0) to CellPos(1, 2)), NumberlinkSolver.Verdict.MULTIPLE),+            Triple(+                3 to 3,+                pairs(+                    CellPos(0, 0) to CellPos(2, 0),+                    CellPos(0, 2) to CellPos(2, 2),+                ),+                NumberlinkSolver.Verdict.MULTIPLE,+            ),+            Triple(1 to 4, pairs(CellPos(0, 0) to CellPos(0, 3)), NumberlinkSolver.Verdict.UNIQUE),+        )+        for ((dims, endpoints, expected) in boards) {+            val (rows, cols) = dims+            val label = "${rows}x$cols"+            val exhaustive = countByEnumeration(rows, cols, endpoints)+            assertEquals(+                expected,+                verdictOf(exhaustive),+                "$label: exhaustive count was $exhaustive",+            )+            assertEquals(+                expected,+                NumberlinkSolver.classify(rectangle(rows, cols), endpoints),+                label,+            )+        }+    }++    private fun verdictOf(count: Int) = when {+        count == 0 -> NumberlinkSolver.Verdict.NONE+        count == 1 -> NumberlinkSolver.Verdict.UNIQUE+        else -> NumberlinkSolver.Verdict.MULTIPLE+    }++    /** Counts legal edge subsets: degree <= 2, endpoints degree 1, blanks 0 or 2, no stray loops. */+    private fun countByEnumeration(rows: Int, cols: Int, endpoints: List<EndpointPair>): Int {+        val colorOf = HashMap<CellPos, Int>()+        endpoints.forEachIndexed { i, ep -> ep.cells.forEach { colorOf[it] = i } }+        val edges = mutableListOf<Pair<CellPos, CellPos>>()+        for (r in 0 until rows) for (c in 0 until cols) {+            if (c + 1 < cols) edges += CellPos(r, c) to CellPos(r, c + 1)+            if (r + 1 < rows) edges += CellPos(r, c) to CellPos(r + 1, c)+        }+        var count = 0+        for (mask in 0 until (1 shl edges.size)) {+            val adjacent = HashMap<CellPos, MutableList<CellPos>>()+            for (i in edges.indices) {+                if (mask shr i and 1 == 0) continue+                val (a, b) = edges[i]+                adjacent.getOrPut(a) { mutableListOf() } += b+                adjacent.getOrPut(b) { mutableListOf() } += a+            }+            var legal = true+            for (r in 0 until rows) for (c in 0 until cols) {+                val cell = CellPos(r, c)+                val degree = adjacent[cell]?.size ?: 0+                val isEndpoint = cell in colorOf+                if (degree > 2 || (isEndpoint && degree != 1) || (!isEndpoint && degree == 1)) {+                    legal = false+                }+            }+            if (!legal) continue+            val walked = HashSet<CellPos>()+            for (ep in endpoints) {+                var previous: CellPos? = null+                var current = ep.cells[0]+                if (!walked.add(current)) { legal = false; break }+                while (true) {+                    val next = adjacent[current]?.firstOrNull { it != previous } ?: break+                    previous = current+                    current = next+                    if (!walked.add(current)) { legal = false; break }+                }+                if (!legal || current != ep.cells[1]) { legal = false; break }+            }+            // Anything used but not walked is a loop of blanks, which is not a solution.+            if (legal && walked.size == adjacent.keys.size) count+++        }+        return count+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/PackFixtures.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/PackFixtures.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/PackFixtures.ktnew file mode 100644index 0000000000..8e2e46384d--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/PackFixtures.kt@@ -0,0 +1,61 @@+package com.vayunmathur.games.pipes.domain++import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.EndpointPair+import com.vayunmathur.games.pipes.data.LevelData+import com.vayunmathur.games.pipes.data.computeAdjacency+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.int+import kotlinx.serialization.json.intOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import java.io.File++/**+ * Reads the shipped packs straight off disk. `LevelPack.init` needs a Context to reach the asset+ * manager, which a JVM unit test has no way to provide.+ */+object PackFixtures {++    private val packsDir = File("src/main/assets/packs")++    fun packNames(): List<String> = packsDir.listFiles()!!.map { it.name }.sorted()++    fun levels(packName: String): List<LevelData> {+        val obj = Json.parseToJsonElement(packsDir.resolve(packName).readText()).jsonObject+        return obj["levels"]!!.jsonArray.map { levelFrom(it.jsonObject) }+    }++    fun allLevels(): List<LevelData> = packNames().flatMap { levels(it) }++    private fun levelFrom(json: kotlinx.serialization.json.JsonObject): LevelData {+        val rows = json["rows"]!!.jsonPrimitive.int+        val cols = json["cols"]!!.jsonPrimitive.int+        val cells = json["cells"]?.jsonArray?.map { cellFrom(it) }?.toSet()+            ?: buildSet { for (r in 0 until rows) for (c in 0 until cols) add(CellPos(r, c)) }+        val endpoints = json["endpoints"]!!.jsonArray.mapIndexed { index, element ->+            val ep = element.jsonObject+            EndpointPair(+                ep["color"]?.jsonPrimitive?.intOrNull ?: index,+                ep["cells"]!!.jsonArray.map { cellFrom(it) },+            )+        }+        return LevelData(+            id = json["id"]!!.jsonPrimitive.content,+            rows = rows,+            cols = cols,+            cells = cells,+            adjacency = computeAdjacency(cells),+            renderPositions = null,+            endpoints = endpoints,+            bridges = emptySet(),+            optimalMoves = json["optimalMoves"]!!.jsonPrimitive.int,+        )+    }++    private fun cellFrom(element: kotlinx.serialization.json.JsonElement): CellPos {+        val pair = element.jsonArray+        return CellPos(pair[0].jsonPrimitive.int, pair[1].jsonPrimitive.int)+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/ShippedPacksTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/ShippedPacksTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/ShippedPacksTest.ktnew file mode 100644index 0000000000..bf1f3a48a5--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/ShippedPacksTest.kt@@ -0,0 +1,51 @@+package com.vayunmathur.games.pipes.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class ShippedPacksTest {++    /**+     * A win needs every cell owned (`PipesViewModel.checkWin`), so a level whose pairs can also be+     * joined while leaving a cell empty is a dead end: the player connects everything and nothing+     * happens. That is issue #552, and it is a property of the level rather than of the code, so it+     * has to be asserted against the shipped assets.+     *+     * The assertion is "never provably more than one solution" rather than "always exactly one"+     * because the widest boards can exhaust the solver's state budget and come back+     * [NumberlinkSolver.Verdict.UNDECIDED]. Undecided is not a defect; MULTIPLE and NONE are.+     */+    @Test+    fun noShippedLevelCanBeSolvedWithoutFillingTheBoard() {+        val broken = mutableListOf<String>()+        for (name in PackFixtures.packNames()) {+            for (level in PackFixtures.levels(name)) {+                val verdict = NumberlinkSolver.classify(level.cells, level.endpoints)+                if (verdict == NumberlinkSolver.Verdict.MULTIPLE || verdict == NumberlinkSolver.Verdict.NONE) {+                    broken += "$name/${level.id}=$verdict"+                }+            }+        }+        assertEquals(emptyList(), broken, "shipped levels that do not force a full board")+    }++    /** The narrower boards are well inside the solver's budget, so they must resolve outright. */+    @Test+    fun narrowPacksAreProvablyUnique() {+        for (name in listOf("5x5.json", "6x6.json", "7x7.json", "8x8.json", "9x9.json")) {+            for (level in PackFixtures.levels(name)) {+                assertEquals(+                    NumberlinkSolver.Verdict.UNIQUE,+                    NumberlinkSolver.classify(level.cells, level.endpoints),+                    "$name/${level.id}",+                )+            }+        }+    }++    @Test+    fun thePoolIsBigEnoughToSeedADay() {+        assertTrue(PackFixtures.allLevels().size >= DailyLevels.LEVELS_PER_DAY)+    }+}