Modern Apps git

← Modern-Apps.git

pipes: make generated levels resist greedy edge solving

Commit
04da0f1f32369e543ba0a51cadbf237f969030ad
Author
Vayun Mathur <[email protected]>
When
2026-12-06 04:28 UTC (9 hours ago)
Parents
7f1e1b6
Owner feedback was that almost every generated level fell to finding
an edge pair and connecting pairs until the board filled, with no
planning ahead. Uniqueness alone does not prevent that: the greedy
simulator solved about 94 percent of baseline generated cells.

Add GreedySolver, a deterministic no-backtracking simulator that
extends endpoints (edge endpoints first) only along forced or
uncontested paths and through same-flow corridors, and scores a
level by the fraction of cells it fills before stalling. Its solved
flag re-validates the result as a real full-cover solution.

Generation now shapes and filters against that strategy. Harder
tiers steer carves away from edge cells, away from their own start
first, across the board and alongside rival flows; finished levels
are rejected above per-tier greedy thresholds (0.95 CASUAL, 0.70
STANDARD, 0.55 EXPERT) or below interior-endpoint and decoy-
adjacency floors. Metrics expose greedy fraction, interior
endpoints, decoys, cross-flow interfaces and endpoint span.
Attempts are bounded per tier (500/1000/1200) and documented as an
offline budget. Attempt seeding now strides by seed so neighbouring
seeds never replay each other's attempts under rejection sampling.

Measured at 6x6 (12 seeds per tier, greedy filled fraction):
CASUAL 0.868, STANDARD 0.597, EXPERT 0.398, with 12/12 levels
emitted per tier and every level solver-verified UNIQUE.

Verified: ./gradlew :games:pipes:lint :games:pipes:lintVitalRelease
:games:pipes:testDevUnitTest (152 tests, all passing) and
:games:pipes:ktlintCheck, all with --max-workers=128.

Diff

games/pipes/AGENTS.md
diff --git a/games/pipes/AGENTS.md b/games/pipes/AGENTS.mdindex 58199b282e..8d29de9f3a 100644--- a/games/pipes/AGENTS.md+++ b/games/pipes/AGENTS.md@@ -24,7 +24,8 @@ _Install: ./install games/pipes (dev by default)._ ### data/ + domain/ — levels + generation - com/vayunmathur/games/pipes/data/PipeModels.kt - com/vayunmathur/games/pipes/data/CompletedLevelsRepository.kt-- com/vayunmathur/games/pipes/domain/LevelGenerator.kt — carve-cover generator with `PipesDifficulty` tiers (CASUAL/STANDARD/EXPERT shaping flow length, turn rate and flow count), seeded split points, solver-verified UNIQUE boards, and `PipesLevelMetrics`/`generateSeeded` for deterministic generation+- com/vayunmathur/games/pipes/domain/LevelGenerator.kt — carve-cover generator with `PipesDifficulty` tiers (CASUAL/STANDARD/EXPERT shaping flow length, turn rate, flow count and anti-greedy pressure), seeded split points, solver-verified UNIQUE boards, and `PipesLevelMetrics`/`generateSeeded` for deterministic generation. Harder tiers steer carves off edges, away from their start and alongside rival flows, then reject levels whose greedy fraction, interior-endpoint fraction or decoy adjacencies miss the tier gates. Generation is bounded per tier (500/1000/1200 attempts) and is an offline asset tool, never a runtime path+- com/vayunmathur/games/pipes/domain/GreedySolver.kt — deterministic no-backtracking greedy simulator (edge endpoints first, forced/uncontested extensions, same-flow corridors); `GreedyResult.filledFraction`/`solved` score how much of a level the greedy edge strategy fills - com/vayunmathur/games/pipes/domain/NumberlinkSolver.kt - com/vayunmathur/games/pipes/domain/DailyLevels.kt ### platform/ — ViewModel + achievements
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/GreedySolver.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/GreedySolver.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/GreedySolver.ktnew file mode 100644index 0000000000..21488f646c--- /dev/null+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/GreedySolver.kt@@ -0,0 +1,221 @@+package com.vayunmathur.games.pipes.domain++import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.LevelData++/**+ * Result of a no-backtracking greedy pass over a level.+ *+ * [filledFraction] is the share of board cells greedy assigned before it stalled (or finished).+ * A level that greedy [solved] has fraction 1.0 and a valid full-cover connection of every pair;+ * a planning-heavy level stalls far below 1.0 because every remaining frontier faces a choice.+ */+data class GreedyResult(+    val filledCells: Int,+    val totalCells: Int,+    val completedFlows: Int,+    val flowCount: Int,+    val solved: Boolean,+    val assignment: Map<CellPos, Int>,+) {+    val filledFraction: Double+        get() = if (totalCells == 0) 0.0 else filledCells.toDouble() / totalCells+}++/**+ * Deterministic simulator of the greedy player the owner described: keep extending endpoints —+ * edge endpoints first — along forced or uncontested paths and through obvious corridors, and+ * never guess, branch or backtrack.+ *+ * The simulator sees only the level (cells, adjacency, endpoints), never a solution, so a wrong+ * uncontested grab can still happen; [GreedyResult.solved] therefore re-validates the final+ * assignment as a real full-cover solution instead of trusting that greedy filled the board.+ *+ * A move is made only when one of these holds for a frontier (an endpoint with no line yet, or+ * the open end of a partly drawn flow, which still needs one more line):+ *  - forced: the frontier has exactly one candidate cell left;+ *  - uncontested: exactly one of its candidate cells is claimed by no other frontier, so a+ *    greedy player grabs that cell and ignores the contested ones;+ *  - corridor: an empty cell has exactly two still-open neighbours and both belong to the same+ *    flow, so the flow must pass straight through it.+ * Candidates are empty cells, the frontier's partner endpoint, or the other open end of the+ * same flow. Frontier order is deterministic: edge cells first, then colour, then position.+ */+object GreedySolver {+    fun evaluate(level: LevelData): GreedyResult =+        evaluate(level.cells, level.adjacency, level.endpoints, level.rows, level.cols)++    fun evaluate(+        cells: Set<CellPos>,+        adjacency: Map<CellPos, List<CellPos>>,+        endpoints: List<com.vayunmathur.games.pipes.data.EndpointPair>,+        rows: Int = (cells.maxOfOrNull { it.row } ?: -1) + 1,+        cols: Int = (cells.maxOfOrNull { it.col } ?: -1) + 1,+    ): GreedyResult {+        if (cells.isEmpty() || endpoints.isEmpty() || endpoints.any { it.cells.size != 2 }) {+            return GreedyResult(0, cells.size, 0, endpoints.size, false, emptyMap())+        }+        val colorOf = HashMap<CellPos, Int>()+        val partnerOf = HashMap<CellPos, CellPos>()+        endpoints.forEachIndexed { index, pair ->+            colorOf[pair.cells[0]] = index+            colorOf[pair.cells[1]] = index+            partnerOf[pair.cells[0]] = pair.cells[1]+            partnerOf[pair.cells[1]] = pair.cells[0]+        }+        val assignment = HashMap<CellPos, Int>(colorOf)+        val degree = HashMap<CellPos, Int>()+        cells.forEach { degree[it] = 0 }+        val edges = mutableSetOf<Set<CellPos>>()++        fun isEndpoint(cell: CellPos) = cell in partnerOf++        fun required(cell: CellPos) = if (isEndpoint(cell)) 1 else 2++        fun isOpen(cell: CellPos) = cell in assignment && (degree[cell] ?: 0) < required(cell)++        fun isEdge(cell: CellPos): Boolean =+            cell.row == 0 ||+                cell.col == 0 ||+                cell.row == rows - 1 ||+                cell.col == cols - 1 ||+                (adjacency[cell] ?: emptyList()).size < 4++        fun connect(+            a: CellPos,+            b: CellPos,+        ) {+            if (!edges.add(setOf(a, b))) return+            degree[a] = (degree[a] ?: 0) + 1+            degree[b] = (degree[b] ?: 0) + 1+        }++        fun frontiers(): List<CellPos> =+            assignment.keys+                .filter { isOpen(it) }+                .sortedWith(compareBy({ if (isEdge(it)) 0 else 1 }, { assignment[it] ?: 0 }, { it.row }, { it.col }))++        fun candidates(frontier: CellPos): List<CellPos> {+            val color = assignment.getValue(frontier)+            return (adjacency[frontier] ?: emptyList())+                .filter { next ->+                    when {+                        next == frontier -> false+                        setOf(frontier, next) in edges -> false+                        next !in assignment -> true+                        // Partner endpoint, or the same flow's other open end meeting in the middle.+                        assignment[next] == color && isOpen(next) -> true+                        else -> false+                    }+                }.sortedWith(compareBy({ it.row }, { it.col }))+        }++        fun contested(+            cell: CellPos,+            excluding: CellPos,+            openFrontiers: List<CellPos>,+        ): Boolean = openFrontiers.any { other -> other != excluding && cell in (adjacency[other] ?: emptyList()) }++        fun corridorMove(): Boolean {+            val open = frontiers()+            val openSet = open.toSet()+            val emptyCells = cells.filter { it !in assignment }.sortedWith(compareBy({ it.row }, { it.col }))+            for (cell in emptyCells) {+                val openNeighbours =+                    (adjacency[cell] ?: emptyList()).filter { it in openSet }+                val stillPossible =+                    (adjacency[cell] ?: emptyList()).filter { next ->+                        next !in assignment || next in openSet+                    }+                if (stillPossible.size == 2 && openNeighbours.size == 2) {+                    val colors = openNeighbours.map { assignment.getValue(it) }.distinct()+                    if (colors.size == 1) {+                        assignment[cell] = colors.single()+                        connect(cell, openNeighbours[0])+                        connect(cell, openNeighbours[1])+                        return true+                    }+                }+            }+            return false+        }++        fun frontierMove(): Boolean {+            val open = frontiers()+            for (frontier in open) {+                val options = candidates(frontier)+                if (options.isEmpty()) continue+                val color = assignment.getValue(frontier)+                val closing = options.filter { it in assignment }+                if (closing.isNotEmpty()) {+                    val target = closing.first()+                    connect(frontier, target)+                    return true+                }+                val uncontested = options.filter { !contested(it, frontier, open) }+                val chosen =+                    when {+                        options.size == 1 -> options.single()+                        uncontested.size == 1 -> uncontested.single()+                        else -> continue+                    }+                assignment[chosen] = color+                connect(frontier, chosen)+                return true+            }+            return false+        }++        var guard = cells.size * 4 + 16+        while (guard-- > 0) {+            if (assignment.size == cells.size && frontiers().isEmpty()) break+            if (corridorMove()) continue+            if (frontierMove()) continue+            break+        }++        val completed =+            endpoints.indices.count { index ->+                flowConnects(index, endpoints[index].cells[0], endpoints[index].cells[1], assignment, edges)+            }+        val solved =+            assignment.size == cells.size &&+                completed == endpoints.size &&+                cells.all { cell -> (degree[cell] ?: 0) == required(cell) }+        return GreedyResult(+            filledCells = assignment.size,+            totalCells = cells.size,+            completedFlows = completed,+            flowCount = endpoints.size,+            solved = solved,+            assignment = assignment.toMap(),+        )+    }++    /** Walks colour [color]'s drawn edges from [start]; true when the walk ends at [goal]. */+    private fun flowConnects(+        color: Int,+        start: CellPos,+        goal: CellPos,+        assignment: Map<CellPos, Int>,+        edges: Set<Set<CellPos>>,+    ): Boolean {+        val neighbours = HashMap<CellPos, MutableList<CellPos>>()+        for (edge in edges) {+            val (a, b) = edge.toList().let { it[0] to it[1] }+            if (assignment[a] != color || assignment[b] != color) continue+            neighbours.getOrPut(a) { mutableListOf() } += b+            neighbours.getOrPut(b) { mutableListOf() } += a+        }+        var previous: CellPos? = null+        var current = start+        val seen = mutableSetOf<CellPos>()+        while (true) {+            if (!seen.add(current)) return false+            if (current == goal) return seen.size == assignment.count { it.value == color }+            val next = neighbours[current]?.firstOrNull { it != previous } ?: return false+            previous = current+            current = next+        }+    }+}
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 4b5bf9f8bd..94c9553de9 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,15 +8,66 @@ import java.util.Locale import kotlin.math.roundToInt import kotlin.random.Random -/** Difficulty tiers for generated boards: structure, not just size, separates them. */+/**+ * Difficulty tiers for generated boards: structure, not just size, separates them.+ *+ * Anti-greedy pressure rises with the tier: [maxGreedyFraction] caps how much of the board the+ * no-backtracking [GreedySolver] may fill, [minInteriorEndpointFraction] and+ * [minDecoyAdjacencies] keep endpoints off the edge and next to rival endpoints, and the carve+ * weights ([edgeAvoidance], [awayFromStartWeight], [interfaceWeight]) steer paths away from+ * edge-hugging forced corridors, away from their own start first, and along rival flows so+ * corridors are contested. CASUAL keeps the friendly carve and only rejects near-total+ * greedy solves. Attempts are bounded per tier ([maxGenerationAttempts]); this generator is an+ * offline asset tool, never a runtime path — on-device generation would need a far smaller cap.+ */ enum class PipesDifficulty(     val earlyStopProb: Float,     val minTurnRate: Double,     val flowScale: Double,+    val maxGreedyFraction: Double,+    val minInteriorEndpointFraction: Double,+    val minDecoyAdjacencies: Int,+    val maxGenerationAttempts: Int,+    val edgeAvoidance: Double,+    val awayFromStartWeight: Double,+    val interfaceWeight: Double, ) {-    CASUAL(earlyStopProb = 0.20f, minTurnRate = 0.08, flowScale = 1.0),-    STANDARD(earlyStopProb = 0.25f, minTurnRate = 0.15, flowScale = 1.0),-    EXPERT(earlyStopProb = 0.12f, minTurnRate = 0.22, flowScale = 0.8),+    CASUAL(+        earlyStopProb = 0.20f,+        minTurnRate = 0.08,+        flowScale = 1.0,+        maxGreedyFraction = 0.95,+        minInteriorEndpointFraction = 0.0,+        minDecoyAdjacencies = 0,+        maxGenerationAttempts = 500,+        edgeAvoidance = 0.0,+        awayFromStartWeight = 0.0,+        interfaceWeight = 0.0,+    ),+    STANDARD(+        earlyStopProb = 0.25f,+        minTurnRate = 0.15,+        flowScale = 1.0,+        maxGreedyFraction = 0.70,+        minInteriorEndpointFraction = 0.35,+        minDecoyAdjacencies = 1,+        maxGenerationAttempts = 1000,+        edgeAvoidance = 1.2,+        awayFromStartWeight = 0.6,+        interfaceWeight = 0.8,+    ),+    EXPERT(+        earlyStopProb = 0.12f,+        minTurnRate = 0.22,+        flowScale = 0.8,+        maxGreedyFraction = 0.55,+        minInteriorEndpointFraction = 0.50,+        minDecoyAdjacencies = 1,+        maxGenerationAttempts = 1200,+        edgeAvoidance = 2.0,+        awayFromStartWeight = 0.9,+        interfaceWeight = 1.1,+    ), }  /** Structural facts about a generated board's (unique) solution. */@@ -27,6 +78,15 @@ data class PipesLevelMetrics(     val turnRate: Double,     val minFlowLength: Int,     val maxFlowLength: Int,+    /** Share of cells the greedy simulator fills; lower means more planning is required. */+    val greedyFraction: Double = 1.0,+    val interiorEndpointFraction: Double = 0.0,+    /** Endpoint cells sitting next to a different flow's endpoint (tempting wrong joins). */+    val decoyAdjacencies: Int = 0,+    /** Solution edges shared between two different flows; higher means more interleaving. */+    val crossFlowInterfaces: Int = 0,+    /** Largest Manhattan distance between a flow's two endpoints. */+    val maxEndpointSpan: Int = 0, )  /** A generated level together with the metrics of the carve that solves it. */@@ -44,6 +104,11 @@ data class GeneratedPipesLevel(  * 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.+ *+ * Generation is bounded: at most [PipesDifficulty.maxGenerationAttempts] carves per call+ * (500 CASUAL / 1000 STANDARD / 1200 EXPERT), each paying for at most a handful of solver proofs+ * while splitting. That is an offline budget — seconds per keeper on large boards — and is why+ * nothing generates levels on a phone at runtime.  */ object LevelGenerator {     fun rectangularCells(@@ -126,16 +191,26 @@ object LevelGenerator {     ): GeneratedPipesLevel? {         val rows = cells.maxOf { it.row } + 1         val cols = cells.maxOf { it.col } + 1+        // Anti-greedy gates only apply where the real solver does: square boards. Custom+        // topologies (hex, portals, wrap) are hand-authored variants and stay exempt.+        val squareAdjacency = computeAdjacency(cells)+        val isSquare =+            adjacency.all { (cell, neighbors) -> neighbors.toSet() == squareAdjacency[cell]?.toSet() } -        for (attempt in 0 until 50) {-            val random = Random(seed + attempt)-            val carved = carveCover(cells, adjacency, random, earlyStopProb) ?: continue+        for (attempt in 0 until difficulty.maxGenerationAttempts) {+            // Stride attempts far apart so seed N's later attempts never replay seed N+1's+            // first attempt (rejection sampling reaches deep into the attempt range).+            val random = Random(seed * 1_000_003L + attempt)+            val carved = carveCover(cells, adjacency, random, earlyStopProb, difficulty) ?: continue             // Difficulty shaping: winding paths (turns) are what make a board fun to trace;             // near-straight carves are rejected before paying for the uniqueness proof.             if (turnRate(carved) < difficulty.minTurnRate) continue             // A carve already breaking the short-pair floor cannot be repaired by splitting             // (splitting only ever makes paths shorter); regenerate instead.             if (shortPairViolation(carved)) continue+            // Cheap anti-greedy gate before the uniqueness proof: edge endpoints are what the+            // greedy edge strategy feeds on, so a mostly-edge carve can never pass below.+            if (isSquare && interiorEndpointFraction(carved, cells) < difficulty.minInteriorEndpointFraction) continue             val paths = splitUntilUniquelySolvable(carved, cells, maxFlows, adjacency, random) ?: continue             val endpoints =                 paths.mapIndexed { index, path ->@@ -155,11 +230,70 @@ object LevelGenerator {                     portals = portals,                     grid = grid,                 )-            return GeneratedPipesLevel(level, metricsOf(paths))+            val metrics = metricsOf(paths, level)+            if (isSquare) {+                // Acceptance: the finished level must resist the greedy simulator and keep+                // its interior / decoy structure after splitting, not just in the raw carve.+                if (metrics.greedyFraction > difficulty.maxGreedyFraction) continue+                if (metrics.interiorEndpointFraction < difficulty.minInteriorEndpointFraction) continue+                if (metrics.decoyAdjacencies < difficulty.minDecoyAdjacencies) continue+            }+            return GeneratedPipesLevel(level, metrics)         }         return null     } +    private fun isEdgeCell(+        cell: CellPos,+        cells: Set<CellPos>,+        adjacency: Map<CellPos, List<CellPos>>,+    ): Boolean {+        val maxDegree = adjacency.values.maxOfOrNull { it.size } ?: 4+        return (adjacency[cell] ?: emptyList()).size < maxDegree+    }++    private fun interiorEndpointFraction(+        paths: List<List<CellPos>>,+        cells: Set<CellPos>,+    ): Double {+        val adjacency = computeAdjacency(cells)+        val ends = paths.flatMap { listOf(it.first(), it.last()) }+        if (ends.isEmpty()) return 0.0+        return ends.count { !isEdgeCell(it, cells, adjacency) }.toDouble() / ends.size+    }++    private fun decoyAdjacencies(+        paths: List<List<CellPos>>,+        adjacency: Map<CellPos, List<CellPos>>,+    ): Int {+        val owner = HashMap<CellPos, Int>()+        paths.forEachIndexed { index, path -> listOf(path.first(), path.last()).forEach { owner[it] = index } }+        var count = 0+        for ((cell, flow) in owner) {+            for (next in adjacency[cell] ?: emptyList()) {+                val other = owner[next]+                if (other != null && other != flow && cell.row * 1000 + cell.col < next.row * 1000 + next.col) count+++            }+        }+        return count+    }++    private fun crossFlowInterfaces(+        paths: List<List<CellPos>>,+        adjacency: Map<CellPos, List<CellPos>>,+    ): Int {+        val owner = HashMap<CellPos, Int>()+        paths.forEachIndexed { index, path -> path.forEach { owner[it] = index } }+        var count = 0+        for ((cell, flow) in owner) {+            for (next in adjacency[cell] ?: emptyList()) {+                val other = owner[next]+                if (other != null && other != flow && cell.row * 1000 + cell.col < next.row * 1000 + next.col) count+++            }+        }+        return count+    }+     /** Turns (direction changes) per step over all paths; straight runs score near zero. */     private fun turnRate(paths: List<List<CellPos>>): Double {         var turns = 0@@ -177,7 +311,10 @@ object LevelGenerator {         return if (steps == 0) 0.0 else turns.toDouble() / steps     } -    private fun metricsOf(paths: List<List<CellPos>>): PipesLevelMetrics {+    private fun metricsOf(+        paths: List<List<CellPos>>,+        level: LevelData? = null,+    ): PipesLevelMetrics {         val lengths = paths.map { it.size }         var turns = 0         for (path in paths) {@@ -190,6 +327,8 @@ object LevelGenerator {             }         }         val steps = lengths.sumOf { (it - 1).coerceAtLeast(0) }+        val adjacency = level?.adjacency ?: computeAdjacency(paths.flatten().toSet())+        val cells = level?.cells ?: paths.flatten().toSet()         return PipesLevelMetrics(             flowCount = paths.size,             flowLengths = lengths,@@ -197,6 +336,15 @@ object LevelGenerator {             turnRate = if (steps == 0) 0.0 else turns.toDouble() / steps,             minFlowLength = lengths.minOrNull() ?: 0,             maxFlowLength = lengths.maxOrNull() ?: 0,+            greedyFraction = if (level != null) GreedySolver.evaluate(level).filledFraction else 1.0,+            interiorEndpointFraction = interiorEndpointFraction(paths, cells),+            decoyAdjacencies = decoyAdjacencies(paths, adjacency),+            crossFlowInterfaces = crossFlowInterfaces(paths, adjacency),+            maxEndpointSpan =+                paths.maxOfOrNull { path ->+                    kotlin.math.abs(path.first().row - path.last().row) ++                        kotlin.math.abs(path.first().col - path.last().col)+                } ?: 0,         )     } @@ -282,9 +430,11 @@ object LevelGenerator {         adjacency: Map<CellPos, List<CellPos>>,         random: Random,         earlyStopProb: Float,+        difficulty: PipesDifficulty = PipesDifficulty.CASUAL,     ): List<List<CellPos>>? {         var unmarked = cells.toSet()         val paths = mutableListOf<List<CellPos>>()+        val completedCells = mutableSetOf<CellPos>()          while (unmarked.isNotEmpty()) {             var chosen: List<CellPos>? = null@@ -292,19 +442,37 @@ object LevelGenerator {             // before declaring the whole carve a failure.             for (retry in 0 until 8) {                 val remaining = unmarked.toMutableSet()-                val start = pickStart(remaining, adjacency, random)+                val start = pickStart(remaining, adjacency, random, cells, difficulty)                 val path = mutableListOf(start)                 remaining.remove(start)                  while (remaining.isNotEmpty()) {-                    val neighbors =-                        (adjacency[path.last()] ?: emptyList())+                    val current = path.last()+                    val scored =+                        (adjacency[current] ?: emptyList())                             .filter { it in remaining }-                            .shuffled(random)+                            .map { candidate ->+                                candidate to+                                    carveScore(+                                        candidate,+                                        current,+                                        path,+                                        completedCells,+                                        cells,+                                        adjacency,+                                        random,+                                        difficulty,+                                    )+                            }.sortedWith(+                                compareByDescending<Pair<CellPos, Double>> {+                                    it.second+                                }.thenBy { it.first.row }.thenBy { it.first.col },+                            )                     val next =-                        neighbors.firstOrNull { candidate ->-                            isStillConnected(remaining - candidate, adjacency)-                        } ?: break+                        scored+                            .firstOrNull { (candidate, _) ->+                                isStillConnected(remaining - candidate, adjacency)+                            }?.first ?: break                     path.add(next)                     remaining.remove(next)                     if (path.size >= 5 && random.nextFloat() < earlyStopProb) break@@ -316,18 +484,76 @@ object LevelGenerator {                     break                 }             }-            paths.add(chosen ?: return null)+            val finished = chosen ?: return null+            paths.add(finished)+            completedCells += finished         }         return paths     } +    /**+     * Order in which the walk tries neighbours. CASUAL is a pure seeded shuffle; harder tiers+     * demote edge cells (forced corridors greedy feeds on), reward stepping away from the+     * flow's start, expanding the flow's span across the board, and running alongside flows+     * already carved (interleaving, so later corridors are contested by a rival).+     */+    private fun carveScore(+        candidate: CellPos,+        current: CellPos,+        path: List<CellPos>,+        completedCells: Set<CellPos>,+        cells: Set<CellPos>,+        adjacency: Map<CellPos, List<CellPos>>,+        random: Random,+        difficulty: PipesDifficulty,+    ): Double {+        var score = random.nextDouble()+        if (difficulty.edgeAvoidance == 0.0 &&+            difficulty.awayFromStartWeight == 0.0 &&+            difficulty.interfaceWeight == 0.0+        ) {+            return score+        }+        if (isEdgeCell(candidate, cells, adjacency)) score -= difficulty.edgeAvoidance+        val start = path.first()+        val awayNow = kotlin.math.abs(current.row - start.row) + kotlin.math.abs(current.col - start.col)+        val awayNext = kotlin.math.abs(candidate.row - start.row) + kotlin.math.abs(candidate.col - start.col)+        if (awayNext > awayNow) score += difficulty.awayFromStartWeight+        if ((adjacency[candidate] ?: emptyList()).any { it in completedCells }) score += difficulty.interfaceWeight+        val rows = path.map { it.row }+        val cols = path.map { it.col }+        if (candidate.row < (rows.minOrNull() ?: candidate.row) ||+            candidate.row > (rows.maxOrNull() ?: candidate.row) ||+            candidate.col < (cols.minOrNull() ?: candidate.col) ||+            candidate.col > (cols.maxOrNull() ?: candidate.col)+        ) {+            score += 0.5+        }+        return score+    }+     /** Prefers a start whose removal keeps the rest connected, so a flow never strands a region. */     private fun pickStart(         unmarked: Set<CellPos>,         adjacency: Map<CellPos, List<CellPos>>,         random: Random,+        cells: Set<CellPos> = unmarked,+        difficulty: PipesDifficulty = PipesDifficulty.CASUAL,     ): CellPos {-        val candidates = unmarked.sortedWith(compareBy({ it.row }, { it.col })).shuffled(random)+        val candidates =+            unmarked+                .sortedWith(compareBy({ it.row }, { it.col }))+                .map { cell ->+                    var score = random.nextDouble()+                    if (difficulty.edgeAvoidance > 0.0 && !isEdgeCell(cell, cells, adjacency)) {+                        score += difficulty.edgeAvoidance+                    }+                    cell to score+                }.sortedWith(+                    compareByDescending<Pair<CellPos, Double>> {+                        it.second+                    }.thenBy { it.first.row }.thenBy { it.first.col },+                ).map { it.first }         return candidates.firstOrNull { isStillConnected(unmarked - it, adjacency) }             ?: candidates.first()     }
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/AntiGreedyGenerationTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/AntiGreedyGenerationTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/AntiGreedyGenerationTest.ktnew file mode 100644index 0000000000..a2543e5df5--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/AntiGreedyGenerationTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.games.pipes.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class AntiGreedyGenerationTest {+    private fun generated(+        difficulty: PipesDifficulty,+        seeds: IntRange = 0..11,+        size: Int = 6,+    ): List<GeneratedPipesLevel> =+        seeds.mapNotNull { seed ->+            LevelGenerator.generateSeeded(+                size,+                size,+                difficulty,+                10_000L + seed * 977L,+                "anti_${difficulty}_${size}_$seed",+            )+        }++    @Test+    fun generatedLevelsPerTierAreUniqueAndBelowGreedyThreshold() {+        for (difficulty in PipesDifficulty.entries) {+            val levels = generated(difficulty)+            assertTrue(levels.size >= 3, "$difficulty emitted only ${levels.size}")+            for (generatedLevel in levels) {+                val level = generatedLevel.level+                assertEquals(+                    NumberlinkSolver.Verdict.UNIQUE,+                    NumberlinkSolver.classify(level.cells, level.endpoints),+                    level.id,+                )+                val greedy = GreedySolver.evaluate(level)+                assertTrue(+                    greedy.filledFraction <= difficulty.maxGreedyFraction,+                    "${level.id} greedy=${greedy.filledFraction} tier=$difficulty",+                )+                assertEquals(greedy.filledFraction, generatedLevel.metrics.greedyFraction, level.id)+                assertTrue(+                    generatedLevel.metrics.interiorEndpointFraction >= difficulty.minInteriorEndpointFraction,+                    "${level.id} interior=${generatedLevel.metrics.interiorEndpointFraction}",+                )+                assertTrue(+                    generatedLevel.metrics.decoyAdjacencies >= difficulty.minDecoyAdjacencies,+                    "${level.id} decoys=${generatedLevel.metrics.decoyAdjacencies}",+                )+                assertTrue(!greedy.solved || difficulty == PipesDifficulty.CASUAL, level.id)+            }+        }+    }++    @Test+    fun greedyResistanceIncreasesWithTier() {+        fun average(difficulty: PipesDifficulty) = generated(difficulty).map { it.metrics.greedyFraction }.average()+        val casual = average(PipesDifficulty.CASUAL)+        val standard = average(PipesDifficulty.STANDARD)+        val expert = average(PipesDifficulty.EXPERT)+        assertTrue(casual > standard, "casual=$casual standard=$standard")+        assertTrue(standard > expert, "standard=$standard expert=$expert")+        assertTrue(expert <= PipesDifficulty.EXPERT.maxGreedyFraction, "expert=$expert")+    }++    @Test+    fun antiGreedyGenerationIsDeterministicPerSeed() {+        for (difficulty in PipesDifficulty.entries) {+            val a = assertNotNull(LevelGenerator.generateSeeded(6, 6, difficulty, 42_424L, "det_a"))+            val b = assertNotNull(LevelGenerator.generateSeeded(6, 6, difficulty, 42_424L, "det_a"))+            assertEquals(a.level.endpoints, b.level.endpoints, difficulty.name)+            assertEquals(a.metrics, b.metrics, difficulty.name)+        }+    }++    @Test+    fun standardAndExpertBoardsUseInteriorAndCrossBoardStructure() {+        for (difficulty in listOf(PipesDifficulty.STANDARD, PipesDifficulty.EXPERT)) {+            val levels = generated(difficulty)+            assertTrue(levels.isNotEmpty(), difficulty.name)+            assertTrue(+                levels.all { it.metrics.interiorEndpointFraction >= 0.35 },+                "$difficulty interiors=${levels.map { it.metrics.interiorEndpointFraction }}",+            )+            assertTrue(+                levels.all { it.metrics.crossFlowInterfaces > 0 },+                "$difficulty interfaces=${levels.map { it.metrics.crossFlowInterfaces }}",+            )+            assertTrue(+                levels.all { it.metrics.maxEndpointSpan >= 3 },+                "$difficulty spans=${levels.map { it.metrics.maxEndpointSpan }}",+            )+        }+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/GreedySolverTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/GreedySolverTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/GreedySolverTest.ktnew file mode 100644index 0000000000..b5e7c8d1b8--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/GreedySolverTest.kt@@ -0,0 +1,122 @@+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 kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class GreedySolverTest {+    private fun level(+        rows: Int,+        cols: Int,+        vararg ends: Pair<CellPos, CellPos>,+    ): LevelData {+        val cells = LevelGenerator.rectangularCells(rows, cols)+        return LevelData(+            id = "greedy_test",+            rows = rows,+            cols = cols,+            cells = cells,+            adjacency = computeAdjacency(cells),+            renderPositions = null,+            endpoints = ends.mapIndexed { index, (a, b) -> EndpointPair(index, listOf(a, b)) },+            bridges = emptySet(),+            optimalMoves = ends.size,+        )+    }++    @Test+    fun trivialStraightColumnsAreFullyGreedySolvable() {+        val result =+            GreedySolver.evaluate(+                level(+                    3,+                    3,+                    CellPos(0, 0) to CellPos(2, 0),+                    CellPos(0, 1) to CellPos(2, 1),+                    CellPos(0, 2) to CellPos(2, 2),+                ),+            )+        assertTrue(result.solved, result.toString())+        assertEquals(1.0, result.filledFraction)+        assertEquals(3, result.completedFlows)+    }++    @Test+    fun singleEdgeFlowIsFullyGreedySolvable() {+        val result = GreedySolver.evaluate(level(1, 4, CellPos(0, 0) to CellPos(0, 3)))+        assertTrue(result.solved)+        assertEquals(1.0, result.filledFraction)+    }++    @Test+    fun interiorCrossingEndpointsStallGreedyImmediately() {+        // Every interior frontier has two uncontested escape cells and contested middle cells:+        // there is no forced first move, so a no-guessing player can only place the endpoints.+        val result =+            GreedySolver.evaluate(+                level(+                    5,+                    5,+                    CellPos(1, 1) to CellPos(3, 3),+                    CellPos(1, 3) to CellPos(3, 1),+                ),+            )+        assertFalse(result.solved)+        assertEquals(4, result.filledCells)+        assertTrue(result.filledFraction <= 0.20, "fraction=${result.filledFraction}")+    }++    @Test+    fun uniqueWorkedExampleIsGreedySolvableWhichIsWhyGenerationMustFilter() {+        // The solver-verified UNIQUE 3x4 board from NumberlinkSolverTest: uniqueness alone+        // does not imply planning — greedy edge/forced moves solve this board completely,+        // which is exactly the failure mode the generator's greedy gate rejects.+        val board =+            level(+                3,+                4,+                CellPos(0, 0) to CellPos(1, 2),+                CellPos(0, 3) to CellPos(2, 1),+                CellPos(1, 1) to CellPos(2, 0),+            )+        assertEquals(NumberlinkSolver.Verdict.UNIQUE, NumberlinkSolver.classify(board.cells, board.endpoints))+        val result = GreedySolver.evaluate(board)+        assertTrue(result.solved, result.toString())+        assertEquals(1.0, result.filledFraction)+    }++    @Test+    fun planningHeavyUniqueBoardStallsGreedy() {+        // Handcrafted arrangement with mostly interior endpoints: greedy stalls far below a+        // full board because its frontiers face contested interior choices.+        val board =+            level(+                5,+                5,+                CellPos(1, 2) to CellPos(3, 1),+                CellPos(1, 4) to CellPos(4, 2),+                CellPos(0, 1) to CellPos(3, 3),+                CellPos(2, 2) to CellPos(4, 4),+            )+        val result = GreedySolver.evaluate(board)+        assertFalse(result.solved, result.toString())+        assertTrue(result.filledFraction < 0.90, "fraction=${result.filledFraction}")+    }++    @Test+    fun greedyEvaluationIsDeterministic() {+        val board =+            level(+                5,+                5,+                CellPos(1, 1) to CellPos(3, 3),+                CellPos(1, 3) to CellPos(3, 1),+            )+        assertEquals(GreedySolver.evaluate(board), GreedySolver.evaluate(board))+    }+}