pipes: rebuild the runtime level generator on the shipped carve-cover algorithm
- Commit
143ade4bf8d739055f01146738d72c8cc821ad7c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 21:16 UTC (4 months ago)
- Parents
b7c530d
Diff
games/pipes/src/main/java/com/vayunmathur/games/pipes/data/LevelGenerator.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/LevelGenerator.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/LevelGenerator.ktindex e40221649a..fb22b6bbb0 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/LevelGenerator.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/LevelGenerator.kt@@ -1,5 +1,6 @@ package com.vayunmathur.games.pipes.data +import kotlin.math.roundToInt import kotlin.random.Random object LevelGenerator {@@ -10,18 +11,30 @@ 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].+ *+ * [earlyStopProb] controls flow length: higher means more, shorter flows.+ */ fun generateLevel( cells: Set<CellPos>, adjacency: Map<CellPos, List<CellPos>>,- numFlows: Int,+ maxFlows: Int, seed: Long,- id: String+ id: String,+ earlyStopProb: Float = 0.25f ): LevelData? { val rows = cells.maxOf { it.row } + 1 val cols = cells.maxOf { it.col } + 1 for (attempt in 0 until 50) {- val (_, endpoints) = tryGenerate(cells, adjacency, numFlows, Random(seed + attempt)) ?: continue+ val paths = carveCover(cells, adjacency, Random(seed + attempt), earlyStopProb) ?: continue+ if (paths.size > maxFlows) continue+ if (shortPairViolation(paths)) continue+ val endpoints = paths.mapIndexed { index, path ->+ EndpointPair(index, listOf(path.first(), path.last()))+ } return LevelData( id = id, rows = rows,@@ -31,62 +44,84 @@ object LevelGenerator { renderPositions = null, endpoints = endpoints, bridges = emptySet(),- optimalMoves = cells.size+ optimalMoves = endpoints.size ) } return null } - private fun tryGenerate(+ /**+ * 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+ * what produced the shipped packs.+ *+ * The flow count has to be an output rather than an input. Fixing it up front forces the final+ * path to be a Hamiltonian walk over whatever is left, which almost never exists above a 7x7+ * board.+ */+ private fun carveCover( cells: Set<CellPos>, adjacency: Map<CellPos, List<CellPos>>,- numFlows: Int,- random: Random- ): Pair<List<List<CellPos>>, List<EndpointPair>>? {- val unmarked = cells.toMutableSet()+ random: Random,+ earlyStopProb: Float+ ): List<List<CellPos>>? {+ var unmarked = cells.toSet() val paths = mutableListOf<List<CellPos>>() - for (flowIndex in 0 until numFlows) {- if (unmarked.isEmpty()) break-- val isLast = flowIndex == numFlows - 1- val start = unmarked.random(random)- val path = mutableListOf(start)- unmarked.remove(start)-- val minLength = if (isLast) unmarked.size + 1 else 3- val maxLength = if (isLast) unmarked.size + 1 else unmarked.size - (numFlows - flowIndex - 1) * 2-- while (path.size < maxLength) {- val current = path.last()- val neighbors = (adjacency[current] ?: emptyList())- .filter { it in unmarked }- .shuffled(random)-- val validNeighbors = neighbors.filter { candidate ->- val remaining = unmarked.toMutableSet()- remaining.remove(candidate)- isStillConnected(remaining, adjacency)+ while (unmarked.isNotEmpty()) {+ var chosen: List<CellPos>? = null+ // A start cell can strand a region no matter how the walk goes; retry a few times+ // before declaring the whole carve a failure.+ for (retry in 0 until 8) {+ val remaining = unmarked.toMutableSet()+ val start = pickStart(remaining, adjacency, random)+ val path = mutableListOf(start)+ remaining.remove(start)++ while (remaining.isNotEmpty()) {+ val neighbors = (adjacency[path.last()] ?: emptyList())+ .filter { it in remaining }+ .shuffled(random)+ val next = neighbors.firstOrNull { candidate ->+ isStillConnected(remaining - candidate, adjacency)+ } ?: break+ path.add(next)+ remaining.remove(next)+ if (path.size >= 3 && random.nextFloat() < earlyStopProb) break } - if (validNeighbors.isEmpty()) break- val next = validNeighbors.first()- path.add(next)- unmarked.remove(next)-- if (!isLast && path.size >= minLength && random.nextFloat() < 0.3f) break+ if (path.size >= 2) {+ chosen = path+ unmarked = remaining+ break+ } }-- if (path.size < 2) return null- paths.add(path)+ paths.add(chosen ?: return null) }+ return paths+ } - if (unmarked.isNotEmpty()) return null+ /** 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+ ): CellPos {+ val candidates = unmarked.sortedWith(compareBy({ it.row }, { it.col })).shuffled(random)+ return candidates.firstOrNull { isStillConnected(unmarked - it, adjacency) }+ ?: candidates.first()+ } - val endpoints = paths.mapIndexed { index, path ->- EndpointPair(index, listOf(path.first(), path.last()))- }- return paths to endpoints+ /**+ * Rejects boards whose pairs sit so close together that the puzzle solves itself. Mirrors+ * `short_pair_violation` in `scripts/pipes/generate_levels.py`: no touching endpoints, at most+ * one pair with a single cell between, and at most two pairs with two or fewer.+ */+ private fun shortPairViolation(paths: List<List<CellPos>>): Boolean {+ if (paths.any { it.size <= 2 }) return true+ if (paths.count { it.size == 3 } > 1) return true+ if (paths.count { it.size <= 4 } > 2) return true+ return false } private fun isStillConnected(cells: Set<CellPos>, adjacency: Map<CellPos, List<CellPos>>): Boolean {@@ -107,18 +142,20 @@ object LevelGenerator { return visited.size == cells.size } + /** 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())+ fun generatePack( name: String, shape: String, cells: Set<CellPos>, adjacency: Map<CellPos, List<CellPos>>, levelCount: Int,- flowRange: IntRange,+ maxFlows: Int, seed: Long ): List<LevelData> = (0 until levelCount).mapNotNull { i -> val currentSeed = seed + i * 100- val numFlows = flowRange.random(Random(currentSeed)) val id = "${name.replace("×", "x").replace(" ", "_")}_${String.format("%03d", i + 1)}"- generateLevel(cells, adjacency, numFlows, currentSeed, id)+ generateLevel(cells, adjacency, maxFlows, currentSeed, id) } }
games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.ktindex e89462baf0..5215ae3324 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.kt@@ -68,7 +68,7 @@ private fun rectangularCells(rows: Int, cols: Int): Set<CellPos> { } } -private fun computeAdjacency(cells: Set<CellPos>): Map<CellPos, List<CellPos>> {+internal fun computeAdjacency(cells: Set<CellPos>): Map<CellPos, List<CellPos>> { val dirs = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) return cells.associateWith { cell -> dirs.mapNotNull { (dr, dc) ->