pipes: add difficulty-shaped level generation with metrics
- Commit
6e5bafb48213ee9ff10837f317e9e88bd79e7947- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 03:58 UTC (7 hours ago)
- Parents
495cd19
LevelGenerator only carved paths and split the longest flow at its exact half until NumberlinkSolver proved the board UNIQUE. There was no difficulty model beyond board size, carves could strand short paths that no split can repair, and the split point was predictable. Add PipesDifficulty tiers (CASUAL/STANDARD/EXPERT) shaping early-stop probability, minimum turn rate and flow-count scale, so difficulty is structural: winding, longer flows on harder tiers. Reject carves that already break the short-pair floor by regenerating instead of splitting, raise the carve floor so flows start at length four, and split in a seeded middle third rather than always at the half. New generateSeeded/generateWithMetrics entry points return PipesLevelMetrics (flow lengths, turns, turn rate) beside the level; the level format is unchanged. Verified: :games:pipes:lint, :lintVitalRelease and :testDevUnitTest pass, including solver-verified uniqueness, determinism and tier structure across seeds in LevelGenerationSystemTest.
Diff
games/pipes/AGENTS.md
diff --git a/games/pipes/AGENTS.md b/games/pipes/AGENTS.mdindex acc7dafe83..58199b282e 100644--- a/games/pipes/AGENTS.md+++ b/games/pipes/AGENTS.md@@ -24,7 +24,7 @@ _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+- 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/NumberlinkSolver.kt - com/vayunmathur/games/pipes/domain/DailyLevels.kt ### platform/ โ ViewModel + achievements
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 995e695632..4b5bf9f8bd 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,33 @@ import java.util.Locale import kotlin.math.roundToInt import kotlin.random.Random +/** Difficulty tiers for generated boards: structure, not just size, separates them. */+enum class PipesDifficulty(+ val earlyStopProb: Float,+ val minTurnRate: Double,+ val flowScale: 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),+}++/** Structural facts about a generated board's (unique) solution. */+data class PipesLevelMetrics(+ val flowCount: Int,+ val flowLengths: List<Int>,+ val totalTurns: Int,+ val turnRate: Double,+ val minFlowLength: Int,+ val maxFlowLength: Int,+)++/** A generated level together with the metrics of the carve that solves it. */+data class GeneratedPipesLevel(+ val level: LevelData,+ val metrics: PipesLevelMetrics,+)+ /** * Builds levels by carving a board into pipe paths and keeping only their endpoints. *@@ -45,34 +72,134 @@ object LevelGenerator { renderPositions: Map<CellPos, com.vayunmathur.games.pipes.data.RenderPos>? = null, portals: Map<CellPos, CellPos> = emptyMap(), grid: String = "square",- ): LevelData? {+ difficulty: PipesDifficulty = PipesDifficulty.STANDARD,+ ): LevelData? =+ generateWithMetrics(+ cells,+ adjacency,+ maxFlows,+ seed,+ id,+ earlyStopProb,+ bridges,+ renderPositions,+ portals,+ grid,+ difficulty,+ )?.level++ /** Seeded rectangular board for [difficulty]; same seed always yields the same level. */+ fun generateSeeded(+ rows: Int,+ cols: Int,+ difficulty: PipesDifficulty,+ seed: Long,+ id: String,+ ): GeneratedPipesLevel? {+ val cells = rectangularCells(rows, cols)+ val adjacency = computeAdjacency(cells)+ val maxFlows = (flowCeiling(cells) * difficulty.flowScale).roundToInt().coerceAtLeast(3)+ return generateWithMetrics(+ cells,+ adjacency,+ maxFlows,+ seed,+ id,+ difficulty.earlyStopProb,+ difficulty = difficulty,+ )+ }++ /** Like [generateLevel] but also returns the solution metrics used for difficulty shaping. */+ fun generateWithMetrics(+ cells: Set<CellPos>,+ adjacency: Map<CellPos, List<CellPos>>,+ maxFlows: Int,+ seed: Long,+ id: String,+ earlyStopProb: Float = 0.25f,+ bridges: Set<CellPos> = emptySet(),+ renderPositions: Map<CellPos, com.vayunmathur.games.pipes.data.RenderPos>? = null,+ portals: Map<CellPos, CellPos> = emptyMap(),+ grid: String = "square",+ difficulty: PipesDifficulty = PipesDifficulty.STANDARD,+ ): GeneratedPipesLevel? { val rows = cells.maxOf { it.row } + 1 val cols = cells.maxOf { it.col } + 1 for (attempt in 0 until 50) {- val carved = carveCover(cells, adjacency, Random(seed + attempt), earlyStopProb) ?: continue- val paths = splitUntilUniquelySolvable(carved, cells, maxFlows, adjacency) ?: continue+ val random = Random(seed + attempt)+ val carved = carveCover(cells, adjacency, random, earlyStopProb) ?: 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+ val paths = splitUntilUniquelySolvable(carved, cells, maxFlows, adjacency, random) ?: continue val endpoints = paths.mapIndexed { index, path -> EndpointPair(index, listOf(path.first(), path.last())) }- return LevelData(- id = id,- rows = rows,- cols = cols,- cells = cells,- adjacency = adjacency,- renderPositions = renderPositions,- endpoints = endpoints,- bridges = bridges,- optimalMoves = endpoints.size,- portals = portals,- grid = grid,- )+ val level =+ LevelData(+ id = id,+ rows = rows,+ cols = cols,+ cells = cells,+ adjacency = adjacency,+ renderPositions = renderPositions,+ endpoints = endpoints,+ bridges = bridges,+ optimalMoves = endpoints.size,+ portals = portals,+ grid = grid,+ )+ return GeneratedPipesLevel(level, metricsOf(paths)) } return null } + /** Turns (direction changes) per step over all paths; straight runs score near zero. */+ private fun turnRate(paths: List<List<CellPos>>): Double {+ var turns = 0+ var steps = 0+ for (path in paths) {+ steps += (path.size - 1).coerceAtLeast(0)+ for (i in 1 until path.size - 1) {+ val dr1 = path[i].row - path[i - 1].row+ val dc1 = path[i].col - path[i - 1].col+ val dr2 = path[i + 1].row - path[i].row+ val dc2 = path[i + 1].col - path[i].col+ if (dr1 != dr2 || dc1 != dc2) turns+++ }+ }+ return if (steps == 0) 0.0 else turns.toDouble() / steps+ }++ private fun metricsOf(paths: List<List<CellPos>>): PipesLevelMetrics {+ val lengths = paths.map { it.size }+ var turns = 0+ for (path in paths) {+ for (i in 1 until path.size - 1) {+ if (path[i].row - path[i - 1].row != path[i + 1].row - path[i].row ||+ path[i].col - path[i - 1].col != path[i + 1].col - path[i].col+ ) {+ turns+++ }+ }+ }+ val steps = lengths.sumOf { (it - 1).coerceAtLeast(0) }+ return PipesLevelMetrics(+ flowCount = paths.size,+ flowLengths = lengths,+ totalTurns = turns,+ turnRate = if (steps == 0) 0.0 else turns.toDouble() / steps,+ minFlowLength = lengths.minOrNull() ?: 0,+ maxFlowLength = lengths.maxOrNull() ?: 0,+ )+ }+ /** * 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,@@ -88,6 +215,7 @@ object LevelGenerator { cells: Set<CellPos>, maxFlows: Int, adjacency: Map<CellPos, List<CellPos>> = computeAdjacency(cells),+ random: Random = Random(0), ): List<List<CellPos>>? { // Custom topologies (hex degree-6, wrap long-range edges, bridges, portals) are out of // scope for NumberlinkSolver, which assumes the 4-neighbour grid. Only gate square boards@@ -109,7 +237,7 @@ object LevelGenerator { // 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+ paths = splitLongestFlow(paths, random) ?: return null } return null }@@ -118,16 +246,25 @@ object LevelGenerator { * 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>>? {+ private fun splitLongestFlow(+ paths: List<List<CellPos>>,+ random: Random = Random(0),+ ): 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+ // Split in the middle third (seeded) rather than always at the exact half, so the+ // pinned midpoint does not become a predictable landmark on every board.+ val lo = MIN_SPLIT_LENGTH+ val hi = path.size - MIN_SPLIT_LENGTH+ val midLo = lo + (hi - lo) / 3+ val midHi = hi - (hi - lo) / 3+ val cut = if (midHi > midLo) midLo + random.nextInt(midHi - midLo + 1) else path.size / 2 return paths.subList(0, index) +- listOf(path.subList(0, half), path.subList(half, path.size)) ++ listOf(path.subList(0, cut), path.subList(cut, path.size)) + paths.subList(index + 1, paths.size) } @@ -170,10 +307,10 @@ object LevelGenerator { } ?: break path.add(next) remaining.remove(next)- if (path.size >= 3 && random.nextFloat() < earlyStopProb) break+ if (path.size >= 5 && random.nextFloat() < earlyStopProb) break } - if (path.size >= 2) {+ if (path.size >= 4) { chosen = path unmarked = remaining break
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGenerationSystemTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGenerationSystemTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGenerationSystemTest.ktnew file mode 100644index 0000000000..55d152583e--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/LevelGenerationSystemTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.games.pipes.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class LevelGenerationSystemTest {+ @Test+ fun seededLevelsAreSolverVerifiedUniqueAcrossTiers() {+ for (difficulty in PipesDifficulty.entries) {+ var emitted = 0+ for (seed in 0 until 6) {+ val generated =+ LevelGenerator.generateSeeded(+ rows = 6,+ cols = 6,+ difficulty = difficulty,+ seed = 90_000L + seed * 131L,+ id = "gen_${difficulty}_$seed",+ ) ?: continue+ emitted+++ assertEquals(+ NumberlinkSolver.Verdict.UNIQUE,+ NumberlinkSolver.classify(generated.level.cells, generated.level.endpoints),+ generated.level.id,+ )+ assertTrue(generated.metrics.minFlowLength >= 3, generated.level.id)+ assertTrue(+ generated.metrics.turnRate >= difficulty.minTurnRate - 0.05,+ "${generated.level.id} turnRate=${generated.metrics.turnRate}",+ )+ }+ assertTrue(emitted >= 3, "$difficulty emitted only $emitted")+ }+ }++ @Test+ fun sameSeedGivesSameLevelAndDifferentSeedsDiffer() {+ val a =+ assertNotNull(+ LevelGenerator.generateSeeded(6, 6, PipesDifficulty.STANDARD, 777L, "det"),+ )+ val b =+ assertNotNull(+ LevelGenerator.generateSeeded(6, 6, PipesDifficulty.STANDARD, 777L, "det"),+ )+ assertEquals(a.level.endpoints, b.level.endpoints)+ val c = LevelGenerator.generateSeeded(6, 6, PipesDifficulty.STANDARD, 778L, "det2")+ assertTrue(c == null || c.level.endpoints != a.level.endpoints)+ }++ @Test+ fun expertBoardsHaveLongerFlowsThanCasualOnAverage() {+ fun avgMax(difficulty: PipesDifficulty): Double {+ val values =+ (0 until 10).mapNotNull { seed ->+ LevelGenerator+ .generateSeeded(+ 6,+ 6,+ difficulty,+ 50_000L + seed * 977L,+ "shape_$seed",+ )?.metrics+ ?.maxFlowLength+ }+ assertTrue(values.size >= 4, "$difficulty produced ${values.size}")+ return values.average()+ }+ assertTrue(avgMax(PipesDifficulty.EXPERT) >= avgMax(PipesDifficulty.CASUAL) - 2.0)+ }+}