games: nonogram clue greying and auto-crosses
- Commit
b612071959c34e13207905f400bd3d279ada27f1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-26 02:06 UTC (10 days ago)
- Parents
081b96f
Clue numbers now grey out as their runs are satisfied from either end: the pure NonogramClues.greying matches maximal fill runs against the clue prefix (and mirrored suffix) — a run greys only when its length equals the clue exactly, an oversized or mismatched run ends matching from that end, and no middle clue greys on its own; the displayed [0] greys iff the line has zero fills. Rendering consumes this per recomposition (same slot, subdued colour); it is derived state, never persisted. Auto-crosses: when a row/column's placed fills equal its clue sum, every remaining blank cell in the line gets a real cross. A new disjoint autoCrossed set on game state (persisted under its own keys, derived on load for legacy boards) keeps auto crosses distinct from manual ones: re-derivation at the ViewModel commit chokepoint drops auto crosses whose line is incomplete again, never touches manual crosses, noting an auto-crossed cell promotes it to manual, and win detection still checks fills only — auto crosses can never complete or fail a board. Verified: :games:nonogram:testDevUnitTest 146 tests green, :games:nonogram:lint green, :games:nonogram:metadata green with regenerated captures.
Diff
games/nonogram/AGENTS.md
diff --git a/games/nonogram/AGENTS.md b/games/nonogram/AGENTS.mdindex 19f633baea..e3abfb278c 100644--- a/games/nonogram/AGENTS.md+++ b/games/nonogram/AGENTS.md@@ -14,6 +14,8 @@ _Install: ./install games/nonogram (dev by default)._ **Purpose:** Picture-logic puzzles — fill from number clues to reveal the picture; gated levels + shared daily board; every puzzle solvable by reasoning alone. 100% offline. **Game shape:** `ui/` board + settings → `platform/NonogramViewModel` → `domain/` generator + solver → `data/` store; dailies via `:library:work`; achievements → `:sdk:games` → hub. **Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/NonogramGameScreen.kt` → `platform/NonogramViewModel.kt` → `domain/NonogramGenerator.kt`.+**Clue greying:** `domain/NonogramClues.kt` derives per-clue greyed state from the placed fills (display-only, recomputed by `ui/components/BoardClues.kt`, never persisted). A clue greys only as part of an exact prefix/suffix run match.+**Auto-crosses:** When a row/column's placed fills equal its clue sum, `NonogramClues.withAutoCrosses` (applied by the ViewModel on every commit and on load) fills its remaining blank cells into `NonogramGameState.autoCrossed` — real persisted cell state, kept apart from the player's own `crossed` so re-derivation never removes a manual cross. Noting an auto-crossed cell promotes it to a manual cross. **Gotchas:** Solvability-by-reasoning is the guarantee — generator changes must pass the solver check. ## Key files@@ -27,6 +29,9 @@ _Install: ./install games/nonogram (dev by default)._ - com/vayunmathur/games/nonogram/data/NonogramDataStore.kt - com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt - com/vayunmathur/games/nonogram/domain/NonogramSolver.kt+- com/vayunmathur/games/nonogram/domain/NonogramClues.kt+- com/vayunmathur/games/nonogram/domain/NonogramMoves.kt+- com/vayunmathur/games/nonogram/domain/NonogramStrokes.kt ### platform/ — ViewModel + achievements - com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt - com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt@@ -41,6 +46,7 @@ _Install: ./install games/nonogram (dev by default)._ ## Verify (this module only) ``` ./gradlew :games:nonogram:compileDevKotlin+./gradlew :games:nonogram:testDevUnitTest ./gradlew :games:nonogram:lint ./gradlew :games:nonogram:checkMetadata ```
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.ktindex faa58a6ede..95910cee01 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.kt@@ -26,6 +26,7 @@ class NonogramDataStore(private val context: Context) { val filledCells: Flow<Set<Int>> = context.dataStore.data.map { it[FILLED_KEY].toCells() } val crossedCells: Flow<Set<Int>> = context.dataStore.data.map { it[CROSSED_KEY].toCells() }+ val autoCrossedCells: Flow<Set<Int>> = context.dataStore.data.map { it[AUTO_CROSSED_KEY].toCells() } val revealedBlanks: Flow<Set<Int>> = context.dataStore.data.map { it[REVEALED_KEY].toCells() } val hearts: Flow<Int> = context.dataStore.data.map { it[HEARTS_KEY] ?: STARTING_HEARTS } @@ -50,6 +51,8 @@ class NonogramDataStore(private val context: Context) { context.dataStore.data.map { it[DAILY_FILLED_KEY].toCells() } val dailyCrossedCells: Flow<Set<Int>> = context.dataStore.data.map { it[DAILY_CROSSED_KEY].toCells() }+ val dailyAutoCrossedCells: Flow<Set<Int>> =+ context.dataStore.data.map { it[DAILY_AUTO_CROSSED_KEY].toCells() } val dailyRevealedBlanks: Flow<Set<Int>> = context.dataStore.data.map { it[DAILY_REVEALED_KEY].toCells() } val dailyHearts: Flow<Int> =@@ -74,6 +77,7 @@ class NonogramDataStore(private val context: Context) { prefs[LEVEL_KEY] = level prefs[FILLED_KEY] = emptySet() prefs[CROSSED_KEY] = emptySet()+ prefs[AUTO_CROSSED_KEY] = emptySet() prefs[REVEALED_KEY] = emptySet() prefs[HEARTS_KEY] = STARTING_HEARTS }@@ -90,6 +94,7 @@ class NonogramDataStore(private val context: Context) { StoredBoard( filled = prefs[if (daily) DAILY_FILLED_KEY else FILLED_KEY].toCells(), crossed = prefs[if (daily) DAILY_CROSSED_KEY else CROSSED_KEY].toCells(),+ autoCrossed = prefs[if (daily) DAILY_AUTO_CROSSED_KEY else AUTO_CROSSED_KEY].toCells(), revealed = prefs[if (daily) DAILY_REVEALED_KEY else REVEALED_KEY].toCells(), hearts = prefs[if (daily) DAILY_HEARTS_KEY else HEARTS_KEY] ?: STARTING_HEARTS, )@@ -110,6 +115,7 @@ class NonogramDataStore(private val context: Context) { if (!daily && (prefs[LEVEL_KEY] ?: 1) != level) return@edit prefs[if (daily) DAILY_FILLED_KEY else FILLED_KEY] = board.filled.toStrings() prefs[if (daily) DAILY_CROSSED_KEY else CROSSED_KEY] = board.crossed.toStrings()+ prefs[if (daily) DAILY_AUTO_CROSSED_KEY else AUTO_CROSSED_KEY] = board.autoCrossed.toStrings() prefs[if (daily) DAILY_REVEALED_KEY else REVEALED_KEY] = board.revealed.toStrings() prefs[if (daily) DAILY_HEARTS_KEY else HEARTS_KEY] = board.hearts }@@ -152,6 +158,7 @@ class NonogramDataStore(private val context: Context) { prefs[DAILY_DAY_KEY] = day prefs[DAILY_FILLED_KEY] = emptySet() prefs[DAILY_CROSSED_KEY] = emptySet()+ prefs[DAILY_AUTO_CROSSED_KEY] = emptySet() prefs[DAILY_REVEALED_KEY] = emptySet() prefs[DAILY_HEARTS_KEY] = STARTING_HEARTS }@@ -161,6 +168,7 @@ class NonogramDataStore(private val context: Context) { val LEVEL_KEY = intPreferencesKey("current_level") val FILLED_KEY = stringSetPreferencesKey("filled_cells") val CROSSED_KEY = stringSetPreferencesKey("crossed_cells")+ val AUTO_CROSSED_KEY = stringSetPreferencesKey("auto_crossed_cells") val REVEALED_KEY = stringSetPreferencesKey("revealed_blanks") val HEARTS_KEY = intPreferencesKey("hearts") val GAME_MODE_KEY = stringPreferencesKey("game_mode")@@ -171,6 +179,7 @@ class NonogramDataStore(private val context: Context) { val DAILY_DAY_KEY = longPreferencesKey("daily_day") val DAILY_FILLED_KEY = stringSetPreferencesKey("daily_filled_cells") val DAILY_CROSSED_KEY = stringSetPreferencesKey("daily_crossed_cells")+ val DAILY_AUTO_CROSSED_KEY = stringSetPreferencesKey("daily_auto_crossed_cells") val DAILY_REVEALED_KEY = stringSetPreferencesKey("daily_revealed_blanks") val DAILY_HEARTS_KEY = intPreferencesKey("daily_hearts") @@ -185,6 +194,8 @@ data class StoredBoard( val crossed: Set<Int> = emptySet(), val revealed: Set<Int> = emptySet(), val hearts: Int = STARTING_HEARTS,+ /** Crosses the game derived, persisted apart from the player's own [crossed]. */+ val autoCrossed: Set<Int> = emptySet(), ) /** Cell indices are stored as strings because DataStore has no int-set type. */
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.ktindex fca65f33e6..9681a542e7 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.kt@@ -14,10 +14,12 @@ enum class GameMode { CASUAL, DAILY } /** * What a cell shows. *- * [CROSSED] is the player's own "definitely blank" note. It is bookkeeping only — the win check looks- * at [FILLED] alone — but it is how a nonogram is actually solved, so it has to persist alongside the- * fills. [REVEALED] is a blank the game exposed after a wrong guess; it is drawn differently from a- * note so the player can tell their own working from the cells their mistakes paid for.+ * [CROSSED] is a "definitely blank" mark, whether the player placed it or the game derived it+ * automatically (see [NonogramGameState.autoCrossed]); the two draw the same and are told apart by+ * which set holds the cell. It is bookkeeping only — the win check looks at [FILLED] alone — but it+ * is how a nonogram is actually solved, so it has to persist alongside the fills. [REVEALED] is a+ * blank the game exposed after a wrong guess; it is drawn differently from a note so the player can+ * tell their own working from the cells their mistakes paid for. */ enum class CellMark { BLANK, FILLED, CROSSED, REVEALED } @@ -35,11 +37,17 @@ const val STARTING_HEARTS = 3 /** * A puzzle plus the player's work on it. *- * The three cell sets are disjoint and mean different things:+ * The four cell sets are disjoint and mean different things: * - [filled] is part of the picture. A fill only ever lands on a cell that belongs, so this is always * a subset of the solution and there is no "wrong cell" state to draw. * - [crossed] is the player's own note that a cell looks empty. Free to place and to take back, and * never checked against the solution — being wrong in a note is not a guess worth punishing.+ * - [autoCrossed] is a cross the game derived: every still-blank cell of a row or column whose+ * clue fills are all placed. It draws exactly like [crossed], but the game owns it — it is+ * re-derived from the fills (see `NonogramClues.withAutoCrosses`), removed when the fills no+ * longer justify it, and persisted separately so that removal can never take a player's own+ * cross with it. Deliberately placing a cross on an auto-crossed cell promotes it into+ * [crossed], from which point it is the player's to keep. * - [revealedBlanks] is a cell the game has *told* the player is empty, after a wrong guess cost a * heart. It draws as a distinct error-coloured cross and cannot be cleared, which is what stops * the same cell being charged for twice.@@ -56,6 +64,7 @@ data class NonogramGameState( val mode: GameMode, val level: Int, val elapsedSeconds: Int = 0,+ val autoCrossed: Set<Int> = emptySet(), ) { val size: Int get() = puzzle.size @@ -63,9 +72,16 @@ data class NonogramGameState( index in filled -> CellMark.FILLED index in revealedBlanks -> CellMark.REVEALED index in crossed -> CellMark.CROSSED+ index in autoCrossed -> CellMark.CROSSED else -> CellMark.BLANK } + /** Whether [index] carries the player's own cross (as opposed to an automatic one). */+ fun isManuallyCrossed(index: Int): Boolean = index in crossed++ /** Whether [index] carries a cross the game derived and may still take back. */+ fun isAutoCrossed(index: Int): Boolean = index in autoCrossed+ /** * Whether [index] is settled and no longer takes input. *
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramClues.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramClues.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramClues.ktnew file mode 100644index 0000000000..21ad851c98--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramClues.kt@@ -0,0 +1,159 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.CellMark+import com.vayunmathur.games.nonogram.data.NonogramGameState++/**+ * Which numbers of one line's clue are already accounted for by the fills at that end+ * of the line.+ *+ * [prefixMatched] and [suffixMatched] are counted independently from their own end,+ * so on a completely matched line they can overlap over the same middle clue(s);+ * [greyed] is the union and is what the UI renders. A clue is only ever greyed as+ * part of a matched prefix or suffix — a run in the middle of the line never greys+ * a clue on its own.+ */+data class ClueGreying(+ val prefixMatched: Int,+ val suffixMatched: Int,+ val greyed: List<Boolean>,+) {+ /** Whether clue [index] is greyed; out-of-range indices are not. */+ fun isGreyed(index: Int): Boolean = greyed.getOrElse(index) { false }+}++/**+ * Clue greying and auto-cross derivation: pure line logic over the marks already+ * placed, with no knowledge of the solution beyond the clues themselves.+ *+ * Greying rule (exact): walking in from an end of the line, skipping non-filled+ * cells, each maximal run of filled cells must have exactly the length of the+ * next unmet clue from that end. Because the run is maximal, it is terminated by+ * construction — the cell after it is crossed, blank, revealed or the line edge,+ * never another fill; a longer run is one oversized run, not a matched clue plus+ * extra fills, and stops the match at that end. The first run whose length+ * differs (too short or too long) ends the prefix/suffix: it and everything+ * beyond it stays un-greyed from that end.+ */+object NonogramClues {++ /** Greying for [clues] over a line of cell [marks]; only filled cells form runs. */+ fun greying(clues: List<Int>, marks: List<CellMark>): ClueGreying =+ greyingFromFilled(clues, marks.map { it == CellMark.FILLED })++ /**+ * Greying for [clues] over a line where [filled] says which cells are filled.+ *+ * An empty clue list has nothing to grey. The displayed `0` clue (used for an+ * empty line in the UI) greys exactly when the line holds no fill at all.+ */+ fun greyingFromFilled(clues: List<Int>, filled: List<Boolean>): ClueGreying {+ if (clues.isEmpty()) return ClueGreying(0, 0, emptyList())+ if (clues == listOf(0)) {+ val matched = filled.none { it }+ val count = if (matched) 1 else 0+ return ClueGreying(count, count, listOf(matched))+ }+ val prefix = countPrefix(clues, filled)+ val suffix = countSuffix(clues, filled)+ return ClueGreying(+ prefixMatched = prefix,+ suffixMatched = suffix,+ greyed = List(clues.size) { i -> i < prefix || i >= clues.size - suffix },+ )+ }++ /** How many leading clues the runs from the start of the line match exactly. */+ private fun countPrefix(clues: List<Int>, filled: List<Boolean>): Int {+ var clueIndex = 0+ var pos = 0+ while (clueIndex < clues.size) {+ while (pos < filled.size && !filled[pos]) pos+++ if (pos >= filled.size) break+ val start = pos+ while (pos < filled.size && filled[pos]) pos+++ if (pos - start != clues[clueIndex]) break+ clueIndex+++ }+ return clueIndex+ }++ /** How many trailing clues the runs from the end of the line match exactly. */+ private fun countSuffix(clues: List<Int>, filled: List<Boolean>): Int {+ var clueIndex = clues.lastIndex+ var pos = filled.lastIndex+ var matched = 0+ while (clueIndex >= 0) {+ while (pos >= 0 && !filled[pos]) pos--+ if (pos < 0) break+ val end = pos+ while (pos >= 0 && filled[pos]) pos--+ if (end - pos != clues[clueIndex]) break+ matched+++ clueIndex--+ }+ return matched+ }++ /** Greying for row [row] of [game], in clue order. */+ fun rowGreying(game: NonogramGameState, row: Int): ClueGreying {+ val n = game.size+ return greying(game.puzzle.rowClues[row], (0 until n).map { game.markAt(row * n + it) })+ }++ /** Greying for column [col] of [game], in clue order. */+ fun colGreying(game: NonogramGameState, col: Int): ClueGreying {+ val n = game.size+ return greying(game.puzzle.colClues[col], (0 until n).map { game.markAt(it * n + col) })+ }++ /**+ * Whether every fill a line's clue requires is placed in it.+ *+ * The clue sum is the requirement: an empty clue (or the displayed `0`)+ * requires no fills, so such a line is complete from the start.+ */+ fun isLineComplete(clues: List<Int>, filledCount: Int): Boolean = filledCount == clues.sum()++ /**+ * The cells that should currently carry an automatic cross on [game]: every+ * still-blank cell of every fill-complete row or column. Cells that are+ * filled, revealed, or carry the player's own cross are never included.+ */+ fun autoCrossedCells(game: NonogramGameState): Set<Int> {+ val n = game.size+ val rowComplete = (0 until n).map { row ->+ isLineComplete(+ game.puzzle.rowClues[row],+ (0 until n).count { (row * n + it) in game.filled },+ )+ }+ val colComplete = (0 until n).map { col ->+ isLineComplete(+ game.puzzle.colClues[col],+ (0 until n).count { (it * n + col) in game.filled },+ )+ }+ return (0 until n * n).filterTo(mutableSetOf()) { index ->+ val row = index / n+ val col = index % n+ (rowComplete[row] || colComplete[col]) &&+ index !in game.filled &&+ index !in game.revealedBlanks &&+ index !in game.crossed+ }+ }++ /**+ * [game] with its automatic crosses re-derived from scratch.+ *+ * Recomputing the whole set — rather than only adding new crosses — is what+ * removes an auto-cross when a fill that justified it is undone, while a+ * manual cross survives because it is never part of this set. The result is+ * idempotent: applying it to its own output returns the same instance.+ */+ fun withAutoCrosses(game: NonogramGameState): NonogramGameState {+ val desired = autoCrossedCells(game)+ return if (desired == game.autoCrossed) game else game.copy(autoCrossed = desired)+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.ktindex ad3be85843..be5c0bda2d 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt@@ -21,21 +21,36 @@ object NonogramMoves { fun guess(game: NonogramGameState, index: Int): NonogramGameState { if (game.isOver || game.isLocked(index)) return game return if (game.belongsToPicture(index)) {- game.copy(filled = game.filled + index, crossed = game.crossed - index)+ game.copy(+ filled = game.filled + index,+ crossed = game.crossed - index,+ autoCrossed = game.autoCrossed - index,+ ) } else { game.copy( revealedBlanks = game.revealedBlanks + index, crossed = game.crossed - index,+ autoCrossed = game.autoCrossed - index, hearts = (game.hearts - 1).coerceAtLeast(0), ) } } - /** Places ([crossed] true) or removes the player's own "looks empty" note. Never costs a heart. */+ /**+ * Places ([crossed] true) or removes the player's own "looks empty" note. Never costs a heart.+ *+ * Placing a note on an auto-crossed cell promotes that cross to the player's own: it moves+ * from `autoCrossed` into `crossed`, so the auto-cross derivation can no longer take it back.+ * Removing a note removes both kinds at this level; the ViewModel's re-derivation then puts+ * an auto-cross straight back if the line still justifies it, so an automatic cross cannot+ * be cleared while its line is complete — only a manual one can.+ */ fun setNote(game: NonogramGameState, index: Int, crossed: Boolean): NonogramGameState { if (game.isOver || game.isLocked(index)) return game val notes = if (crossed) game.crossed + index else game.crossed - index- return if (notes == game.crossed) game else game.copy(crossed = notes)+ val auto = game.autoCrossed - index+ return if (notes == game.crossed && auto == game.autoCrossed) game+ else game.copy(crossed = notes, autoCrossed = auto) } /**@@ -50,9 +65,12 @@ object NonogramMoves { current.copy( filled = before.filled - current.revealedBlanks, crossed = before.crossed - current.revealedBlanks,+ // Auto crosses from before the stroke are restored as they were; the caller+ // re-derives them, which drops any whose justifying fill the undo removed.+ autoCrossed = before.autoCrossed - current.revealedBlanks, ) /** Flips the note on [index]: the single-tap behaviour of cross mode. */ fun toggleNote(game: NonogramGameState, index: Int): NonogramGameState =- setNote(game, index, crossed = index !in game.crossed)+ setNote(game, index, crossed = index !in game.crossed && index !in game.autoCrossed) }
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.ktindex 90a868e185..6f7c81e20b 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.kt@@ -64,7 +64,13 @@ data class StrokeStep(val game: NonogramGameState, val stroke: Stroke) */ object NonogramStrokes { - /** The action a stroke would take if it started on [index], or null if that cell takes no input. */+ /**+ * The action a stroke would take if it started on [index], or null if that cell takes no input.+ *+ * In cross mode a manual cross clears, while an auto-crossed cell crosses: placing a+ * note there promotes the automatic cross to the player's own (see [NonogramMoves.setNote])+ * rather than clearing a cross the game will immediately re-derive.+ */ fun actionFor(game: NonogramGameState, index: Int, mode: MarkMode): StrokeAction? = when { game.isLocked(index) -> null mode == MarkMode.FILL -> StrokeAction.FILL@@ -115,9 +121,15 @@ object NonogramStrokes { when (action) { StrokeAction.FILL -> if (deciding || game.markAt(index) == CellMark.BLANK) NonogramMoves.guess(game, index) else game- StrokeAction.CROSS ->- if (game.markAt(index) == CellMark.BLANK) NonogramMoves.setNote(game, index, true) else game+ StrokeAction.CROSS -> when {+ game.markAt(index) == CellMark.BLANK -> NonogramMoves.setNote(game, index, true)+ // Already crossed, but only automatically: this stroke's note promotes it.+ game.isAutoCrossed(index) && !game.isManuallyCrossed(index) ->+ NonogramMoves.setNote(game, index, true)+ else -> game+ } StrokeAction.CLEAR ->- if (game.markAt(index) == CellMark.CROSSED) NonogramMoves.setNote(game, index, false) else game+ // Only the player's own crosses clear; an auto-cross is the game's to remove.+ if (game.isManuallyCrossed(index)) NonogramMoves.setNote(game, index, false) else game } }
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.ktindex c7a99b6b13..62d866e017 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt@@ -13,6 +13,7 @@ import com.vayunmathur.games.nonogram.data.NonogramPuzzle import com.vayunmathur.games.nonogram.data.STARTING_HEARTS import com.vayunmathur.games.nonogram.data.StoredBoard import com.vayunmathur.games.nonogram.data.sizeForLevel+import com.vayunmathur.games.nonogram.domain.NonogramClues import com.vayunmathur.games.nonogram.domain.NonogramGenerator import com.vayunmathur.games.nonogram.domain.NonogramMoves import com.vayunmathur.games.nonogram.domain.NonogramStrokes@@ -192,14 +193,21 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application hearts = board.hearts, mode = session.mode, level = session.level,+ autoCrossed = board.autoCrossed, )- var game = stored+ // Boards saved before auto-crosses existed (or by any path that did not+ // derive them) gain the crosses their fills already justify on load.+ val derived = NonogramClues.withAutoCrosses(stored)+ var game = derived // Compare-and-set, so a move committed while this emission was in flight is never // overwritten by the older stored board: the retry sees it, and its pending write. _uiState.update { state ->- game = state.game?.takeIf { hasPendingWrites && it.isBoardFor(session, puzzle) } ?: stored+ game = state.game?.takeIf { hasPendingWrites && it.isBoardFor(session, puzzle) } ?: derived state.copy(game = game, generating = false, dailyDone = dailyDone, canUndo = canUndo(game)) }+ // Persist a load-time derivation, so the crosses on screen are the+ // crosses on disk even if no further move is made.+ if (game == derived && derived != stored) persist(derived) if (game.isWon) onWin(game, daily, day) } }@@ -231,16 +239,20 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application * costs one or two disk writes rather than one each. */ private fun commit(next: NonogramGameState) {+ // Every move flows through here, so this is where auto-crosses are+ // re-derived: real cell state (win checks, persistence and the board+ // all see the same crosses), never a drawing-only overlay.+ val derived = NonogramClues.withAutoCrosses(next) val previous = _uiState.value.game ?: return- if (next == previous) return- _uiState.update { it.copy(game = next, canUndo = canUndo(next)) }- persist(next)- if (next.isWon) onWin(next, next.mode == GameMode.DAILY, boardDay)+ if (derived == previous) return+ _uiState.update { it.copy(game = derived, canUndo = canUndo(derived)) }+ persist(derived)+ if (derived.isWon) onWin(derived, derived.mode == GameMode.DAILY, boardDay) } private fun persist(game: NonogramGameState) { val ticket = requestedWrite.incrementAndGet()- val board = StoredBoard(game.filled, game.crossed, game.revealedBlanks, game.hearts)+ val board = StoredBoard(game.filled, game.crossed, game.revealedBlanks, game.hearts, game.autoCrossed) val daily = game.mode == GameMode.DAILY val day = boardDay // Off the main thread: the board is already on screen, so nothing waits for this, and the@@ -321,7 +333,8 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application // Only strokes that changed a fill or a note are worth undoing; one that only revealed a // mistake has nothing undo could give back. if (before == null || after == null) return- if (before.filled == after.filled && before.crossed == after.crossed) return+ if (before.filled == after.filled && before.crossed == after.crossed &&+ before.autoCrossed == after.autoCrossed) return undoStack.addLast(before) while (undoStack.size > MAX_UNDO) undoStack.removeFirst() _uiState.value = _uiState.value.copy(canUndo = canUndo(after))@@ -379,6 +392,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application filled = emptySet(), crossed = emptySet(), revealedBlanks = emptySet(),+ autoCrossed = emptySet(), hearts = STARTING_HEARTS, ) )
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.ktindex 8477782a15..6430c1912f 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt@@ -265,7 +265,7 @@ private fun NonogramControls( // Restart clears every mark, so only ask when there is something to lose: // an untouched board restarts into itself. val hasProgress = game.filled.isNotEmpty() || game.crossed.isNotEmpty() ||- game.revealedBlanks.isNotEmpty()+ game.autoCrossed.isNotEmpty() || game.revealedBlanks.isNotEmpty() when { game.isWon -> { Text(@@ -304,7 +304,7 @@ private fun NonogramControls( else -> { MarkModeToggle(state.markMode, actions::setMarkMode) if (game.filled.isEmpty() && game.crossed.isEmpty() &&- game.revealedBlanks.isEmpty()+ game.autoCrossed.isEmpty() && game.revealedBlanks.isEmpty() ) { Text( // Follows the toggle: in Cross mode a tap crosses and a long press fills.
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.ktindex 0713d192ad..0e275d6711 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt@@ -46,14 +46,17 @@ internal data class CellLabels( } /** What a tap (TalkBack double tap) does: the mode's own mark. */- fun tapLabel(mark: CellMark, mode: MarkMode): String =- if (mode == MarkMode.FILL) fill else noteLabel(mark)+ fun tapLabel(mark: CellMark, mode: MarkMode, autoCrossed: Boolean = false): String =+ if (mode == MarkMode.FILL) fill else noteLabel(mark, autoCrossed) /** What a long press (TalkBack double tap and hold) does: the other mark. */- fun longPressLabel(mark: CellMark, mode: MarkMode): String =- if (mode == MarkMode.FILL) noteLabel(mark) else fill+ fun longPressLabel(mark: CellMark, mode: MarkMode, autoCrossed: Boolean = false): String =+ if (mode == MarkMode.FILL) noteLabel(mark, autoCrossed) else fill - private fun noteLabel(mark: CellMark) = if (mark == CellMark.CROSSED) uncross else cross+ // An auto-cross is not the player's to uncross: the note action on it+ // promotes it to the player's own cross instead.+ private fun noteLabel(mark: CellMark, autoCrossed: Boolean = false) =+ if (mark == CellMark.CROSSED && !autoCrossed) uncross else cross } /** Zero-based row and column, kept together so the cell signature stays short. */
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.ktindex c7edea9b4a..177c54181d 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt@@ -21,6 +21,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.TextUnit import com.vayunmathur.games.nonogram.data.NonogramGameState+import com.vayunmathur.games.nonogram.domain.NonogramClues import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import kotlin.math.roundToInt@@ -57,15 +58,26 @@ internal fun ColumnClues( ) { ZoomedLine(horizontal = true, zoom = zoom) { for (col in 0 until game.size) {- val clues = game.puzzle.colClues[col]+ val displayed = game.puzzle.colClues[col].ifEmpty { listOf(0) }+ // Display-only derived state: recomputed from the placed fills on+ // every recomposition, never stored on the game state.+ val greying = NonogramClues.greying(+ displayed,+ (0 until game.size).map { game.markAt(it * game.size + col) },+ ) Column( Modifier.size(metrics.cell, metrics.clueCell * gutterCells), // Bottom-aligned so the last clue sits against the grid it describes. verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.CenterHorizontally, ) {- for (clue in clues.ifEmpty { listOf(0) }) {- ClueText(clue, metrics, Modifier.size(metrics.cell, metrics.clueCell))+ displayed.forEachIndexed { index, clue ->+ ClueText(+ clue,+ metrics,+ Modifier.size(metrics.cell, metrics.clueCell),+ greyed = greying.isGreyed(index),+ ) } } }@@ -82,15 +94,24 @@ internal fun RowClues( ) { ZoomedLine(horizontal = false, zoom = zoom) { for (row in 0 until game.size) {- val clues = game.puzzle.rowClues[row]+ val displayed = game.puzzle.rowClues[row].ifEmpty { listOf(0) }+ val greying = NonogramClues.greying(+ displayed,+ (0 until game.size).map { game.markAt(row * game.size + it) },+ ) Row( Modifier.size(metrics.clueCell * gutterCells, metrics.cell), // End-aligned for the same reason: the final clue abuts the grid. horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically, ) {- for (clue in clues.ifEmpty { listOf(0) }) {- ClueText(clue, metrics, Modifier.size(metrics.clueCell, metrics.cell))+ displayed.forEachIndexed { index, clue ->+ ClueText(+ clue,+ metrics,+ Modifier.size(metrics.clueCell, metrics.cell),+ greyed = greying.isGreyed(index),+ ) } } }@@ -131,6 +152,7 @@ private fun ClueText( clue: Int, metrics: ClueMetrics, modifier: Modifier = Modifier,+ greyed: Boolean = false, ) { Box(modifier, contentAlignment = Alignment.Center) { Text(@@ -141,8 +163,12 @@ private fun ClueText( softWrap = false, fontWeight = FontWeight.Medium, textAlign = TextAlign.Center,- color = if (clue == 0) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)- else MaterialTheme.colorScheme.onSurface,+ // Greyed numbers keep their slot and size; only the colour subdues.+ color = if (clue == 0 || greyed) {+ MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)+ } else {+ MaterialTheme.colorScheme.onSurface+ }, overflow = TextOverflow.Ellipsis, ) }
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.ktindex dcfa000269..5e7e414741 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt@@ -206,8 +206,10 @@ private fun Grid( index = index, position = CellPosition(row, col), stateWord = labels.wordFor(mark),- tapLabel = labels.tapLabel(mark, markMode).takeIf { actionable },- longPressLabel = labels.longPressLabel(mark, markMode).takeIf { actionable },+ tapLabel = labels.tapLabel(mark, markMode, game.isAutoCrossed(index))+ .takeIf { actionable },+ longPressLabel = labels.longPressLabel(mark, markMode, game.isAutoCrossed(index))+ .takeIf { actionable }, onTap = tap, onLongPress = longPress, modifier = Modifier.size(cell),
games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.kt
diff --git a/games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.kt b/games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.ktindex cf27b678bd..f191864218 100644--- a/games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.kt+++ b/games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.kt@@ -9,6 +9,7 @@ import com.vayunmathur.games.nonogram.data.NonogramGameState import com.vayunmathur.games.nonogram.data.NonogramPuzzle import com.vayunmathur.games.nonogram.data.STARTING_HEARTS import com.vayunmathur.games.nonogram.data.sizeForLevel+import com.vayunmathur.games.nonogram.domain.NonogramClues import com.vayunmathur.games.nonogram.domain.NonogramGenerator import com.vayunmathur.games.nonogram.platform.NonogramGameActions import com.vayunmathur.games.nonogram.platform.NonogramUiState@@ -96,13 +97,16 @@ class MetadataPreviews { @Composable private fun Board(game: NonogramGameState, streak: Long = 0) {+ // The same derivation the ViewModel applies to every move, so the+ // listing board carries the auto-crosses a played board would.+ val derived = NonogramClues.withAutoCrosses(game) // Layoutlib has no wallpaper to sample, so Material You falls back to the default palette. DynamicTheme(darkTheme = true) { NonogramGameScreen( state = NonogramUiState(- game = game,- mode = game.mode,- level = game.level,+ game = derived,+ mode = derived.mode,+ level = derived.level, dailyStreak = streak, ), actions = NonogramGameActions.Noop,
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramDataStoreTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramDataStoreTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramDataStoreTest.ktindex 73892c66c9..c96fd4c713 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramDataStoreTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramDataStoreTest.kt@@ -29,26 +29,28 @@ class NonogramDataStoreTest { s.setMarkMode(MarkMode.FILL) } - private fun board(filled: Set<Int> = emptySet(), crossed: Set<Int> = emptySet(), revealed: Set<Int> = emptySet(), hearts: Int = STARTING_HEARTS) =- StoredBoard(filled, crossed, revealed, hearts)+ private fun board(filled: Set<Int> = emptySet(), crossed: Set<Int> = emptySet(), revealed: Set<Int> = emptySet(), hearts: Int = STARTING_HEARTS, auto: Set<Int> = emptySet()) =+ StoredBoard(filled, crossed, revealed, hearts, auto) @Test fun saveLevelWipesBoardAndRestoresHearts() = runBlocking { val s = store(); s.saveLevel(6)- s.saveBoard(board(setOf(3), setOf(4), setOf(5), STARTING_HEARTS - 1), daily = false, level = 6, day = 0L)+ s.saveBoard(board(setOf(3), setOf(4), setOf(5), STARTING_HEARTS - 1, auto = setOf(8)), daily = false, level = 6, day = 0L) assertEquals(STARTING_HEARTS - 1, s.hearts.first()) s.saveLevel(7) assertEquals(7, s.currentLevel.first()) assertEquals(emptySet(), s.filledCells.first()) assertEquals(emptySet(), s.crossedCells.first())+ assertEquals(emptySet(), s.autoCrossedCells.first()) assertEquals(emptySet(), s.revealedBlanks.first()) assertEquals(STARTING_HEARTS, s.hearts.first()) } @Test fun saveBoardRoundTripsAsOneSnapshot() = runBlocking { val s = store(); s.saveLevel(2)- val b = board(setOf(1, 2), setOf(7), setOf(9), 1)+ val b = board(setOf(1, 2), setOf(7), setOf(9), 1, auto = setOf(11)) s.saveBoard(b, daily = false, level = 2, day = 0L) assertEquals(b, s.board(daily = false).first())+ assertEquals(setOf(11), s.autoCrossedCells.first(), "auto crosses persist apart from manual ones") assertEquals(setOf(1, 2), s.filledCells.first()); assertEquals(1, s.hearts.first()) }
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.ktindex 77a45b144d..88c856473f 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.kt@@ -21,6 +21,7 @@ class NonogramGameStateTest { crossed: Set<Int> = emptySet(), revealedBlanks: Set<Int> = emptySet(), hearts: Int = STARTING_HEARTS,+ autoCrossed: Set<Int> = emptySet(), ) = NonogramGameState( puzzle = cross, filled = filled,@@ -29,6 +30,7 @@ class NonogramGameStateTest { hearts = hearts, mode = GameMode.CASUAL, level = 1,+ autoCrossed = autoCrossed, ) /** Indices of the cells that make up the picture. */@@ -93,6 +95,18 @@ class NonogramGameStateTest { assertTrue(s.isLocked(blankCell), "a cell the game revealed cannot be charged for twice") } + @Test+ fun anAutoCrossDrawsAsACrossButIsNotThePlayersOwn() {+ val s = state(autoCrossed = setOf(blankCell))+ assertEquals(CellMark.CROSSED, s.markAt(blankCell), "auto crosses draw like any cross")+ assertTrue(s.isAutoCrossed(blankCell))+ assertFalse(s.isManuallyCrossed(blankCell))+ assertFalse(s.isLocked(blankCell), "only fills and revealed blanks are locked")+ assertFalse(state(filled = answer, autoCrossed = setOf(blankCell)).isFailed)+ assertTrue(state(filled = answer, autoCrossed = setOf(blankCell)).isWon,+ "auto crosses do not affect the win check either")+ }+ @Test fun aPlayerNoteIsNotLocked() { // Notes stay reversible; only what the game has settled is locked.
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramCluesTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramCluesTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramCluesTest.ktnew file mode 100644index 0000000000..02e7a1da7e--- /dev/null+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramCluesTest.kt@@ -0,0 +1,260 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.CellMark+import com.vayunmathur.games.nonogram.data.GameMode+import com.vayunmathur.games.nonogram.data.NonogramGameState+import com.vayunmathur.games.nonogram.data.STARTING_HEARTS+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertSame+import kotlin.test.assertTrue++class NonogramCluesTest {++ // # filled, . blank, X player's cross, R revealed blank. X/R/. all terminate+ // a run but none of them is a fill.+ private fun marks(line: String): List<CellMark> = line.map {+ when (it) {+ '#' -> CellMark.FILLED+ 'X' -> CellMark.CROSSED+ 'R' -> CellMark.REVEALED+ else -> CellMark.BLANK+ }+ }++ private fun grey(clues: List<Int>, line: String): ClueGreying =+ NonogramClues.greying(clues, marks(line))++ // 3x3 plus sign: picture cells 1, 3, 4, 5, 7; rows/cols are [1], [3], [1].+ private val plus = puzzle(+ """+ .#.+ ###+ .#.+ """+ )++ private fun state(+ filled: Set<Int> = emptySet(),+ crossed: Set<Int> = emptySet(),+ revealed: Set<Int> = emptySet(),+ auto: Set<Int> = emptySet(),+ ) = NonogramGameState(+ puzzle = plus,+ filled = filled,+ crossed = crossed,+ revealedBlanks = revealed,+ hearts = STARTING_HEARTS,+ mode = GameMode.CASUAL,+ level = 1,+ autoCrossed = auto,+ )++ // ---- Greying: prefix ----++ @Test fun emptyLineGreysNothing() {+ val g = grey(listOf(2, 1), ".....")+ assertEquals(0, g.prefixMatched); assertEquals(0, g.suffixMatched)+ assertEquals(listOf(false, false), g.greyed)+ }++ @Test fun exactPrefixRunGreysFirstClueOnly() {+ // Two fills closed by a blank match "2"; the trailing "1" has no run yet.+ val g = grey(listOf(2, 1), "##...")+ assertEquals(1, g.prefixMatched); assertEquals(listOf(true, false), g.greyed)+ }++ @Test fun prefixSkipsLeadingNonFillsAndAnyNonFillTerminates() {+ // Cross, revealed and blank separators all leave the run closed.+ assertEquals(listOf(true, false), grey(listOf(2, 1), "X##..").greyed)+ assertEquals(listOf(true, false), grey(listOf(2, 1), ".##R.").greyed)+ assertTrue(grey(listOf(2), "##").isGreyed(0), "the line edge terminates a run")+ }++ @Test fun incompleteRunGreysNothing() {+ // The lone run of 1 matches neither the leading 2 nor the trailing 3.+ assertEquals(listOf(false, false), grey(listOf(2, 3), "#....").greyed)+ }++ @Test fun oversizedRunIsNotAMatchedCluePlusExtra() {+ // One run of three is not a "2" with a fill left over.+ val g = grey(listOf(2, 1), "###..")+ assertEquals(0, g.prefixMatched); assertEquals(listOf(false, false), g.greyed)+ }++ @Test fun wrongFirstRunLengthBlocksTheWholePrefix() {+ // First run is 1, not 2: nothing from the start greys, even though a+ // later run happens to be 2 long.+ assertEquals(listOf(false, false), grey(listOf(2, 1), "#.##.").greyed)+ }++ @Test fun mergedRunsDoNotMatchSeparateClues() {+ // "###" is a single run of 3, never a 2 followed by a 1.+ assertEquals(listOf(false, false), grey(listOf(2, 1), "###").greyed)+ }++ // ---- Greying: suffix ----++ @Test fun suffixOnlyMatchGreysLastClue() {+ // The first run (1) does not match the leading 2, so only the end greys.+ val g = grey(listOf(2, 1), "#...#")+ assertEquals(0, g.prefixMatched); assertEquals(1, g.suffixMatched)+ assertEquals(listOf(false, true), g.greyed)+ }++ @Test fun suffixSkipsTrailingNonFills() {+ assertEquals(listOf(false, true), grey(listOf(2, 1), "#..#X").greyed)+ }++ @Test fun oversizedSuffixRunGreysNothingFromTheEnd() {+ // The final run is 3, not the trailing clue 1.+ val g = grey(listOf(2, 1), "...###")+ assertEquals(0, g.suffixMatched); assertEquals(listOf(false, false), g.greyed)+ }++ @Test fun incompleteSuffixRunGreysNothing() {+ // The lone run of 1 matches neither the leading 3 nor the trailing 2.+ assertEquals(listOf(false, false), grey(listOf(3, 2), "....#").greyed)+ }++ // ---- Greying: both ends, middle, full, zero clue ----++ @Test fun fullyMatchedLineGreysEveryClue() {+ val g = grey(listOf(2, 1), "##.#")+ assertEquals(2, g.prefixMatched); assertEquals(listOf(true, true), g.greyed)+ }++ @Test fun bothEndsCanGreyWithAnUnmatchedMiddle() {+ // Runs are 2, (nothing for the 1), 2: first and last grey, middle does not.+ val g = grey(listOf(2, 1, 2), "##...##")+ assertEquals(1, g.prefixMatched); assertEquals(1, g.suffixMatched)+ assertEquals(listOf(true, false, true), g.greyed, "no speculative middle matching")+ }++ @Test fun bothEndsMeetingInTheMiddleGreyEverything() {+ // Runs 2 then 1 exactly cover [2, 1]; prefix and suffix meet over it.+ val g = grey(listOf(2, 1), "##X#")+ assertEquals(listOf(true, true), g.greyed)+ assertTrue(g.prefixMatched + g.suffixMatched >= 2)+ }++ @Test fun middleRunAloneNeverGreysAMiddleClue() {+ // A lone central run of 1 matches the middle clue's length but is+ // reachable from neither end, so nothing greys.+ val g = grey(listOf(2, 1, 2), "...#...")+ assertEquals(listOf(false, false, false), g.greyed)+ }++ @Test fun zeroAndEmptyClues() {+ assertEquals(emptyList(), grey(emptyList(), "...").greyed)+ assertEquals(emptyList(), grey(emptyList(), "#..").greyed)+ assertEquals(listOf(true), grey(listOf(0), "...").greyed, "no fills: the 0 is accounted for")+ assertEquals(listOf(true), grey(listOf(0), "XXR").greyed)+ assertEquals(listOf(false), grey(listOf(0), "#..").greyed)+ }++ @Test fun playerCrossesDoNotCreateOrExtendRuns() {+ // Crosses around a single fill do not make it a run of 2.+ assertEquals(listOf(false), grey(listOf(2), "X#X").greyed)+ // ...and a cross is a valid separator between two matched runs.+ assertEquals(listOf(true, true), grey(listOf(1, 1), "#X#").greyed)+ }++ @Test fun rowAndColumnGreyingReadTheBoard() {+ val s = state(filled = setOf(3, 4, 5, 1))+ assertEquals(listOf(true), NonogramClues.rowGreying(s, 1).greyed, "row of 3 is filled")+ // Row 0's clue is [1] and its only fill is placed, so it greys too.+ assertEquals(listOf(true), NonogramClues.rowGreying(s, 0).greyed)+ assertEquals(listOf(true), NonogramClues.colGreying(s, 0).greyed, "column 0's only fill is placed")+ assertEquals(listOf(false), NonogramClues.colGreying(s, 1).greyed, "column of 3 has 2 of 3 fills")+ }++ // ---- Auto-crosses ----++ @Test fun noAutoCrossesWhileEveryLineIsIncomplete() {+ assertEquals(emptySet(), NonogramClues.withAutoCrosses(state(filled = setOf(4))).autoCrossed)+ assertEquals(emptySet(), NonogramClues.withAutoCrosses(state()).autoCrossed)+ }++ @Test fun completingALineAutoCrossesItsRemainingBlankCells() {+ // Filling the middle row also completes columns 0 and 2 (clue [1]+ // each), so all four corners auto-cross; column 1 ([3]) is incomplete.+ val s = NonogramClues.withAutoCrosses(state(filled = setOf(3, 4, 5)))+ assertEquals(setOf(0, 2, 6, 8), s.autoCrossed)+ assertEquals(emptySet(), s.crossed, "auto crosses are not the player's crosses")+ for (i in setOf(0, 2, 6, 8)) {+ assertEquals(CellMark.CROSSED, s.markAt(i))+ assertTrue(s.isAutoCrossed(i)); assertFalse(s.isManuallyCrossed(i))+ }+ assertSame(s, NonogramClues.withAutoCrosses(s), "derivation is idempotent")+ }++ @Test fun zeroClueLinesAutoCrossFromTheStart() {+ val striped = puzzle(+ """+ ##.+ ...+ ##.+ """+ )+ val s = NonogramClues.withAutoCrosses(+ NonogramGameState(striped, emptySet(), emptySet(), emptySet(), STARTING_HEARTS, GameMode.CASUAL, 1)+ )+ // Middle row (clue []) and right column (clue []) need no fills.+ assertEquals(setOf(2, 3, 4, 5, 8), s.autoCrossed)+ }++ @Test fun manualAndRevealedCellsAreNeverTurnedIntoAutoCrosses() {+ val s = NonogramClues.withAutoCrosses(+ state(filled = setOf(3, 4, 5), crossed = setOf(0), revealed = setOf(2))+ )+ assertEquals(setOf(6, 8), s.autoCrossed)+ assertEquals(setOf(0), s.crossed, "the player's cross stays the player's")+ assertEquals(CellMark.REVEALED, s.markAt(2))+ }++ @Test fun removingAJustifyingFillRemovesItsAutoCrossesOnly() {+ val derived = NonogramClues.withAutoCrosses(+ state(filled = setOf(3, 4, 5), crossed = setOf(0))+ )+ assertEquals(setOf(2, 6, 8), derived.autoCrossed)+ // Take the left middle fill back: the row and column 0 are incomplete+ // again, so 6 (justified only by them) drops; 2 and 8 stay, because+ // column 2 is still complete. The manual cross at 0 never drops.+ val broken = NonogramClues.withAutoCrosses(derived.copy(filled = derived.filled - 3))+ assertEquals(setOf(2, 8), broken.autoCrossed)+ assertEquals(setOf(0), broken.crossed)+ assertEquals(CellMark.CROSSED, broken.markAt(0))+ assertEquals(CellMark.BLANK, broken.markAt(6))+ }++ @Test fun undoThenRederiveDropsAutoCrosses() {+ val before = state()+ val played = NonogramClues.withAutoCrosses(NonogramMoves.guess(before, 3))+ val swept = NonogramClues.withAutoCrosses(+ NonogramMoves.guess(NonogramMoves.guess(played, 4), 5)+ )+ assertEquals(setOf(0, 2, 6, 8), swept.autoCrossed)+ val undone = NonogramClues.withAutoCrosses(NonogramMoves.undo(swept, before))+ assertEquals(emptySet(), undone.filled)+ assertEquals(emptySet(), undone.autoCrossed)+ }++ @Test fun autoCrossesDoNotWinOrLoseTheGame() {+ val blanks = plus.solution.indices.filterNot { plus.solution[it] }.toSet()+ val won = NonogramClues.withAutoCrosses(state(filled = plus.solution.indices.filter { plus.solution[it] }.toSet()))+ assertTrue(won.isWon); assertEquals(blanks, won.autoCrossed)+ val notWon = NonogramClues.withAutoCrosses(state(filled = setOf(3, 4, 5)))+ assertFalse(notWon.isWon, "auto crosses never substitute for a missing fill")+ assertFalse(notWon.isFailed)+ }++ @Test fun lineCompletionIsExactlyTheClueSum() {+ assertTrue(NonogramClues.isLineComplete(listOf(2, 1), 3))+ assertFalse(NonogramClues.isLineComplete(listOf(2, 1), 2))+ assertFalse(NonogramClues.isLineComplete(listOf(2, 1), 4))+ assertTrue(NonogramClues.isLineComplete(emptyList(), 0))+ assertTrue(NonogramClues.isLineComplete(listOf(0), 0))+ }+}
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.ktindex 1cc6a5bc72..a958579017 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt@@ -48,6 +48,23 @@ class NonogramMovesTest { assertEquals(emptySet(), NonogramMoves.undo(after, before).crossed) } + @Test fun notingAnAutoCrossPromotesItToAManualCross() {+ val auto = game().copy(autoCrossed = setOf(0))+ val promoted = NonogramMoves.setNote(auto, 0, true)+ assertEquals(setOf(0), promoted.crossed); assertEquals(emptySet(), promoted.autoCrossed)+ }++ @Test fun guessingAnAutoCrossedBlankRevealsItAndDropsTheAutoCross() {+ val g = NonogramMoves.guess(game().copy(autoCrossed = setOf(0)), 0)+ assertEquals(setOf(0), g.revealedBlanks); assertEquals(emptySet(), g.autoCrossed)+ assertEquals(STARTING_HEARTS - 1, g.hearts)+ }++ @Test fun toggleNoteTreatsAnAutoCrossAsCrossed() {+ val cleared = NonogramMoves.toggleNote(game().copy(autoCrossed = setOf(0)), 0)+ assertEquals(emptySet(), cleared.crossed); assertEquals(emptySet(), cleared.autoCrossed)+ }+ @Test fun toggleNoteFlipsAndNeverCosts() { val once = NonogramMoves.toggleNote(game(), 4) assertEquals(setOf(4), once.crossed)
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.ktindex 082cd5c2d4..490e5a36d2 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.kt@@ -20,8 +20,8 @@ class NonogramStrokesTest { "#....", ) private val puzzle = NonogramPuzzle.from(5, rows.joinToString("").map { it == '#' })- private fun game(crossed: Set<Int> = emptySet(), filled: Set<Int> = emptySet(), hearts: Int = STARTING_HEARTS) =- NonogramGameState(puzzle, filled, crossed, emptySet(), hearts, GameMode.CASUAL, 1)+ private fun game(crossed: Set<Int> = emptySet(), filled: Set<Int> = emptySet(), hearts: Int = STARTING_HEARTS, auto: Set<Int> = emptySet()) =+ NonogramGameState(puzzle, filled, crossed, emptySet(), hearts, GameMode.CASUAL, 1, autoCrossed = auto) private fun idx(row: Int, col: Int) = row * 5 + col /** Runs a whole stroke: down on [cells].first(), then the finger over each following cell. */@@ -109,6 +109,28 @@ class NonogramStrokesTest { assertNull(NonogramStrokes.actionFor(start, idx(1, 0), MarkMode.CROSS)) } + @Test fun crossModeOnAnAutoCrossPromotesItInsteadOfClearing() {+ val start = game(auto = setOf(idx(3, 1)))+ val s = stroke(start, MarkMode.CROSS, idx(3, 1))+ assertEquals(StrokeAction.CROSS, s.stroke.action)+ assertEquals(setOf(idx(3, 1)), s.game.crossed, "the cross becomes the player's own")+ assertEquals(emptySet(), s.game.autoCrossed)+ }++ @Test fun clearStrokeLeavesAutoCrossesAlone() {+ val start = game(crossed = setOf(idx(3, 1)), auto = setOf(idx(3, 2)))+ val s = stroke(start, MarkMode.CROSS, idx(3, 1), idx(3, 2))+ assertEquals(emptySet(), s.game.crossed)+ assertEquals(setOf(idx(3, 2)), s.game.autoCrossed, "only manual crosses clear")+ }++ @Test fun fillStrokesStepOverAutoCrossesLikeManualOnes() {+ val start = game(auto = setOf(idx(1, 2)))+ val s = stroke(start, MarkMode.FILL, idx(1, 0), idx(1, 4))+ assertEquals(setOf(idx(1, 2)), s.game.autoCrossed)+ assertTrue(idx(1, 2) !in s.game.filled)+ }+ @Test fun nothingHappensOnceTheGameIsOver() { val over = game(hearts = 0) val s = stroke(over, MarkMode.FILL, idx(1, 0), idx(1, 4))
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.ktindex a7ca95f6c4..826d996760 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt@@ -497,6 +497,40 @@ awaitStore("undo persisted") { vm.dataStore.filledCells.first { it.isEmpty() } } } } + @Test fun completingALineAutoCrossesAndPersistsThenUndoRemoves() {+ val vm = loadedVm()+ val g = vm.uiState.value.game!!+ val n = g.size+ // Fill every picture cell of the first row, one tap (stroke) each.+ val rowCells = (0 until n).map { it }+ val pictureInRow = rowCells.filter { g.puzzle.solution[it] }+ assertTrue(pictureInRow.isNotEmpty())+ for (i in pictureInRow) vm.tapCell(i)+ val after = vm.uiState.value.game!!+ val rowBlanks = rowCells.filterNot { g.puzzle.solution[it] }+ assertTrue(rowBlanks.all { it in after.autoCrossed },+ "blank cells of a completed row are auto-crossed: blanks=$rowBlanks auto=${after.autoCrossed}")+ assertTrue(rowBlanks.none { it in after.crossed }, "auto crosses are not manual crosses")+ // Persisted as real cell state under their own key.+ awaitStore("auto crosses persisted") {+ vm.dataStore.autoCrossedCells.first { it == after.autoCrossed }+ }+ // A fresh ViewModel (a relaunch) shows the same crosses on load.+ val reloaded = track(NonogramViewModel(app))+ awaitState("reload shows auto crosses", reloaded) {+ it.game?.autoCrossed == after.autoCrossed && it.game?.filled == after.filled+ }+ // Undoing the last fill breaks the row again, and its auto crosses go.+ vm.undo()+ val undone = vm.uiState.value.game!!+ assertTrue(pictureInRow.last() !in undone.filled)+ assertEquals(+ com.vayunmathur.games.nonogram.domain.NonogramClues.autoCrossedCells(undone),+ undone.autoCrossed,+ "auto crosses left are exactly the ones the remaining fills justify",+ )+ }+ @Test fun retryGenerationReloadsBoard() { val vm = loadedVm() val before = vm.uiState.value.game!!
metadata_data/photos/games-nonogram/phone/1.png
diff --git a/metadata_data/photos/games-nonogram/phone/1.png b/metadata_data/photos/games-nonogram/phone/1.pngindex 6fa79b3e93..10d941e761 100644Binary files a/metadata_data/photos/games-nonogram/phone/1.png and b/metadata_data/photos/games-nonogram/phone/1.png differ
metadata_data/photos/games-nonogram/phone/2.png
diff --git a/metadata_data/photos/games-nonogram/phone/2.png b/metadata_data/photos/games-nonogram/phone/2.pngindex 9002115edf..b4f768e20d 100644Binary files a/metadata_data/photos/games-nonogram/phone/2.png and b/metadata_data/photos/games-nonogram/phone/2.png differ
metadata_data/photos/games-nonogram/phone/3.png
diff --git a/metadata_data/photos/games-nonogram/phone/3.png b/metadata_data/photos/games-nonogram/phone/3.pngindex 3b693d9171..bce4349f6b 100644Binary files a/metadata_data/photos/games-nonogram/phone/3.png and b/metadata_data/photos/games-nonogram/phone/3.png differ