sudoku: add answer mode with rejection, digit lockout and lives (#893)
- Commit
194eded3e9e34eba589c34abe8c6e851c2358eb5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-10-31 17:33 UTC (1 month ago)
- Parents
e6e870a
Adds an opt-in answer mode to Sudoku, toggled by a switch on the home screen and persisted in DataStore. When on, new puzzles reject wrong digits instead of accepting them silently: the tapped keypad key flashes red and fades back, nothing is placed, and one of three lives is spent. Losing the last life ends the puzzle as a loss and offers a retry of the same grid with refilled lives. The mode is stored globally but snapshotted per game when the puzzle is dealt, so flipping the switch mid-game never rewrites the rules under the player; restart keeps the same puzzle and mode. Notes are never judged and cost nothing, undo restores entries only and cannot refund a life, hints always place correct digits for free, and a completed digit's keypad key is greyed out in answer mode only -- classic mode keeps accepting and moving digits as before. The tap decision table lives in domain/AnswerMode as pure Kotlin so it is unit-testable without an Application; the ViewModel only carries decisions out. The keypad flash runs on the library motion scheme (animatedColor) with local flash state, and lives render through the shared HeartsRow. Store screenshots re-rendered identically, so no preview images changed. Verified with :games:sudoku:compileDevKotlin, :games:sudoku: testDevUnitTest (41 tests, 13 new covering rejection, digit completion, lives and game-over), ./check sudoku (detekt and lint green), and :games:sudoku:metadata. On-device play -- the flash timing, hearts row, and game-over overlay -- still needs a handset.
Diff
games/sudoku/build.gradle.kts
diff --git a/games/sudoku/build.gradle.kts b/games/sudoku/build.gradle.ktsindex f33050bd3d..40f0357b2e 100644--- a/games/sudoku/build.gradle.kts+++ b/games/sudoku/build.gradle.kts@@ -17,4 +17,5 @@ android { dependencies { implementation(project(":sdk:games"))+ implementation(libs.androidx.datastore.preferences) }
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.ktnew file mode 100644index 0000000000..61f088a470--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt@@ -0,0 +1,32 @@+package com.vayunmathur.games.sudoku.data++import android.content.Context+import androidx.datastore.preferences.core.booleanPreferencesKey+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++private val Context.dataStore by preferencesDataStore(name = "settings")++/**+ * The answer-mode switch on the home screen.+ *+ * Persisted on its own rather than folded into the stats record because it is a preference, not a+ * result: stats are keyed per variant and rewritten on every game, while this is one global default+ * read when a puzzle is dealt. The game itself carries a snapshot — see+ * [SudokuGameState.answerMode] — so toggling mid-game cannot rewrite the rules under the player.+ */+class SudokuDataStore(private val context: Context) {++ /** Whether new puzzles reject wrong digits and cost lives. Off until the player opts in. */+ val answerMode: Flow<Boolean> = context.dataStore.data.map { it[ANSWER_MODE_KEY] ?: false }++ suspend fun setAnswerMode(enabled: Boolean) {+ context.dataStore.edit { it[ANSWER_MODE_KEY] = enabled }+ }++ private companion object {+ val ANSWER_MODE_KEY = booleanPreferencesKey("answer_mode")+ }+}
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 0af8132b32..c4780f0cf9 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@@ -40,6 +40,14 @@ fun sudokuSymbol(digit: Int): String = private const val MAX_NUMERIC_DIGIT = 9 private const val LETTER_BASE_DIGIT = 10 +/**+ * Lives granted when a puzzle starts in answer mode.+ *+ * One number for every board size: a wrong attempt costs the same whatever the grid, because the+ * lives are about how many slips the player gets, not about the board's shape.+ */+const val ANSWER_MODE_LIVES = 3+ /** * How many cells the generator leaves filled in. *@@ -107,9 +115,27 @@ data class SudokuGameState( val hintsUsed: Int = 0, val isWon: Boolean = false, val usedUndo: Boolean = false,+ /**+ * Answer mode for this game, snapshotted when the puzzle is dealt.+ *+ * The persisted preference is a global default, but the game carries its own copy so a game in+ * progress keeps the rules it started with — toggling the switch on the home screen cannot+ * rewrite the rules mid-puzzle. A wrong digit is never placed; it costs a life instead.+ */+ val answerMode: Boolean = false,+ /**+ * Lives left, meaningful only when [answerMode] is on.+ *+ * Undo snapshots cover entries and notes only — never this — so undoing cannot refund a life+ * spent on a rejected digit. Zero ends the game; see [isGameOver].+ */+ val livesRemaining: Int = ANSWER_MODE_LIVES, ) { val variant: String get() = "${size.name}_${difficulty.name}" + /** True when answer mode has run out of lives but the grid is not solved. */+ val isGameOver: Boolean get() = answerMode && livesRemaining <= 0 && !isComplete+ /** The digit showing in [index], given or entered, or 0 if the cell is blank. */ fun valueAt(index: Int): Int = givens[index].takeIf { it != 0 } ?: entries[index] @@ -142,16 +168,27 @@ data class SudokuGameState( val isComplete: Boolean get() = (0 until size.cellCount).all { valueAt(it) == solution[it] } companion object {- /** A fresh game from [puzzle], with every non-given cell blank. */- fun from(puzzle: Puzzle): SudokuGameState = SudokuGameState(+ /** A fresh game from [puzzle], with every non-given cell blank and a full set of lives. */+ fun from(puzzle: Puzzle, answerMode: Boolean = false): SudokuGameState = SudokuGameState( size = puzzle.size, difficulty = puzzle.difficulty, givens = puzzle.givens, solution = puzzle.solution, entries = List(puzzle.size.cellCount) { 0 }, notes = List(puzzle.size.cellCount) { 0 },+ answerMode = answerMode,+ livesRemaining = ANSWER_MODE_LIVES, ) }++ /**+ * True when every copy of [digit] is on the board — givens plus correct entries.+ *+ * Counts the digit itself rather than cells, so a digit that appears nine times as givens (a+ * fully-clued digit on a lucky 6x6) is complete from the first frame with nothing entered.+ */+ fun isDigitComplete(digit: Int): Boolean =+ (0 until size.cellCount).count { valueAt(it) == digit } >= size.side } /** The one snapshot the undo stack stores per move. */
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/AnswerMode.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/AnswerMode.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/AnswerMode.ktnew file mode 100644index 0000000000..82a5516854--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/AnswerMode.kt@@ -0,0 +1,75 @@+package com.vayunmathur.games.sudoku.domain++import com.vayunmathur.games.sudoku.data.SudokuGameState++/**+ * The pure rules of answer mode: which keypad taps mean what, before anything is stored.+ *+ * Lives in `domain` rather than the ViewModel so the whole decision table is unit-testable without+ * an `Application`: [decide] reads the game and the tapped digit and says what should happen, and+ * the ViewModel carries it out (history, state flow, stats, keypad flash). Nothing here touches+ * Android, coroutines, or Compose.+ *+ * The table, in order:+ *+ * - no usable selection (nothing selected, a given cell, or an ended game) is ignored;+ * - notes mode always toggles a pencil mark — possibilities are never judged and cost nothing;+ * - re-tapping the digit already showing erases the cell, in either mode;+ * - in answer mode a digit that disagrees with the solution is rejected: never placed, one life;+ * - anything else is placed, exactly as classic mode always has.+ */+object AnswerMode {++ /**+ * What a tap on [digit] should do to [game].+ *+ * Guards collapse into one check so the table stays readable as written: an unusable selection+ * has a single cause from the caller's point of view (there is nowhere to write), whatever the+ * underlying reason.+ */+ fun decide(game: SudokuGameState, digit: Int): DigitAttempt {+ val index = game.selected+ val usable = index in 0 until game.size.cellCount &&+ !game.isGiven(index) &&+ !game.isWon &&+ !game.isGameOver+ if (!usable) return DigitAttempt.Ignore+ if (game.notesMode) return DigitAttempt.Note(index, digit)+ if (game.entries[index] == digit) return DigitAttempt.Erase(index)+ if (game.answerMode && digit != game.solution[index]) return DigitAttempt.Reject(digit)+ return DigitAttempt.Place(index, digit)+ }++ /**+ * Spends the life a rejection costs.+ *+ * The board is otherwise untouched — the digit was never placed, so there is nothing for undo+ * to restore and nothing for a hint to correct. Flooring at zero keeps a double-tap on the last+ * life from driving the count negative.+ */+ fun applyRejection(game: SudokuGameState): SudokuGameState =+ game.copy(livesRemaining = (game.livesRemaining - 1).coerceAtLeast(0))+}++/**+ * One keypad tap, classified.+ *+ * [Ignore] covers every "nowhere to write" case alike, because the UI does the same thing for all+ * of them: nothing. [Reject] carries the digit so the pad knows which key to flash.+ */+sealed interface DigitAttempt {+ /** Nothing selected, a given cell, or an ended game: there is nowhere to write. */+ data object Ignore : DigitAttempt++ /** Pencil-mark toggle; never judged and never costs a life. */+ data class Note(val index: Int, val digit: Int) : DigitAttempt++ /** Re-tapping the digit already showing, which clears the cell. */+ data class Erase(val index: Int) : DigitAttempt++ /** A digit that may be written; correct by construction in answer mode. */+ data class Place(val index: Int, val digit: Int) : DigitAttempt++ /** A wrong digit in answer mode: refused, never placed, one life. */+ data class Reject(val digit: Int) : DigitAttempt+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuUiContract.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuUiContract.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuUiContract.ktindex c76678acbd..a92c3b2977 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuUiContract.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuUiContract.kt@@ -31,9 +31,24 @@ interface SudokuActions { * [game] is null only before the first puzzle has been generated; the board shows a spinner then. * Generation happens on a background dispatcher because digging a 9x9 runs the solver once per * removed clue.+ *+ * [rejectedDigit] is the last keypad digit answer mode refused to place, or null if none has been+ * refused. It is write-once per attempt — every rejection carries a fresh sequence number, so two+ * wrong taps on the same key still animate twice — and it is never cleared: the keypad's flash runs+ * its course locally, and clearing here would cut a flash short if a correct digit landed meanwhile. */ data class SudokuUiState( val game: SudokuGameState? = null, val canUndo: Boolean = false, val generating: Boolean = false,+ val rejectedDigit: RejectedDigit? = null, )++/**+ * A keypad digit answer mode rejected, with a sequence number telling repeats apart.+ *+ * The pad needs more than the digit: tapping a wrong 7 twice in a row must flash twice, and a+ * state that still says "7" would not recompose. Each rejection bumps [attempt], so every one is a+ * new value even for the same [digit].+ */+data class RejectedDigit(val digit: Int, val attempt: Long)
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 358d71d449..8c040e1b5c 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@@ -3,18 +3,24 @@ package com.vayunmathur.games.sudoku.platform import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.games.sudoku.data.ANSWER_MODE_LIVES import com.vayunmathur.games.sudoku.data.BoardSize import com.vayunmathur.games.sudoku.data.Difficulty import com.vayunmathur.games.sudoku.data.GameConfig+import com.vayunmathur.games.sudoku.data.SudokuDataStore import com.vayunmathur.games.sudoku.data.SudokuGameState import com.vayunmathur.games.sudoku.data.SudokuSnapshot import com.vayunmathur.games.sudoku.data.SudokuStatsRepository+import com.vayunmathur.games.sudoku.domain.AnswerMode+import com.vayunmathur.games.sudoku.domain.DigitAttempt import com.vayunmathur.games.sudoku.domain.SudokuGenerator import com.vayunmathur.library.util.AchievementsManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -34,6 +40,21 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application), val uiState: StateFlow<SudokuUiState> = _uiState.asStateFlow() private val statsRepository = SudokuStatsRepository(application)+ private val settingsStore = SudokuDataStore(application)++ /**+ * The global default new puzzles are dealt with; the game in progress carries its own copy.+ *+ * Shared while the home screen is up so the switch reflects the stored value. Read once per+ * deal — see [newGame] — rather than observed live, so toggling the switch cannot rewrite a+ * game already in progress.+ */+ val answerMode: StateFlow<Boolean> = settingsStore.answerMode+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)++ fun setAnswerMode(enabled: Boolean) {+ viewModelScope.launch { settingsStore.setAnswerMode(enabled) }+ } /** Undo snapshots, oldest first. Cleared whenever a new puzzle is dealt. */ private val history = ArrayDeque<SudokuSnapshot>()@@ -41,6 +62,9 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application), /** Set when the player ever tries a digit that disagrees with the solution. */ private var madeMistake = false + /** Sequence numbers for answer-mode rejections, so repeats of one digit still animate. */+ private var rejectionAttempt = 0L+ val achievementsManager: AchievementsManager = run { val json = application.assets.open("achievements.json").bufferedReader().readText() SudokuAchievementsManager(application, json, statsRepository)@@ -60,18 +84,31 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application), * Deals a new puzzle for [config], replacing anything in progress. * * Generation is dispatched to [Dispatchers.Default] and the board is blanked first, so the- * screen shows a spinner instead of freezing while a 9x9 Expert is dug.+ * screen shows a spinner instead of freezing while a 9x9 Expert is dug. The game snapshots the+ * current answer-mode preference rather than observing it, so the rules it is dealt with are+ * the rules it keeps even if the switch moves mid-game. */ fun newGame(config: GameConfig) {+ newGame(config, answerMode.value)+ }++ /**+ * Deals a new puzzle with an explicit ruleset, for previews and tests.+ *+ * The no-flag overload above is the one the screens call; this one lets a caller deal an answer+ * game without touching the persisted preference.+ */+ fun newGame(config: GameConfig, answerMode: Boolean) { history.clear() madeMistake = false+ rejectionAttempt = 0 _uiState.value = SudokuUiState(generating = true) viewModelScope.launch { val puzzle = withContext(Dispatchers.Default) { SudokuGenerator.generate(config.size, config.difficulty, Random.Default) } statsRepository.recordGamePlayed(config.size, config.difficulty)- _uiState.value = SudokuUiState(game = SudokuGameState.from(puzzle))+ _uiState.value = SudokuUiState(game = SudokuGameState.from(puzzle, answerMode)) } } @@ -89,34 +126,52 @@ 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 digit that disagrees with the solution goes in exactly like any other, with no highlight and no- * complaint. The player finds out only because [checkWin] never fires, which keeps the deduction- * theirs to do; the attempt is remembered for the `no_mistakes` achievement.+ * What the tap *means* is decided by [AnswerMode.decide] — this only carries it out. In+ * particular a digit that disagrees with the solution goes in silently in classic mode (the+ * player finds out only because the win never fires), while in answer mode it is refused: never+ * placed, one life spent, the key flashes. The refusal is remembered for the `no_mistakes`+ * achievement exactly like a classic-mode wrong entry. */ 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+ when (val attempt = AnswerMode.decide(game, digit)) {+ is DigitAttempt.Ignore -> return+ is DigitAttempt.Reject -> rejectDigit(attempt.digit)+ is DigitAttempt.Note -> enterNote(game, attempt.index, attempt.digit)+ is DigitAttempt.Erase -> eraseEntry(game, attempt.index)+ is DigitAttempt.Place -> placeDigit(game, attempt.index, attempt.digit)+ }+ } + /**+ * Clears one entered digit; re-tapping a digit is how the pad doubles as an eraser.+ *+ * Pencil marks on the cell go too: they were candidates for a digit the player just took back.+ */+ private fun eraseEntry(game: SudokuGameState, index: Int) { pushHistory(game)- if (game.notesMode) {- val bit = 1 shl (digit - 1)- mutate { state ->- state.copy(- notes = state.notes.replacing(index, state.notes[index] xor bit),- entries = state.entries.replacing(index, 0),- moveCount = state.moveCount + 1,- )- }- return+ mutate { state ->+ state.copy(+ entries = state.entries.replacing(index, 0),+ notes = state.notes.replacing(index, 0),+ moveCount = state.moveCount + 1,+ ) }+ } - // Tapping the digit already there means "take it back".- val next = if (game.entries[index] == digit) 0 else digit- if (next != 0 && next != game.solution[index]) madeMistake = true+ /**+ * Writes one digit onto the board.+ *+ * In answer mode this is only ever reached with the correct digit — wrong ones are rejected+ * before they get here — so the mistake accounting below only ever fires for classic games,+ * exactly as it always has.+ */+ private fun placeDigit(game: SudokuGameState, index: Int, digit: Int) {+ pushHistory(game)+ if (digit != game.solution[index]) madeMistake = true mutate { state -> state.copy(- entries = state.entries.replacing(index, next),+ entries = state.entries.replacing(index, digit), // A written digit makes its own pencil marks meaningless. notes = state.notes.replacing(index, 0), moveCount = state.moveCount + 1,@@ -125,10 +180,47 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application), checkWin() } + /**+ * Toggles one pencil mark, unconditionally.+ *+ * Extracted from [enterDigit] so the answer-mode guard sits in one place: notes are written+ * digits' rough drafts, and refusing to pencil in a wrong digit would make the mode unusable+ * for the elimination it is meant to encourage.+ */+ private fun enterNote(game: SudokuGameState, index: Int, digit: Int) {+ pushHistory(game)+ val bit = 1 shl (digit - 1)+ mutate { state ->+ state.copy(+ notes = state.notes.replacing(index, state.notes[index] xor bit),+ entries = state.entries.replacing(index, 0),+ moveCount = state.moveCount + 1,+ )+ }+ }++ /**+ * Refuses [digit]: no placement, one life spent, and the key flashes.+ *+ * The life is spent even on a game this ends — the board that hits zero shows the loss as the+ * cost of the tap that caused it, rather than freezing first. History is untouched, so there+ * is nothing to undo: nothing changed on the board. [madeMistake] is set too, keeping answer+ * games eligible for the same `no_mistakes` accounting as classic ones.+ */+ private fun rejectDigit(digit: Int) {+ madeMistake = true+ rejectionAttempt+++ mutate { state -> AnswerMode.applyRejection(state) }+ _uiState.update { it.copy(rejectedDigit = RejectedDigit(digit, rejectionAttempt)) }+ val game = _uiState.value.game ?: return+ if (game.isGameOver) statsRepository.recordGameLost(game.size, game.difficulty)+ }+ override fun clearCell() { val game = _uiState.value.game ?: return val index = game.selected- if (index !in 0 until game.size.cellCount || game.isGiven(index) || game.isWon) return+ if (index !in 0 until game.size.cellCount || game.isGiven(index)) return+ if (game.isWon || game.isGameOver) return pushHistory(game) mutate { state -> state.copy(@@ -146,10 +238,13 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application), * digit sits elsewhere would leave the player deducing from something false. Only once the grid is * consistent does it fill a blank, preferring the selected one so help lands where they are * looking.+ *+ * A hint always places a correct digit, so it costs no life in answer mode — and in answer mode+ * there are never wrong digits to correct first, because wrong digits are never placed. */ override fun hint() { val game = _uiState.value.game ?: return- if (game.isWon) return+ if (game.isWon || game.isGameOver) return val index = game.wrongIndices().firstOrNull() ?: game.selected.takeIf { it >= 0 && !game.isGiven(it) && game.valueAt(it) == 0 } ?: game.blankIndices().firstOrNull()@@ -174,11 +269,12 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application), _uiState.update { it.copy(canUndo = history.isNotEmpty()) } } - /** Clears the player's work but keeps the same puzzle. */+ /** Clears the player's work but keeps the same puzzle — and, in answer mode, refills lives. */ override fun restart() { val game = _uiState.value.game ?: return history.clear() madeMistake = false+ rejectionAttempt = 0 _uiState.value = SudokuUiState( game = game.copy( entries = List(game.size.cellCount) { 0 },@@ -189,6 +285,7 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application), hintsUsed = 0, isWon = false, usedUndo = false,+ livesRemaining = ANSWER_MODE_LIVES, ) ) }@@ -203,7 +300,7 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application), fun incrementTimer() { val game = _uiState.value.game ?: return- if (game.isWon) return+ if (game.isWon || game.isGameOver) return mutate { it.copy(elapsedSeconds = it.elapsedSeconds + 1) } }
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.ktindex 518a53a0c8..09750ed1c3 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt@@ -22,6 +22,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.games.sudoku.R+import com.vayunmathur.games.sudoku.data.ANSWER_MODE_LIVES+import com.vayunmathur.games.sudoku.data.SudokuGameState import com.vayunmathur.games.sudoku.platform.SudokuActions import com.vayunmathur.games.sudoku.platform.SudokuUiState import com.vayunmathur.games.sudoku.ui.components.NumberPad@@ -39,6 +41,7 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.game.GameResultOverlay+import com.vayunmathur.library.ui.game.HeartsRow import com.vayunmathur.library.ui.game.formatDuration import com.vayunmathur.library.ui.isCompactHeight import com.vayunmathur.library.ui.isExpandedWidth@@ -113,12 +116,13 @@ fun GameBoardScreen( .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(Spacing.md), ) {- HintsUsed(game.hintsUsed)+ StatusRow(game) NumberPad( game = game, onDigit = actions::enterDigit, modifier = Modifier.fillMaxWidth(),+ rejected = state.rejectedDigit, ) ActionBar(state, actions, onExit)@@ -149,12 +153,13 @@ fun GameBoardScreen( modifier = Modifier.fillMaxWidth(), ) - HintsUsed(game.hintsUsed)+ StatusRow(game) NumberPad( game = game, onDigit = actions::enterDigit, modifier = Modifier.fillMaxWidth(),+ rejected = state.rejectedDigit, ) ActionBar(state, actions, onExit)@@ -178,6 +183,20 @@ fun GameBoardScreen( } } }++ // Answer mode spent its last life: the board is dead, and the only way forward is a+ // fresh attempt at the same puzzle — restart keeps the grid and refills the lives.+ if (game.isGameOver) {+ GameResultOverlay(+ title = stringResource(R.string.out_of_lives),+ won = false,+ onPlayAgain = { actions.restart() },+ playAgainLabel = stringResource(R.string.try_again),+ onBack = onExit,+ ) {+ Text(stringResource(R.string.out_of_lives_message))+ }+ } } } }@@ -193,6 +212,27 @@ private fun HintsUsed(hintsUsed: Int) { } } +/**+ * The status line above the pad: hints so far, and the lives left in answer mode.+ *+ * Nothing renders for a classic game with no hints yet, exactly as before — the row only exists+ * when it has something to say.+ */+@Composable+private fun StatusRow(game: SudokuGameState) {+ if (game.hintsUsed == 0 && !game.answerMode) return+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ HintsUsed(game.hintsUsed)+ if (game.answerMode) {+ HeartsRow(remaining = game.livesRemaining, total = ANSWER_MODE_LIVES)+ }+ }+}+ @Composable private fun ActionBar( state: SudokuUiState,@@ -201,6 +241,9 @@ private fun ActionBar( ) { val game = state.game ?: return var confirmGiveUp by remember { mutableStateOf(false) }+ // Won or out of lives: the board takes no more input, so erase and hint go quiet too. Undo+ // stays as it is — it only restores entries, which cannot revive a finished game either way.+ val ended = game.isWon || game.isGameOver Column(verticalArrangement = Arrangement.spacedBy(Spacing.sm)) { Row( Modifier.fillMaxWidth(),@@ -221,7 +264,7 @@ private fun ActionBar( OutlinedButton( onClick = { actions.clearCell() }, modifier = Modifier.weight(1f),- enabled = !game.isWon,+ enabled = !ended, ) { Text(stringResource(R.string.erase)) } OutlinedButton( onClick = { actions.undo() },@@ -231,7 +274,7 @@ private fun ActionBar( OutlinedButton( onClick = { actions.hint() }, modifier = Modifier.weight(1f),- enabled = !game.isWon,+ enabled = !ended, ) { Text(stringResource(R.string.hint)) } } TextButton(
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/HomeScreen.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/HomeScreen.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/HomeScreen.ktindex c74217b5c9..e7bbda3911 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/HomeScreen.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/HomeScreen.kt@@ -28,6 +28,7 @@ import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.DesktopMaxWidthContainer import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.SettingsSwitchRow import com.vayunmathur.library.ui.Spacing import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior@@ -41,6 +42,7 @@ fun HomeScreen( viewModel: SudokuViewModel, ) { val uiState by viewModel.uiState.collectAsState()+ val answerMode by viewModel.answerMode.collectAsState() var showConfig by remember { mutableStateOf(false) } // Seeds the picker with the last thing played, so a player grinding one setting taps twice. var lastConfig by remember { mutableStateOf(GameConfig()) }@@ -78,6 +80,16 @@ fun HomeScreen( modifier = Modifier.fillMaxWidth(), ) { Text(stringResource(UiR.string.new_game)) } + // The only setting: whether new puzzles reject wrong digits. Changing it never touches+ // a game in progress — the board snapshots the value when it is dealt.+ SettingsSwitchRow(+ title = stringResource(R.string.answer_mode),+ supportingText = stringResource(R.string.answer_mode_description),+ checked = answerMode,+ onCheckedChange = { viewModel.setAnswerMode(it) },+ modifier = Modifier.fillMaxWidth(),+ )+ Row( Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(Spacing.sm),
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/NumberPad.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/NumberPad.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/NumberPad.ktindex 5d0e9a0fc7..d8ca233214 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/NumberPad.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/NumberPad.kt@@ -11,8 +11,14 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription@@ -24,8 +30,11 @@ import com.vayunmathur.games.sudoku.R import com.vayunmathur.games.sudoku.data.BoardSize import com.vayunmathur.games.sudoku.data.SudokuGameState import com.vayunmathur.games.sudoku.data.sudokuSymbol+import com.vayunmathur.games.sudoku.platform.RejectedDigit import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.animatedColor+import kotlinx.coroutines.delay /** * The digit keys, laid out as a grid in the board's own box shape.@@ -40,14 +49,21 @@ import com.vayunmathur.library.ui.Text * They are drawn like the grid's own cells — background-coloured inside, outlined — rather than as * filled buttons, so a block of ten of them does not dominate the screen above the board it serves. *- * No key is ever disabled. A wrong digit is accepted silently, so there is nothing to gate on, and a- * digit that already appears the maximum number of times may still be one the player wants to move.+ * In classic mode no key is ever disabled: a wrong digit is accepted silently, so there is nothing+ * to gate on, and a digit that already appears the maximum number of times may still be one the+ * player wants to move. In answer mode wrong digits can never land, so a digit with every copy on+ * the board is done — its key is greyed out — and a refused digit flashes red on its key.+ *+ * @param rejected the last digit answer mode refused, with a sequence number telling repeats+ * apart. The pad flashes the matching key and settles back on its own; the state is never cleared,+ * so a correct entry landing mid-flash cannot cut it short. */ @Composable fun NumberPad( game: SudokuGameState, onDigit: (Int) -> Unit, modifier: Modifier = Modifier,+ rejected: RejectedDigit? = null, ) { val size = game.size Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) {@@ -59,6 +75,11 @@ fun NumberPad( digit = digit, size = size, notesMode = game.notesMode,+ // Only answer mode can complete a digit: classic entries may be wrong or+ // moved, so the count proves nothing there.+ enabled = !game.answerMode || !game.isDigitComplete(digit),+ flashing = rejected?.digit == digit,+ flashKey = rejected?.attempt, onClick = { onDigit(digit) }, ) }@@ -73,15 +94,56 @@ fun NumberPad( * In notes mode the digit shrinks into the slot it would occupy as a pencil mark, so the key is a * preview of the mark it will place — which is also what tells the player the mode is on, without * needing a second colour for it.+ *+ * A refused digit tints the key red and settles back on its own: [flashing] turns on when a+ * rejection names this key and [flashKey] tells repeats apart, so two wrong taps on one key flash+ * twice. The lit flag is local state rather than a round-trip through the ViewModel — a round-trip+ * would cut the flash short whenever a correct digit lands meanwhile. */ @Composable private fun DigitKey( digit: Int, size: BoardSize, notesMode: Boolean,+ enabled: Boolean,+ flashing: Boolean,+ flashKey: Long?, onClick: () -> Unit, ) { val scheme = MaterialTheme.colorScheme+ var lit by remember { mutableStateOf(false) }+ // Keyed on both: a second rejection names a new attempt even for the same digit, and a rejection+ // of another digit must switch this key's flash off — cancelling the delay would otherwise leave+ // it stuck red, since the cancelled coroutine never reaches the reset.+ LaunchedEffect(flashing, flashKey) {+ if (flashing && flashKey != null) {+ lit = true+ delay(FLASH_MILLIS)+ lit = false+ } else {+ lit = false+ }+ }+ // On the scheme's effects spec rather than a hand-rolled tween, so the fade matches the app.+ val background = animatedColor(+ when {+ lit -> scheme.errorContainer+ !enabled -> scheme.surfaceContainerHighest+ else -> scheme.background+ }+ )+ val contentColor = when {+ lit -> scheme.onErrorContainer+ // A finished digit reads as done, not broken: surface text rather than the error colour.+ !enabled -> scheme.onSurface.copy(alpha = DISABLED_ALPHA)+ else -> scheme.onSurface+ }+ // Pencil marks keep their own quieter colour, dimming only when the key itself is done or lit.+ val noteColor = when {+ lit -> scheme.onErrorContainer+ !enabled -> scheme.onSurfaceVariant.copy(alpha = DISABLED_ALPHA)+ else -> scheme.onSurfaceVariant+ } val label = sudokuSymbol(digit) val description = stringResource( if (notesMode) R.string.cd_note_key else R.string.cd_digit_key,@@ -90,18 +152,18 @@ private fun DigitKey( Box( Modifier .size(KeySize)- .background(scheme.background)+ .background(background) .border(OutlineWidth, scheme.outline)- .clickable(onClick = onClick)+ .clickable(enabled = enabled, onClick = onClick) .clearAndSetSemantics { contentDescription = description }, contentAlignment = Alignment.Center, ) { if (notesMode) {- NoteSlot(digit = digit, label = label, size = size)+ NoteSlot(digit = digit, label = label, size = size, contentColor = noteColor) } else { Text( text = label,- color = scheme.onSurface,+ color = contentColor, fontSize = FullFontSize, textAlign = TextAlign.Center, )@@ -119,7 +181,7 @@ private fun DigitKey( * still tells the player exactly which mark the tap will place. */ @Composable-private fun NoteSlot(digit: Int, label: String, size: BoardSize) {+private fun NoteSlot(digit: Int, label: String, size: BoardSize, contentColor: Color) { val slotHeight = KeySize / size.boxRows val target = digit - 1 Column(Modifier.fillMaxSize()) {@@ -139,7 +201,7 @@ private fun NoteSlot(digit: Int, label: String, size: BoardSize) { if (row * size.boxCols + col == target) { Text( text = label,- color = MaterialTheme.colorScheme.onSurfaceVariant,+ color = contentColor, fontSize = NoteFontSize, // Matched to the slot, or the glyph's own line box overflows it and the // bottom row of a 3x4 pad is clipped.@@ -163,6 +225,12 @@ private val OutlineWidth = 1.dp /** Size of a digit that a tap will write into the grid. */ private val FullFontSize = 19.sp +/** How long a refused key stays red before settling back, in milliseconds. */+private const val FLASH_MILLIS = 450L++/** Alpha of a finished digit's key: reads as done rather than broken. */+private const val DISABLED_ALPHA = 0.38f+ /** * Size of a digit a tap will pencil in. *
games/sudoku/src/main/res/values/strings.xml
diff --git a/games/sudoku/src/main/res/values/strings.xml b/games/sudoku/src/main/res/values/strings.xmlindex fc85df55ac..9510d2a4b8 100644--- a/games/sudoku/src/main/res/values/strings.xml+++ b/games/sudoku/src/main/res/values/strings.xml@@ -17,6 +17,19 @@ <!-- GameConfigDialog: Board size option, a 12 by 12 grid of 3x4 boxes. Noun, dimensions --> <string name="size_twelve" translatable="false">12x12</string> + <!-- HomeScreen: Title of the answer-mode setting row. Noun phrase -->+ <string name="answer_mode">Answer mode</string>+ <!-- HomeScreen: Explanation of answer mode under its title. Sentence -->+ <string name="answer_mode_description">Wrong digits are rejected and cost a life. Three strikes ends the puzzle.</string>+ <!-- GameBoardScreen: Lives counter next to the hearts row, e.g. Lives: 2. Noun plural -->+ <string name="lives">Lives</string>+ <!-- GameOverOverlay: Title shown when answer mode runs out of lives. Declarative -->+ <string name="out_of_lives">Out of lives</string>+ <!-- GameOverOverlay: Explains the loss and offers another try. Sentence -->+ <string name="out_of_lives_message">Three wrong digits ended this puzzle. Try again?</string>+ <!-- GameOverOverlay: Starts a fresh puzzle with the same size and difficulty. Verb phrase -->+ <string name="try_again">Try Again</string>+ <!-- GameConfigDialog: Hardest difficulty, fewest clues given. Adjective --> <string name="difficulty_expert">Expert</string>
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/AnswerModeTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/AnswerModeTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/AnswerModeTest.ktnew file mode 100644index 0000000000..500969787e--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/AnswerModeTest.kt@@ -0,0 +1,152 @@+package com.vayunmathur.games.sudoku.domain++import com.vayunmathur.games.sudoku.data.ANSWER_MODE_LIVES+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.SudokuGameState+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertTrue++class AnswerModeTest {++ private val puzzle = SudokuGenerator.generate(BoardSize.SIX, Difficulty.EASY, Random(1))+ private val fresh = SudokuGameState.from(puzzle, answerMode = true)+ private val classic = SudokuGameState.from(puzzle)++ /** A cell the player is allowed to fill in. */+ private val blank = puzzle.givens.indices.first { puzzle.givens[it] == 0 }++ /** Digits that do and do not belong in [blank]. */+ private val rightDigit = puzzle.solution[blank]+ private val wrongDigit = (1..puzzle.size.side).first { it != rightDigit }++ @Test+ fun aWrongDigitIsRejectedAndNeverPlaced() {+ val attempt = AnswerMode.decide(fresh.copy(selected = blank), wrongDigit)+ assertIs<DigitAttempt.Reject>(attempt)+ assertEquals(wrongDigit, attempt.digit, "the pad must know which key to flash")+ }++ @Test+ fun aCorrectDigitIsPlaced() {+ val attempt = AnswerMode.decide(fresh.copy(selected = blank), rightDigit)+ assertIs<DigitAttempt.Place>(attempt)+ assertEquals(blank, attempt.index)+ }++ @Test+ fun classicModeStillAcceptsWrongDigits() {+ // The silent-accept contract predates answer mode and must not change.+ val attempt = AnswerMode.decide(classic.copy(selected = blank), wrongDigit)+ assertIs<DigitAttempt.Place>(attempt)+ }++ @Test+ fun notesAreNeverJudged() {+ // Pencil marks are possibilities, not claims: even a wrong digit pencils in freely.+ val game = fresh.copy(selected = blank, notesMode = true)+ val attempt = AnswerMode.decide(game, wrongDigit)+ assertIs<DigitAttempt.Note>(attempt)+ }++ @Test+ fun retappingTheShownDigitErasesEvenInAnswerMode() {+ val game = fresh.copy(+ selected = blank,+ entries = fresh.entries.toMutableList().also { it[blank] = rightDigit },+ )+ assertIs<DigitAttempt.Erase>(AnswerMode.decide(game, rightDigit))+ }++ @Test+ fun givensUnselectedAndEndedGamesAreIgnored() {+ val given = puzzle.givens.indices.first { puzzle.givens[it] != 0 }+ assertIs<DigitAttempt.Ignore>(AnswerMode.decide(fresh.copy(selected = given), rightDigit))+ assertIs<DigitAttempt.Ignore>(AnswerMode.decide(fresh, wrongDigit))+ assertIs<DigitAttempt.Ignore>(+ AnswerMode.decide(fresh.copy(selected = blank, isWon = true), wrongDigit),+ "a won game takes no more input",+ )+ assertIs<DigitAttempt.Ignore>(+ AnswerMode.decide(fresh.copy(selected = blank, livesRemaining = 0), wrongDigit),+ "a game out of lives takes no more input",+ )+ }++ @Test+ fun rejectionSpendsOneLifeAndLeavesTheBoardUntouched() {+ val game = fresh.copy(selected = blank)+ val after = AnswerMode.applyRejection(game)+ assertEquals(ANSWER_MODE_LIVES - 1, after.livesRemaining)+ assertEquals(0, after.valueAt(blank), "the refused digit must not be on the board")+ assertEquals(game.entries, after.entries)+ assertEquals(game.notes, after.notes)+ }++ @Test+ fun rejectionFloorsAtZero() {+ val game = fresh.copy(livesRemaining = 0)+ assertEquals(0, AnswerMode.applyRejection(game).livesRemaining)+ }++ @Test+ fun zeroLivesIsGameOverButOnlyInAnswerMode() {+ assertTrue(fresh.copy(livesRemaining = 0).isGameOver)+ assertFalse(fresh.copy(livesRemaining = 1).isGameOver)+ // Classic games have no lives, so the counter must never end them.+ assertFalse(classic.copy(livesRemaining = 0).isGameOver)+ }++ @Test+ fun aSolvedBoardIsNeverGameOver() {+ val solved = fresh.copy(+ entries = List(puzzle.size.cellCount) {+ if (fresh.isGiven(it)) 0 else puzzle.solution[it]+ },+ livesRemaining = 0,+ )+ assertTrue(solved.isComplete)+ assertFalse(solved.isGameOver, "the winning tap lands before the life hits zero")+ }++ @Test+ fun completedDigitsAreDetected() {+ // Only blanks can be "still missing": a holder that is a given shows its digit already.+ val blanks = blanksHolding(rightDigit)+ val entries = fresh.entries.toMutableList()+ if (blanks.size >= 2) {+ blanks.dropLast(1).forEach { entries[it] = rightDigit }+ val almost = fresh.copy(entries = entries)+ assertFalse(almost.isDigitComplete(rightDigit), "one copy still missing")+ }+ blanks.forEach { entries[it] = rightDigit }+ assertTrue(fresh.copy(entries = entries).isDigitComplete(rightDigit))+ }++ @Test+ fun aFullyCluedDigitIsCompleteFromTheFirstFrame() {+ // A digit that needs no entry is complete with nothing placed: the pad must grey it out+ // without waiting for the player to do anything.+ val clued = (1..puzzle.size.side).firstOrNull { digit ->+ (0 until puzzle.size.cellCount).count {+ puzzle.givens[it] == digit+ } >= puzzle.size.side+ }+ if (clued == null) return // This seed leaves every digit short; nothing to assert.+ assertTrue(fresh.isDigitComplete(clued))+ }++ @Test+ fun anIncompleteDigitIsNotComplete() {+ val digit = (1..puzzle.size.side).first { !fresh.isDigitComplete(it) }+ assertFalse(fresh.isDigitComplete(digit))+ }++ /** Blank cells whose solution is [digit] — the only copies the player can still place. */+ private fun blanksHolding(digit: Int): List<Int> =+ (0 until puzzle.size.cellCount).filter { puzzle.solution[it] == digit && puzzle.givens[it] == 0 }+}