nonogram: apply moves in memory first, persist in background (#ux-audit)
- Commit
1dbc16b14baa4d84cf5f6b495816750168300ac6- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 01:14 UTC (23 days ago)
- Parents
74544f4
Symptom: every tap waited for a DataStore write before the cell changed, so the board felt laggy, and two quick taps in Cross mode on the same cell both added an X instead of adding then removing it. Root cause: tapCell()/crossCell() launched a DataStore edit and the UI only updated when the marks flow re-emitted (observeMarks). Each tap was judged against the last *echoed* state: the second Cross tap still saw the cell as unmarked and wrote "add note" again. The per-set flows were also combined separately, so an emission could pair the fills of one write with the hearts of the previous one. Fix (same pattern as Arrows: in-memory state is the source of truth): - New pure domain/NonogramMoves (guess / setNote / toggleNote) computes the next board; commit() shows it immediately, checks for a win, and persists a whole-board snapshot in the background. - Writes are serialised behind a Mutex in move order; a snapshot that a newer one has superseded before it starts is skipped, so a burst of taps costs one or two disk writes. Next level's saveLevel() runs behind the same lock so it never overtakes the winning move. - NonogramDataStore.board(daily) reads all four values from one preferences snapshot; saveBoard() writes them in one edit and is dropped if the stored level/daily day has since moved on, so a queued snapshot can't paint the old puzzle's marks onto the next one. - While writes are pending, marks-flow emissions for the board already on screen are ignored (they are lagging echoes); loads and mode/level switches still come from the store. - setMarkMode() and restartLevel() also update in memory first. - Removed the now-unused per-cell DataStore edits (fillCell, setNote, revealBlank, clearMarks). Hearts can no longer be double-charged or refunded by racing writes because every move is applied serially to the single in-memory board. User-visible effect: cells change on the frame you tap them, a double tap in Cross mode toggles the X on and off, and progress still survives a relaunch. Verification: NonogramMovesTest (pure transitions), DataStore tests for snapshot round-trip, casual/daily independence and the stale-level / stale-day guards, and Robolectric VM tests asserting the board changes synchronously with the tap, the double Cross tap nets to no X, and a burst of moves persists and reloads in a fresh ViewModel.
Diff
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 fb28d58cbe..faa58a6ede 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@@ -79,55 +79,39 @@ class NonogramDataStore(private val context: Context) { } } - /** Clears the current level's marks and restores its hearts, for restart and for a failed board. */- suspend fun clearMarks(daily: Boolean) {- context.dataStore.edit { prefs ->- prefs[if (daily) DAILY_FILLED_KEY else FILLED_KEY] = emptySet()- prefs[if (daily) DAILY_CROSSED_KEY else CROSSED_KEY] = emptySet()- prefs[if (daily) DAILY_REVEALED_KEY else REVEALED_KEY] = emptySet()- prefs[if (daily) DAILY_HEARTS_KEY else HEARTS_KEY] = STARTING_HEARTS- }- }-- /** Marks [index] as part of the picture. */- suspend fun fillCell(index: Int, daily: Boolean) {- val filledKey = if (daily) DAILY_FILLED_KEY else FILLED_KEY- val crossedKey = if (daily) DAILY_CROSSED_KEY else CROSSED_KEY- context.dataStore.edit { prefs ->- prefs[filledKey] = prefs[filledKey].toCells().plus(index).toStrings()- // A confirmed fill makes any note on the same cell meaningless.- prefs[crossedKey] = prefs[crossedKey].toCells().minus(index).toStrings()- }- }-- /** Adds or removes the player's own "looks empty" note on [index]. Never touches hearts. */- suspend fun setNote(index: Int, crossed: Boolean, daily: Boolean) {- val crossedKey = if (daily) DAILY_CROSSED_KEY else CROSSED_KEY- context.dataStore.edit { prefs ->- val notes = prefs[crossedKey].toCells()- prefs[crossedKey] = (if (crossed) notes + index else notes - index).toStrings()- }+ /**+ * The whole board for one mode, read from a single preferences snapshot.+ *+ * One flow rather than combining the per-set flows above: each of those collects the store+ * separately, so a combine of them can briefly pair the fills of one write with the hearts of the+ * previous one.+ */+ fun board(daily: Boolean): Flow<StoredBoard> = context.dataStore.data.map { prefs ->+ StoredBoard(+ filled = prefs[if (daily) DAILY_FILLED_KEY else FILLED_KEY].toCells(),+ crossed = prefs[if (daily) DAILY_CROSSED_KEY else 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,+ ) } /**- * Records that [index] turned out to be empty, and spends the heart it cost.+ * Writes the board the ViewModel holds in memory, in one edit. *- * The heart is decremented from the stored value *inside* the transaction rather than written as a- * number worked out beforehand. Two wrong taps in quick succession would otherwise both read the- * same heart count and write the same result, so only one would be charged - and a later write- * carrying a stale count could put a spent heart back.+ * The ViewModel is the source of truth while a puzzle is open — it applies each move to its own+ * state first and persists afterwards — so this stores a whole snapshot rather than replaying a+ * delta against whatever is on disk. The write is dropped if the store has since moved on to a+ * different casual [level] or daily [day]: a snapshot that was queued behind "Next level" or a+ * daily rollover must not paint the previous puzzle's marks onto the new one. */- suspend fun revealBlank(index: Int, daily: Boolean) {- val revealedKey = if (daily) DAILY_REVEALED_KEY else REVEALED_KEY- val crossedKey = if (daily) DAILY_CROSSED_KEY else CROSSED_KEY- val heartsKey = if (daily) DAILY_HEARTS_KEY else HEARTS_KEY+ suspend fun saveBoard(board: StoredBoard, daily: Boolean, level: Int, day: Long) { context.dataStore.edit { prefs ->- val revealed = prefs[revealedKey].toCells()- // Already revealed means already paid for; re-tapping must not charge again.- if (index in revealed) return@edit- prefs[revealedKey] = (revealed + index).toStrings()- prefs[crossedKey] = prefs[crossedKey].toCells().minus(index).toStrings()- prefs[heartsKey] = ((prefs[heartsKey] ?: STARTING_HEARTS) - 1).coerceAtLeast(0)+ if (daily && prefs[DAILY_DAY_KEY] != day) return@edit+ 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_REVEALED_KEY else REVEALED_KEY] = board.revealed.toStrings()+ prefs[if (daily) DAILY_HEARTS_KEY else HEARTS_KEY] = board.hearts } } @@ -195,6 +179,14 @@ class NonogramDataStore(private val context: Context) { } } +/** One mode's stored marks and hearts; see [NonogramDataStore.board]. */+data class StoredBoard(+ val filled: Set<Int> = emptySet(),+ val crossed: Set<Int> = emptySet(),+ val revealed: Set<Int> = emptySet(),+ val hearts: Int = STARTING_HEARTS,+)+ /** Cell indices are stored as strings because DataStore has no int-set type. */ private fun Set<String>?.toCells(): Set<Int> = this?.mapNotNullTo(mutableSetOf()) { it.toIntOrNull() } ?: emptySet()
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.ktnew file mode 100644index 0000000000..3e8a14048a--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt@@ -0,0 +1,44 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.NonogramGameState++/**+ * What a single move does to a board, as pure state transitions.+ *+ * The ViewModel applies these to the board it holds in memory and only then persists the result, so+ * a tap is judged against the state the player is looking at rather than whatever DataStore last+ * echoed back. Every function returns the board unchanged when the move does not apply (game over, or+ * a cell the game has already settled), which is what lets callers fire them freely.+ */+object NonogramMoves {++ /**+ * A fill attempt on [index].+ *+ * A cell that belongs to the picture is filled; one that does not is revealed as blank and costs a+ * heart. Either way any note on the cell is dropped, since the game has now settled it.+ */+ 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)+ } else {+ game.copy(+ revealedBlanks = game.revealedBlanks + index,+ crossed = game.crossed - index,+ hearts = (game.hearts - 1).coerceAtLeast(0),+ )+ }+ }++ /** Places ([crossed] true) or removes the player's own "looks empty" note. Never costs a heart. */+ 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)+ }++ /** 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)+}
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 c1270b9961..5350158ad6 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@@ -1,6 +1,7 @@ package com.vayunmathur.games.nonogram.platform import android.app.Application+import java.util.concurrent.atomic.AtomicLong import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.games.nonogram.data.DAILY_SIZE@@ -10,8 +11,10 @@ import com.vayunmathur.games.nonogram.data.NonogramDataStore 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.StoredBoard import com.vayunmathur.games.nonogram.data.sizeForLevel import com.vayunmathur.games.nonogram.domain.NonogramGenerator+import com.vayunmathur.games.nonogram.domain.NonogramMoves import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.library.util.DailyChallengeStore import com.vayunmathur.library.util.DailyStreakReporter@@ -26,6 +29,8 @@ import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /**@@ -142,85 +147,110 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application } /**- * Streams the player's marks onto [puzzle].+ * Streams the stored marks onto [puzzle].+ *+ * This is how a board is *loaded*; after that the ViewModel's own copy is the source of truth and+ * moves are applied to it directly (see [commit]). While any write is still queued, an emission+ * for the board already on screen is a lagging echo of an earlier move and is ignored — applying+ * it would briefly roll the board back, and judging the next tap against it is how two quick+ * cross taps used to both add an X. * * Daily marks are blanked whenever the stored day is not the day being played, so a stale write * from yesterday can never show up on today's board even if the rollover edit was interrupted. */ private suspend fun observeMarks(session: Session, puzzle: NonogramPuzzle, day: Long) { val daily = session.mode == GameMode.DAILY- val filledFlow = if (daily) dataStore.dailyFilledCells else dataStore.filledCells- val crossedFlow = if (daily) dataStore.dailyCrossedCells else dataStore.crossedCells- val revealedFlow = if (daily) dataStore.dailyRevealedBlanks else dataStore.revealedBlanks- val heartsFlow = if (daily) dataStore.dailyHearts else dataStore.hearts-- // Two stages because the typed `combine` overloads stop at five flows.- val boardFlow = combine(filledFlow, crossedFlow, revealedFlow, heartsFlow) {- filled, crossed, revealed, hearts ->- Marks(filled, crossed, revealed, hearts, dailyDone = false)- }+ boardDay = day - combine(boardFlow, dataStore.dailyDay, dailyStore.lastCompletedDayFlow) {- marks, storedDay, lastCompleted ->+ combine(dataStore.board(daily), dataStore.dailyDay, dailyStore.lastCompletedDayFlow) {+ board, storedDay, lastCompleted -> // Anything stored against a different day is yesterday's work and must not be shown. val stale = daily && storedDay != day- if (stale) {- Marks(emptySet(), emptySet(), emptySet(), STARTING_HEARTS, lastCompleted == day)- } else {- marks.copy(dailyDone = lastCompleted == day)- }- }.collectLatest { marks ->- val game = NonogramGameState(+ (if (stale) StoredBoard() else board) to (lastCompleted == day)+ }.collectLatest { (board, dailyDone) ->+ val onScreen = _uiState.value.game+ ?.takeIf { hasPendingWrites && it.isBoardFor(session, puzzle) }+ val game = onScreen ?: NonogramGameState( puzzle = puzzle,- filled = marks.filled,- crossed = marks.crossed,- revealedBlanks = marks.revealed,- hearts = marks.hearts,+ filled = board.filled,+ crossed = board.crossed,+ revealedBlanks = board.revealed,+ hearts = board.hearts, mode = session.mode, level = session.level, ) _uiState.value = _uiState.value.copy( game = game, generating = false,- dailyDone = marks.dailyDone,+ dailyDone = dailyDone, ) if (game.isWon) onWin(game, daily, day) } } - private data class Marks(- val filled: Set<Int>,- val crossed: Set<Int>,- val revealed: Set<Int>,- val hearts: Int,- val dailyDone: Boolean,- )+ private fun NonogramGameState.isBoardFor(session: Session, puzzle: NonogramPuzzle): Boolean =+ this.puzzle == puzzle && mode == session.mode && level == session.level++ /** The daily the board on screen belongs to, so a queued write cannot land on the next day's. */+ private var boardDay: Long = Long.MIN_VALUE /**- * Tap: places whichever mark [MarkMode] selects.+ * Serialises every board write, so snapshots land in the order the moves were made and a level+ * change queued after them is never overtaken.+ */+ private val writeLock = Mutex()++ /** Tickets for queued and finished board writes; equal when nothing is waiting to be persisted. */+ private val requestedWrite = AtomicLong(0)+ private val completedWrite = AtomicLong(0)++ private val hasPendingWrites: Boolean get() = completedWrite.get() != requestedWrite.get()++ /**+ * Shows [next] at once and persists it in the background. *- * In fill mode a cell that belongs to the picture is filled and one that does not costs a heart. In- * cross mode a tap only ever writes the player's own note, so it is always free — which is the- * point of the mode: crossing off a long run of cells should not be a gamble.+ * The board on screen updates in the same frame as the tap instead of after a DataStore round+ * trip, and every later move is judged against this state. Writes are queued behind [writeLock];+ * one that has been superseded by a newer snapshot before it starts is skipped, so a burst of taps+ * costs one or two disk writes rather than one each. */- override fun tapCell(index: Int) {- val game = _uiState.value.game ?: return- if (game.isOver || game.isLocked(index)) return- if (_uiState.value.markMode == MarkMode.CROSS) {- toggleNote(game, index)- return- }+ private fun commit(next: NonogramGameState) {+ val previous = _uiState.value.game ?: return+ if (next == previous) return+ _uiState.value = _uiState.value.copy(game = next)+ persist(next)+ if (next.isWon) onWin(next, next.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 daily = game.mode == GameMode.DAILY+ val day = boardDay viewModelScope.launch {- if (game.belongsToPicture(index)) {- dataStore.fillCell(index, daily)- } else {- dataStore.revealBlank(index, daily)+ writeLock.withLock {+ if (ticket == requestedWrite.get()) dataStore.saveBoard(board, daily, game.level, day) }+ completedWrite.accumulateAndGet(ticket, ::maxOf) } } + /**+ * Tap: places whichever mark [MarkMode] selects.+ *+ * In fill mode a cell that belongs to the picture is filled and one that does not costs a heart. In+ * cross mode a tap only ever writes the player's own note, so it is always free — which is the+ * point of the mode: crossing off a long run of cells should not be a gamble.+ */+ override fun tapCell(index: Int) {+ val state = _uiState.value+ val game = state.game ?: return+ commit(+ if (state.markMode == MarkMode.CROSS) NonogramMoves.toggleNote(game, index)+ else NonogramMoves.guess(game, index)+ )+ }+ /** * Long press: the other mark from whatever the mode is. *@@ -229,29 +259,17 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application * is the player's own working, and being wrong in a note is not a guess the game should punish. */ override fun crossCell(index: Int) {- val game = _uiState.value.game ?: return- if (game.isOver || game.isLocked(index)) return- if (_uiState.value.markMode == MarkMode.CROSS) {- val daily = game.mode == GameMode.DAILY- viewModelScope.launch {- if (game.belongsToPicture(index)) {- dataStore.fillCell(index, daily)- } else {- dataStore.revealBlank(index, daily)- }- }- } else {- toggleNote(game, index)- }- }-- private fun toggleNote(game: NonogramGameState, index: Int) {- val daily = game.mode == GameMode.DAILY- val alreadyNoted = index in game.crossed- viewModelScope.launch { dataStore.setNote(index, !alreadyNoted, daily) }+ val state = _uiState.value+ val game = state.game ?: return+ commit(+ if (state.markMode == MarkMode.CROSS) NonogramMoves.guess(game, index)+ else NonogramMoves.toggleNote(game, index)+ ) } override fun setMarkMode(mode: MarkMode) {+ // In memory first, so a tap straight after switching uses the new mode.+ _uiState.value = _uiState.value.copy(markMode = mode) viewModelScope.launch { dataStore.setMarkMode(mode) } } @@ -271,12 +289,21 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application if (state.generating || !game.isWon) return val target = game.level + 1 _uiState.value = state.copy(generating = true)- viewModelScope.launch { dataStore.saveLevel(target) }+ // Behind the write lock so the winning move's snapshot lands first.+ viewModelScope.launch { writeLock.withLock { dataStore.saveLevel(target) } } } + /** Clears every mark and restores the hearts, on screen at once and on disk behind it. */ override fun restartLevel() {- val daily = _uiState.value.mode == GameMode.DAILY- viewModelScope.launch { dataStore.clearMarks(daily) }+ val game = _uiState.value.game ?: return+ commit(+ game.copy(+ filled = emptySet(),+ crossed = emptySet(),+ revealedBlanks = emptySet(),+ hearts = STARTING_HEARTS,+ )+ ) } /**
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 ce7a69e058..73892c66c9 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,9 +29,12 @@ 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)+ @Test fun saveLevelWipesBoardAndRestoresHearts() = runBlocking {- val s = store()- s.fillCell(3, daily = false); s.setNote(4, true, daily = false); s.revealBlank(5, daily = false)+ val s = store(); s.saveLevel(6)+ s.saveBoard(board(setOf(3), setOf(4), setOf(5), STARTING_HEARTS - 1), daily = false, level = 6, day = 0L) assertEquals(STARTING_HEARTS - 1, s.hearts.first()) s.saveLevel(7) assertEquals(7, s.currentLevel.first())@@ -41,35 +44,33 @@ class NonogramDataStoreTest { assertEquals(STARTING_HEARTS, s.hearts.first()) } - @Test fun fillRemovesNoteAndNotesToggle() = runBlocking {+ @Test fun saveBoardRoundTripsAsOneSnapshot() = runBlocking { val s = store(); s.saveLevel(2)- s.setNote(10, true, daily = false); assertEquals(setOf(10), s.crossedCells.first())- s.fillCell(10, daily = false)- assertEquals(setOf(10), s.filledCells.first()); assertEquals(emptySet(), s.crossedCells.first())- s.setNote(11, true, daily = false); s.setNote(11, false, daily = false)- assertEquals(emptySet(), s.crossedCells.first())+ val b = board(setOf(1, 2), setOf(7), setOf(9), 1)+ s.saveBoard(b, daily = false, level = 2, day = 0L)+ assertEquals(b, s.board(daily = false).first())+ assertEquals(setOf(1, 2), s.filledCells.first()); assertEquals(1, s.hearts.first()) } - @Test fun revealBlankChargesOnceAndClearsNote() = runBlocking {+ @Test fun saveBoardIsDroppedOnceTheLevelHasMovedOn() = runBlocking { val s = store(); s.saveLevel(3)- s.setNote(20, true, daily = false)- s.revealBlank(20, daily = false)- assertEquals(setOf(20), s.revealedBlanks.first()); assertEquals(emptySet(), s.crossedCells.first())- assertEquals(STARTING_HEARTS - 1, s.hearts.first())- s.revealBlank(20, daily = false)- assertEquals(STARTING_HEARTS - 1, s.hearts.first(), "second reveal must not charge again")- s.revealBlank(21, daily = false); s.revealBlank(22, daily = false)- assertEquals(0, s.hearts.first())- s.revealBlank(23, daily = false); assertEquals(0, s.hearts.first(), "hearts floor at zero")+ s.saveLevel(4)+ // A snapshot of level 3 queued behind "Next level" must not land on level 4.+ s.saveBoard(board(filled = setOf(1)), daily = false, level = 3, day = 0L)+ assertEquals(StoredBoard(), s.board(daily = false).first()) } - @Test fun clearMarksCasualAndDailyAreIndependent() = runBlocking {+ @Test fun saveBoardCasualAndDailyAreIndependent() = runBlocking { val s = store(); s.saveLevel(4); s.ensureDailyDay(19_000L)- s.fillCell(1, daily = false); s.fillCell(2, daily = true)- s.clearMarks(daily = false)+ s.saveBoard(board(filled = setOf(1)), daily = false, level = 4, day = 19_000L)+ s.saveBoard(board(filled = setOf(2)), daily = true, level = 4, day = 19_000L)+ assertEquals(setOf(1), s.filledCells.first()); assertEquals(setOf(2), s.dailyFilledCells.first())+ s.saveBoard(StoredBoard(), daily = false, level = 4, day = 19_000L) assertEquals(emptySet(), s.filledCells.first()); assertEquals(setOf(2), s.dailyFilledCells.first())- s.clearMarks(daily = true)- assertEquals(emptySet(), s.dailyFilledCells.first()); assertEquals(STARTING_HEARTS, s.dailyHearts.first())+ // Yesterday's daily snapshot is dropped after the rollover.+ s.ensureDailyDay(19_001L)+ s.saveBoard(board(filled = setOf(3)), daily = true, level = 4, day = 19_000L)+ assertEquals(emptySet(), s.dailyFilledCells.first()) } @Test fun recordCompletedOnceBanksEachWinKeyOnce() = runBlocking {@@ -85,7 +86,8 @@ class NonogramDataStoreTest { @Test fun dailyRolloverClearsOnlyOnDayChange() = runBlocking { val s = store()- s.ensureDailyDay(20_000L); s.fillCell(5, daily = true); s.revealBlank(6, daily = true)+ s.ensureDailyDay(20_000L)+ s.saveBoard(board(setOf(5), revealed = setOf(6), hearts = 2), daily = true, level = 1, day = 20_000L) s.ensureDailyDay(20_000L) assertEquals(setOf(5), s.dailyFilledCells.first(), "same day must keep work") s.ensureDailyDay(20_001L)
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.ktnew file mode 100644index 0000000000..0291442239--- /dev/null+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt@@ -0,0 +1,40 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.GameMode+import com.vayunmathur.games.nonogram.data.NonogramGameState+import com.vayunmathur.games.nonogram.data.NonogramPuzzle+import com.vayunmathur.games.nonogram.data.STARTING_HEARTS+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertSame++class NonogramMovesTest {+ // 3x3 plus sign: picture cells 1, 3, 4, 5, 7.+ private val puzzle = NonogramPuzzle.from(3, listOf(false, true, false, true, true, true, false, true, false))+ private fun game(hearts: Int = STARTING_HEARTS) =+ NonogramGameState(puzzle, emptySet(), emptySet(), emptySet(), hearts, GameMode.CASUAL, 1)++ @Test fun guessFillsAPictureCellAndDropsItsNote() {+ val g = NonogramMoves.guess(NonogramMoves.setNote(game(), 1, true), 1)+ assertEquals(setOf(1), g.filled); assertEquals(emptySet(), g.crossed); assertEquals(STARTING_HEARTS, g.hearts)+ }++ @Test fun guessOnABlankRevealsItAndCostsOneHeart() {+ val g = NonogramMoves.guess(game(), 0)+ assertEquals(setOf(0), g.revealedBlanks); assertEquals(STARTING_HEARTS - 1, g.hearts)+ assertSame(g, NonogramMoves.guess(g, 0), "a revealed cell is settled and never charged twice")+ }++ @Test fun movesAreIgnoredOnceTheGameIsOver() {+ val failed = game(hearts = 0)+ assertSame(failed, NonogramMoves.guess(failed, 1))+ assertSame(failed, NonogramMoves.toggleNote(failed, 0))+ }++ @Test fun toggleNoteFlipsAndNeverCosts() {+ val once = NonogramMoves.toggleNote(game(), 4)+ assertEquals(setOf(4), once.crossed)+ val twice = NonogramMoves.toggleNote(once, 4)+ assertEquals(emptySet(), twice.crossed); assertEquals(STARTING_HEARTS, twice.hearts)+ }+}
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 173e4f48e8..78a7a9bb0f 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@@ -76,6 +76,42 @@ class NonogramViewModelTest { await("long press fills") { vm.uiState.value.game?.filled?.contains(noteCell) == true } } + @Test fun movesUpdateTheBoardBeforeAnyWriteLands() {+ val vm = loadedVm()+ val g = vm.uiState.value.game!!+ val correct = g.puzzle.solution.indices.first { g.puzzle.solution[it] }+ // No await: the board on screen changes in the same call as the tap.+ vm.tapCell(correct)+ assertTrue(correct in vm.uiState.value.game!!.filled, "fill must show before DataStore echoes it")+ vm.setMarkMode(MarkMode.CROSS)+ assertEquals(MarkMode.CROSS, vm.uiState.value.markMode, "mode switch applies at once")+ val note = g.puzzle.solution.indices.first { it != correct }+ vm.tapCell(note)+ assertTrue(note in vm.uiState.value.game!!.crossed)+ vm.tapCell(note)+ assertFalse(note in vm.uiState.value.game!!.crossed, "second quick tap must clear the X, not add it again")+ // And the store catches up to what is on screen.+ await("persisted") {+ runBlocking { vm.dataStore.filledCells.first() } == setOf(correct) &&+ runBlocking { vm.dataStore.crossedCells.first() }.isEmpty()+ }+ assertTrue(correct in vm.uiState.value.game!!.filled)+ assertFalse(note in vm.uiState.value.game!!.crossed)+ }++ @Test fun rapidMovesAllPersistInOrder() {+ val vm = loadedVm()+ val g = vm.uiState.value.game!!+ val picture = g.puzzle.solution.indices.filter { g.puzzle.solution[it] }+ val target = picture.take(picture.size - 1)+ for (i in target) vm.tapCell(i)+ assertEquals(target.toSet(), vm.uiState.value.game!!.filled)+ await("last snapshot wins") { runBlocking { vm.dataStore.filledCells.first() } == target.toSet() }+ // A fresh ViewModel (a relaunch) loads exactly what was played.+ val again = NonogramViewModel(app)+ await("reload") { again.uiState.value.game?.filled == target.toSet() }+ }+ @Test fun longPressInFillModeNotesAndRestartClears() { val vm = loadedVm() val g = vm.uiState.value.game!!