Modern Apps git

← Modern-Apps.git

pipes: cut another colour's line when drawing into it (#ux-audit)

Commit
92f677ba5a2c61ba19cbaaf9f09c70b262fea3f8
Author
Vayun Mathur <[email protected]>
When
2026-11-13 01:20 UTC (23 days ago)
Parents
ba8fd2f
Symptom: dragging a pipe into a cell already used by another colour
just stopped the stroke. To re-route, the player had to go and break
the other line by hand first, then come back.

Root cause: StrokeRules.isValidStep (formerly the ViewModel's
isFreeForColor) rejected any non-bridge cell owned by another colour.

Fix:
- New pure domain/BoardState.kt: the board model (paths + cellOwner)
  moves here as BoardState, with PipesGameState kept as a typealias so
  the screens, previews and tests are unchanged. BoardEdits.applyStroke
  replaces a colour's line with a stroke and cuts every other line the
  stroke crosses outside a bridge just before the crossing, keeping the
  part attached to the dot it was drawn from and dropping a remnant
  shorter than two cells. BoardEdits.owners rebuilds ownership; a
  bridge keeps its first owner while that line still crosses it, as
  before.
- StrokeRules.isValidStep no longer blocks other colours' cells
  (foreign dots still block). When a diagonal hop can go through
  either shared neighbour, extend prefers the one that cuts nothing.
- PipesViewModel: while a stroke is open, gameState is a preview
  (preDrawState with the stroke applied), recomputed on each step from
  preDrawState. A line the finger crosses shows as cut immediately and
  comes back whole if the finger backs out before releasing. commitDraw
  applies the same edit, and pushes the pre-stroke board onto the undo
  history, so one Undo restores both the stroke and the cut line. The
  old clearColor and the hand-rolled ownership merge in commitDraw are
  replaced by applyStroke; grabbing an endpoint still lifts that
  colour's line immediately (changed separately).

User-visible effect: drawing into another colour cuts that colour at
the crossing, like other flow games; Undo restores it.

Verification: new BoardEditsTest (cut keeps the drawn-from end, short
remnants dropped, bridges shared not cut and keep their owner, short
stroke removes the colour, re-applying a line is an identity);
StrokeRulesTest updated (other lines no longer block, diagonal prefers
the cut-free neighbour); PipesStrokeTest draws into a real 5x5 level,
checks the preview cut, the restore on backing out, the committed cut,
ownership, and that one Undo restores the cut line.

Diff

games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.ktnew file mode 100644index 0000000000..7d6f1c7684--- /dev/null+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.kt@@ -0,0 +1,67 @@+package com.vayunmathur.games.pipes.domain++import com.vayunmathur.games.pipes.data.CellPos+import com.vayunmathur.games.pipes.data.LevelData++/**+ * One board position: each colour's drawn line, plus which colour owns each covered cell.+ *+ * Every non-bridge cell is covered by at most one line. A bridge cell can carry two lines;+ * its owner is the one drawn first (the under-pipe), and the other humps over it.+ */+data class BoardState(+    val paths: Map<Int, List<CellPos>> = emptyMap(),+    val cellOwner: Map<CellPos, Int> = emptyMap(),+)++/** Pure edits on a [BoardState]. */+object BoardEdits {++    /**+     * [base] with [color]'s line replaced by [stroke] (or removed, when the stroke is shorter+     * than two cells). Any other colour's line that the stroke crosses outside a bridge is+     * cut just before the crossing, keeping the part attached to the dot it was drawn from;+     * a remnant shorter than two cells is dropped.+     */+    fun applyStroke(level: LevelData, base: BoardState, color: Int, stroke: List<CellPos>): BoardState {+        val strokeCells = stroke.toSet()+        val paths = mutableMapOf<Int, List<CellPos>>()+        for ((c, path) in base.paths) {+            if (c == color) continue+            val cut = path.indexOfFirst { it in strokeCells && it !in level.bridges }+            val kept = if (cut < 0) path else path.subList(0, cut).toList()+            if (kept.size >= 2) paths[c] = kept+        }+        if (stroke.size >= 2) paths[color] = stroke+        return BoardState(paths, owners(level, paths, base.cellOwner, color))+    }++    /**+     * Ownership for [paths]. A bridge keeps its previous owner while that line still crosses+     * it; otherwise a crosser other than the newest line ([newest]) takes it, so a fresh+     * stroke humps over whatever was already there.+     */+    fun owners(+        level: LevelData,+        paths: Map<Int, List<CellPos>>,+        prior: Map<CellPos, Int> = emptyMap(),+        newest: Int? = null,+    ): Map<CellPos, Int> {+        val out = mutableMapOf<CellPos, Int>()+        val crossers = mutableMapOf<CellPos, MutableList<Int>>()+        for ((c, path) in paths.entries.sortedBy { it.key }) {+            for (cell in path) {+                if (cell in level.bridges) crossers.getOrPut(cell) { mutableListOf() }.add(c) else out[cell] = c+            }+        }+        for ((cell, colors) in crossers) {+            val previous = prior[cell]+            out[cell] = if (previous != null && previous in colors) {+                previous+            } else {+                colors.firstOrNull { it != newest } ?: colors.first()+            }+        }+        return out+    }+}
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.ktindex 2cd898e292..0dcedd6a5e 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.kt@@ -7,8 +7,9 @@ import kotlin.math.abs /**  * Pure rules for growing one colour's stroke as the finger moves.  *- * [owners] is the board's cell ownership the stroke is checked against (the committed- * board with the stroke's own colour already lifted when it was grabbed by an endpoint).+ * [owners] is the ownership of the board as it was before the stroke. A stroke may run+ * into another colour's line (that line is cut there, see [BoardEdits.applyStroke]) but+ * never onto another colour's dot.  */ object StrokeRules { @@ -19,7 +20,8 @@ object StrokeRules {      *   back it is, so a fast backtrack never stalls.      * - An adjacent free cell is appended.      * - A cell two steps away through a shared neighbour (a diagonal move, or a sample that-     *   skipped a cell) is reached through that neighbour.+     *   skipped a cell) is reached through that neighbour, preferring one that cuts no+     *   other colour's line.      * - A finished stroke (it reached its partner dot) stays put.      */     fun extend(@@ -32,13 +34,13 @@ object StrokeRules {         if (path.isEmpty() || cell !in level.cells || isComplete(level, color, path)) return path         val idx = path.indexOf(cell)         if (idx >= 0) return path.subList(0, idx + 1).toList()-        if (isValidStep(level, owners, color, path, cell)) return path + cell-        val via = level.adjacency[path.last()].orEmpty().firstOrNull { n ->+        if (isValidStep(level, color, path, cell)) return path + cell+        val via = level.adjacency[path.last()].orEmpty().filter { n ->             cell in level.adjacency[n].orEmpty() &&-                isValidStep(level, owners, color, path, n) &&+                isValidStep(level, color, path, n) &&                 !isComplete(level, color, path + n) &&-                isValidStep(level, owners, color, path + n, cell)-        }+                isValidStep(level, color, path + n, cell)+        }.minByOrNull { n -> if (owners[n].let { it == null || it == color }) 0 else 1 }         return if (via != null) path + via + cell else path     } @@ -55,10 +57,12 @@ object StrokeRules {         }     } -    /** Whether [cell] may follow [path] directly. */+    /**+     * Whether [cell] may follow [path] directly. Cells owned by other colours are allowed:+     * the crossing cuts that line.+     */     fun isValidStep(         level: LevelData,-        owners: Map<CellPos, Int>,         color: Int,         path: List<CellPos>,         cell: CellPos,@@ -66,9 +70,7 @@ object StrokeRules {         if (cell in path) return false         val neighbors = level.adjacency[path.last()] ?: return false         if (cell !in neighbors || isForeignEndpoint(level, color, cell)) return false-        if (!isStraightThroughBridge(level, path, cell)) return false-        val owner = owners[cell] ?: return true-        return owner == color || cell in level.bridges+        return isStraightThroughBridge(level, path, cell)     }      private fun isForeignEndpoint(level: LevelData, color: Int, cell: CellPos): Boolean =
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 a2afd04d9d..e8fc8e9493 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@@ -5,6 +5,8 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.games.pipes.data.CellPos import com.vayunmathur.games.pipes.data.CompletedLevelsRepository+import com.vayunmathur.games.pipes.domain.BoardEdits+import com.vayunmathur.games.pipes.domain.BoardState import com.vayunmathur.games.pipes.domain.DailyLevels import com.vayunmathur.games.pipes.domain.StrokeRules import com.vayunmathur.games.pipes.data.LevelData@@ -28,10 +30,8 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -data class PipesGameState(-    val paths: Map<Int, List<CellPos>> = emptyMap(),-    val cellOwner: Map<CellPos, Int> = emptyMap()-)+/** The board position the screens draw; the pure model lives in domain/. */+typealias PipesGameState = BoardState  data class PipesUiState(     val packIndex: Int = -1,@@ -211,122 +211,69 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),         val levelData = s.levelData ?: return         val endpointColor = levelData.endpoints.find { ep -> cell in ep.cells }?.colorIndex -        if (endpointColor != null) {+        val base = s.gameState+        val (color, stroke) = if (endpointColor != null) {             // Grabbing an endpoint always restarts that color: its current line breaks             // right away (like grabbing a line partway does) so the drag is free to take             // a different route. Releasing without drawing leaves the line cleared.-            val brokenState = clearColor(s.gameState, endpointColor)-            _uiState.update {-                it.copy(-                    activeColor = endpointColor,-                    activePath = listOf(cell),-                    gameState = brokenState,-                    preDrawState = it.gameState-                )-            }-            return-        }--        val ownerColor = s.gameState.cellOwner[cell] ?: return-        val path = s.gameState.paths[ownerColor] ?: return-        val idx = path.indexOf(cell)-        if (idx >= 0) {-            _uiState.update {-                it.copy(-                    activeColor = ownerColor,-                    activePath = path.take(idx + 1),-                    preDrawState = it.gameState,-                )-            }+            endpointColor to listOf(cell)+        } else {+            val ownerColor = base.cellOwner[cell] ?: return+            val idx = base.paths[ownerColor]?.indexOf(cell) ?: -1+            if (idx < 0) return+            ownerColor to base.paths.getValue(ownerColor).take(idx + 1)         }-    }--    /** Removes [color]'s line from the board, leaving every other color untouched. */-    private fun clearColor(state: PipesGameState, color: Int): PipesGameState {-        val remaining = state.paths - color-        // Rebuild ownership so a bridge shared with the cleared color falls back to its-        // remaining crosser instead of being orphaned (single-owner map caveat).-        val newCellOwner = mutableMapOf<CellPos, Int>()-        for ((c, path) in remaining) {-            for (cell in path) {-                val current = newCellOwner[cell]-                if (current == null || current == c) {-                    newCellOwner[cell] = c-                }-            }+        _uiState.update {+            it.copy(+                activeColor = color,+                activePath = stroke,+                gameState = BoardEdits.applyStroke(levelData, base, color, stroke),+                preDrawState = base,+            )         }-        // Non-bridge cells keep first-writer wins implicitly via path order; bridges allow sharing-        // so last-writer fallback above is fine — commitDraw preserves first owner on redraw.-        return PipesGameState(remaining, newCellOwner)     } +    /**+     * While a stroke is open, [PipesUiState.gameState] is a preview: the board from before+     * the stroke with the stroke applied, so other colours it crosses show as cut and come+     * back intact if the finger backs out again. Undo returns to [PipesUiState.preDrawState].+     */     override fun extendPath(cell: CellPos) {         val s = _uiState.value         val activeColor = s.activeColor ?: return         val levelData = s.levelData ?: return         if (s.isLevelWon) return-        val next = StrokeRules.extend(levelData, s.gameState.cellOwner, activeColor, s.activePath, cell)-        if (next != s.activePath) _uiState.update { it.copy(activePath = next) }+        val base = s.preDrawState ?: s.gameState+        val next = StrokeRules.extend(levelData, base.cellOwner, activeColor, s.activePath, cell)+        if (next == s.activePath) return+        _uiState.update {+            it.copy(activePath = next, gameState = BoardEdits.applyStroke(levelData, base, activeColor, next))+        }     }      override fun commitDraw() {         val s = _uiState.value         val activeColor = s.activeColor ?: return+        val levelData = s.levelData ?: return         if (s.isLevelWon) return          val newPath = s.activePath         val preDrawState = s.preDrawState ?: s.gameState--        if (newPath.size < 2) {-            if (s.gameState != preDrawState) {-                // Tapped an endpoint without drawing: keep the line broken, but make it undoable.-                _uiState.update {-                    it.copy(-                        history = it.history + preDrawState,-                        activeColor = null,-                        activePath = emptyList(),-                        preDrawState = null-                    )-                }-            } else {-                _uiState.update {-                    it.copy(-                        activeColor = null,-                        activePath = emptyList(),-                        gameState = preDrawState,-                        preDrawState = null,-                    )-                }-            }-            return-        }--        val currentState = s.gameState-        val newCellOwner = currentState.cellOwner.toMutableMap()--        currentState.paths[activeColor]?.forEach { c ->-            if (newCellOwner[c] == activeColor) newCellOwner.remove(c)-        }--        val newPaths = currentState.paths.toMutableMap()-        newPaths[activeColor] = newPath-        val bridges = s.levelData?.bridges ?: emptySet()-        for (cell in newPath) {-            if (cell in bridges && newCellOwner[cell] != null && newCellOwner[cell] != activeColor) continue-            newCellOwner[cell] = activeColor-        }--        val newGameState = PipesGameState(newPaths, newCellOwner)+        val newGameState = BoardEdits.applyStroke(levelData, preDrawState, activeColor, newPath)+        // A stroke that only broke a line (released on its own start cell) counts as a move+        // only when it actually removed something.+        val counts = newPath.size >= 2 || newGameState != preDrawState          _uiState.update {             it.copy(                 gameState = newGameState,-                history = it.history + preDrawState,+                history = if (counts) it.history + preDrawState else it.history,                 activeColor = null,                 activePath = emptyList(),                 preDrawState = null             )         }+        if (newPath.size < 2) return          viewModelScope.launch(Dispatchers.IO) {             repository.incrementTotalPipesPlaced()
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/BoardEditsTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/BoardEditsTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/BoardEditsTest.ktnew file mode 100644index 0000000000..c51dae4dd1--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/BoardEditsTest.kt@@ -0,0 +1,62 @@+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.assertNull++class BoardEditsTest {+    private fun p(r: Int, c: Int) = CellPos(r, c)+    private val cells = buildSet { for (r in 0 until 5) for (c in 0 until 5) add(p(r, c)) }+    private fun level(bridges: Set<CellPos> = emptySet()) = LevelData(+        "e", 5, 5, cells, computeAdjacency(cells), null,+        listOf(EndpointPair(0, listOf(p(0, 0), p(4, 0))), EndpointPair(1, listOf(p(2, 0), p(2, 4)))),+        bridges, 2,+    )++    /** Blue (1) drawn from (2,4) leftwards along row 2 to (2,1). */+    private val blue = listOf(p(2, 4), p(2, 3), p(2, 2), p(2, 1))++    private fun board(level: LevelData) =+        BoardState(mapOf(1 to blue), BoardEdits.owners(level, mapOf(1 to blue)))++    @Test fun crossingAnotherLineCutsItKeepingTheDrawnFromEnd() {+        val level = level()+        val red = listOf(p(0, 0), p(0, 1), p(0, 2), p(1, 2), p(2, 2), p(3, 2))+        val out = BoardEdits.applyStroke(level, board(level), 0, red)+        assertEquals(red, out.paths[0])+        assertEquals(listOf(p(2, 4), p(2, 3)), out.paths[1])+        assertEquals(0, out.cellOwner[p(2, 2)])+        assertNull(out.cellOwner[p(2, 1)])+        assertEquals(1, out.cellOwner[p(2, 3)])+    }++    @Test fun aRemnantShorterThanTwoCellsIsDropped() {+        val level = level()+        val red = listOf(p(0, 0), p(0, 1), p(0, 2), p(0, 3), p(1, 3), p(2, 3))+        val out = BoardEdits.applyStroke(level, board(level), 0, red)+        assertNull(out.paths[1])+    }++    @Test fun bridgesAreSharedNotCutAndKeepTheirFirstOwner() {+        val level = level(bridges = setOf(p(2, 2)))+        val red = listOf(p(0, 0), p(0, 1), p(0, 2), p(1, 2), p(2, 2), p(3, 2))+        val out = BoardEdits.applyStroke(level, board(level), 0, red)+        assertEquals(blue, out.paths[1])+        assertEquals(1, out.cellOwner[p(2, 2)])+    }++    @Test fun shortStrokeRemovesTheColourAndBaseIsUntouched() {+        val level = level()+        val base = board(level)+        val out = BoardEdits.applyStroke(level, base, 1, listOf(p(2, 4)))+        assertEquals(emptyMap(), out.paths)+        assertEquals(emptyMap(), out.cellOwner)+        assertEquals(blue, base.paths[1])+        // Re-applying the same line is an identity, which is what makes no-op strokes detectable.+        assertEquals(base, BoardEdits.applyStroke(level, base, 1, blue))+    }+}
games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/StrokeRulesTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/StrokeRulesTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/StrokeRulesTest.ktindex aedf260490..70ed3c5512 100644--- a/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/StrokeRulesTest.kt+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/domain/StrokeRulesTest.kt@@ -35,8 +35,8 @@ class StrokeRulesTest {         assertTrue(via == p(1, 2) || via == p(2, 1), "via=$via")     } -    @Test fun diagonalAvoidsABlockedNeighbour() {-        // (2,1) belongs to blue, so the route must go through (1,2).+    @Test fun diagonalPrefersTheNeighbourThatCutsNothing() {+        // (2,1) belongs to blue, so the route goes through (1,2) and cuts nothing.         val out = ext(listOf(p(0, 0), p(1, 0), p(1, 1)), p(2, 2), owners = mapOf(p(2, 1) to 1))         assertEquals(listOf(p(0, 0), p(1, 0), p(1, 1), p(1, 2), p(2, 2)), out)     }@@ -56,11 +56,11 @@ class StrokeRulesTest {         assertEquals(path, ext(path, p(2, 2)))     } -    @Test fun foreignEndpointsAndOwnedCellsBlock() {+    @Test fun foreignEndpointsBlockButOtherLinesDoNot() {         assertEquals(listOf(p(0, 3)), StrokeRules.extend(level, emptyMap(), 0, listOf(p(0, 3)), p(0, 4)))-        assertEquals(listOf(p(0, 0)), ext(listOf(p(0, 0)), p(0, 1), owners = mapOf(p(0, 1) to 1)))-        // No route around through a blocked neighbour either-        assertEquals(listOf(p(0, 0)), ext(listOf(p(0, 0)), p(0, 2), owners = mapOf(p(0, 1) to 1)))+        // Running into blue's line is allowed: BoardEdits.applyStroke cuts blue there.+        assertEquals(listOf(p(0, 0), p(0, 1)), ext(listOf(p(0, 0)), p(0, 1), owners = mapOf(p(0, 1) to 1)))+        assertEquals(listOf(p(0, 0), p(0, 1), p(0, 2)), ext(listOf(p(0, 0)), p(0, 2), owners = mapOf(p(0, 1) to 1)))     }      @Test fun completedStrokeStaysPut() {
games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesStrokeTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesStrokeTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesStrokeTest.ktindex d968824336..3604f28eb9 100644--- a/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesStrokeTest.kt+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/platform/PipesStrokeTest.kt@@ -87,4 +87,32 @@ class PipesStrokeTest {         assertEquals(listOf(ep.cells[0]), vm.uiState.value.activePath)         vm.commitDraw()     }++    @Test fun drawingIntoAnotherColourCutsItAndUndoRestoresIt() {+        // 5x5_001:  . 0 1 . 2 / . . 2 . . / . . 1 . . / . . . . . / . . . . 0+        val vm = vm()+        assertEquals("5×5_001", vm.level.id)+        val green = listOf(CellPos(1, 2), CellPos(1, 3), CellPos(1, 4), CellPos(0, 4))+        draw(vm, green)+        assertEquals(green, vm.uiState.value.gameState.paths[2])+        // Red climbs column 4 into green's line at (1,4).+        vm.startDraw(CellPos(4, 4))+        vm.extendPath(CellPos(3, 4)); vm.extendPath(CellPos(2, 4)); vm.extendPath(CellPos(1, 4))+        assertEquals(CellPos(1, 4), vm.uiState.value.activePath.last())+        // The preview already shows green cut just before the crossing...+        assertEquals(green.take(2), vm.uiState.value.gameState.paths[2])+        // ...and backing out restores it while the stroke is still open.+        vm.extendPath(CellPos(2, 4))+        assertEquals(green, vm.uiState.value.gameState.paths[2])+        vm.extendPath(CellPos(1, 4))+        vm.commitDraw()+        assertEquals(green.take(2), vm.uiState.value.gameState.paths[2])+        assertEquals(0, vm.uiState.value.gameState.cellOwner[CellPos(1, 4)])+        assertNull(vm.uiState.value.gameState.cellOwner[CellPos(0, 4)])+        assertEquals(2, vm.getCurrentMoves())+        // The cut is part of the same move: one undo brings green back whole.+        vm.onUndo()+        assertEquals(green, vm.uiState.value.gameState.paths[2])+        assertNull(vm.uiState.value.gameState.paths[0])+    } }