Modern Apps git

← Modern-Apps.git

sudoku: new game with size/difficulty picker and generated puzzles

Commit
2aacbc5855c3f3b95564a96b373f55e9ccbe0cdc
Author
vayun-mathur <[email protected]>
When
2026-08-24 02:30 UTC (3 months ago)
Parents
2145a00

Diff

games/hub/src/main/AndroidManifest.xml
diff --git a/games/hub/src/main/AndroidManifest.xml b/games/hub/src/main/AndroidManifest.xmlindex 387cf1695e..69b5601ce2 100644--- a/games/hub/src/main/AndroidManifest.xml+++ b/games/hub/src/main/AndroidManifest.xml@@ -17,6 +17,7 @@         <package android:name="com.vayunmathur.games.wordmaker" />         <package android:name="com.vayunmathur.games.logicgate" />         <package android:name="com.vayunmathur.games.voxels" />+        <package android:name="com.vayunmathur.games.sudoku" />         <package android:name="com.vayunmathur.games" />         <intent>             <action android:name="android.intent.action.MAIN" />
games/sudoku/build.gradle.kts
diff --git a/games/sudoku/build.gradle.kts b/games/sudoku/build.gradle.ktsnew file mode 100644index 0000000000..f33050bd3d--- /dev/null+++ b/games/sudoku/build.gradle.kts@@ -0,0 +1,20 @@+plugins {+    id("common-conventions-app")+    // Listing screenshots come from Compose previews (src/screenshotTest), not from an+    // instrumented test on a device. Same `:games:sudoku:metadata` task name either way.+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "grid_3x3"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.games.sudoku"+    }+}++dependencies {+    implementation(project(":sdk:games"))+}
games/sudoku/src/main/AndroidManifest.xml
diff --git a/games/sudoku/src/main/AndroidManifest.xml b/games/sudoku/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..b5ea5ad3d6--- /dev/null+++ b/games/sudoku/src/main/AndroidManifest.xml@@ -0,0 +1,28 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="com.vayunmathur.games.hub.permission.READ_GAME_DATA" />+    <uses-permission android:name="com.vayunmathur.games.hub.permission.WRITE_GAME_DATA" />++    <application+        android:allowBackup="true"+        android:backupAgent=".platform.AppBackupAgent"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>+    </application>++</manifest>
games/sudoku/src/main/assets/achievements.json
diff --git a/games/sudoku/src/main/assets/achievements.json b/games/sudoku/src/main/assets/achievements.jsonnew file mode 100644index 0000000000..2b8c82c8ed--- /dev/null+++ b/games/sudoku/src/main/assets/achievements.json@@ -0,0 +1,55 @@+[+  {+    "id": "first_win",+    "name": "Solved",+    "description": "Complete your first puzzle!"+  },+  {+    "id": "win_nine",+    "name": "Full House",+    "description": "Complete a 9x9 puzzle."+  },+  {+    "id": "win_expert",+    "name": "Expert Hand",+    "description": "Complete an Expert puzzle."+  },+  {+    "id": "no_hints",+    "name": "Unaided",+    "description": "Complete a 9x9 puzzle without using a hint."+  },+  {+    "id": "no_mistakes",+    "name": "Flawless",+    "description": "Complete a puzzle without ever entering a wrong digit."+  },+  {+    "id": "speed_nine",+    "name": "Quick Thinker",+    "description": "Complete a 9x9 puzzle in under five minutes."+  },+  {+    "id": "every_size",+    "name": "Shape Shifter",+    "description": "Complete a puzzle on every board size."+  },+  {+    "id": "wins_10",+    "name": "Regular",+    "description": "Complete 10 puzzles.",+    "targetProgress": 10+  },+  {+    "id": "wins_50",+    "name": "Devoted",+    "description": "Complete 50 puzzles.",+    "targetProgress": 50+  },+  {+    "id": "win_streak_5",+    "name": "On A Roll",+    "description": "Win five puzzles in a row.",+    "targetProgress": 5+  }+]
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/MainActivity.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/MainActivity.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/MainActivity.ktnew file mode 100644index 0000000000..aed18572fa--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/MainActivity.kt@@ -0,0 +1,22 @@+package com.vayunmathur.games.sudoku++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.games.sudoku.platform.SudokuViewModel+import com.vayunmathur.library.ui.DynamicTheme++class MainActivity : ComponentActivity() {+    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                val viewModel: SudokuViewModel = viewModel()+                Navigation(viewModel)+            }+        }+    }+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/Navigation.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/Navigation.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/Navigation.ktnew file mode 100644index 0000000000..04054bb5a0--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/Navigation.kt@@ -0,0 +1,40 @@+package com.vayunmathur.games.sudoku++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import com.vayunmathur.games.sudoku.platform.AppBackupAgent+import com.vayunmathur.games.sudoku.platform.SudokuViewModel+import com.vayunmathur.games.sudoku.ui.GameScreen+import com.vayunmathur.games.sudoku.ui.HomeScreen+import com.vayunmathur.library.ui.AchievementNotification+import com.vayunmathur.library.ui.GameCenterScreen+import com.vayunmathur.library.util.GameHubComposeHook+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack++@Composable+fun Navigation(viewModel: SudokuViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Home)+    val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()+    GameHubComposeHook("sudoku", viewModel.achievementsManager)+    Box(Modifier.fillMaxSize()) {+        MainNavigation(backStack) {+            entry<Route.Home> { HomeScreen(backStack, viewModel) }+            entry<Route.Game> { GameScreen(backStack, viewModel, it.config) }+            entry<Route.GameCenter> {+                GameCenterScreen(+                    backupAgent = AppBackupAgent(),+                    manager = viewModel.achievementsManager,+                    onBack = { backStack.pop() },+                )+            }+        }+        newAchievement?.let {+            AchievementNotification(it) { viewModel.dismissAchievementNotification() }+        }+    }+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/Route.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/Route.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/Route.ktnew file mode 100644index 0000000000..37ee232f10--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/Route.kt@@ -0,0 +1,21 @@+package com.vayunmathur.games.sudoku++import com.vayunmathur.games.sudoku.data.GameConfig+import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+    @Serializable+    data object Home : Route++    /**+     * Carries the [GameConfig] so the board can deal itself a puzzle if it is ever entered without+     * one in memory — the ViewModel holds the grid but nothing restores it after process death.+     */+    @Serializable+    data class Game(val config: GameConfig) : Route++    @Serializable+    data object GameCenter : Route+}
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.ktnew file mode 100644index 0000000000..d6fc25d0e2--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt@@ -0,0 +1,132 @@+package com.vayunmathur.games.sudoku.data++import kotlinx.serialization.Serializable++/**+ * The three board shapes on offer, each with the box geometry that goes with it.+ *+ * [boxRows] x [boxCols] must equal [side], because a Sudoku box has to hold exactly as many cells+ * as a row does — that is what makes "every digit once per box" the same strength of constraint as+ * "every digit once per row". 6x6 is the only asymmetric one (2 rows of 3), which is why the box+ * dimensions are stored rather than derived from a square root.+ */+@Serializable+enum class BoardSize(val side: Int, val boxRows: Int, val boxCols: Int) {+    FOUR(4, 2, 2),+    SIX(6, 2, 3),+    NINE(9, 3, 3);++    val cellCount: Int get() = side * side++    /** Index of the box containing [index], counting left-to-right then top-to-bottom. */+    fun boxOf(index: Int): Int {+        val row = index / side+        val col = index % side+        return (row / boxRows) * (side / boxCols) + (col / boxCols)+    }+}++/**+ * How many cells the generator leaves filled in.+ *+ * The clue counts are fractions of the board rather than absolute numbers so one difficulty means+ * roughly the same amount of deduction on a 4x4 as on a 9x9. [clueFraction] is a target, not a+ * guarantee: digging stops early if removing any remaining clue would leave the puzzle with more+ * than one solution, so an EXPERT 4x4 often lands well above its target simply because tiny grids+ * run out of removable cells.+ */+@Serializable+enum class Difficulty(val clueFraction: Double) {+    EASY(0.60),+    MEDIUM(0.46),+    HARD(0.36),+    EXPERT(0.28);++    /** Target number of givens for [size]. Never below the point where digging is pointless. */+    fun targetClues(size: BoardSize): Int =+        maxOf((size.cellCount * clueFraction).toInt(), size.side + 1)+}++/** The options chosen on the home screen, carried into puzzle generation. */+@Serializable+data class GameConfig(+    val size: BoardSize = BoardSize.NINE,+    val difficulty: Difficulty = Difficulty.MEDIUM,+) {+    /** Stats key component, so records are tracked per board shape and difficulty. */+    val variant: String get() = "${size.name}_${difficulty.name}"+}++/**+ * A generated puzzle: the clues the player starts with and the unique grid they lead to.+ *+ * 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.+ */+data class Puzzle(+    val size: BoardSize,+    val difficulty: Difficulty,+    val givens: List<Int>,+    val solution: List<Int>,+)++/**+ * Everything about a game in progress.+ *+ * [entries] and [notes] are parallel to [Puzzle.givens] and are only ever read where the given is+ * 0 — a cell the puzzle supplied can't be typed over. [notes] holds pencil marks as a bitmask+ * (bit `d - 1` set means digit `d` is pencilled in) so the whole board is a flat `List<Int>` and+ * therefore cheap to snapshot onto the undo stack.+ */+data class SudokuGameState(+    val size: BoardSize,+    val difficulty: Difficulty,+    val givens: List<Int>,+    val solution: List<Int>,+    val entries: List<Int>,+    val notes: List<Int>,+    val selected: Int = -1,+    val notesMode: Boolean = false,+    val moveCount: Int = 0,+    val elapsedSeconds: Int = 0,+    val hintsUsed: Int = 0,+    val isWon: Boolean = false,+    val usedUndo: Boolean = false,+) {+    val variant: String get() = "${size.name}_${difficulty.name}"++    /** 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]++    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]+    }++    /** 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 }++    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(+            size = puzzle.size,+            difficulty = puzzle.difficulty,+            givens = puzzle.givens,+            solution = puzzle.solution,+            entries = List(puzzle.size.cellCount) { 0 },+            notes = List(puzzle.size.cellCount) { 0 },+        )+    }+}++/** The one snapshot the undo stack stores per move. */+data class SudokuSnapshot(+    val entries: List<Int>,+    val notes: List<Int>,+)
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.ktnew file mode 100644index 0000000000..3a8fbba80b--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.kt@@ -0,0 +1,101 @@+package com.vayunmathur.games.sudoku.data++import android.content.Context+import android.content.SharedPreferences+import androidx.core.content.edit+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * One record's worth of history. [bestTimeSeconds] starts at [Int.MAX_VALUE] so "no time yet" and+ * "finished instantly" stay distinguishable and `min` works without a null check.+ */+@Serializable+data class GameStats(+    val gamesPlayed: Int = 0,+    val gamesWon: Int = 0,+    val currentWinStreak: Int = 0,+    val bestWinStreak: Int = 0,+    val bestTimeSeconds: Int = Int.MAX_VALUE,+)++/**+ * Played/won/streak/best-time records, kept per board size and difficulty.+ *+ * Records are keyed by variant rather than rolled into one number because a best time only means+ * something next to the shape it was set on — 90 seconds is a slow 4x4 and a remarkable 9x9. The+ * home screen still wants a single figure per size, so [getSizeStats] aggregates by key prefix+ * instead of keeping a second denormalised record that could drift.+ *+ * Reads are synchronous and happen during composition. That is fine for SharedPreferences, which is+ * an in-memory map after the first load, and is the reason this is not a DataStore.+ */+class SudokuStatsRepository(context: Context) {+    private val prefs: SharedPreferences =+        context.getSharedPreferences("sudoku_stats", Context.MODE_PRIVATE)+    private val json = Json { ignoreUnknownKeys = true }++    private fun key(size: BoardSize, difficulty: Difficulty) =+        "${sizePrefix(size)}__${difficulty.name}"++    private fun sizePrefix(size: BoardSize) = "stats_${size.name}"++    private fun readKey(key: String): GameStats? =+        prefs.getString(key, null)?.let { json.decodeFromString<GameStats>(it) }++    fun getStats(size: BoardSize, difficulty: Difficulty): GameStats =+        readKey(key(size, difficulty)) ?: GameStats()++    /** Every difficulty's record for [size], summed for played/won and best-of for the rest. */+    fun getSizeStats(size: BoardSize): GameStats {+        val records = Difficulty.entries.mapNotNull { readKey(key(size, it)) }+        if (records.isEmpty()) return GameStats()+        return GameStats(+            gamesPlayed = records.sumOf { it.gamesPlayed },+            gamesWon = records.sumOf { it.gamesWon },+            currentWinStreak = records.maxOf { it.currentWinStreak },+            bestWinStreak = records.maxOf { it.bestWinStreak },+            bestTimeSeconds = records.minOf { it.bestTimeSeconds },+        )+    }++    private fun save(size: BoardSize, difficulty: Difficulty, stats: GameStats) {+        prefs.edit { putString(key(size, difficulty), json.encodeToString(stats)) }+    }++    /** Counted when the puzzle is dealt, so an abandoned game still shows up as played. */+    fun recordGamePlayed(size: BoardSize, difficulty: Difficulty) {+        val stats = getStats(size, difficulty)+        save(size, difficulty, stats.copy(gamesPlayed = stats.gamesPlayed + 1))+    }++    fun recordGameWon(size: BoardSize, difficulty: Difficulty, timeSeconds: Int) {+        val stats = getStats(size, difficulty)+        val streak = stats.currentWinStreak + 1+        save(+            size, difficulty,+            stats.copy(+                gamesWon = stats.gamesWon + 1,+                currentWinStreak = streak,+                bestWinStreak = maxOf(stats.bestWinStreak, streak),+                bestTimeSeconds = minOf(stats.bestTimeSeconds, timeSeconds),+            )+        )+    }++    fun recordGameLost(size: BoardSize, difficulty: Difficulty) {+        val stats = getStats(size, difficulty)+        save(size, difficulty, stats.copy(currentWinStreak = 0))+    }++    fun getTotalGamesWon(): Int =+        BoardSize.entries.sumOf { size -> Difficulty.entries.sumOf { getStats(size, it).gamesWon } }++    fun getBestWinStreak(): Int =+        BoardSize.entries.maxOfOrNull { getSizeStats(it).bestWinStreak } ?: 0++    /** Best time on [difficulty] across every board size, or null if it has never been won. */+    fun getBestTime(difficulty: Difficulty): Int? =+        BoardSize.entries.minOf { getStats(it, difficulty).bestTimeSeconds }+            .takeIf { it < Int.MAX_VALUE }+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/SudokuGenerator.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/SudokuGenerator.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/SudokuGenerator.ktnew file mode 100644index 0000000000..d6686fb1e7--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/SudokuGenerator.kt@@ -0,0 +1,54 @@+package com.vayunmathur.games.sudoku.domain++import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.Puzzle+import kotlin.random.Random++/**+ * Fill a grid at random, then remove clues for as long as the answer stays unique.+ *+ * Generating this way rather than dealing from a shipped set means the puzzle is always new, and+ * the uniqueness check is what makes it fair: a player is never asked to guess between two valid+ * completions. The cost is one [SudokuSolver.countSolutions] call per removal attempt, which is why+ * the solver is bitmasked and MRV-ordered and why callers run this off the main thread.+ */+object SudokuGenerator {++    /**+     * A puzzle of [size] whose clue count approaches [Difficulty.targetClues].+     *+     * Digging walks the cells in a random order and keeps a removal only when the grid still has+     * exactly one solution, so the result is always solvable by deduction alone. It stops at the+     * target, or earlier if every remaining clue turns out to be load-bearing — small boards run out+     * of slack long before EXPERT's target, so the returned puzzle can hold more clues than asked+     * for. It never holds fewer.+     */+    fun generate(size: BoardSize, difficulty: Difficulty, rng: Random): Puzzle {+        val solver = SudokuSolver(size)+        val solution = solver.solve(List(size.cellCount) { 0 }, rng)+            ?: error("every empty ${size.side}x${size.side} grid has a completion")++        val working = solution.toMutableList()+        var clues = size.cellCount+        val target = difficulty.targetClues(size)++        for (index in (0 until size.cellCount).shuffled(rng)) {+            if (clues <= target) break+            val removed = working[index]+            working[index] = 0+            if (solver.countSolutions(working) == 1) {+                clues--+            } else {+                working[index] = removed+            }+        }++        return Puzzle(+            size = size,+            difficulty = difficulty,+            givens = working.toList(),+            solution = solution,+        )+    }+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/SudokuSolver.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/SudokuSolver.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/SudokuSolver.ktnew file mode 100644index 0000000000..03a891310a--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/domain/SudokuSolver.kt@@ -0,0 +1,155 @@+package com.vayunmathur.games.sudoku.domain++import com.vayunmathur.games.sudoku.data.BoardSize+import kotlin.random.Random++/**+ * Backtracking search over one board shape, used both to fill a grid and to prove a dug puzzle+ * still has exactly one answer.+ *+ * Candidates are held as bitmasks per row, column and box, so testing whether a digit fits is three+ * AND operations rather than a scan of 3 x [BoardSize.side] cells. The search always expands the+ * blank cell with the fewest candidates first (minimum remaining values); on a 9x9 that is the+ * difference between a generator that finishes in milliseconds and one that visibly stalls the+ * board while [countSolutions] runs once per dug cell.+ *+ * An instance owns mutable scratch state, so it is not safe to share across threads and not+ * reentrant. Create one per generation pass and keep it on a background dispatcher.+ */+class SudokuSolver(private val size: BoardSize) {+    private val side = size.side+    private val cells = size.cellCount+    private val full = (1 shl side) - 1+    private val boxOf = IntArray(cells) { size.boxOf(it) }++    private val grid = IntArray(cells)+    private val rowMask = IntArray(side)+    private val colMask = IntArray(side)+    private val boxMask = IntArray(side)++    /**+     * Number of ways [initial] can be completed, stopping once [limit] have been found.+     *+     * The result is "at least this many", not an exact total: subtree counts are added whole, so a+     * generous [limit] can be overshot. Callers checking uniqueness want to know "one, or more than+     * one" and never the true total, which for a heavily dug grid can run to millions. The default+     * [limit] of 2 is exactly that question — a return of 1 means unique.+     */+    fun countSolutions(initial: List<Int>, limit: Int = 2): Int {+        if (!load(initial)) return 0+        return count(limit)+    }++    /**+     * One completion of [initial], or null if it has none.+     *+     * Passing an [rng] shuffles the digit order at every branch, which is what turns a blank grid+     * into an arbitrary filled board instead of the same canonical one every time.+     */+    fun solve(initial: List<Int>, rng: Random? = null): List<Int>? {+        if (!load(initial)) return null+        return if (search(rng)) grid.toList() else null+    }++    /** Seeds the masks from [initial]. False if [initial] already breaks a constraint. */+    private fun load(initial: List<Int>): Boolean {+        grid.fill(0)+        rowMask.fill(0)+        colMask.fill(0)+        boxMask.fill(0)+        for (index in 0 until cells) {+            val digit = initial[index]+            if (digit != 0 && !place(index, digit)) return false+        }+        return true+    }++    private fun count(limit: Int): Int {+        val index = bestCell()+        if (index == -1) return 1+        var mask = candidates(index)+        var total = 0+        while (mask != 0) {+            val bit = mask and (-mask)+            mask = mask xor bit+            place(index, bitToDigit(bit))+            total += count(limit)+            unplace(index)+            if (total >= limit) return total+        }+        return total+    }++    private fun search(rng: Random?): Boolean {+        val index = bestCell()+        if (index == -1) return true+        val digits = digitsOf(candidates(index))+        for (digit in if (rng == null) digits else digits.shuffled(rng)) {+            place(index, digit)+            if (search(rng)) return true+            unplace(index)+        }+        return false+    }++    /**+     * The blank cell with the fewest candidates, or -1 when the grid is full.+     *+     * A cell with no candidates at all is returned immediately: it is a dead end, and reporting it+     * lets the caller fail on the spot rather than branching on the rest of the board first.+     */+    private fun bestCell(): Int {+        var best = -1+        var bestCount = side + 1+        for (index in 0 until cells) {+            if (grid[index] != 0) continue+            val count = Integer.bitCount(candidates(index))+            if (count < bestCount) {+                bestCount = count+                best = index+                if (count <= 1) break+            }+        }+        return best+    }++    private fun candidates(index: Int): Int =+        full and (rowMask[index / side] or colMask[index % side] or boxMask[boxOf[index]]).inv()++    /** Assumes [digit] is a candidate at [index]; the search only ever offers candidates. */+    private fun place(index: Int, digit: Int): Boolean {+        val bit = 1 shl (digit - 1)+        val row = index / side+        val col = index % side+        val box = boxOf[index]+        if ((rowMask[row] or colMask[col] or boxMask[box]) and bit != 0) return false+        grid[index] = digit+        rowMask[row] = rowMask[row] or bit+        colMask[col] = colMask[col] or bit+        boxMask[box] = boxMask[box] or bit+        return true+    }++    private fun unplace(index: Int) {+        val digit = grid[index]+        if (digit == 0) return+        val bit = (1 shl (digit - 1)).inv()+        grid[index] = 0+        rowMask[index / side] = rowMask[index / side] and bit+        colMask[index % side] = colMask[index % side] and bit+        boxMask[boxOf[index]] = boxMask[boxOf[index]] and bit+    }++    private fun digitsOf(mask: Int): List<Int> {+        val out = ArrayList<Int>(side)+        var remaining = mask+        while (remaining != 0) {+            val bit = remaining and (-remaining)+            remaining = remaining xor bit+            out.add(bitToDigit(bit))+        }+        return out+    }++    private fun bitToDigit(bit: Int): Int = Integer.numberOfTrailingZeros(bit) + 1+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/AppBackupAgent.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/AppBackupAgent.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..324ba012d4--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/AppBackupAgent.kt@@ -0,0 +1,10 @@+package com.vayunmathur.games.sudoku.platform++import com.vayunmathur.library.util.BaseBackupAgent++class AppBackupAgent : BaseBackupAgent() {+    override val prefNames: List<String> get() = listOf("sudoku_stats")++    // The shared DataStoreUtils file, holding AchievementsManager unlocks.+    override val datastoreNames: List<String> get() = listOf("datastore_default")+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuAchievementsManager.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuAchievementsManager.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuAchievementsManager.ktnew file mode 100644index 0000000000..3132227d70--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuAchievementsManager.kt@@ -0,0 +1,48 @@+package com.vayunmathur.games.sudoku.platform++import android.content.Context+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.SudokuStatsRepository+import com.vayunmathur.library.util.AchievementsManager++class SudokuAchievementsManager(+    context: Context,+    json: String,+    private val statsRepository: SudokuStatsRepository,+) : AchievementsManager(context, json) {++    /**+     * Back-fills from the stats file on launch, so an achievement added in a later release is+     * awarded for work the player has already done rather than only for the next puzzle they finish.+     *+     * Only the counters that survive in [SudokuStatsRepository] can be recovered this way. Anything+     * about how a single game was played (hints, mistakes) is gone once the game ends, so those are+     * unlocked from the win handler instead.+     */+    override fun checkExistingAchievements() {+        val totalWins = statsRepository.getTotalGamesWon()+        if (totalWins > 0) onAchievementUnlocked("first_win")+        if (statsRepository.getSizeStats(BoardSize.NINE).gamesWon > 0) {+            onAchievementUnlocked("win_nine")+        }+        if (BoardSize.entries.any { statsRepository.getStats(it, Difficulty.EXPERT).gamesWon > 0 }) {+            onAchievementUnlocked("win_expert")+        }+        if (BoardSize.entries.all { statsRepository.getSizeStats(it).gamesWon > 0 }) {+            onAchievementUnlocked("every_size")+        }+        if (statsRepository.getSizeStats(BoardSize.NINE).bestTimeSeconds < SPEED_SECONDS) {+            onAchievementUnlocked("speed_nine")+        }++        onProgressUpdated("wins_10", totalWins)+        onProgressUpdated("wins_50", totalWins)+        onProgressUpdated("win_streak_5", statsRepository.getBestWinStreak())+    }++    companion object {+        /** Matches the "under five minutes" wording of the `speed_nine` description. */+        const val SPEED_SECONDS = 300+    }+}
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.ktnew file mode 100644index 0000000000..c76678acbd--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuUiContract.kt@@ -0,0 +1,39 @@+package com.vayunmathur.games.sudoku.platform++import com.vayunmathur.games.sudoku.data.SudokuGameState++/**+ * The UI contract between [SudokuViewModel] and the board.+ *+ * The board takes this interface rather than the ViewModel itself so it can be rendered by a+ * `@Preview` — which is what the store listing images are generated from. It lives in `platform`+ * rather than next to the board so the dependency runs one way: `ui` depends on `platform`, and the+ * ViewModel implements this.+ *+ * Every member has a no-op default, so [Noop] is the whole implementation a preview needs.+ */+interface SudokuActions {+    fun selectCell(index: Int) {}+    fun enterDigit(digit: Int) {}+    fun clearCell() {}+    fun toggleNotesMode() {}+    fun hint() {}+    fun undo() {}+    fun restart() {}+    fun giveUp() {}++    companion object { val Noop: SudokuActions = object : SudokuActions {} }+}++/**+ * What the board needs to draw itself.+ *+ * [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.+ */+data class SudokuUiState(+    val game: SudokuGameState? = null,+    val canUndo: Boolean = false,+    val generating: Boolean = false,+)
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.ktnew file mode 100644index 0000000000..9c8ef98bce--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt@@ -0,0 +1,260 @@+package com.vayunmathur.games.sudoku.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+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.SudokuGameState+import com.vayunmathur.games.sudoku.data.SudokuSnapshot+import com.vayunmathur.games.sudoku.data.SudokuStatsRepository+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.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlin.random.Random++/**+ * Owns the puzzle in progress.+ *+ * The board is held in memory only. The Activity declares every `configChanges` it can, so this+ * survives rotation and theme changes without a saved-state handle; a puzzle is lost on process+ * death, which matches the other games in this family and is why the home screen offers "Continue"+ * rather than a saved-game list.+ */+class SudokuViewModel(application: Application) : AndroidViewModel(application), SudokuActions {++    private val _uiState = MutableStateFlow(SudokuUiState())+    val uiState: StateFlow<SudokuUiState> = _uiState.asStateFlow()++    private val statsRepository = SudokuStatsRepository(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. */+    private var madeMistake = false++    val achievementsManager: AchievementsManager = run {+        val json = application.assets.open("achievements.json").bufferedReader().readText()+        SudokuAchievementsManager(application, json, statsRepository)+    }++    init {+        achievementsManager.checkExistingAchievements()+    }++    fun hasActiveGame(): Boolean = _uiState.value.game?.isWon == false++    fun getStats(config: GameConfig) = statsRepository.getStats(config.size, config.difficulty)++    fun getSizeStats(size: BoardSize) = statsRepository.getSizeStats(size)++    /**+     * 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.+     */+    fun newGame(config: GameConfig) {+        history.clear()+        madeMistake = false+        _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))+        }+    }++    override fun selectCell(index: Int) {+        mutate { it.copy(selected = if (it.selected == index) -1 else index) }+    }++    override fun toggleNotesMode() {+        mutate { it.copy(notesMode = !it.notesMode) }+    }++    /**+     * Writes [digit] into the selected cell, as a pencil mark when notes mode is on.+     *+     * 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.+     */+    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) {+            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+        }++        val next = if (game.entries[index] == digit) 0 else digit+        if (next != 0 && next != game.solution[index]) madeMistake = true+        mutate { state ->+            state.copy(+                entries = state.entries.replacing(index, next),+                // A confirmed digit makes its own pencil marks meaningless.+                notes = state.notes.replacing(index, 0),+                moveCount = state.moveCount + 1,+            )+        }+        checkWin()+    }++    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+        pushHistory(game)+        mutate { state ->+            state.copy(+                entries = state.entries.replacing(index, 0),+                notes = state.notes.replacing(index, 0),+                moveCount = state.moveCount + 1,+            )+        }+    }++    /**+     * 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.+     */+    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] }+            ?: return++        pushHistory(game)+        mutate { state ->+            state.copy(+                entries = state.entries.replacing(index, state.solution[index]),+                notes = state.notes.replacing(index, 0),+                selected = index,+                hintsUsed = state.hintsUsed + 1,+                moveCount = state.moveCount + 1,+            )+        }+        checkWin()+    }++    override fun undo() {+        val snapshot = history.removeLastOrNull() ?: return+        mutate { it.copy(entries = snapshot.entries, notes = snapshot.notes, usedUndo = true) }+        _uiState.update { it.copy(canUndo = history.isNotEmpty()) }+    }++    /** Clears the player's work but keeps the same puzzle. */+    override fun restart() {+        val game = _uiState.value.game ?: return+        history.clear()+        madeMistake = false+        _uiState.value = SudokuUiState(+            game = game.copy(+                entries = List(game.size.cellCount) { 0 },+                notes = List(game.size.cellCount) { 0 },+                selected = -1,+                moveCount = 0,+                elapsedSeconds = 0,+                hintsUsed = 0,+                isWon = false,+                usedUndo = false,+            )+        )+    }++    /** Abandons an unfinished puzzle, which breaks the win streak for that variant. */+    override fun giveUp() {+        val game = _uiState.value.game ?: return+        if (!game.isWon) statsRepository.recordGameLost(game.size, game.difficulty)+        history.clear()+        _uiState.value = SudokuUiState()+    }++    fun incrementTimer() {+        val game = _uiState.value.game ?: return+        if (game.isWon) return+        mutate { it.copy(elapsedSeconds = it.elapsedSeconds + 1) }+    }++    fun dismissAchievementNotification() = achievementsManager.dismissNotification()++    /**+     * The one place a win is recorded, so stats and achievements can never disagree about what+     * happened. Every path that can complete the grid ends up here.+     */+    private fun checkWin() {+        val game = _uiState.value.game ?: return+        if (game.isWon || !game.isComplete) return+        mutate { it.copy(isWon = true, selected = -1) }++        statsRepository.recordGameWon(game.size, game.difficulty, game.elapsedSeconds)+        val manager = achievementsManager+        manager.onAchievementUnlocked("first_win")+        if (game.size == BoardSize.NINE) {+            manager.onAchievementUnlocked("win_nine")+            if (game.hintsUsed == 0) manager.onAchievementUnlocked("no_hints")+            if (game.elapsedSeconds < SudokuAchievementsManager.SPEED_SECONDS) {+                manager.onAchievementUnlocked("speed_nine")+            }+        }+        if (game.difficulty == Difficulty.EXPERT) {+            manager.onAchievementUnlocked("win_expert")+        }+        if (!madeMistake) manager.onAchievementUnlocked("no_mistakes")+        if (BoardSize.entries.all { statsRepository.getSizeStats(it).gamesWon > 0 }) {+            manager.onAchievementUnlocked("every_size")+        }+        val totalWins = statsRepository.getTotalGamesWon()+        manager.onProgressUpdated("wins_10", totalWins)+        manager.onProgressUpdated("wins_50", totalWins)+        manager.onProgressUpdated("win_streak_5", statsRepository.getBestWinStreak())+    }++    private fun pushHistory(game: SudokuGameState) {+        history.addLast(SudokuSnapshot(game.entries, game.notes))+        if (history.size > MAX_HISTORY) history.removeFirst()+        _uiState.update { it.copy(canUndo = true) }+    }++    private inline fun mutate(transform: (SudokuGameState) -> SudokuGameState) {+        _uiState.update { state ->+            val game = state.game ?: return@update state+            state.copy(game = transform(game))+        }+    }++    private companion object {+        /**+         * Undo depth. A snapshot is two lists of at most 81 ints, so this is a few hundred KB at+         * worst — bounded mainly so a long session cannot grow without limit.+         */+        const val MAX_HISTORY = 200+    }+}++/** [this] with [index] replaced by [value]. */+private fun List<Int>.replacing(index: Int, value: Int): List<Int> =+    toMutableList().also { it[index] = value }
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/DisplayNames.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/DisplayNames.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/DisplayNames.ktnew file mode 100644index 0000000000..1f748d6f22--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/DisplayNames.kt@@ -0,0 +1,30 @@+package com.vayunmathur.games.sudoku.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.games.sudoku.R+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty++/**+ * Display names live here rather than on the enums so `data` stays free of Android types and the+ * enums can be used from the generator and its unit tests without a resource lookup.+ */+@Composable+fun BoardSize.displayName(): String = stringResource(+    when (this) {+        BoardSize.FOUR -> R.string.size_four+        BoardSize.SIX -> R.string.size_six+        BoardSize.NINE -> R.string.size_nine+    }+)++@Composable+fun Difficulty.displayName(): String = stringResource(+    when (this) {+        Difficulty.EASY -> R.string.difficulty_easy+        Difficulty.MEDIUM -> R.string.difficulty_medium+        Difficulty.HARD -> R.string.difficulty_hard+        Difficulty.EXPERT -> R.string.difficulty_expert+    }+)
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.ktnew file mode 100644index 0000000000..0d7aa70d20--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt@@ -0,0 +1,216 @@+package com.vayunmathur.games.sudoku.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+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.widthIn+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+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.platform.SudokuActions+import com.vayunmathur.games.sudoku.platform.SudokuUiState+import com.vayunmathur.games.sudoku.ui.components.NumberPad+import com.vayunmathur.games.sudoku.ui.components.SudokuGrid+import com.vayunmathur.library.ui.AppBarAlignment+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.FilledTonalButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior++/** Caps the grid on tablets, where a full-width board would put the digits absurdly far apart. */+private val BoardMaxWidth = 520.dp++/**+ * The board, with no dependency on the ViewModel so it can be rendered from a `@Preview` — see+ * `src/screenshotTest`.+ */+@Composable+fun GameBoardScreen(+    state: SudokuUiState,+    actions: SudokuActions,+    onExit: () -> Unit,+) {+    val game = state.game+    AppScaffold(+        title = if (game == null) stringResource(R.string.app_name)+        else "${game.size.displayName()} · ${game.difficulty.displayName()}",+        onNavigateBack = onExit,+        alignment = AppBarAlignment.Center,+        actions = {+            if (game != null) {+                Text(+                    formatTime(game.elapsedSeconds),+                    style = MaterialTheme.typography.titleMedium,+                    modifier = Modifier.padding(end = Spacing.lg),+                )+            }+        },+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        Box(+            Modifier+                .fillMaxSize()+                .padding(padding),+            contentAlignment = Alignment.TopCenter,+        ) {+            if (game == null) {+                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+                    CircularProgressIndicator()+                }+                return@Box+            }++            Column(+                Modifier+                    .widthIn(max = BoardMaxWidth)+                    .fillMaxWidth()+                    .padding(horizontal = Spacing.md),+                verticalArrangement = Arrangement.spacedBy(Spacing.md),+            ) {+                SudokuGrid(+                    game = game,+                    onSelect = actions::selectCell,+                    modifier = Modifier.fillMaxWidth(),+                )++                if (game.hintsUsed > 0) {+                    Text(+                        "${stringResource(R.string.hints_used)}: ${game.hintsUsed}",+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }++                NumberPad(+                    game = game,+                    onDigit = actions::enterDigit,+                    modifier = Modifier.fillMaxWidth(),+                )++                ActionBar(state, actions, onExit)+            }++            if (game.isWon) {+                WinOverlay(+                    elapsedSeconds = game.elapsedSeconds,+                    hintsUsed = game.hintsUsed,+                    onPlayAgain = { actions.restart() },+                    onBack = onExit,+                )+            }+        }+    }+}++@Composable+private fun ActionBar(+    state: SudokuUiState,+    actions: SudokuActions,+    onExit: () -> Unit,+) {+    val game = state.game ?: return+    Column(verticalArrangement = Arrangement.spacedBy(Spacing.sm)) {+        Row(+            Modifier.fillMaxWidth(),+            horizontalArrangement = Arrangement.spacedBy(Spacing.sm),+        ) {+            // Tonal fill is the "on" state for notes mode; the label alone is too easy to miss.+            if (game.notesMode) {+                FilledTonalButton(+                    onClick = { actions.toggleNotesMode() },+                    modifier = Modifier.weight(1f),+                ) { Text(stringResource(R.string.notes)) }+            } else {+                OutlinedButton(+                    onClick = { actions.toggleNotesMode() },+                    modifier = Modifier.weight(1f),+                ) { Text(stringResource(R.string.notes)) }+            }+            OutlinedButton(+                onClick = { actions.clearCell() },+                modifier = Modifier.weight(1f),+                enabled = !game.isWon,+            ) { Text(stringResource(R.string.erase)) }+            OutlinedButton(+                onClick = { actions.undo() },+                modifier = Modifier.weight(1f),+                enabled = state.canUndo,+            ) { Text(stringResource(com.vayunmathur.library.ui.R.string.undo)) }+            OutlinedButton(+                onClick = { actions.hint() },+                modifier = Modifier.weight(1f),+                enabled = !game.isWon,+            ) { Text(stringResource(R.string.hint)) }+        }+        TextButton(+            onClick = {+                actions.giveUp()+                onExit()+            },+            modifier = Modifier.fillMaxWidth(),+        ) { Text(stringResource(R.string.give_up)) }+    }+}++@Composable+private fun WinOverlay(+    elapsedSeconds: Int,+    hintsUsed: Int,+    onPlayAgain: () -> Unit,+    onBack: () -> Unit,+) {+    Box(+        Modifier+            .fillMaxSize()+            // Scrim, so the card reads as modal instead of letting the number pad show around it.+            .background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.7f))+            .padding(Spacing.lg),+        contentAlignment = Alignment.Center,+    ) {+        Surface(+            shape = MaterialTheme.shapes.extraLarge,+            color = MaterialTheme.colorScheme.surfaceContainerHigh,+        ) {+            Column(+                Modifier.padding(Spacing.xl),+                horizontalAlignment = Alignment.CenterHorizontally,+                verticalArrangement = Arrangement.spacedBy(Spacing.md),+            ) {+                Text(+                    stringResource(R.string.congratulations),+                    style = MaterialTheme.typography.headlineSmall,+                    color = MaterialTheme.colorScheme.primary,+                )+                Text("${stringResource(R.string.time)}: ${formatTime(elapsedSeconds)}")+                if (hintsUsed > 0) {+                    Text(+                        "${stringResource(R.string.hints_used)}: $hintsUsed",+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }+                Button(onClick = onPlayAgain, Modifier.fillMaxWidth()) {+                    Text(stringResource(R.string.play_again))+                }+                TextButton(onClick = onBack, Modifier.fillMaxWidth()) {+                    Text(stringResource(R.string.back))+                }+            }+        }+    }+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.ktnew file mode 100644index 0000000000..8921c63918--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.kt@@ -0,0 +1,46 @@+package com.vayunmathur.games.sudoku.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.games.sudoku.Route+import com.vayunmathur.games.sudoku.data.GameConfig+import com.vayunmathur.games.sudoku.platform.SudokuViewModel+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.delay++/**+ * The only place the board touches the ViewModel.+ *+ * It deals a puzzle if there is not one already — reached by entering this route after process+ * death, when the route survived but the in-memory grid did not — and drives the 1 Hz clock.+ * Everything else is handed to the stateless [GameBoardScreen], which is what the store-listing+ * previews render.+ */+@Composable+fun GameScreen(+    backStack: NavBackStack<Route>,+    viewModel: SudokuViewModel,+    config: GameConfig,+) {+    val uiState by viewModel.uiState.collectAsState()++    LaunchedEffect(config) {+        if (uiState.game == null && !uiState.generating) viewModel.newGame(config)+    }++    val running = uiState.game?.isWon == false+    LaunchedEffect(running) {+        while (running) {+            delay(1000)+            viewModel.incrementTimer()+        }+    }++    GameBoardScreen(+        state = uiState,+        actions = viewModel,+        onExit = { backStack.pop() },+    )+}
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.ktnew file mode 100644index 0000000000..d97c894d06--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/HomeScreen.kt@@ -0,0 +1,154 @@+package com.vayunmathur.games.sudoku.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+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.runtime.Composable+import androidx.compose.runtime.collectAsState+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.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import com.vayunmathur.games.sudoku.R+import com.vayunmathur.games.sudoku.Route+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.GameConfig+import com.vayunmathur.games.sudoku.platform.SudokuViewModel+import com.vayunmathur.games.sudoku.ui.dialogs.GameConfigDialog+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconEmojiEvents+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack++@Composable+fun HomeScreen(+    backStack: NavBackStack<Route>,+    viewModel: SudokuViewModel,+) {+    val uiState by viewModel.uiState.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()) }++    AppScaffold(+        title = stringResource(R.string.app_name),+        actions = {+            IconButton(onClick = { backStack.add(Route.GameCenter) }) {+                IconEmojiEvents()+            }+        },+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        Column(+            Modifier+                .fillMaxSize()+                .padding(padding)+                .padding(Spacing.lg),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(Spacing.md),+        ) {+            val active = uiState.game?.takeIf { !it.isWon }+            if (active != null) {+                Button(+                    onClick = {+                        backStack.add(+                            Route.Game(GameConfig(active.size, active.difficulty))+                        )+                    },+                    modifier = Modifier.fillMaxWidth(),+                ) { Text(stringResource(R.string.continue_game)) }+            }+            Button(+                onClick = { showConfig = true },+                modifier = Modifier.fillMaxWidth(),+            ) { Text(stringResource(R.string.new_game)) }++            Row(+                Modifier.fillMaxWidth(),+                horizontalArrangement = Arrangement.spacedBy(Spacing.sm),+            ) {+                BoardSize.entries.forEach { size ->+                    SizeStatsCard(size, viewModel, Modifier.weight(1f))+                }+            }+        }+    }++    if (showConfig) {+        GameConfigDialog(+            initial = lastConfig,+            onStart = { config ->+                showConfig = false+                lastConfig = config+                viewModel.newGame(config)+                backStack.add(Route.Game(config))+            },+            onDismiss = { showConfig = false },+        )+    }+}++@Composable+private fun SizeStatsCard(+    size: BoardSize,+    viewModel: SudokuViewModel,+    modifier: Modifier = Modifier,+) {+    val stats = viewModel.getSizeStats(size)+    Card(modifier) {+        Column(+            Modifier+                .padding(Spacing.md)+                .fillMaxWidth(),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(Spacing.xs),+        ) {+            Text(+                size.displayName(),+                style = MaterialTheme.typography.titleSmall,+                textAlign = TextAlign.Center,+            )+            Text(+                "${stats.gamesWon}/${stats.gamesPlayed}",+                style = MaterialTheme.typography.bodyLarge,+                textAlign = TextAlign.Center,+            )+            Text(+                stringResource(R.string.won),+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                textAlign = TextAlign.Center,+            )+            if (stats.bestTimeSeconds < Int.MAX_VALUE) {+                Text(+                    formatTime(stats.bestTimeSeconds),+                    style = MaterialTheme.typography.bodySmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                    textAlign = TextAlign.Center,+                )+            }+        }+    }+}++/** `mm:ss`, and `h:mm:ss` once a puzzle has run past the hour. */+fun formatTime(seconds: Int): String {+    val hours = seconds / 3600+    val minutes = (seconds % 3600) / 60+    val secs = seconds % 60+    return if (hours > 0) "%d:%02d:%02d".format(hours, minutes, secs)+    else "%02d:%02d".format(minutes, secs)+}
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.ktnew file mode 100644index 0000000000..f9891f21f2--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/NumberPad.kt@@ -0,0 +1,93 @@+package com.vayunmathur.games.sudoku.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.sp+import com.vayunmathur.games.sudoku.data.SudokuGameState+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ButtonDefaults+import com.vayunmathur.library.ui.FilledTonalButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text++/**+ * The digit keys.+ *+ * A digit that has been placed as many times as the board is wide is disabled rather than hidden,+ * so the keys never reflow under the player's thumb mid-game. Notes mode keeps every digit enabled,+ * because a pencil mark for a finished digit is still a legitimate thing to jot down while ruling+ * it out.+ */+@Composable+fun NumberPad(+    game: SudokuGameState,+    onDigit: (Int) -> Unit,+    modifier: Modifier = Modifier,+) {+    val side = game.size.side+    // 4 and 6 fit one row; 9 splits so the keys stay wide enough to hit.+    val perRow = if (side > 6) 5 else side+    Column(modifier, verticalArrangement = Arrangement.spacedBy(Spacing.sm)) {+        var digit = 1+        while (digit <= side) {+            val rowEnd = minOf(digit + perRow - 1, side)+            Row(+                Modifier.fillMaxWidth(),+                horizontalArrangement = Arrangement.spacedBy(Spacing.sm),+            ) {+                for (d in digit..rowEnd) {+                    val exhausted = !game.notesMode && game.placedCount(d) >= side+                    DigitKey(+                        digit = d,+                        enabled = !exhausted && !game.isWon,+                        highlighted = game.notesMode,+                        onClick = { onDigit(d) },+                        modifier = Modifier.weight(1f),+                    )+                }+                // Keeps the last row's keys the same width as a full row's.+                repeat(perRow - (rowEnd - digit + 1)) {+                    Column(Modifier.weight(1f)) {}+                }+            }+            digit = rowEnd + 1+        }+    }+}++@Composable+private fun DigitKey(+    digit: Int,+    enabled: Boolean,+    highlighted: Boolean,+    onClick: () -> Unit,+    modifier: Modifier = Modifier,+) {+    val label = @Composable {+        Text(+            text = digit.toString(),+            style = MaterialTheme.typography.headlineSmall,+            fontSize = 22.sp,+        )+    }+    if (highlighted) {+        FilledTonalButton(+            onClick = onClick,+            modifier = modifier,+            enabled = enabled,+            contentPadding = ButtonDefaults.TextButtonContentPadding,+        ) { label() }+    } else {+        Button(+            onClick = onClick,+            modifier = modifier,+            enabled = enabled,+            contentPadding = ButtonDefaults.TextButtonContentPadding,+        ) { label() }+    }+}
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.ktnew file mode 100644index 0000000000..d1742ba744--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt@@ -0,0 +1,227 @@+package com.vayunmathur.games.sudoku.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxHeight+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.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.games.sudoku.R+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.SudokuGameState+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import androidx.compose.ui.res.stringResource++/**+ * The playing grid.+ *+ * Cells are laid out as plain composables and every line is painted once by [drawGridLines] on top,+ * rather than each cell drawing its own border. Per-cell borders would double up on shared edges,+ * so a box boundary would read as two adjacent thick lines instead of one.+ */+@Composable+fun SudokuGrid(+    game: SudokuGameState,+    onSelect: (Int) -> Unit,+    modifier: Modifier = Modifier,+) {+    val size = game.size+    val side = size.side+    val scheme = MaterialTheme.colorScheme+    val selected = game.selected+    val selectedValue = if (selected >= 0) game.valueAt(selected) else 0++    BoxWithConstraints(modifier.aspectRatio(1f)) {+        val cell: Dp = maxWidth / side+        Column {+            for (row in 0 until side) {+                Row {+                    for (col in 0 until side) {+                        val index = row * side + col+                        SudokuCell(+                            game = game,+                            index = index,+                            isSelected = index == selected,+                            // Shared row, column or box: the lines the player is reasoning along.+                            isPeer = selected >= 0 && index != selected && arePeers(size, index, selected),+                            // Every copy of the digit under the cursor, wherever it sits.+                            isSameValue = selectedValue != 0 &&+                                index != selected &&+                                game.valueAt(index) == selectedValue,+                            modifier = Modifier+                                .size(cell)+                                .clickable { onSelect(index) },+                        )+                    }+                }+            }+        }+        Box(+            Modifier+                .fillMaxSize()+                .drawGridLines(size, scheme.outlineVariant, scheme.onSurface)+        )+    }+}++/** True when [a] and [b] share a row, a column or a box. */+private fun arePeers(size: BoardSize, a: Int, b: Int): Boolean {+    val side = size.side+    return a / side == b / side || a % side == b % side || size.boxOf(a) == size.boxOf(b)+}++@Composable+private fun SudokuCell(+    game: SudokuGameState,+    index: Int,+    isSelected: Boolean,+    isPeer: Boolean,+    isSameValue: Boolean,+    modifier: Modifier = Modifier,+) {+    val scheme = MaterialTheme.colorScheme+    val value = game.valueAt(index)+    val wrong = game.isWrong(index)+    val given = game.isGiven(index)++    val background = when {+        isSelected -> scheme.primary.copy(alpha = 0.40f)+        isSameValue -> scheme.tertiary.copy(alpha = 0.30f)+        isPeer -> scheme.primary.copy(alpha = 0.13f)+        else -> Color.Transparent+    }++    val digitColor = when {+        wrong -> scheme.error+        given -> scheme.onSurface+        else -> scheme.primary+    }++    val spoken = if (value == 0) stringResource(R.string.cd_empty) else value.toString()+    val side = game.size.side+    val description =+        stringResource(R.string.cd_cell, index / side + 1, index % side + 1, spoken)+    Box(+        modifier+            .background(background)+            .clearAndSetSemantics { contentDescription = description },+        contentAlignment = Alignment.Center,+    ) {+        when {+            value != 0 -> Text(+                text = value.toString(),+                color = digitColor,+                // Sized from the cell so a 4x4 does not render tiny digits in large squares.+                fontSize = (game.size.digitScale * 22).sp,+                fontWeight = if (given) FontWeight.Bold else FontWeight.Medium,+                textAlign = TextAlign.Center,+            )++            game.notes[index] != 0 -> NoteMarks(game.size, game.notes[index])+        }+    }+}++/**+ * Pencil marks, arranged in the board's own box shape.+ *+ * Reusing [BoardSize.boxRows] x [BoardSize.boxCols] means digit `d` always sits in the same corner+ * of a cell that it does in a box, so the marks read as a miniature of the grid: 3x3 for 9x9, two+ * rows of three for 6x6, 2x2 for 4x4.+ */+@Composable+private fun NoteMarks(size: BoardSize, mask: Int) {+    // Weighted rows and columns rather than laid-out text: a space is narrower than a digit, so+    // padding absent marks with " " would let the columns drift out of line.+    Column(Modifier.fillMaxSize()) {+        for (row in 0 until size.boxRows) {+            Row(+                Modifier+                    .fillMaxWidth()+                    .weight(1f)+            ) {+                for (col in 0 until size.boxCols) {+                    val digit = row * size.boxCols + col + 1+                    Box(+                        Modifier+                            .weight(1f)+                            .fillMaxHeight(),+                        contentAlignment = Alignment.Center,+                    ) {+                        if (mask and (1 shl (digit - 1)) != 0) {+                            Text(+                                text = digit.toString(),+                                color = MaterialTheme.colorScheme.onSurfaceVariant,+                                fontSize = (size.digitScale * 8).sp,+                                lineHeight = (size.digitScale * 9).sp,+                                textAlign = TextAlign.Center,+                            )+                        }+                    }+                }+            }+        }+    }+}++/**+ * Every cell edge, with box boundaries and the outer frame drawn heavier.+ *+ * Drawn in one pass over the whole grid so shared edges are painted exactly once.+ */+private fun Modifier.drawGridLines(+    size: BoardSize,+    thin: Color,+    thick: Color,+) = drawBehind {+    val side = size.side+    val step = this.size.width / side+    val thinPx = 1.dp.toPx()+    val thickPx = 2.5f * thinPx++    for (i in 0..side) {+        val offset = i * step+        // The outer frame and the box seams carry the heavy stroke.+        val vertical = i % size.boxCols == 0 || i == side+        val horizontal = i % size.boxRows == 0 || i == side+        drawLine(+            color = if (vertical) thick else thin,+            start = Offset(offset, 0f),+            end = Offset(offset, this.size.height),+            strokeWidth = if (vertical) thickPx else thinPx,+        )+        drawLine(+            color = if (horizontal) thick else thin,+            start = Offset(0f, offset),+            end = Offset(this.size.width, offset),+            strokeWidth = if (horizontal) thickPx else thinPx,+        )+    }+}++/** Scales type with the board: a 4x4 cell is more than twice the width of a 9x9 cell. */+private val BoardSize.digitScale: Float+    get() = when (this) {+        BoardSize.FOUR -> 1.6f+        BoardSize.SIX -> 1.25f+        BoardSize.NINE -> 1f+    }
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/dialogs/GameConfigDialog.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/dialogs/GameConfigDialog.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/dialogs/GameConfigDialog.ktnew file mode 100644index 0000000000..d7a2d43438--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/dialogs/GameConfigDialog.kt@@ -0,0 +1,92 @@+package com.vayunmathur.games.sudoku.ui.dialogs++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+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.res.stringResource+import com.vayunmathur.games.sudoku.R+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.ui.displayName+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SegmentedButton+import com.vayunmathur.library.ui.SegmentedButtonDefaults+import com.vayunmathur.library.ui.SingleChoiceSegmentedButtonRow+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * Picks the board size and difficulty for a new puzzle.+ *+ * Both choices are local state: nothing reaches the ViewModel until the player confirms, so backing+ * out cannot disturb a game already in progress.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun GameConfigDialog(+    initial: GameConfig,+    onStart: (GameConfig) -> Unit,+    onDismiss: () -> Unit,+) {+    var size by remember { mutableStateOf(initial.size) }+    var difficulty by remember { mutableStateOf(initial.difficulty) }++    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(stringResource(R.string.new_puzzle)) },+        text = {+            Column(+                Modifier.fillMaxWidth(),+                horizontalAlignment = Alignment.CenterHorizontally,+                verticalArrangement = Arrangement.spacedBy(Spacing.md),+            ) {+                Text(+                    stringResource(R.string.board_size),+                    style = MaterialTheme.typography.labelLarge,+                )+                SingleChoiceSegmentedButtonRow {+                    BoardSize.entries.forEachIndexed { index, value ->+                        SegmentedButton(+                            shape = SegmentedButtonDefaults.itemShape(index, BoardSize.entries.size),+                            onClick = { size = value },+                            selected = size == value,+                        ) { Text(value.displayName()) }+                    }+                }+                Text(+                    stringResource(R.string.difficulty),+                    style = MaterialTheme.typography.labelLarge,+                )+                SingleChoiceSegmentedButtonRow {+                    Difficulty.entries.forEachIndexed { index, value ->+                        SegmentedButton(+                            shape = SegmentedButtonDefaults.itemShape(index, Difficulty.entries.size),+                            onClick = { difficulty = value },+                            selected = difficulty == value,+                        ) { Text(value.displayName()) }+                    }+                }+                Button(+                    onClick = { onStart(GameConfig(size, difficulty)) },+                    modifier = Modifier.fillMaxWidth(),+                ) { Text(stringResource(R.string.new_game)) }+            }+        },+        confirmButton = {},+        dismissButton = {+            TextButton(onClick = onDismiss) { Text(stringResource(R.string.back)) }+        },+    )+}
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.xmlnew file mode 100644index 0000000000..8f97f16af5--- /dev/null+++ b/games/sudoku/src/main/res/values/strings.xml@@ -0,0 +1,59 @@+<?xml version="1.0" encoding="utf-8"?>+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">+    <!-- Manifest / HomeScreen TopAppBar: App name. Noun, proper -->+    <string name="app_name" translatable="false">Sudoku</string>++    <!-- HomeScreen: Primary CTA opening the size and difficulty picker. Verb phrase -->+    <string name="new_game">New Game</string>+    <!-- HomeScreen: Button shown when an unfinished puzzle is still in memory. Verb -->+    <string name="continue_game">Continue</string>+    <!-- GameConfigDialog: Title of the size and difficulty picker dialog. Verb phrase -->+    <string name="new_puzzle">New Puzzle</string>+    <!-- GameConfigDialog: Label above the board size segmented buttons. Noun -->+    <string name="board_size">Board size</string>+    <!-- GameConfigDialog: Label above the difficulty segmented buttons. Noun -->+    <string name="difficulty">Difficulty</string>+    <!-- GameConfigDialog / WinOverlay: Dismiss button. Verb -->+    <string name="back">Back</string>++    <!-- GameConfigDialog: Board size option, a 4 by 4 grid of 2x2 boxes. Noun, dimensions -->+    <string name="size_four" translatable="false">4x4</string>+    <!-- GameConfigDialog: Board size option, a 6 by 6 grid of 2x3 boxes. Noun, dimensions -->+    <string name="size_six" translatable="false">6x6</string>+    <!-- GameConfigDialog: Board size option, a 9 by 9 grid of 3x3 boxes. Noun, dimensions -->+    <string name="size_nine" translatable="false">9x9</string>++    <!-- GameConfigDialog: Easiest difficulty, most clues given. Adjective -->+    <string name="difficulty_easy">Easy</string>+    <!-- GameConfigDialog: Middle difficulty. Adjective -->+    <string name="difficulty_medium">Medium</string>+    <!-- GameConfigDialog: Second hardest difficulty. Adjective -->+    <string name="difficulty_hard">Hard</string>+    <!-- GameConfigDialog: Hardest difficulty, fewest clues given. Adjective -->+    <string name="difficulty_expert">Expert</string>++    <!-- GameBoardScreen action bar: Toggles whether taps write pencil marks. Noun used as a label -->+    <string name="notes">Notes</string>+    <!-- GameBoardScreen action bar: Fills one cell with its correct digit. Noun -->+    <string name="hint">Hint</string>+    <!-- GameBoardScreen action bar: Clears the selected cell. Verb -->+    <string name="erase">Erase</string>+    <!-- GameBoardScreen action bar: Abandons the puzzle, recorded as a loss. Verb phrase -->+    <string name="give_up">Give Up</string>+    <!-- GameBoardScreen TopAppBar: Label preceding the hint counter, e.g. Hints: 2. Noun plural -->+    <string name="hints_used">Hints</string>++    <!-- WinOverlay: Celebratory title shown when the grid is completed. Declarative -->+    <string name="congratulations">Congratulations!</string>+    <!-- WinOverlay: Label for the finishing time, e.g. Time: 04:12. Noun -->+    <string name="time">Time</string>+    <!-- WinOverlay: Restarts the same puzzle from empty. Verb phrase -->+    <string name="play_again">Play Again</string>+    <!-- HomeScreen stat card: Label under the won-of-played ratio. Verb past participle -->+    <string name="won">won</string>++    <!-- GameBoardScreen: Content description of a single grid cell. %1$d = row number starting at 1, e.g. 3. %2$d = column number starting at 1, e.g. 7. %3$s = the digit showing or the word for empty, e.g. 5 -->+    <string name="cd_cell">Row <xliff:g id="row" example="3">%1$d</xliff:g>, column <xliff:g id="column" example="7">%2$d</xliff:g>, <xliff:g id="value" example="5">%3$s</xliff:g></string>+    <!-- GameBoardScreen: Spoken in place of a digit for a cell with nothing in it. Adjective -->+    <string name="cd_empty">empty</string>+</resources>
games/sudoku/src/main/res/xml/data_extraction_rules.xml
diff --git a/games/sudoku/src/main/res/xml/data_extraction_rules.xml b/games/sudoku/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..27bfc8fa6f--- /dev/null+++ b/games/sudoku/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,34 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+  Sudoku. Audited state: the "sudoku_stats" SharedPreferences file+  (AppBackupAgent.prefNames) holding per size-and-difficulty played/won counts,+  win streaks and best times, plus filesDir/datastore_default.preferences_pb,+  the shared DataStoreUtils file holding the AchievementsManager unlocks. No+  Room database, no in-progress board (the puzzle lives only in the ViewModel),+  nothing written to external storage - achievements.json is a read-only APK+  asset and every puzzle is generated on device. Back everything up; it is a+  few KB of pure user progress.+  SCOPE: sudoku declares android:backupAgent=".platform.AppBackupAgent" and does+  NOT set android:fullBackupOnly, so Android uses key/value backup and the+  <cloud-backup> section below is NOT consulted. Cloud content is exactly+  AppBackupAgent's prefNames = ["sudoku_stats"] plus datastoreNames =+  ["datastore_default"], which is the same data this file would have sent.+  <device-transfer> IS governed here, and these rules become the cloud control+  too if the backupAgent is ever removed.+-->+<data-extraction-rules>+    <cloud-backup>+        <include domain="root" path="." />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <include domain="external" path="." />+    </cloud-backup>+    <device-transfer>+        <include domain="root" path="." />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <include domain="external" path="." />+    </device-transfer>+</data-extraction-rules>
games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.kt
diff --git a/games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.kt b/games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.ktnew file mode 100644index 0000000000..54f807920b--- /dev/null+++ b/games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.kt@@ -0,0 +1,147 @@+package com.vayunmathur.games.sudoku++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.SudokuGameState+import com.vayunmathur.games.sudoku.domain.SudokuGenerator+import com.vayunmathur.games.sudoku.platform.SudokuActions+import com.vayunmathur.games.sudoku.platform.SudokuUiState+import com.vayunmathur.games.sudoku.ui.GameBoardScreen+import com.vayunmathur.library.ui.DynamicTheme+import kotlin.random.Random++/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */+private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"++/**+ * The store listing images.+ *+ * Previews must be members of a class and carry both `@PreviewTest` and `@Preview`, or the+ * screenshot engine discovers no tests. The `PreviewN` names set the order they appear in the+ * listing, because the collector sorts by filename. Run `./gradlew :games:sudoku:metadata`.+ *+ * Boards come from [SudokuGenerator] with a fixed seed rather than 81 transcribed digits: the same+ * seed gives the same puzzle on any machine, so the images are reproducible from a clean checkout+ * and are guaranteed to be legal puzzles. [GameBoardScreen] has no polling `LaunchedEffect` — the+ * clock lives in the stateful `GameScreen` — so a preview settles on the first frame.+ */+class MetadataPreviews {++    @PreviewTest+    @Preview(name = "1-puzzle", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview1Puzzle() {+        Board(+            game(+                size = BoardSize.NINE,+                difficulty = Difficulty.MEDIUM,+                seed = 20260824,+                filled = 14,+                selected = 40,+                elapsed = 232,+            )+        )+    }++    @PreviewTest+    @Preview(name = "2-notes", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview2Notes() {+        val base = game(+            size = BoardSize.NINE,+            difficulty = Difficulty.HARD,+            seed = 4711,+            filled = 6,+            selected = 30,+            elapsed = 96,+        )+        Board(base.copy(notesMode = true, notes = pencilMarks(base)))+    }++    @PreviewTest+    @Preview(name = "3-small", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview3Small() {+        Board(+            game(+                size = BoardSize.SIX,+                difficulty = Difficulty.EASY,+                seed = 991,+                filled = 5,+                selected = 20,+                elapsed = 41,+            )+        )+    }++    @PreviewTest+    @Preview(name = "4-solved", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview4Solved() {+        val base = game(BoardSize.NINE, Difficulty.EXPERT, seed = 2024, filled = 0, elapsed = 511)+        Board(base.copy(entries = base.blanksFilled(), isWon = true))+    }++    @Composable+    private fun Board(game: SudokuGameState) {+        // Layoutlib has no wallpaper to sample, so Material You falls back to the default palette.+        DynamicTheme(darkTheme = true) {+            GameBoardScreen(+                state = SudokuUiState(game = game, canUndo = game.moveCount > 0),+                actions = SudokuActions.Noop,+                onExit = {},+            )+        }+    }++    /**+     * A game part-way through, with [filled] of the blanks correctly entered.+     *+     * Only correct digits are placed, so no preview shows an error state by accident.+     */+    private fun game(+        size: BoardSize,+        difficulty: Difficulty,+        seed: Int,+        filled: Int,+        selected: Int = -1,+        elapsed: Int = 0,+    ): SudokuGameState {+        val puzzle = SudokuGenerator.generate(size, difficulty, Random(seed))+        val state = SudokuGameState.from(puzzle)+        val blanks = puzzle.givens.indices.filter { puzzle.givens[it] == 0 }.take(filled)+        val entries = state.entries.toMutableList()+        blanks.forEach { entries[it] = puzzle.solution[it] }+        return state.copy(+            entries = entries,+            selected = selected,+            elapsedSeconds = elapsed,+            moveCount = filled,+        )+    }++    /** Every remaining blank filled in, for the win shot. */+    private fun SudokuGameState.blanksFilled(): List<Int> =+        List(size.cellCount) { if (isGiven(it)) 0 else solution[it] }++    /**+     * Plausible pencil marks: two or three candidates in the first few blank cells, so the notes+     * shot shows the mini-grid layout rather than an empty board.+     */+    private fun pencilMarks(game: SudokuGameState): List<Int> {+        val notes = game.notes.toMutableList()+        val blanks = game.givens.indices.filter { game.valueAt(it) == 0 }+        blanks.take(9).forEachIndexed { position, index ->+            val first = game.solution[index]+            val second = (first % game.size.side) + 1+            val third = ((first + 3) % game.size.side) + 1+            var mask = (1 shl (first - 1)) or (1 shl (second - 1))+            if (position % 2 == 0) mask = mask or (1 shl (third - 1))+            notes[index] = mask+        }+        return notes+    }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuGeneratorTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuGeneratorTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuGeneratorTest.ktnew file mode 100644index 0000000000..32e41039a6--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuGeneratorTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.games.sudoku.domain++import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class SudokuGeneratorTest {++    @Test+    fun everyPuzzleHasExactlyOneSolution() {+        // The whole promise of the generator: the player never has to guess.+        for (size in BoardSize.entries) {+            for (difficulty in Difficulty.entries) {+                val puzzle = SudokuGenerator.generate(size, difficulty, Random(11))+                assertEquals(+                    1,+                    SudokuSolver(size).countSolutions(puzzle.givens),+                    "${size.name}/${difficulty.name}",+                )+            }+        }+    }++    @Test+    fun solutionIsLegalAndAgreesWithTheClues() {+        for (size in BoardSize.entries) {+            val puzzle = SudokuGenerator.generate(size, Difficulty.MEDIUM, Random(5))+            assertLegal(size, puzzle.solution)+            puzzle.givens.forEachIndexed { index, given ->+                if (given != 0) {+                    assertEquals(puzzle.solution[index], given, "clue at $index")+                }+            }+        }+    }++    @Test+    fun clueCountNeverFallsBelowTheTarget() {+        // Digging stops early when a clue turns out to be load-bearing, so the count can only be+        // at or above the target - never below it.+        for (size in BoardSize.entries) {+            for (difficulty in Difficulty.entries) {+                val puzzle = SudokuGenerator.generate(size, difficulty, Random(3))+                val clues = puzzle.givens.count { it != 0 }+                assertTrue(+                    clues >= difficulty.targetClues(size),+                    "${size.name}/${difficulty.name} had $clues clues, " ++                        "target ${difficulty.targetClues(size)}",+                )+            }+        }+    }++    @Test+    fun harderDifficultiesGiveNoMoreClues() {+        val size = BoardSize.NINE+        val counts = Difficulty.entries.map { difficulty ->+            SudokuGenerator.generate(size, difficulty, Random(9)).givens.count { it != 0 }+        }+        assertEquals(counts, counts.sortedDescending(), "clue counts should not increase: $counts")+    }++    @Test+    fun sameSeedGivesSamePuzzle() {+        val first = SudokuGenerator.generate(BoardSize.NINE, Difficulty.HARD, Random(77))+        val second = SudokuGenerator.generate(BoardSize.NINE, Difficulty.HARD, Random(77))+        assertEquals(first.givens, second.givens)+        assertEquals(first.solution, second.solution)+    }++    @Test+    fun everyPuzzleLeavesSomethingToDo() {+        for (size in BoardSize.entries) {+            for (difficulty in Difficulty.entries) {+                val puzzle = SudokuGenerator.generate(size, difficulty, Random(21))+                assertTrue(+                    puzzle.givens.any { it == 0 },+                    "${size.name}/${difficulty.name} was handed over already complete",+                )+            }+        }+    }+}
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuSolverTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuSolverTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuSolverTest.ktnew file mode 100644index 0000000000..2d387620e3--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/domain/SudokuSolverTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.games.sudoku.domain++import com.vayunmathur.games.sudoku.data.BoardSize+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class SudokuSolverTest {++    @Test+    fun emptyGridIsFilledLegally() {+        for (size in BoardSize.entries) {+            val solved = assertNotNull(+                SudokuSolver(size).solve(blank(size)),+                "${size.name} should be solvable from empty",+            )+            assertLegal(size, solved)+        }+    }++    @Test+    fun seededSolveIsReproducible() {+        val size = BoardSize.NINE+        val first = SudokuSolver(size).solve(blank(size), Random(42))+        val second = SudokuSolver(size).solve(blank(size), Random(42))+        assertEquals(first, second)+    }++    @Test+    fun differentSeedsGiveDifferentGrids() {+        val size = BoardSize.NINE+        val first = SudokuSolver(size).solve(blank(size), Random(1))+        val second = SudokuSolver(size).solve(blank(size), Random(2))+        assertTrue(first != second, "two seeds should not agree on a whole 9x9")+    }++    @Test+    fun contradictoryGridHasNoSolution() {+        val size = BoardSize.FOUR+        // Two 1s in the same row cannot both be right.+        val grid = blank(size).toMutableList().also {+            it[0] = 1+            it[1] = 1+        }+        assertNull(SudokuSolver(size).solve(grid))+        assertEquals(0, SudokuSolver(size).countSolutions(grid))+    }++    @Test+    fun emptyGridHasManySolutions() {+        val size = BoardSize.FOUR+        // Capped at 2: the point is only that it is not unique.+        assertEquals(2, SudokuSolver(size).countSolutions(blank(size)))+    }++    @Test+    fun completeGridCountsAsExactlyOne() {+        val size = BoardSize.SIX+        val solved = assertNotNull(SudokuSolver(size).solve(blank(size), Random(7)))+        assertEquals(1, SudokuSolver(size).countSolutions(solved))+    }++    @Test+    fun countStopsAtTheGivenLimit() {+        val size = BoardSize.FOUR+        assertEquals(1, SudokuSolver(size).countSolutions(blank(size), limit = 1))+        // Subtree totals are added whole, so the result can overshoot the limit - it is a+        // "found at least this many" answer, which is all the uniqueness check needs.+        val capped = SudokuSolver(size).countSolutions(blank(size), limit = 5)+        assertTrue(capped >= 5, "expected at least 5, got $capped")+        assertTrue(capped < 288, "should have stopped well short of all 288 solutions, got $capped")+    }++    @Test+    fun solverInstanceCanBeReused() {+        // The generator calls countSolutions repeatedly on one instance, so the masks must reset.+        val size = BoardSize.SIX+        val solver = SudokuSolver(size)+        val solved = assertNotNull(solver.solve(blank(size), Random(3)))+        repeat(3) {+            assertEquals(1, solver.countSolutions(solved), "reuse #$it")+        }+    }+}++internal fun blank(size: BoardSize) = List(size.cellCount) { 0 }++/** Fails unless every row, column and box of [grid] holds each digit exactly once. */+internal fun assertLegal(size: BoardSize, grid: List<Int>) {+    val side = size.side+    val expected = (1..side).toSet()+    for (i in 0 until side) {+        assertEquals(+            expected,+            (0 until side).map { grid[i * side + it] }.toSet(),+            "row $i of ${size.name}",+        )+        assertEquals(+            expected,+            (0 until side).map { grid[it * side + i] }.toSet(),+            "column $i of ${size.name}",+        )+        assertEquals(+            expected,+            grid.indices.filter { size.boxOf(it) == i }.map { grid[it] }.toSet(),+            "box $i of ${size.name}",+        )+    }+}
library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.ktindex 8bf8e45e30..a5d8ac4df7 100644--- a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt+++ b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt@@ -37,6 +37,7 @@ private fun resolveGameMetadata(             "unblockjam" -> "Unblock Jam"             "wordmaker" -> "Wordmaker"             "logicgate" -> "Logic Gates"+            "sudoku" -> "Sudoku"             else -> gameId.replaceFirstChar { it.uppercase() }         },         description = null,
metadata_data/games-sudoku.md
diff --git a/metadata_data/games-sudoku.md b/metadata_data/games-sudoku.mdnew file mode 100644index 0000000000..8767478034--- /dev/null+++ b/metadata_data/games-sudoku.md@@ -0,0 +1,5 @@+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.
metadata_data/photos/games-sudoku/1.png
diff --git a/metadata_data/photos/games-sudoku/1.png b/metadata_data/photos/games-sudoku/1.pngnew file mode 100644index 0000000000..5e9a00ae73Binary files /dev/null and b/metadata_data/photos/games-sudoku/1.png differ
metadata_data/photos/games-sudoku/2.png
diff --git a/metadata_data/photos/games-sudoku/2.png b/metadata_data/photos/games-sudoku/2.pngnew file mode 100644index 0000000000..e6dd3fb305Binary files /dev/null and b/metadata_data/photos/games-sudoku/2.png differ
metadata_data/photos/games-sudoku/3.png
diff --git a/metadata_data/photos/games-sudoku/3.png b/metadata_data/photos/games-sudoku/3.pngnew file mode 100644index 0000000000..6790cba554Binary files /dev/null and b/metadata_data/photos/games-sudoku/3.png differ
metadata_data/photos/games-sudoku/4.png
diff --git a/metadata_data/photos/games-sudoku/4.png b/metadata_data/photos/games-sudoku/4.pngnew file mode 100644index 0000000000..74ac9178f8Binary files /dev/null and b/metadata_data/photos/games-sudoku/4.png differ
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 7eccc80fbb..024f1d9c1a 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -78,6 +78,7 @@ include(":games:pipes") include(":games:solitaire") include(":games:logicgate") include(":games:voxels")+include(":games:sudoku") include(":games:hub") include(":email") include(":weather")