Modern Apps git

← Modern-Apps.git

sudoku: refuse wrong digits; nonogram: add 3 hearts

Commit
68187097b7222fe3045bcb7ace1b77250f853634
Author
vayun-mathur <[email protected]>
When
2026-08-24 05:41 UTC (3 months ago)
Parents
364b146

Diff

games/nonogram/src/main/assets/achievements.json
diff --git a/games/nonogram/src/main/assets/achievements.json b/games/nonogram/src/main/assets/achievements.jsonindex 7d79d6f02b..a88b9b708e 100644--- a/games/nonogram/src/main/assets/achievements.json+++ b/games/nonogram/src/main/assets/achievements.json@@ -12,7 +12,7 @@   {     "id": "no_mistakes",     "name": "Careful Reader",-    "description": "Complete a puzzle without ever filling a wrong cell."+    "description": "Complete a puzzle without losing a single heart."   },   {     "id": "first_daily",
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 71003b9ef9..009ad3f237 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@@ -1,7 +1,6 @@ package com.vayunmathur.games.nonogram.data  import android.content.Context-import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey@@ -27,14 +26,14 @@ 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 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 }      val gameMode: Flow<GameMode> = context.dataStore.data.map { prefs ->         prefs[GAME_MODE_KEY]?.let { runCatching { GameMode.valueOf(it) }.getOrNull() }             ?: GameMode.CASUAL     } -    val showMistakes: Flow<Boolean> = context.dataStore.data.map { it[SHOW_MISTAKES_KEY] ?: true }-     /** Lifetime count of completed puzzles, which survives [saveLevel] clearing the board. */     val puzzlesCompleted: Flow<Int> = context.dataStore.data.map { it[COMPLETED_KEY] ?: 0 } @@ -45,57 +44,80 @@ 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 dailyRevealedBlanks: Flow<Set<Int>> =+        context.dataStore.data.map { it[DAILY_REVEALED_KEY].toCells() }+    val dailyHearts: Flow<Int> =+        context.dataStore.data.map { it[DAILY_HEARTS_KEY] ?: STARTING_HEARTS }      suspend fun setGameMode(mode: GameMode) {         context.dataStore.edit { it[GAME_MODE_KEY] = mode.name }     } -    suspend fun setShowMistakes(enabled: Boolean) {-        context.dataStore.edit { it[SHOW_MISTAKES_KEY] = enabled }-    }-     /**      * Moves to [level] and wipes the board in the same write.      *-     * One edit rather than two, so a crash between them cannot leave the previous level's marks on the-     * new puzzle.+     * One edit rather than four, so a crash between them cannot leave the previous level's marks or+     * spent hearts attached to the new puzzle.      */     suspend fun saveLevel(level: Int) {         context.dataStore.edit { prefs ->             prefs[LEVEL_KEY] = level             prefs[FILLED_KEY] = emptySet()             prefs[CROSSED_KEY] = emptySet()+            prefs[REVEALED_KEY] = emptySet()+            prefs[HEARTS_KEY] = STARTING_HEARTS         }     } -    /** Clears the current level's marks without advancing, for the restart button. */+    /** 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()         }     }      /**-     * Records the mark on [index], keeping the two sets disjoint.+     * Records that [index] turned out to be empty, and spends the heart it cost.      *-     * A cell is either filled, crossed, or neither, so setting one mark always removes the other.+     * 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.      */-    suspend fun setMark(index: Int, mark: CellMark, daily: Boolean) {-        val filledKey = if (daily) DAILY_FILLED_KEY else FILLED_KEY+    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         context.dataStore.edit { prefs ->-            val filled = prefs[filledKey].toCells().toMutableSet()-            val crossed = prefs[crossedKey].toCells().toMutableSet()-            filled.remove(index)-            crossed.remove(index)-            when (mark) {-                CellMark.FILLED -> filled.add(index)-                CellMark.CROSSED -> crossed.add(index)-                CellMark.BLANK -> Unit-            }-            prefs[filledKey] = filled.mapTo(mutableSetOf()) { it.toString() }-            prefs[crossedKey] = crossed.mapTo(mutableSetOf()) { it.toString() }+            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)         }     } @@ -121,6 +143,8 @@ class NonogramDataStore(private val context: Context) {             prefs[DAILY_DAY_KEY] = day             prefs[DAILY_FILLED_KEY] = emptySet()             prefs[DAILY_CROSSED_KEY] = emptySet()+            prefs[DAILY_REVEALED_KEY] = emptySet()+            prefs[DAILY_HEARTS_KEY] = STARTING_HEARTS         }     } @@ -128,13 +152,16 @@ 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 REVEALED_KEY = stringSetPreferencesKey("revealed_blanks")+        val HEARTS_KEY = intPreferencesKey("hearts")         val GAME_MODE_KEY = stringPreferencesKey("game_mode")-        val SHOW_MISTAKES_KEY = booleanPreferencesKey("show_mistakes")         val COMPLETED_KEY = intPreferencesKey("puzzles_completed")          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_REVEALED_KEY = stringSetPreferencesKey("daily_revealed_blanks")+        val DAILY_HEARTS_KEY = intPreferencesKey("daily_hearts")          /** Sentinel for "no daily played yet"; distinct from epoch day 0, which is a real date. */         const val NO_DAY = Long.MIN_VALUE@@ -144,3 +171,5 @@ class NonogramDataStore(private val context: Context) { /** 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()++private fun Set<Int>.toStrings(): Set<String> = mapTo(mutableSetOf()) { it.toString() }
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 7489939670..96c671dc96 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@@ -19,43 +19,67 @@ enum class GameMode { CASUAL, DAILY }  */ enum class CellMark { BLANK, FILLED, CROSSED } +/** Hearts a level starts with. Three wrong guesses and the board has to be retried. */+const val STARTING_HEARTS = 3+ /**  * A puzzle plus the player's work on it.  *- * [filled] and [crossed] are disjoint sets of cell indices: marking a cell one way clears the other,- * because a cell cannot be both. Storing them as sets rather than a per-cell list keeps the DataStore- * write small — only the cells actually touched are persisted.+ * The three 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.+ *  - [revealedBlanks] is a cell the game has *told* the player is empty, after a wrong guess cost a+ *    heart. It draws the same as a cross but cannot be cleared, which is what stops the same cell+ *    being charged for twice.+ *+ * Storing them as sets rather than per-cell lists keeps the DataStore write small — only the cells+ * actually touched are persisted.  */ data class NonogramGameState(     val puzzle: NonogramPuzzle,     val filled: Set<Int>,     val crossed: Set<Int>,+    val revealedBlanks: Set<Int>,+    val hearts: Int,     val mode: GameMode,     val level: Int,     val elapsedSeconds: Int = 0, ) {     val size: Int get() = puzzle.size -    fun markAt(index: Int): CellMark = when (index) {-        in filled -> CellMark.FILLED-        in crossed -> CellMark.CROSSED+    fun markAt(index: Int): CellMark = when {+        index in filled -> CellMark.FILLED+        index in crossed || index in revealedBlanks -> CellMark.CROSSED         else -> CellMark.BLANK     }      /**-     * Won when the filled cells are exactly the solution's.+     * Whether [index] is settled and no longer takes input.      *-     * Crosses are ignored, and an over-filled grid does not count — the sets must match, not merely-     * cover.+     * A correct fill and a revealed blank are both facts the game has confirmed, so re-tapping either+     * does nothing rather than undoing them.+     */+    fun isLocked(index: Int): Boolean = index in filled || index in revealedBlanks++    /**+     * Won when every cell of the picture has been filled in.+     *+     * The subset check is belt-and-braces: [filled] should never hold a cell outside the picture, but+     * a size comparison alone would silently accept a board restored from progress that predates that+     * guarantee.      */     val isWon: Boolean-        get() = filled.size == puzzle.filledCount &&-            filled.all { puzzle.solution[it] }+        get() = filled.size == puzzle.filledCount && filled.all { puzzle.solution[it] }++    /** Failed once the hearts run out, unless the last guess also finished the picture. */+    val isFailed: Boolean get() = hearts <= 0 && !isWon -    /** Cells the player filled that should be blank, so the board can point out a wrong guess. */-    fun isMistake(index: Int): Boolean = index in filled && !puzzle.solution[index]+    val isOver: Boolean get() = isWon || isFailed -    val hasMistake: Boolean get() = filled.any { !puzzle.solution[it] }+    /** Whether [index] belongs to the picture, which is what a tap on it is judged against. */+    fun belongsToPicture(index: Int): Boolean = puzzle.solution[index] }  /**
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.ktindex 9889045352..6add3db564 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt@@ -14,10 +14,10 @@ import com.vayunmathur.games.nonogram.data.NonogramGameState  * Every member has a no-op default, so `Noop` is the whole implementation a preview needs.  */ interface NonogramGameActions {-    /** Tap: cycles blank to filled to crossed and back. */+    /** Tap: fills a cell of the picture, or spends a heart on one that is not. */     fun tapCell(index: Int) {} -    /** Long press: crosses a cell directly, skipping the fill step. */+    /** Long press: crosses a cell out as a note, or takes the cross back. Never costs a heart. */     fun crossCell(index: Int) {}      fun nextLevel() {}@@ -32,7 +32,6 @@ data class NonogramUiState(     val game: NonogramGameState? = null,     val mode: GameMode = GameMode.CASUAL,     val level: Int = 1,-    val showMistakes: Boolean = true,     val dailyStreak: Long = 0,     /** True once today's daily has been completed, which swaps the next-level button for a note. */     val dailyDone: Boolean = false,@@ -42,7 +41,6 @@ data class NonogramUiState( )  interface SettingsActions {-    fun setShowMistakes(enabled: Boolean) {}     fun setReminderEnabled(enabled: Boolean) {}     fun setReminderTime(hour: Int, minute: Int) {} @@ -50,7 +48,6 @@ interface SettingsActions { }  data class SettingsUiState(-    val showMistakes: Boolean = true,     val reminderEnabled: Boolean = false,     val reminderHour: Int = 20,     val reminderMinute: Int = 0,
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 89545f6c9c..717c9104d1 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@@ -3,12 +3,12 @@ package com.vayunmathur.games.nonogram.platform import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope-import com.vayunmathur.games.nonogram.data.CellMark import com.vayunmathur.games.nonogram.data.DAILY_SIZE import com.vayunmathur.games.nonogram.data.GameMode 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.sizeForLevel import com.vayunmathur.games.nonogram.domain.NonogramGenerator import com.vayunmathur.library.util.AchievementsManager@@ -75,9 +75,8 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application             combine(                 dataStore.gameMode,                 dataStore.currentLevel,-                dataStore.showMistakes,                 dailyStore.currentStreak,-            ) { mode, level, showMistakes, streak -> Session(mode, level, showMistakes, streak) }+            ) { mode, level, streak -> Session(mode, level, streak) }                 .collectLatest { session -> load(session) }         }     }@@ -86,7 +85,6 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application     private data class Session(         val mode: GameMode,         val level: Int,-        val showMistakes: Boolean,         val streak: Long,     ) @@ -98,7 +96,6 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application         _uiState.value = _uiState.value.copy(             mode = session.mode,             level = session.level,-            showMistakes = session.showMistakes,             dailyStreak = session.streak,             generating = true,             generationFailed = false,@@ -133,55 +130,86 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application         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 -        combine(filledFlow, crossedFlow, dataStore.dailyDay, dailyStore.lastCompletedDayFlow) {-            filled, crossed, storedDay, lastCompleted ->+        // 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)+        }++        combine(boardFlow, dataStore.dailyDay, dailyStore.lastCompletedDayFlow) {+            marks, storedDay, lastCompleted ->+            // Anything stored against a different day is yesterday's work and must not be shown.             val stale = daily && storedDay != day-            Triple(-                if (stale) emptySet() else filled,-                if (stale) emptySet() else crossed,-                lastCompleted == day,-            )-        }.collectLatest { (filled, crossed, dailyDone) ->+            if (stale) {+                Marks(emptySet(), emptySet(), emptySet(), STARTING_HEARTS, lastCompleted == day)+            } else {+                marks.copy(dailyDone = lastCompleted == day)+            }+        }.collectLatest { marks ->             val game = NonogramGameState(                 puzzle = puzzle,-                filled = filled,-                crossed = crossed,+                filled = marks.filled,+                crossed = marks.crossed,+                revealedBlanks = marks.revealed,+                hearts = marks.hearts,                 mode = session.mode,                 level = session.level,             )             _uiState.value = _uiState.value.copy(                 game = game,                 generating = false,-                dailyDone = dailyDone,+                dailyDone = marks.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,+    )++    /**+     * Tap: fills a cell that belongs to the picture, or spends a heart on one that does not.+     *+     * A wrong guess is recorded as a *revealed* blank, not as an ordinary note, so it cannot be cleared+     * and then tapped again — one wrong cell costs exactly one heart however many times it is prodded.+     * Correct fills are locked for the same reason.+     *+     * The player's own notes stay freely reversible; only a cell the game has settled is locked.+     */     override fun tapCell(index: Int) {         val game = _uiState.value.game ?: return-        if (game.isWon) return-        // Blank -> filled -> crossed -> blank, so one finger can reach every state.-        val next = when (game.markAt(index)) {-            CellMark.BLANK -> CellMark.FILLED-            CellMark.FILLED -> CellMark.CROSSED-            CellMark.CROSSED -> CellMark.BLANK+        if (game.isOver || game.isLocked(index)) return++        val daily = game.mode == GameMode.DAILY+        viewModelScope.launch {+            if (game.belongsToPicture(index)) {+                dataStore.fillCell(index, daily)+            } else {+                dataStore.revealBlank(index, daily)+            }         }-        setMark(index, next)     } +    /**+     * Long press: crosses a cell out as a note, or takes the note back.+     *+     * Free either way, even on a cell that does turn out to belong to the picture: a cross 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.isWon) return-        val next =-            if (game.markAt(index) == CellMark.CROSSED) CellMark.BLANK else CellMark.CROSSED-        setMark(index, next)-    }--    private fun setMark(index: Int, mark: CellMark) {-        val daily = _uiState.value.mode == GameMode.DAILY-        viewModelScope.launch { dataStore.setMark(index, mark, daily) }+        if (game.isOver || game.isLocked(index)) return+        val daily = game.mode == GameMode.DAILY+        val alreadyNoted = index in game.crossed+        viewModelScope.launch { dataStore.setNote(index, !alreadyNoted, daily) }     }      override fun nextLevel() {@@ -199,10 +227,6 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application         viewModelScope.launch { dataStore.setGameMode(mode) }     } -    override fun setShowMistakes(enabled: Boolean) {-        viewModelScope.launch { dataStore.setShowMistakes(enabled) }-    }-     override fun setReminderEnabled(enabled: Boolean) {         viewModelScope.launch {             reminderSettings.setEnabled(enabled)@@ -250,7 +274,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application             val manager = achievementsManager             manager.onAchievementUnlocked("first_puzzle")             if (game.size >= BIG_PICTURE_SIZE) manager.onAchievementUnlocked("big_picture")-            if (!game.hasMistake) manager.onAchievementUnlocked("no_mistakes")+            if (game.hearts == STARTING_HEARTS) manager.onAchievementUnlocked("no_mistakes")             manager.onProgressUpdated("puzzles_10", total)             manager.onProgressUpdated("puzzles_50", total) 
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 121f505506..10a8d0eb0a 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@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue@@ -15,11 +16,15 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.vayunmathur.games.nonogram.R import com.vayunmathur.games.nonogram.data.GameMode+import com.vayunmathur.games.nonogram.data.STARTING_HEARTS import com.vayunmathur.games.nonogram.platform.NonogramGameActions import com.vayunmathur.games.nonogram.platform.NonogramUiState import com.vayunmathur.games.nonogram.ui.components.NonogramBoard@@ -32,6 +37,7 @@ import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.IconArrowDropDown import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconEmojiEvents+import com.vayunmathur.library.ui.IconFavorite import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton@@ -43,6 +49,30 @@ import com.vayunmathur.library.ui.appBarScrollBehavior /** Caps the board on tablets, where a full-width grid would give absurdly large cells. */ private val BoardMaxWidth = 460.dp +/**+ * The hearts left.+ *+ * Spent hearts stay in place as dimmed shapes rather than disappearing, so the row does not reflow and+ * the player can see at a glance how much margin is gone.+ */+@Composable+private fun Hearts(hearts: Int) {+    val safe = hearts.coerceAtLeast(0)+    val description = pluralStringResource(R.plurals.cd_hearts, safe, safe)+    Row(+        Modifier.clearAndSetSemantics { contentDescription = description },+        horizontalArrangement = Arrangement.spacedBy(Spacing.xs),+    ) {+        repeat(STARTING_HEARTS) { index ->+            IconFavorite(+                Modifier.size(20.dp),+                tint = if (index >= hearts) MaterialTheme.colorScheme.surfaceContainerHighest+                else MaterialTheme.colorScheme.error,+            )+        }+    }+}+ /**  * The board, with no dependency on the ViewModel so it can be rendered from a `@Preview` — see  * `src/screenshotTest`.@@ -109,9 +139,10 @@ fun NonogramGameScreen(                 ) { CircularProgressIndicator() }                  else -> {+                    Hearts(game.hearts)+                     NonogramBoard(                         game = game,-                        showMistakes = state.showMistakes,                         onTap = actions::tapCell,                         onLongPress = actions::crossCell,                         modifier = Modifier@@ -119,34 +150,53 @@ fun NonogramGameScreen(                             .fillMaxWidth(),                     ) -                    if (game.isWon) {-                        Text(-                            stringResource(R.string.solved),-                            style = MaterialTheme.typography.titleLarge,-                            color = MaterialTheme.colorScheme.primary,-                        )-                        if (daily) {+                    when {+                        game.isWon -> {                             Text(-                                stringResource(R.string.daily_come_back_tomorrow),-                                style = MaterialTheme.typography.bodyMedium,-                                textAlign = TextAlign.Center,+                                stringResource(R.string.solved),+                                style = MaterialTheme.typography.titleLarge,+                                color = MaterialTheme.colorScheme.primary,                             )-                        } else {-                            Button(-                                onClick = { actions.nextLevel() },-                                modifier = Modifier.fillMaxWidth(),-                            ) { Text(stringResource(R.string.next_level)) }+                            if (daily) {+                                Text(+                                    stringResource(R.string.daily_come_back_tomorrow),+                                    style = MaterialTheme.typography.bodyMedium,+                                    textAlign = TextAlign.Center,+                                )+                            } else {+                                Button(+                                    onClick = { actions.nextLevel() },+                                    modifier = Modifier.fillMaxWidth(),+                                ) { Text(stringResource(R.string.next_level)) }+                            }                         }-                    } else {-                        if (game.filled.isEmpty() && game.crossed.isEmpty()) {++                        game.isFailed -> {                             Text(-                                stringResource(R.string.how_to_play),-                                style = MaterialTheme.typography.bodySmall,-                                color = MaterialTheme.colorScheme.onSurfaceVariant,+                                stringResource(R.string.out_of_hearts),+                                style = MaterialTheme.typography.titleLarge,+                                color = MaterialTheme.colorScheme.error,                             )+                            Button(+                                onClick = { actions.restartLevel() },+                                modifier = Modifier.fillMaxWidth(),+                            ) { Text(stringResource(R.string.try_again)) }                         }-                        OutlinedButton(onClick = { actions.restartLevel() }) {-                            Text(stringResource(R.string.restart))++                        else -> {+                            if (game.filled.isEmpty() && game.crossed.isEmpty() &&+                                game.revealedBlanks.isEmpty()+                            ) {+                                Text(+                                    stringResource(R.string.how_to_play),+                                    style = MaterialTheme.typography.bodySmall,+                                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                                    textAlign = TextAlign.Center,+                                )+                            }+                            OutlinedButton(onClick = { actions.restartLevel() }) {+                                Text(stringResource(R.string.restart))+                            }                         }                     }                 }
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.ktindex 41a489baa8..3405a81ba1 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.kt@@ -6,7 +6,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.res.stringResource-import com.vayunmathur.games.nonogram.R import com.vayunmathur.games.nonogram.platform.NonogramViewModel import com.vayunmathur.games.nonogram.platform.SettingsActions import com.vayunmathur.games.nonogram.platform.SettingsUiState@@ -15,28 +14,23 @@ import com.vayunmathur.library.ui.DailyReminderSettingsSection import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.ui.SettingsSection-import com.vayunmathur.library.ui.SettingsSwitchRow import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.rememberPermissionRequest  /** Binds [NonogramViewModel] to the stateless [SettingsScreen]. */ @Composable fun SettingsPage(viewModel: NonogramViewModel, onBack: () -> Unit) {-    val uiState by viewModel.uiState.collectAsState()     val reminderEnabled by viewModel.reminderEnabled.collectAsState()     val reminderMinutes by viewModel.reminderMinutesOfDay.collectAsState()     val requestNotifications = rememberPermissionRequest(Manifest.permission.POST_NOTIFICATIONS)      SettingsScreen(         state = SettingsUiState(-            showMistakes = uiState.showMistakes,             reminderEnabled = reminderEnabled,             reminderHour = (reminderMinutes / 60).toInt(),             reminderMinute = (reminderMinutes % 60).toInt(),         ),         actions = object : SettingsActions {-            override fun setShowMistakes(enabled: Boolean) = viewModel.setShowMistakes(enabled)             override fun setReminderEnabled(enabled: Boolean) {                 // Asked for lazily, on opt-in only, so the screen never blocks on a prompt.                 if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {@@ -64,14 +58,6 @@ fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, onBack: ()         },         scrollBehavior = appBarScrollBehavior(),     ) {-        SettingsSection {-            SettingsSwitchRow(-                title = stringResource(R.string.show_mistakes),-                supportingText = stringResource(R.string.show_mistakes_description),-                checked = state.showMistakes,-                onCheckedChange = { actions.setShowMistakes(it) },-            )-        }         DailyReminderSettingsSection(             enabled = state.reminderEnabled,             hour = state.reminderHour,
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 5d60fbde78..7eb3123820 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@@ -46,7 +46,6 @@ import com.vayunmathur.library.ui.Text @Composable fun NonogramBoard(     game: NonogramGameState,-    showMistakes: Boolean,     onTap: (Int) -> Unit,     onLongPress: (Int) -> Unit,     modifier: Modifier = Modifier,@@ -74,7 +73,7 @@ fun NonogramBoard(             }             Row {                 RowClues(game, rowGutterCells, cell, clueCell, fontSize, lineHeight)-                Grid(game, showMistakes, cell, onTap, onLongPress)+                Grid(game, cell, onTap, onLongPress)             }         }     }@@ -157,7 +156,6 @@ private fun ClueText( @Composable private fun Grid(     game: NonogramGameState,-    showMistakes: Boolean,     cell: Dp,     onTap: (Int) -> Unit,     onLongPress: (Int) -> Unit,@@ -172,7 +170,6 @@ private fun Grid(                         NonogramCell(                             game = game,                             index = index,-                            showMistakes = showMistakes,                             onTap = { onTap(index) },                             onLongPress = { onLongPress(index) },                             modifier = Modifier.size(cell),@@ -193,7 +190,6 @@ private fun Grid( private fun NonogramCell(     game: NonogramGameState,     index: Int,-    showMistakes: Boolean,     onTap: () -> Unit,     onLongPress: () -> Unit,     modifier: Modifier = Modifier,@@ -201,19 +197,15 @@ private fun NonogramCell(     val scheme = MaterialTheme.colorScheme     val haptics = LocalHapticFeedback.current     val mark = game.markAt(index)-    val mistake = showMistakes && game.isMistake(index) -    val background = when {-        mistake -> scheme.error-        mark == CellMark.FILLED -> scheme.onSurface-        else -> Color.Transparent-    }+    // No mistake colour: a fill only ever lands on a cell that belongs to the picture, because a wrong+    // guess is turned into a cross instead.+    val background = if (mark == CellMark.FILLED) scheme.onSurface else Color.Transparent -    val stateWord = when {-        mistake -> stringResource(R.string.cd_mistake)-        mark == CellMark.FILLED -> stringResource(R.string.cd_filled)-        mark == CellMark.CROSSED -> stringResource(R.string.cd_crossed)-        else -> stringResource(R.string.cd_blank)+    val stateWord = when (mark) {+        CellMark.FILLED -> stringResource(R.string.cd_filled)+        CellMark.CROSSED -> stringResource(R.string.cd_crossed)+        CellMark.BLANK -> stringResource(R.string.cd_blank)     }     val description = stringResource(         R.string.cd_cell,@@ -225,7 +217,7 @@ private fun NonogramCell(     Box(         modifier             .background(background)-            .pointerInput(index, game.isWon) {+            .pointerInput(index, game.isOver, game.isLocked(index)) {                 detectTapGestures(                     onTap = { onTap() },                     onLongPress = {
games/nonogram/src/main/res/values/strings.xml
diff --git a/games/nonogram/src/main/res/values/strings.xml b/games/nonogram/src/main/res/values/strings.xmlindex acc6b5e199..d3481758e5 100644--- a/games/nonogram/src/main/res/values/strings.xml+++ b/games/nonogram/src/main/res/values/strings.xml@@ -21,18 +21,21 @@     <!-- DailyStatusBar: Current daily streak length. %1$d = consecutive days, e.g. 5 -->     <string name="daily_streak">Streak: <xliff:g id="days" example="5">%1$d</xliff:g></string>     <!-- NonogramGameScreen: Hint under a fresh board explaining the two gestures. Imperative sentence -->-    <string name="how_to_play">Tap to fill, tap again to cross out</string>+    <string name="how_to_play">Tap to fill, long press to cross out</string>+    <!-- NonogramGameScreen: Shown when the last heart is spent. Declarative, sympathetic -->+    <string name="out_of_hearts">Out of hearts!</string>++    <!-- NonogramGameScreen: Content description of the hearts remaining. %1$d = hearts left, 0 to 3, e.g. 2 -->+    <plurals name="cd_hearts">+        <item quantity="one"><xliff:g id="count" example="1">%1$d</xliff:g> heart left</item>+        <item quantity="other"><xliff:g id="count" example="2">%1$d</xliff:g> hearts left</item>+    </plurals>      <!-- NonogramGameScreen: Shown when no fair puzzle could be generated for this level. Sentence -->     <string name="generation_failed">Could not build a puzzle for this level.</string>-    <!-- NonogramGameScreen: Retries generation after a failure. Verb -->+    <!-- NonogramGameScreen: Retries generation after a failure, and the level after running out of hearts. Verb -->     <string name="try_again">Try Again</string> -    <!-- SettingsScreen: Toggle for highlighting cells filled in that should be blank. Noun phrase -->-    <string name="show_mistakes">Highlight mistakes</string>-    <!-- SettingsScreen: Explains what the highlight-mistakes toggle does. Sentence -->-    <string name="show_mistakes_description">Mark filled cells that do not belong to the picture.</string>-     <!-- NonogramBoard: Content description of a cell. %1$d = row number starting at 1, e.g. 4. %2$d = column number starting at 1, e.g. 6. %3$s = the cell's state word, e.g. Filled -->     <string name="cd_cell">Row <xliff:g id="row" example="4">%1$d</xliff:g>, column <xliff:g id="column" example="6">%2$d</xliff:g>, <xliff:g id="state" example="Filled">%3$s</xliff:g></string>     <!-- NonogramBoard: Cell state, painted as part of the picture. Verb past participle -->@@ -41,6 +44,4 @@     <string name="cd_crossed">Crossed out</string>     <!-- NonogramBoard: Cell state, untouched. Adjective -->     <string name="cd_blank">Blank</string>-    <!-- NonogramBoard: Content description of a filled cell that does not belong to the picture. Noun -->-    <string name="cd_mistake">Mistake</string> </resources>
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 89cb56b45b..d143e22d95 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@@ -7,6 +7,7 @@ import com.vayunmathur.games.nonogram.data.DAILY_SIZE 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 com.vayunmathur.games.nonogram.data.sizeForLevel import com.vayunmathur.games.nonogram.domain.NonogramGenerator import com.vayunmathur.games.nonogram.platform.NonogramGameActions@@ -34,7 +35,7 @@ class MetadataPreviews {     @Preview(name = "1-level", device = PHONE, showSystemUi = true)     @Composable     fun Preview1Level() {-        // Part-way through a 10x10, with some cells crossed out as a player would leave them.+        // Part-way through a 10x10, with some cells crossed out and one heart already spent.         val puzzle = level(12)         val correct = puzzle.solution.indices.filter { puzzle.solution[it] }         val blanks = puzzle.solution.indices.filter { !puzzle.solution[it] }@@ -43,7 +44,10 @@ class MetadataPreviews {                 puzzle = puzzle,                 level = 12,                 filled = correct.take(correct.size / 2).toSet(),-                crossed = blanks.take(blanks.size / 3).toSet(),+                crossed = blanks.drop(1).take(blanks.size / 3).toSet(),+                // One cell the player got wrong, which is what the missing heart paid for.+                revealedBlanks = setOf(blanks.first()),+                hearts = STARTING_HEARTS - 1,             )         )     }@@ -119,11 +123,15 @@ class MetadataPreviews {         level: Int,         filled: Set<Int>,         crossed: Set<Int>,+        revealedBlanks: Set<Int> = emptySet(),         mode: GameMode = GameMode.CASUAL,+        hearts: Int = STARTING_HEARTS,     ) = NonogramGameState(         puzzle = puzzle,         filled = filled,         crossed = crossed,+        revealedBlanks = revealedBlanks,+        hearts = hearts,         mode = mode,         level = level,     )
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 ca6ce5cea6..0c450e3898 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@@ -16,25 +16,37 @@ class NonogramGameStateTest {         """     ) -    private fun state(filled: Set<Int> = emptySet(), crossed: Set<Int> = emptySet()) =-        NonogramGameState(-            puzzle = cross,-            filled = filled,-            crossed = crossed,-            mode = GameMode.CASUAL,-            level = 1,-        )--    /** Indices of the cells that should be filled in [cross]. */+    private fun state(+        filled: Set<Int> = emptySet(),+        crossed: Set<Int> = emptySet(),+        revealedBlanks: Set<Int> = emptySet(),+        hearts: Int = STARTING_HEARTS,+    ) = NonogramGameState(+        puzzle = cross,+        filled = filled,+        crossed = crossed,+        revealedBlanks = revealedBlanks,+        hearts = hearts,+        mode = GameMode.CASUAL,+        level = 1,+    )++    /** Indices of the cells that make up the picture. */     private val answer = cross.solution.indices.filter { cross.solution[it] }.toSet() +    /** A cell that is not part of the picture. */+    private val blankCell = cross.solution.indices.first { !cross.solution[it] }+     @Test-    fun aFreshBoardIsNotWon() {-        assertFalse(state().isWon)+    fun aFreshBoardIsNotWonAndHasEveryHeart() {+        val s = state()+        assertFalse(s.isWon)+        assertFalse(s.isFailed)+        assertEquals(STARTING_HEARTS, s.hearts)     }      @Test-    fun fillingExactlyTheSolutionWins() {+    fun fillingTheWholePictureWins() {         assertTrue(state(filled = answer).isWon)     } @@ -42,7 +54,7 @@ class NonogramGameStateTest {     fun crossesDoNotAffectTheWinCheck() {         val blanks = cross.solution.indices.filterNot { cross.solution[it] }.toSet()         assertTrue(state(filled = answer, crossed = blanks).isWon)-        assertTrue(state(filled = answer, crossed = emptySet()).isWon)+        assertTrue(state(filled = answer).isWon)     }      @Test@@ -50,34 +62,56 @@ class NonogramGameStateTest {         assertFalse(state(filled = answer - answer.first()).isWon)     } +    @Test+    fun runningOutOfHeartsFailsTheBoard() {+        val s = state(hearts = 0)+        assertTrue(s.isFailed)+        assertTrue(s.isOver)+        assertFalse(s.isWon)+    }++    @Test+    fun finishingOnTheLastHeartIsAWinNotAFailure() {+        // An invariant guard rather than a reachable position: winning must always beat failing when+        // both conditions hold at once.+        val s = state(filled = answer, hearts = 0)+        assertTrue(s.isWon)+        assertFalse(s.isFailed)+    }+     @Test     fun anExtraFilledCellIsNotAWin() {-        // Over-filling must not pass: the sets have to match, not merely cover the solution.-        val extra = cross.solution.indices.first { !cross.solution[it] }-        assertFalse(state(filled = answer + extra).isWon)+        // Fills should never land outside the picture, but a board restored from older progress could+        // carry one, and the size comparison alone would wrongly call that finished.+        assertFalse(state(filled = answer + blankCell).isWon)+    }++    @Test+    fun aRevealedBlankDrawsAsACrossButIsLocked() {+        val s = state(revealedBlanks = setOf(blankCell))+        assertEquals(CellMark.CROSSED, s.markAt(blankCell))+        assertTrue(s.isLocked(blankCell), "a cell the game revealed cannot be charged for twice")     }      @Test-    fun aWrongFillIsReportedAsAMistake() {-        val wrong = cross.solution.indices.first { !cross.solution[it] }-        val s = state(filled = setOf(wrong))-        assertTrue(s.isMistake(wrong))-        assertTrue(s.hasMistake)+    fun aPlayerNoteIsNotLocked() {+        // Notes stay reversible; only what the game has settled is locked.+        val s = state(crossed = setOf(blankCell))+        assertEquals(CellMark.CROSSED, s.markAt(blankCell))+        assertFalse(s.isLocked(blankCell))     }      @Test-    fun aCorrectFillIsNotAMistake() {-        val right = answer.first()-        val s = state(filled = setOf(right))-        assertFalse(s.isMistake(right))-        assertFalse(s.hasMistake)+    fun aCorrectFillIsLocked() {+        val filledCell = answer.first()+        assertTrue(state(filled = setOf(filledCell)).isLocked(filledCell))     }      @Test-    fun aCrossedBlankIsNeverAMistake() {-        // Crosses are bookkeeping; being wrong about one is not the same as painting a wrong cell.-        val s = state(crossed = answer)-        assertFalse(s.hasMistake)+    fun belongsToPictureIdentifiesWhichTapsAreFree() {+        // This is what the ViewModel judges a tap against, so it decides where hearts are spent.+        for (index in answer) assertTrue(state().belongsToPicture(index), "cell $index")+        assertFalse(state().belongsToPicture(blankCell))     }      @Test
games/sudoku/src/main/assets/achievements.json
diff --git a/games/sudoku/src/main/assets/achievements.json b/games/sudoku/src/main/assets/achievements.jsonindex 2b8c82c8ed..7462bd8444 100644--- a/games/sudoku/src/main/assets/achievements.json+++ b/games/sudoku/src/main/assets/achievements.json@@ -22,7 +22,7 @@   {     "id": "no_mistakes",     "name": "Flawless",-    "description": "Complete a puzzle without ever entering a wrong digit."+    "description": "Complete a puzzle without a single wrong guess."   },   {     "id": "speed_nine",
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.ktindex d6fc25d0e2..5e744c89cf 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt@@ -62,7 +62,7 @@ data class GameConfig(  *  * Both lists are [BoardSize.cellCount] long and use 0 for "blank"; digits are 1-based. Keeping the  * solution alongside the clues is what lets a hint fill one correct cell without re-running the- * solver, and lets a wrong entry be flagged immediately rather than only at the end.+ * solver, and lets a digit that does not belong be refused as it is entered.  */ data class Puzzle(     val size: BoardSize,@@ -101,15 +101,27 @@ data class SudokuGameState(      fun isGiven(index: Int): Boolean = givens[index] != 0 -    /** True when [index] holds a digit that disagrees with the solution. */-    fun isWrong(index: Int): Boolean {-        val value = valueAt(index)-        return value != 0 && value != solution[index]-    }+    /**+     * Whether [digit] may be written into [index].+     *+     * A digit that disagrees with the solution is refused outright rather than written and flagged, so+     * the grid only ever holds correct entries. That is why there is no "wrong cell" state to render:+     * it cannot occur.+     *+     * Clearing a cell is not a write and does not go through here.+     */+    fun accepts(index: Int, digit: Int): Boolean =+        !isWon &&+            index in 0 until size.cellCount &&+            !isGiven(index) &&+            digit == solution[index]      /** How many of [digit] are already placed, so the number pad can retire finished digits. */     fun placedCount(digit: Int): Int = (0 until size.cellCount).count { valueAt(it) == digit } +    /** Cells with nothing in them yet, which is what a hint picks from. */+    fun blankIndices(): List<Int> = (0 until size.cellCount).filter { valueAt(it) == 0 }+     val isComplete: Boolean get() = (0 until size.cellCount).all { valueAt(it) == solution[it] }      companion object {
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.ktindex 9c8ef98bce..95b283e46d 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt@@ -38,7 +38,7 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),     /** Undo snapshots, oldest first. Cleared whenever a new puzzle is dealt. */     private val history = ArrayDeque<SudokuSnapshot>() -    /** Set when the player ever types a digit that disagrees with the solution. */+    /** Set when the player ever tries a digit that disagrees with the solution. */     private var madeMistake = false      val achievementsManager: AchievementsManager = run {@@ -88,14 +88,18 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),      *      * Re-entering the digit already showing clears the cell instead, so the number pad doubles as a      * toggle and the player rarely needs the separate erase button.+     *+     * A confirmed digit that disagrees with the solution is refused: nothing is written, no move is+     * counted, and the board does not change. The attempt is still remembered for the `no_mistakes`+     * achievement, which is the only trace a wrong guess leaves.      */     override fun enterDigit(digit: Int) {         val game = _uiState.value.game ?: return         val index = game.selected         if (index !in 0 until game.size.cellCount || game.isGiven(index) || game.isWon) return -        pushHistory(game)         if (game.notesMode) {+            pushHistory(game)             val bit = 1 shl (digit - 1)             mutate { state ->                 state.copy(@@ -107,11 +111,20 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),             return         } -        val next = if (game.entries[index] == digit) 0 else digit-        if (next != 0 && next != game.solution[index]) madeMistake = true+        // Tapping the digit already there means "take it back", which is always allowed.+        if (game.entries[index] == digit) {+            clearCell()+            return+        }+        if (!game.accepts(index, digit)) {+            madeMistake = true+            return+        }++        pushHistory(game)         mutate { state ->             state.copy(-                entries = state.entries.replacing(index, next),+                entries = state.entries.replacing(index, digit),                 // A confirmed digit makes its own pencil marks meaningless.                 notes = state.notes.replacing(index, 0),                 moveCount = state.moveCount + 1,@@ -137,14 +150,15 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),     /**      * Fills one cell with its correct digit.      *-     * Prefers the selected cell so a stuck player gets help where they are looking; otherwise it-     * takes the first blank or wrong cell, so a hint is never wasted on a cell that is already right.+     * Prefers the selected cell so a stuck player gets help where they are looking; otherwise it takes+     * the first blank. Entries are always correct, so a blank cell is the only thing a hint can help+     * with.      */     override fun hint() {         val game = _uiState.value.game ?: return         if (game.isWon) return-        val index = game.selected.takeIf { it >= 0 && !game.isGiven(it) && game.valueAt(it) != game.solution[it] }-            ?: (0 until game.size.cellCount).firstOrNull { !game.isGiven(it) && game.valueAt(it) != game.solution[it] }+        val index = game.selected.takeIf { it >= 0 && !game.isGiven(it) && game.valueAt(it) == 0 }+            ?: game.blankIndices().firstOrNull()             ?: return          pushHistory(game)
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.ktindex d1742ba744..8943e897c3 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt@@ -100,7 +100,6 @@ private fun SudokuCell( ) {     val scheme = MaterialTheme.colorScheme     val value = game.valueAt(index)-    val wrong = game.isWrong(index)     val given = game.isGiven(index)      val background = when {@@ -110,11 +109,9 @@ private fun SudokuCell(         else -> Color.Transparent     } -    val digitColor = when {-        wrong -> scheme.error-        given -> scheme.onSurface-        else -> scheme.primary-    }+    // Givens are the puzzle, entries are the player's work, so they read differently. There is no+    // wrong-cell colour because a wrong digit is refused rather than written.+    val digitColor = if (given) scheme.onSurface else scheme.primary      val spoken = if (value == 0) stringResource(R.string.cd_empty) else value.toString()     val side = game.size.side
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuGameStateTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuGameStateTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuGameStateTest.ktnew file mode 100644index 0000000000..c4798afb60--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuGameStateTest.kt@@ -0,0 +1,108 @@+package com.vayunmathur.games.sudoku.data++import com.vayunmathur.games.sudoku.domain.SudokuGenerator+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class SudokuGameStateTest {++    private val puzzle = SudokuGenerator.generate(BoardSize.FOUR, Difficulty.EASY, Random(1))+    private val fresh = SudokuGameState.from(puzzle)++    /** A cell the player is allowed to fill in. */+    private val blank = puzzle.givens.indices.first { puzzle.givens[it] == 0 }++    /** A digit that does not belong in [blank]. */+    private val wrongDigit =+        (1..puzzle.size.side).first { it != puzzle.solution[blank] }++    @Test+    fun theCorrectDigitIsAccepted() {+        assertTrue(fresh.accepts(blank, puzzle.solution[blank]))+    }++    @Test+    fun aWrongDigitIsRefused() {+        // The whole point: the grid never holds a digit that disagrees with the solution.+        assertFalse(fresh.accepts(blank, wrongDigit))+    }++    @Test+    fun givenCellsRefuseEverything() {+        val given = puzzle.givens.indices.first { puzzle.givens[it] != 0 }+        for (digit in 1..puzzle.size.side) {+            assertFalse(fresh.accepts(given, digit), "digit $digit into a given")+        }+    }++    @Test+    fun outOfRangeCellsAreRefused() {+        assertFalse(fresh.accepts(-1, 1))+        assertFalse(fresh.accepts(puzzle.size.cellCount, 1))+    }++    @Test+    fun aFinishedGridRefusesFurtherWrites() {+        val solved = fresh.copy(+            entries = List(puzzle.size.cellCount) { if (fresh.isGiven(it)) 0 else puzzle.solution[it] },+            isWon = true,+        )+        assertTrue(solved.isComplete)+        assertFalse(solved.accepts(blank, puzzle.solution[blank]))+    }++    @Test+    fun blankIndicesAreExactlyTheEmptyCells() {+        assertEquals(+            puzzle.givens.indices.filter { puzzle.givens[it] == 0 },+            fresh.blankIndices(),+        )+        // Filling one removes it from the list, which is what stops a hint reusing that cell.+        val filled = fresh.copy(entries = fresh.entries.toMutableList().also {+            it[blank] = puzzle.solution[blank]+        })+        assertFalse(blank in filled.blankIndices())+    }++    @Test+    fun placedCountOnlyCountsWhatIsOnTheBoard() {+        val digit = puzzle.solution[blank]+        val before = fresh.placedCount(digit)+        val after = fresh.copy(entries = fresh.entries.toMutableList().also {+            it[blank] = digit+        }).placedCount(digit)+        assertEquals(before + 1, after)+    }++    @Test+    fun aGridIsCompleteOnlyWhenEveryCellMatchesTheSolution() {+        assertFalse(fresh.isComplete)+        val solved = fresh.copy(+            entries = List(puzzle.size.cellCount) { if (fresh.isGiven(it)) 0 else puzzle.solution[it] }+        )+        assertTrue(solved.isComplete)+    }++    @Test+    fun clueFractionsOnlyEverGetHarder() {+        val targets = Difficulty.entries.map { it.targetClues(BoardSize.NINE) }+        assertEquals(targets, targets.sortedDescending(), "clue targets should fall: $targets")+    }++    @Test+    fun boxGeometryCoversEveryCellExactlyOnce() {+        for (size in BoardSize.entries) {+            val counts = IntArray(size.side)+            for (index in 0 until size.cellCount) counts[size.boxOf(index)]+++            // Every box must hold exactly as many cells as a row does, or the box constraint would+            // be weaker or stronger than the row constraint.+            assertTrue(+                counts.all { it == size.side },+                "${size.name} box sizes were ${counts.toList()}",+            )+        }+    }+}
metadata_data/games-nonogram.md
diff --git a/metadata_data/games-nonogram.md b/metadata_data/games-nonogram.mdindex 2f1b046612..4607f753fd 100644--- a/metadata_data/games-nonogram.md+++ b/metadata_data/games-nonogram.md@@ -3,4 +3,5 @@ A picture logic puzzle, with a new one every day Fill the grid from the number clues to reveal the hidden picture. One level is open at a time, plus a fresh daily puzzle shared by everyone on the same date. Every puzzle is generated on device and checked to be solvable by reasoning-alone, so you never have to guess.+alone, so you never have to guess. You get three hearts per board, and a cell+that turns out to be empty costs you one.
metadata_data/games-sudoku.md
diff --git a/metadata_data/games-sudoku.md b/metadata_data/games-sudoku.mdindex 8767478034..cc5b5604d6 100644--- a/metadata_data/games-sudoku.md+++ b/metadata_data/games-sudoku.md@@ -1,5 +1,6 @@ A classic number puzzle, generated fresh every game  Pick a board size and a difficulty and play a puzzle generated on the spot. Every-puzzle has exactly one solution, so it can always be finished by reasoning alone.-Includes 4x4, 6x6 and 9x9 grids, pencil marks, hints and undo.+puzzle has exactly one solution, so it can always be finished by reasoning alone,+and a digit that does not belong simply will not go in. Includes 4x4, 6x6 and 9x9+grids, pencil marks, hints and undo.
metadata_data/photos/games-nonogram/1.png
diff --git a/metadata_data/photos/games-nonogram/1.png b/metadata_data/photos/games-nonogram/1.pngindex e3b37f651a..11004fa5cd 100644Binary files a/metadata_data/photos/games-nonogram/1.png and b/metadata_data/photos/games-nonogram/1.png differ
metadata_data/photos/games-nonogram/2.png
diff --git a/metadata_data/photos/games-nonogram/2.png b/metadata_data/photos/games-nonogram/2.pngindex feb8fcbcb9..d6f3f2ee2b 100644Binary files a/metadata_data/photos/games-nonogram/2.png and b/metadata_data/photos/games-nonogram/2.png differ
metadata_data/photos/games-nonogram/3.png
diff --git a/metadata_data/photos/games-nonogram/3.png b/metadata_data/photos/games-nonogram/3.pngindex 4ce1589292..ac1a5c01f6 100644Binary files a/metadata_data/photos/games-nonogram/3.png and b/metadata_data/photos/games-nonogram/3.png differ
metadata_data/photos/games-nonogram/4.png
diff --git a/metadata_data/photos/games-nonogram/4.png b/metadata_data/photos/games-nonogram/4.pngindex b423ee02bb..a78d164a62 100644Binary files a/metadata_data/photos/games-nonogram/4.png and b/metadata_data/photos/games-nonogram/4.png differ