Modern Apps git

← Modern-Apps.git

minesweeper: new game with size/density picker and safe first tap

Commit
3b09777fcd578bfcd7997cdc33390c39db4a7d51
Author
vayun-mathur <[email protected]>
When
2026-08-24 02:51 UTC (3 months ago)
Parents
2aacbc5

Diff

games/hub/src/main/AndroidManifest.xml
diff --git a/games/hub/src/main/AndroidManifest.xml b/games/hub/src/main/AndroidManifest.xmlindex 69b5601ce2..de93a7f54d 100644--- a/games/hub/src/main/AndroidManifest.xml+++ b/games/hub/src/main/AndroidManifest.xml@@ -18,6 +18,7 @@         <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.minesweeper" />         <package android:name="com.vayunmathur.games" />         <intent>             <action android:name="android.intent.action.MAIN" />
games/minesweeper/build.gradle.kts
diff --git a/games/minesweeper/build.gradle.kts b/games/minesweeper/build.gradle.ktsnew file mode 100644index 0000000000..6f8482d673--- /dev/null+++ b/games/minesweeper/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:minesweeper:metadata` task name either way.+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "flag"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.games.minesweeper"+    }+}++dependencies {+    implementation(project(":sdk:games"))+}
games/minesweeper/src/main/AndroidManifest.xml
diff --git a/games/minesweeper/src/main/AndroidManifest.xml b/games/minesweeper/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..b5ea5ad3d6--- /dev/null+++ b/games/minesweeper/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/minesweeper/src/main/assets/achievements.json
diff --git a/games/minesweeper/src/main/assets/achievements.json b/games/minesweeper/src/main/assets/achievements.jsonnew file mode 100644index 0000000000..97f0a5fe72--- /dev/null+++ b/games/minesweeper/src/main/assets/achievements.json@@ -0,0 +1,50 @@+[+  {+    "id": "first_win",+    "name": "Swept",+    "description": "Clear your first field!"+  },+  {+    "id": "win_large",+    "name": "Wide Open",+    "description": "Clear a large field."+  },+  {+    "id": "win_expert",+    "name": "Dense Work",+    "description": "Clear a field on Expert density."+  },+  {+    "id": "no_flags_needed",+    "name": "From Memory",+    "description": "Clear a field without placing a single flag."+  },+  {+    "id": "speed_win",+    "name": "Light Touch",+    "description": "Clear a field in under a minute."+  },+  {+    "id": "first_chord",+    "name": "Two At Once",+    "description": "Open a group of cells by tapping a satisfied number."+  },+  {+    "id": "wins_10",+    "name": "Steady Hand",+    "description": "Clear 10 fields.",+    "targetProgress": 10+  },+  {+    "id": "wins_50",+    "name": "Bomb Disposal",+    "description": "Clear 50 fields.",+    "targetProgress": 50+  },+  {+    "id": "win_streak_5",+    "name": "Unshaken",+    "description": "Clear five fields in a row.",+    "targetProgress": 5+  }+]
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/MainActivity.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/MainActivity.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/MainActivity.ktnew file mode 100644index 0000000000..635304000b--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/MainActivity.kt@@ -0,0 +1,22 @@+package com.vayunmathur.games.minesweeper++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.minesweeper.platform.MinesweeperViewModel+import com.vayunmathur.library.ui.DynamicTheme++class MainActivity : ComponentActivity() {+    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                val viewModel: MinesweeperViewModel = viewModel()+                Navigation(viewModel)+            }+        }+    }+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/Navigation.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/Navigation.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/Navigation.ktnew file mode 100644index 0000000000..99106e2402--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/Navigation.kt@@ -0,0 +1,40 @@+package com.vayunmathur.games.minesweeper++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.minesweeper.platform.AppBackupAgent+import com.vayunmathur.games.minesweeper.platform.MinesweeperViewModel+import com.vayunmathur.games.minesweeper.ui.GameScreen+import com.vayunmathur.games.minesweeper.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: MinesweeperViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Home)+    val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()+    GameHubComposeHook("minesweeper", 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/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/Route.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/Route.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/Route.ktnew file mode 100644index 0000000000..f73de744b4--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/Route.kt@@ -0,0 +1,21 @@+package com.vayunmathur.games.minesweeper++import com.vayunmathur.games.minesweeper.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 field if it is ever entered without one+     * in memory — the ViewModel holds the field but nothing restores it after process death.+     */+    @Serializable+    data class Game(val config: GameConfig) : Route++    @Serializable+    data object GameCenter : Route+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/MinesweeperModels.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/MinesweeperModels.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/MinesweeperModels.ktnew file mode 100644index 0000000000..1d00f213e3--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/MinesweeperModels.kt@@ -0,0 +1,148 @@+package com.vayunmathur.games.minesweeper.data++import kotlinx.serialization.Serializable+import kotlin.math.roundToInt++/**+ * Field dimensions, chosen to stay playable in portrait on a phone.+ *+ * Columns are the binding constraint: a cell has to stay wide enough to hit with a thumb, so the+ * larger sizes grow mostly downward and scroll. The classic 30-column expert field is deliberately+ * absent — it is unusable at this width.+ */+@Serializable+enum class BoardSize(val cols: Int, val rows: Int) {+    SMALL(8, 10),+    MEDIUM(10, 14),+    LARGE(12, 18);++    val cellCount: Int get() = cols * rows+}++/**+ * Mine density, as a fraction of the field.+ *+ * A fraction rather than a fixed count so a difficulty feels the same on every size. The classic+ * presets sit around 0.12 (beginner) to 0.21 (expert), which is roughly the range spanned here.+ */+@Serializable+enum class Difficulty(val mineFraction: Double) {+    EASY(0.10),+    MEDIUM(0.15),+    HARD(0.19),+    EXPERT(0.23);++    /**+     * Mines on a [size] field.+     *+     * Capped so the opening tap always has somewhere to go: the first reveal clears the tapped cell+     * and its eight neighbours, so the field needs at least that many safe squares.+     */+    fun mineCount(size: BoardSize): Int =+        (size.cellCount * mineFraction).roundToInt().coerceIn(1, size.cellCount - MIN_SAFE_CELLS)++    private companion object {+        /** A cell plus its eight neighbours, which the first tap always opens. */+        const val MIN_SAFE_CELLS = 9+    }+}++/** The options chosen on the home screen, carried into field generation. */+@Serializable+data class GameConfig(+    val size: BoardSize = BoardSize.MEDIUM,+    val difficulty: Difficulty = Difficulty.MEDIUM,+) {+    /** Stats key component, so records are tracked per field shape and density. */+    val variant: String get() = "${size.name}_${difficulty.name}"+}++/** How a game ended, or that it is still going. */+enum class GameOutcome { PLAYING, WON, LOST }++/**+ * Everything about a field in progress.+ *+ * Geometry is held as plain [cols] and [rows] rather than a [BoardSize], so the rules work on any+ * rectangle and can be tested against layouts far smaller than any the picker offers. The chosen+ * [BoardSize] and [Difficulty] belong to the session, not the field, and live on the UI state.+ *+ * [mines] is all false until the first tap: mines are laid *after* the opening reveal so it can never+ * be a loss. [neighbourCounts] is derived from [mines] once at generation and cached, because it is+ * read for every cell on every recomposition.+ *+ * All four per-cell lists are `cols * rows` long and indexed row-major.+ */+data class MinesweeperGameState(+    val cols: Int,+    val rows: Int,+    val mineCount: Int,+    val mines: List<Boolean>,+    val neighbourCounts: List<Int>,+    val revealed: List<Boolean>,+    val flagged: List<Boolean>,+    val outcome: GameOutcome = GameOutcome.PLAYING,+    /** The mine that ended it, so the board can single it out from the ones merely shown. */+    val explodedAt: Int = -1,+    val elapsedSeconds: Int = 0,+    /** False until the first reveal, which is when the mines are laid and the clock starts. */+    val started: Boolean = false,+) {+    val cellCount: Int get() = cols * rows+    val flagsPlaced: Int get() = flagged.count { it }++    /** Counts down as flags go in. Goes negative if the player over-flags, which is a useful signal. */+    val minesRemaining: Int get() = mineCount - flagsPlaced++    val isOver: Boolean get() = outcome != GameOutcome.PLAYING++    /** Won once every cell that is not a mine has been revealed; flags are not required. */+    val isCleared: Boolean get() = (0 until cellCount).all { mines[it] || revealed[it] }++    /** Indices of the up-to-eight cells touching [index], including diagonals. */+    fun neighbours(index: Int): List<Int> = neighbourIndices(cols, rows, index)++    companion object {+        /**+         * A field with no mines laid yet.+         *+         * The player sees a blank grid and the first tap decides where the mines go, so the opening+         * move is always safe and always opens an area.+         */+        fun empty(config: GameConfig): MinesweeperGameState = of(+            cols = config.size.cols,+            rows = config.size.rows,+            mineCount = config.difficulty.mineCount(config.size),+        )++        /** A blank field of arbitrary dimensions. */+        fun of(cols: Int, rows: Int, mineCount: Int): MinesweeperGameState {+            val cells = cols * rows+            return MinesweeperGameState(+                cols = cols,+                rows = rows,+                mineCount = mineCount,+                mines = List(cells) { false },+                neighbourCounts = List(cells) { 0 },+                revealed = List(cells) { false },+                flagged = List(cells) { false },+            )+        }+    }+}++/** Indices of the up-to-eight cells touching [index] on a [cols] x [rows] field, diagonals included. */+fun neighbourIndices(cols: Int, rows: Int, index: Int): List<Int> {+    val row = index / cols+    val col = index % cols+    val out = ArrayList<Int>(8)+    for (dr in -1..1) {+        for (dc in -1..1) {+            if (dr == 0 && dc == 0) continue+            val r = row + dr+            val c = col + dc+            if (r in 0 until rows && c in 0 until cols) out.add(r * cols + c)+        }+    }+    return out+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/MinesweeperStatsRepository.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/MinesweeperStatsRepository.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/MinesweeperStatsRepository.ktnew file mode 100644index 0000000000..071a4ed09f--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/MinesweeperStatsRepository.kt@@ -0,0 +1,95 @@+package com.vayunmathur.games.minesweeper.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 field size and mine density.+ *+ * Records are keyed by variant rather than rolled into one number because a best time only means+ * something next to the field it was set on. The home screen wants a single figure per size, so+ * [getSizeStats] aggregates by key rather than 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 MinesweeperStatsRepository(context: Context) {+    private val prefs: SharedPreferences =+        context.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE)+    private val json = Json { ignoreUnknownKeys = true }++    private fun key(size: BoardSize, difficulty: Difficulty) = "stats_${size.name}__${difficulty.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 density'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 on the first reveal rather than when the field is dealt, so backing straight out of a+     * board you never touched does not show up as a played game.+     */+    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+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/domain/FieldGenerator.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/domain/FieldGenerator.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/domain/FieldGenerator.ktnew file mode 100644index 0000000000..82192122cf--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/domain/FieldGenerator.kt@@ -0,0 +1,43 @@+package com.vayunmathur.games.minesweeper.domain++import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import com.vayunmathur.games.minesweeper.data.neighbourIndices+import kotlin.random.Random++/**+ * Lays mines after the opening tap.+ *+ * Deferring generation until the first reveal is what makes the opening move safe. It is not only the+ * tapped cell that is kept clear but its eight neighbours too, so the first reveal is always a zero+ * and always cascades into an opening area — a field where the first tap uncovers a lone "5" is+ * technically survivable but gives the player nothing to reason from.+ */+object FieldGenerator {++    /**+     * [state] with mines laid, none of them on or touching [safeIndex].+     *+     * If the mine count leaves no room for a clear neighbourhood the safe zone shrinks to just+     * [safeIndex] — the tap still cannot lose, it simply might not cascade. Difficulty caps density+     * so this only bites on fields far denser than the picker offers.+     */+    fun lay(state: MinesweeperGameState, safeIndex: Int, rng: Random): MinesweeperGameState {+        val cells = state.cellCount+        val fullSafeZone = neighbourIndices(state.cols, state.rows, safeIndex) + safeIndex+        val safeZone =+            if (cells - fullSafeZone.size >= state.mineCount) fullSafeZone.toSet() else setOf(safeIndex)++        val mineSet = (0 until cells)+            .filterNot { it in safeZone }+            .shuffled(rng)+            .take(state.mineCount)+            .toSet()++        val mines = List(cells) { it in mineSet }+        val counts = List(cells) { index ->+            if (mines[index]) 0+            else neighbourIndices(state.cols, state.rows, index).count { mines[it] }+        }+        return state.copy(mines = mines, neighbourCounts = counts, started = true)+    }+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/domain/MinesweeperRules.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/domain/MinesweeperRules.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/domain/MinesweeperRules.ktnew file mode 100644index 0000000000..493ba8dcbd--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/domain/MinesweeperRules.kt@@ -0,0 +1,103 @@+package com.vayunmathur.games.minesweeper.domain++import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState++/**+ * The rules, as pure functions on a state.+ *+ * Kept out of the ViewModel so the cascade and chord logic — the two things most likely to be+ * subtly wrong — can be unit tested without an Android dependency.+ */+object MinesweeperRules {++    /**+     * Reveals [index] and, when it sees no mines, everything reachable from it.+     *+     * Flagged cells are skipped: the player has asserted a mine there, and opening it from a cascade+     * would throw away that judgement (and usually end the game). Revealing a mine loses.+     */+    fun reveal(state: MinesweeperGameState, index: Int): MinesweeperGameState {+        if (state.isOver || state.revealed[index] || state.flagged[index]) return state++        if (state.mines[index]) {+            return state.copy(+                revealed = state.revealed.replacing(index, true),+                outcome = GameOutcome.LOST,+                explodedAt = index,+            )+        }++        val revealed = state.revealed.toMutableList()+        // Iterative flood fill; a recursive one overflows the stack on a large open field.+        val queue = ArrayDeque<Int>()+        queue.addLast(index)+        revealed[index] = true+        while (queue.isNotEmpty()) {+            val current = queue.removeFirst()+            if (state.neighbourCounts[current] != 0) continue+            for (neighbour in state.neighbours(current)) {+                if (revealed[neighbour] || state.flagged[neighbour]) continue+                revealed[neighbour] = true+                if (state.neighbourCounts[neighbour] == 0) queue.addLast(neighbour)+            }+        }++        return state.copy(revealed = revealed).settleIfCleared()+    }++    /**+     * Cycles the flag on [index].+     *+     * Only unrevealed cells can be flagged; a revealed cell's state is already known, so flagging it+     * would be meaningless and would corrupt the remaining-mines count.+     */+    fun toggleFlag(state: MinesweeperGameState, index: Int): MinesweeperGameState {+        if (state.isOver || state.revealed[index]) return state+        return state.copy(flagged = state.flagged.replacing(index, !state.flagged[index]))+    }++    /**+     * Opens every unflagged neighbour of an already-revealed number, but only once exactly that many+     * flags surround it.+     *+     * This is the standard chord. It deliberately trusts the player's flags: if one is wrong the+     * chord uncovers a mine and the game is lost, which is the accepted risk that makes it a+     * meaningful shortcut rather than a free action.+     */+    fun chord(state: MinesweeperGameState, index: Int): MinesweeperGameState {+        if (state.isOver || !state.revealed[index]) return state+        val count = state.neighbourCounts[index]+        if (count == 0) return state++        val neighbours = state.neighbours(index)+        if (neighbours.count { state.flagged[it] } != count) return state++        var next = state+        for (neighbour in neighbours) {+            if (next.isOver) break+            if (!next.revealed[neighbour] && !next.flagged[neighbour]) {+                next = reveal(next, neighbour)+            }+        }+        return next.settleIfCleared()+    }++    /**+     * Marks a win once every safe cell is open.+     *+     * Remaining mines are flagged for the player rather than left blank, so the finished board reads+     * as complete and the flag counter lands on zero.+     */+    private fun MinesweeperGameState.settleIfCleared(): MinesweeperGameState {+        if (isOver || !isCleared) return this+        return copy(+            outcome = GameOutcome.WON,+            flagged = List(cellCount) { mines[it] },+        )+    }+}++/** [this] with [index] replaced by [value]. */+internal fun <T> List<T>.replacing(index: Int, value: T): List<T> =+    toMutableList().also { it[index] = value }
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/AppBackupAgent.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/AppBackupAgent.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..49f4e2c119--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/AppBackupAgent.kt@@ -0,0 +1,10 @@+package com.vayunmathur.games.minesweeper.platform++import com.vayunmathur.library.util.BaseBackupAgent++class AppBackupAgent : BaseBackupAgent() {+    override val prefNames: List<String> get() = listOf("minesweeper_stats")++    // The shared DataStoreUtils file, holding AchievementsManager unlocks.+    override val datastoreNames: List<String> get() = listOf("datastore_default")+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperAchievementsManager.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperAchievementsManager.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperAchievementsManager.ktnew file mode 100644index 0000000000..9ab7110dc0--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperAchievementsManager.kt@@ -0,0 +1,44 @@+package com.vayunmathur.games.minesweeper.platform++import android.content.Context+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.MinesweeperStatsRepository+import com.vayunmathur.library.util.AchievementsManager++class MinesweeperAchievementsManager(+    context: Context,+    json: String,+    private val statsRepository: MinesweeperStatsRepository,+) : 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 field they clear.+     *+     * Only the counters that survive in [MinesweeperStatsRepository] can be recovered. Anything about+     * how a single game was played — flags placed, whether a chord was used — 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.LARGE).gamesWon > 0) {+            onAchievementUnlocked("win_large")+        }+        if (BoardSize.entries.any { statsRepository.getStats(it, Difficulty.EXPERT).gamesWon > 0 }) {+            onAchievementUnlocked("win_expert")+        }+        val best = BoardSize.entries.minOf { statsRepository.getSizeStats(it).bestTimeSeconds }+        if (best < FAST_WIN_SECONDS) onAchievementUnlocked("speed_win")++        onProgressUpdated("wins_10", totalWins)+        onProgressUpdated("wins_50", totalWins)+        onProgressUpdated("win_streak_5", statsRepository.getBestWinStreak())+    }++    private companion object {+        /** Matches the "under a minute" wording of the `speed_win` description. */+        const val FAST_WIN_SECONDS = 60+    }+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperUiContract.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperUiContract.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperUiContract.ktnew file mode 100644index 0000000000..ad5b080a50--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperUiContract.kt@@ -0,0 +1,38 @@+package com.vayunmathur.games.minesweeper.platform++import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState++/**+ * The UI contract between [MinesweeperViewModel] 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 MinesweeperActions {+    /** Tap: opens a covered cell, or chords an already-open number. */+    fun tapCell(index: Int) {}++    /** Long press: cycles the flag. */+    fun flagCell(index: Int) {}++    fun restart() {}+    fun giveUp() {}++    companion object { val Noop: MinesweeperActions = object : MinesweeperActions {} }+}++/**+ * What the board needs to draw itself.+ *+ * [config] lives here rather than on the game state because the chosen size and density belong to+ * the session, not the field — the rules work on any rectangle.+ */+data class MinesweeperUiState(+    val config: GameConfig = GameConfig(),+    val game: MinesweeperGameState? = null,+)
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.ktnew file mode 100644index 0000000000..4908ee8a07--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.kt@@ -0,0 +1,173 @@+package com.vayunmathur.games.minesweeper.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import com.vayunmathur.games.minesweeper.data.MinesweeperStatsRepository+import com.vayunmathur.games.minesweeper.domain.FieldGenerator+import com.vayunmathur.games.minesweeper.domain.MinesweeperRules+import com.vayunmathur.library.util.AchievementsManager+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlin.random.Random++/**+ * Owns the field in progress.+ *+ * The field 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 game 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.+ *+ * Unlike sudoku there is no generation cost worth dispatching off the main thread: laying mines is a+ * shuffle and one pass for the neighbour counts, so it runs inline on the first tap.+ */+class MinesweeperViewModel(application: Application) :+    AndroidViewModel(application), MinesweeperActions {++    private val _uiState = MutableStateFlow(MinesweeperUiState())+    val uiState: StateFlow<MinesweeperUiState> = _uiState.asStateFlow()++    private val statsRepository = MinesweeperStatsRepository(application)++    /**+     * Whether the player has placed a flag this game.+     *+     * Cannot be read off the finished state: winning marks every remaining mine, so a cleared board+     * always looks fully flagged regardless of what the player actually did.+     */+    private var placedAnyFlag = false++    val achievementsManager: AchievementsManager = run {+        val json = application.assets.open("achievements.json").bufferedReader().readText()+        MinesweeperAchievementsManager(application, json, statsRepository)+    }++    init {+        achievementsManager.checkExistingAchievements()+    }++    fun hasActiveGame(): Boolean = _uiState.value.game?.isOver == false++    fun getSizeStats(size: BoardSize) = statsRepository.getSizeStats(size)++    /** Deals a blank field for [config]. Mines are not laid until the first tap. */+    fun newGame(config: GameConfig) {+        placedAnyFlag = false+        _uiState.value = MinesweeperUiState(+            config = config,+            game = MinesweeperGameState.empty(config),+        )+    }++    /**+     * Opens a covered cell, or chords an open number.+     *+     * The first tap also lays the mines, keeping itself and its neighbours clear, so the opening move+     * can never lose. That is also where the game counts as played — backing out of a field you never+     * touched should not show up in the stats.+     */+    override fun tapCell(index: Int) {+        val state = _uiState.value+        val game = state.game ?: return+        if (game.isOver) return++        val laid = if (game.started) game else {+            statsRepository.recordGamePlayed(state.config.size, state.config.difficulty)+            FieldGenerator.lay(game, index, Random.Default)+        }++        val next =+            if (laid.revealed[index]) {+                MinesweeperRules.chord(laid, index).also { chorded ->+                    // Only counts when the chord was legal and actually opened something.+                    if (chorded !== laid) achievementsManager.onAchievementUnlocked("first_chord")+                }+            } else {+                MinesweeperRules.reveal(laid, index)+            }++        publish(next)+    }++    override fun flagCell(index: Int) {+        val game = _uiState.value.game ?: return+        // Flagging before the first reveal would have nothing to flag: the mines are not laid yet.+        if (!game.started || game.isOver) return+        val next = MinesweeperRules.toggleFlag(game, index)+        if (next.flagsPlaced > game.flagsPlaced) placedAnyFlag = true+        publish(next)+    }++    /** A fresh field with the same settings. */+    override fun restart() {+        newGame(_uiState.value.config)+    }++    /** Abandons an unfinished field, which breaks the win streak for that variant. */+    override fun giveUp() {+        val state = _uiState.value+        val game = state.game ?: return+        if (game.started && !game.isOver) {+            statsRepository.recordGameLost(state.config.size, state.config.difficulty)+        }+        _uiState.value = MinesweeperUiState(config = state.config)+    }++    fun incrementTimer() {+        val game = _uiState.value.game ?: return+        if (!game.started || game.isOver) return+        _uiState.update { it.copy(game = game.copy(elapsedSeconds = game.elapsedSeconds + 1)) }+    }++    fun dismissAchievementNotification() = achievementsManager.dismissNotification()++    /**+     * Stores [next] and, when it has just ended, records the result.+     *+     * Every path that can finish a game goes through here, so stats and achievements can never+     * disagree about what happened.+     */+    private fun publish(next: MinesweeperGameState) {+        val previous = _uiState.value.game+        _uiState.update { it.copy(game = next) }++        val justEnded = previous != null && !previous.isOver && next.isOver+        if (!justEnded) return++        val config = _uiState.value.config+        when (next.outcome) {+            GameOutcome.WON -> onWin(next)+            GameOutcome.LOST -> statsRepository.recordGameLost(config.size, config.difficulty)+            GameOutcome.PLAYING -> Unit+        }+    }++    private fun onWin(game: MinesweeperGameState) {+        val config = _uiState.value.config+        statsRepository.recordGameWon(config.size, config.difficulty, game.elapsedSeconds)++        val manager = achievementsManager+        manager.onAchievementUnlocked("first_win")+        if (config.size == BoardSize.LARGE) manager.onAchievementUnlocked("win_large")+        if (config.difficulty == Difficulty.EXPERT) manager.onAchievementUnlocked("win_expert")+        if (!placedAnyFlag) manager.onAchievementUnlocked("no_flags_needed")+        if (game.elapsedSeconds < FAST_WIN_SECONDS) manager.onAchievementUnlocked("speed_win")++        val totalWins = statsRepository.getTotalGamesWon()+        manager.onProgressUpdated("wins_10", totalWins)+        manager.onProgressUpdated("wins_50", totalWins)+        manager.onProgressUpdated("win_streak_5", statsRepository.getBestWinStreak())+    }++    private companion object {+        /** Matches the "under a minute" wording of the `speed_win` description. */+        const val FAST_WIN_SECONDS = 60+    }+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/DisplayNames.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/DisplayNames.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/DisplayNames.ktnew file mode 100644index 0000000000..30f1be503c--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/DisplayNames.kt@@ -0,0 +1,39 @@+package com.vayunmathur.games.minesweeper.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.games.minesweeper.R+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.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.SMALL -> R.string.size_small+        BoardSize.MEDIUM -> R.string.size_medium+        BoardSize.LARGE -> R.string.size_large+    }+)++@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+    }+)++/** `mm:ss`, and `h:mm:ss` once a field 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/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.ktnew file mode 100644index 0000000000..55b75980d7--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.kt@@ -0,0 +1,190 @@+package com.vayunmathur.games.minesweeper.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.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.minesweeper.R+import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.platform.MinesweeperActions+import com.vayunmathur.games.minesweeper.platform.MinesweeperUiState+import com.vayunmathur.games.minesweeper.ui.components.MineFieldGrid+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.IconFlag+import com.vayunmathur.library.ui.MaterialTheme+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 field on tablets, where a full-width board would give absurdly large cells. */+private val FieldMaxWidth = 480.dp++/**+ * The board, with no dependency on the ViewModel so it can be rendered from a `@Preview` — see+ * `src/screenshotTest`.+ */+@Composable+fun GameBoardScreen(+    state: MinesweeperUiState,+    actions: MinesweeperActions,+    onExit: () -> Unit,+) {+    val game = state.game+    val mineCount = state.config.difficulty.mineCount(state.config.size)+    AppScaffold(+        // Size name plus the mine count rather than size plus density name: the two enums share+        // labels ("Medium" and "Medium"), and the raw count is what a player actually wants to know.+        title = "${state.config.size.displayName()} · " ++            pluralStringResource(R.plurals.mine_count, mineCount, mineCount),+        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 = FieldMaxWidth)+                    .fillMaxWidth()+                    .verticalScroll(rememberScrollState())+                    .padding(horizontal = Spacing.md, vertical = Spacing.sm),+                verticalArrangement = Arrangement.spacedBy(Spacing.md),+            ) {+                Row(+                    Modifier.fillMaxWidth(),+                    horizontalArrangement = Arrangement.Center,+                    verticalAlignment = Alignment.CenterVertically,+                ) {+                    IconFlag(tint = MaterialTheme.colorScheme.error)+                    Text(+                        " ${game.minesRemaining}",+                        style = MaterialTheme.typography.titleMedium,+                    )+                }++                MineFieldGrid(+                    game = game,+                    onTap = actions::tapCell,+                    onLongPress = actions::flagCell,+                    modifier = Modifier.fillMaxWidth(),+                )++                if (!game.started) {+                    Text(+                        stringResource(R.string.how_to_play),+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                        modifier = Modifier.fillMaxWidth(),+                    )+                }++                Row(+                    Modifier.fillMaxWidth(),+                    horizontalArrangement = Arrangement.spacedBy(Spacing.sm),+                ) {+                    Button(+                        onClick = { actions.restart() },+                        modifier = Modifier.weight(1f),+                    ) { Text(stringResource(R.string.new_field_button)) }+                    TextButton(+                        onClick = {+                            actions.giveUp()+                            onExit()+                        },+                        modifier = Modifier.weight(1f),+                    ) { Text(stringResource(R.string.give_up)) }+                }+            }++            if (game.isOver) {+                ResultOverlay(+                    won = game.outcome == GameOutcome.WON,+                    elapsedSeconds = game.elapsedSeconds,+                    onPlayAgain = { actions.restart() },+                    onBack = onExit,+                )+            }+        }+    }+}++@Composable+private fun ResultOverlay(+    won: Boolean,+    elapsedSeconds: Int,+    onPlayAgain: () -> Unit,+    onBack: () -> Unit,+) {+    Box(+        Modifier+            .fillMaxSize()+            // Scrim, so the card reads as modal instead of letting the field 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(if (won) R.string.cleared else R.string.boom),+                    style = MaterialTheme.typography.headlineSmall,+                    color = if (won) MaterialTheme.colorScheme.primary+                    else MaterialTheme.colorScheme.error,+                )+                // A losing time is not an achievement, so it is only shown on a win.+                if (won) Text("${stringResource(R.string.time)}: ${formatTime(elapsedSeconds)}")+                Button(onClick = onPlayAgain, Modifier.fillMaxWidth()) {+                    Text(stringResource(R.string.play_again))+                }+                TextButton(onClick = onBack, Modifier.fillMaxWidth()) {+                    Text(stringResource(R.string.back))+                }+            }+        }+    }+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameScreen.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameScreen.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameScreen.ktnew file mode 100644index 0000000000..f750ab0938--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameScreen.kt@@ -0,0 +1,46 @@+package com.vayunmathur.games.minesweeper.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.minesweeper.Route+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.platform.MinesweeperViewModel+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.delay++/**+ * The only place the board touches the ViewModel.+ *+ * It deals a field if there is not one already — reached by entering this route after process death,+ * when the route survived but the in-memory field 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: MinesweeperViewModel,+    config: GameConfig,+) {+    val uiState by viewModel.uiState.collectAsState()++    LaunchedEffect(config) {+        if (uiState.game == null) viewModel.newGame(config)+    }++    // The clock starts on the first reveal, not on entering the screen.+    val running = uiState.game?.let { it.started && !it.isOver } == true+    LaunchedEffect(running) {+        while (running) {+            delay(1000)+            viewModel.incrementTimer()+        }+    }++    GameBoardScreen(+        state = uiState,+        actions = viewModel,+        onExit = { backStack.pop() },+    )+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/HomeScreen.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/HomeScreen.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/HomeScreen.ktnew file mode 100644index 0000000000..85325cac00--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/HomeScreen.kt@@ -0,0 +1,136 @@+package com.vayunmathur.games.minesweeper.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.minesweeper.R+import com.vayunmathur.games.minesweeper.Route+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.platform.MinesweeperViewModel+import com.vayunmathur.games.minesweeper.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: MinesweeperViewModel,+) {+    val uiState by viewModel.uiState.collectAsState()+    var showConfig by remember { mutableStateOf(false) }++    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),+        ) {+            if (viewModel.hasActiveGame()) {+                Button(+                    onClick = { backStack.add(Route.Game(uiState.config)) },+                    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(+            // Seeded with the last thing played, so a player grinding one setting taps twice.+            initial = uiState.config,+            onStart = { config ->+                showConfig = false+                viewModel.newGame(config)+                backStack.add(Route.Game(config))+            },+            onDismiss = { showConfig = false },+        )+    }+}++@Composable+private fun SizeStatsCard(+    size: BoardSize,+    viewModel: MinesweeperViewModel,+    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.cleared_count),+                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,+                )+            }+        }+    }+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/components/MineFieldGrid.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/components/MineFieldGrid.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/components/MineFieldGrid.ktnew file mode 100644index 0000000000..882c4d1ae0--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/components/MineFieldGrid.kt@@ -0,0 +1,163 @@+package com.vayunmathur.games.minesweeper.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.games.minesweeper.R+import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import com.vayunmathur.library.ui.ColorScheme+import com.vayunmathur.library.ui.IconFlag+import com.vayunmathur.library.ui.IconMine+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * The mine field.+ *+ * Cells are square and sized from the available width, so a taller field simply gets taller rather+ * than squeezing the cells. Tap and long press are handled per cell by [detectTapGestures] rather+ * than by `clickable` + `combinedClickable`, because the flag gesture needs to fire on press-and-hold+ * without also delivering the tap that would open the cell.+ */+@Composable+fun MineFieldGrid(+    game: MinesweeperGameState,+    onTap: (Int) -> Unit,+    onLongPress: (Int) -> Unit,+    modifier: Modifier = Modifier,+) {+    Column(modifier) {+        for (row in 0 until game.rows) {+            Row(Modifier.fillMaxWidth()) {+                for (col in 0 until game.cols) {+                    val index = row * game.cols + col+                    MineCell(+                        game = game,+                        index = index,+                        onTap = { onTap(index) },+                        onLongPress = { onLongPress(index) },+                        // weight + aspectRatio keeps the cells square whatever the column count.+                        modifier = Modifier+                            .weight(1f)+                            .aspectRatio(1f),+                    )+                }+            }+        }+    }+}++@Composable+private fun MineCell(+    game: MinesweeperGameState,+    index: Int,+    onTap: () -> Unit,+    onLongPress: () -> Unit,+    modifier: Modifier = Modifier,+) {+    val scheme = MaterialTheme.colorScheme+    val haptics = LocalHapticFeedback.current++    val revealed = game.revealed[index]+    val flagged = game.flagged[index]+    val isMine = game.mines[index]+    val count = game.neighbourCounts[index]+    val lost = game.outcome == GameOutcome.LOST++    // Mines are hidden during play - they are the thing being deduced. On a loss the field is opened+    // up; on a win the mines are shown as the flags the player earned rather than as bare mines.+    val showMine = isMine && (revealed || lost)+    val showFlag = flagged && !showMine++    val background = when {+        index == game.explodedAt -> scheme.error+        revealed || showMine -> scheme.surfaceContainerLowest+        else -> scheme.surfaceContainerHighest+    }++    val position = stringResource(+        R.string.cd_position,+        index / game.cols + 1,+        index % game.cols + 1,+    )+    val stateWord = when {+        showMine -> stringResource(R.string.cd_mine)+        showFlag -> stringResource(R.string.cd_flagged)+        !revealed -> stringResource(R.string.cd_covered)+        count == 0 -> stringResource(R.string.cd_empty)+        else -> pluralStringResource(R.plurals.cd_count, count, count)+    }++    Box(+        modifier+            .padding(CellGap)+            .clip(MaterialTheme.shapes.extraSmall)+            .background(background)+            .pointerInput(index, game.isOver, game.started) {+                detectTapGestures(+                    onTap = { onTap() },+                    onLongPress = {+                        // Confirms the flag without the player having to look away from the field.+                        haptics.performHapticFeedback(HapticFeedbackType.LongPress)+                        onLongPress()+                    },+                )+            }+            .clearAndSetSemantics { contentDescription = "$position, $stateWord" },+        contentAlignment = Alignment.Center,+    ) {+        when {+            showMine -> IconMine(+                Modifier.fillMaxSize(0.7f),+                tint = if (index == game.explodedAt) scheme.onError else scheme.onSurfaceVariant,+            )++            showFlag -> IconFlag(Modifier.fillMaxSize(0.65f), tint = scheme.error)++            revealed && count > 0 -> Text(+                text = count.toString(),+                color = countColor(count, scheme),+                fontWeight = FontWeight.Bold,+                fontSize = 15.sp,+            )+        }+    }+}++/** Gap between cells, so the field reads as a grid without needing drawn lines. */+private val CellGap = 1.dp++/**+ * The traditional per-number colours, mapped onto theme roles so they still work in both light and+ * dark and against a dynamic palette. Beyond four the numbers are rare enough that one shared colour+ * is fine, and the count is bold enough to read regardless.+ */+private fun countColor(count: Int, scheme: ColorScheme): Color = when (count) {+    1 -> scheme.primary+    2 -> scheme.tertiary+    3 -> scheme.error+    4 -> scheme.secondary+    else -> scheme.onSurface+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/dialogs/GameConfigDialog.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/dialogs/GameConfigDialog.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/dialogs/GameConfigDialog.ktnew file mode 100644index 0000000000..f6bbb4ba29--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/dialogs/GameConfigDialog.kt@@ -0,0 +1,92 @@+package com.vayunmathur.games.minesweeper.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.minesweeper.R+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.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 field size and mine density for a new game.+ *+ * Both choices are local state: nothing reaches the ViewModel until the player confirms, so backing+ * out cannot disturb a field already in progress. The resulting mine count is shown live, because+ * "Hard" means little without knowing it is 33 mines in 168 cells.+ */+@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_field)) },+        text = {+            Column(+                Modifier.fillMaxWidth(),+                horizontalAlignment = Alignment.CenterHorizontally,+                verticalArrangement = Arrangement.spacedBy(Spacing.md),+            ) {+                Text(stringResource(R.string.field_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()) }+                    }+                }+                Text(+                    "${difficulty.mineCount(size)} / ${size.cellCount}",+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+                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/minesweeper/src/main/res/values/strings.xml
diff --git a/games/minesweeper/src/main/res/values/strings.xml b/games/minesweeper/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..8ed0bf9cf9--- /dev/null+++ b/games/minesweeper/src/main/res/values/strings.xml@@ -0,0 +1,74 @@+<?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">Minesweeper</string>++    <!-- HomeScreen: Primary CTA opening the size and density picker. Verb phrase -->+    <string name="new_game">New Game</string>+    <!-- HomeScreen: Button shown when an unfinished field is still in memory. Verb -->+    <string name="continue_game">Continue</string>+    <!-- GameConfigDialog: Title of the size and density picker dialog. Noun phrase -->+    <string name="new_field">New Field</string>+    <!-- GameConfigDialog: Label above the field size segmented buttons. Noun -->+    <string name="field_size">Field size</string>+    <!-- GameConfigDialog: Label above the mine density segmented buttons. Noun -->+    <string name="difficulty">Mines</string>+    <!-- GameConfigDialog / WinOverlay: Dismiss button. Verb -->+    <string name="back">Back</string>++    <!-- GameConfigDialog: Smallest field, 8 columns by 10 rows. Adjective -->+    <string name="size_small">Small</string>+    <!-- GameConfigDialog: Middle field, 10 columns by 14 rows. Adjective -->+    <string name="size_medium">Medium</string>+    <!-- GameConfigDialog: Largest field, 12 columns by 18 rows. Adjective -->+    <string name="size_large">Large</string>++    <!-- GameConfigDialog: Lowest mine density, about one cell in ten. Adjective -->+    <string name="difficulty_easy">Easy</string>+    <!-- GameConfigDialog: Middle mine density. Adjective -->+    <string name="difficulty_medium">Medium</string>+    <!-- GameConfigDialog: Second highest mine density. Adjective -->+    <string name="difficulty_hard">Hard</string>+    <!-- GameConfigDialog: Highest mine density, close to a quarter of the field. Adjective -->+    <string name="difficulty_expert">Expert</string>++    <!-- GameBoardScreen: Hint under the field explaining the two gestures. Imperative sentence -->+    <string name="how_to_play">Tap to open, long press to flag</string>+    <!-- GameBoardScreen TopAppBar: Subtitle giving the total mine count, after the size name. Quantified noun -->+    <plurals name="mine_count">+        <!-- Singular, only reachable on the very smallest field at the lowest density -->+        <item quantity="one"><xliff:g id="count" example="1">%1$d</xliff:g> mine</item>+        <item quantity="other"><xliff:g id="count" example="21">%1$d</xliff:g> mines</item>+    </plurals>+    <!-- GameBoardScreen action bar: Abandons the field, recorded as a loss. Verb phrase -->+    <string name="give_up">Give Up</string>+    <!-- GameBoardScreen: Starts a fresh field with the same settings. Verb phrase -->+    <string name="new_field_button">New Field</string>++    <!-- WinOverlay: Celebratory title shown when the field is cleared. Declarative -->+    <string name="cleared">Field Cleared!</string>+    <!-- LossOverlay: Title shown when a mine is opened. Declarative, sympathetic -->+    <string name="boom">Boom!</string>+    <!-- WinOverlay: Label for the finishing time, e.g. Time: 01:24. Noun -->+    <string name="time">Time</string>+    <!-- WinOverlay / LossOverlay: Plays another field with the same settings. Verb phrase -->+    <string name="play_again">Play Again</string>+    <!-- HomeScreen stat card: Label under the cleared-of-played ratio. Verb past participle -->+    <string name="cleared_count">cleared</string>++    <!-- GameBoardScreen: Content description of a covered cell. Adjective -->+    <string name="cd_covered">Covered</string>+    <!-- GameBoardScreen: Content description of a flagged cell. Verb past participle -->+    <string name="cd_flagged">Flagged</string>+    <!-- GameBoardScreen: Content description of a revealed mine. Noun -->+    <string name="cd_mine">Mine</string>+    <!-- GameBoardScreen: Content description of an open cell touching no mines. Adjective -->+    <string name="cd_empty">Empty</string>+    <!-- GameBoardScreen: Content description of an open cell, giving its mine count. %1$d = number of adjacent mines, 1 to 8, e.g. 3 -->+    <plurals name="cd_count">+        <item quantity="one"><xliff:g id="count" example="1">%1$d</xliff:g> mine nearby</item>+        <item quantity="other"><xliff:g id="count" example="3">%1$d</xliff:g> mines nearby</item>+    </plurals>+    <!-- GameBoardScreen: Content description prefix locating a cell. %1$d = row number starting at 1, e.g. 4. %2$d = column number starting at 1, e.g. 6 -->+    <string name="cd_position">Row <xliff:g id="row" example="4">%1$d</xliff:g>, column <xliff:g id="column" example="6">%2$d</xliff:g></string>+</resources>
games/minesweeper/src/main/res/xml/data_extraction_rules.xml
diff --git a/games/minesweeper/src/main/res/xml/data_extraction_rules.xml b/games/minesweeper/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..d8fd8295db--- /dev/null+++ b/games/minesweeper/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,34 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+  Minesweeper. Audited state: the "minesweeper_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 field lives only in the ViewModel),+  nothing written to external storage - achievements.json is a read-only APK+  asset and every field is generated on device. Back everything up; it is a few+  KB of pure user progress.+  SCOPE: minesweeper 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 = ["minesweeper_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/minesweeper/src/screenshotTest/kotlin/com/vayunmathur/games/minesweeper/MetadataPreviews.kt
diff --git a/games/minesweeper/src/screenshotTest/kotlin/com/vayunmathur/games/minesweeper/MetadataPreviews.kt b/games/minesweeper/src/screenshotTest/kotlin/com/vayunmathur/games/minesweeper/MetadataPreviews.ktnew file mode 100644index 0000000000..2bc9398389--- /dev/null+++ b/games/minesweeper/src/screenshotTest/kotlin/com/vayunmathur/games/minesweeper/MetadataPreviews.kt@@ -0,0 +1,102 @@+package com.vayunmathur.games.minesweeper++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import com.vayunmathur.games.minesweeper.domain.FieldGenerator+import com.vayunmathur.games.minesweeper.domain.MinesweeperRules+import com.vayunmathur.games.minesweeper.platform.MinesweeperActions+import com.vayunmathur.games.minesweeper.platform.MinesweeperUiState+import com.vayunmathur.games.minesweeper.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:minesweeper:metadata`.+ *+ * Fields come from [FieldGenerator] with a fixed seed and are then played through the real+ * [MinesweeperRules], so every image is a position that could actually occur — no hand-forged state+ * that the rules would never produce. [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-midgame", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview1MidGame() {+        val config = GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM)+        var game = opened(config, seed = 20260824)+        // A few flags, so the counter and the flag glyph both appear.+        for (index in game.mines.indices.filter { game.mines[it] }.take(4)) {+            game = MinesweeperRules.toggleFlag(game, index)+        }+        Board(config, game.copy(elapsedSeconds = 74))+    }++    @PreviewTest+    @Preview(name = "2-large", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview2Large() {+        val config = GameConfig(BoardSize.LARGE, Difficulty.HARD)+        val game = opened(config, seed = 77)+        Board(config, game.copy(elapsedSeconds = 142))+    }++    @PreviewTest+    @Preview(name = "3-fresh", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview3Fresh() {+        val config = GameConfig(BoardSize.SMALL, Difficulty.EASY)+        Board(config, MinesweeperGameState.empty(config))+    }++    @PreviewTest+    @Preview(name = "4-cleared", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview4Cleared() {+        val config = GameConfig(BoardSize.SMALL, Difficulty.EASY)+        val blank = MinesweeperGameState.empty(config)+        var game = FieldGenerator.lay(blank, safeIndex = interior(config), rng = Random(5))+        // Open every safe cell, which is what the rules treat as a win.+        for (index in 0 until game.cellCount) {+            if (!game.mines[index]) game = MinesweeperRules.reveal(game, index)+        }+        Board(config, game.copy(elapsedSeconds = 53))+    }++    @Composable+    private fun Board(config: GameConfig, game: MinesweeperGameState) {+        // Layoutlib has no wallpaper to sample, so Material You falls back to the default palette.+        DynamicTheme(darkTheme = true) {+            GameBoardScreen(+                state = MinesweeperUiState(config = config, game = game),+                actions = MinesweeperActions.Noop,+                onExit = {},+            )+        }+    }++    /** A field with the opening area revealed, the position a player actually starts from. */+    private fun opened(config: GameConfig, seed: Int): MinesweeperGameState {+        val blank = MinesweeperGameState.empty(config)+        val safeIndex = interior(config)+        val laid = FieldGenerator.lay(blank, safeIndex, Random(seed))+        return MinesweeperRules.reveal(laid, safeIndex)+    }++    /** A cell with all eight neighbours on the board, so the opening reveal always cascades. */+    private fun interior(config: GameConfig): Int =+        (config.size.rows / 2) * config.size.cols + config.size.cols / 2+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/FieldGeneratorTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/FieldGeneratorTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/FieldGeneratorTest.ktnew file mode 100644index 0000000000..dbba276423--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/FieldGeneratorTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.games.minesweeper.domain++import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import com.vayunmathur.games.minesweeper.data.neighbourIndices+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class FieldGeneratorTest {++    @Test+    fun laysExactlyTheRequestedNumberOfMines() {+        for (size in BoardSize.entries) {+            for (difficulty in Difficulty.entries) {+                val blank = MinesweeperGameState.empty(GameConfig(size, difficulty))+                val laid = FieldGenerator.lay(blank, safeIndex = 0, rng = Random(4))+                assertEquals(+                    difficulty.mineCount(size),+                    laid.mines.count { it },+                    "${size.name}/${difficulty.name}",+                )+            }+        }+    }++    @Test+    fun theFirstTapAndItsNeighboursAreAlwaysClear() {+        // This is the fairness guarantee: the opening move can never lose and always cascades.+        for (size in BoardSize.entries) {+            for (difficulty in Difficulty.entries) {+                val blank = MinesweeperGameState.empty(GameConfig(size, difficulty))+                val safeIndex = interiorIndex(size)+                repeat(20) { seed ->+                    val laid = FieldGenerator.lay(blank, safeIndex, Random(seed))+                    assertFalse(laid.mines[safeIndex], "${size.name}/${difficulty.name} seed $seed")+                    for (n in neighbourIndices(size.cols, size.rows, safeIndex)) {+                        assertFalse(laid.mines[n], "neighbour $n, ${size.name} seed $seed")+                    }+                }+            }+        }+    }++    @Test+    fun theFirstRevealNeverLosesAndAlwaysOpensAnArea() {+        for (size in BoardSize.entries) {+            for (difficulty in Difficulty.entries) {+                val blank = MinesweeperGameState.empty(GameConfig(size, difficulty))+                val safeIndex = interiorIndex(size)+                val laid = FieldGenerator.lay(blank, safeIndex, Random(99))+                val opened = MinesweeperRules.reveal(laid, safeIndex)+                assertTrue(+                    opened.outcome != GameOutcome.LOST,+                    "${size.name}/${difficulty.name} lost on the opening tap",+                )+                // An interior tap has eight neighbours and is guaranteed to be a zero, so the+                // cascade opens at least the full 3x3 around it.+                assertTrue(+                    opened.revealed.count { it } >= 9,+                    "${size.name}/${difficulty.name} opened only " ++                        "${opened.revealed.count { it }} cells",+                )+            }+        }+    }++    @Test+    fun neighbourCountsAgreeWithTheMinesLaid() {+        val blank = MinesweeperGameState.empty(GameConfig(BoardSize.MEDIUM, Difficulty.HARD))+        val laid = FieldGenerator.lay(blank, safeIndex = 0, rng = Random(17))+        for (index in 0 until laid.cellCount) {+            val expected =+                if (laid.mines[index]) 0+                else neighbourIndices(laid.cols, laid.rows, index).count { laid.mines[it] }+            assertEquals(expected, laid.neighbourCounts[index], "cell $index")+        }+    }++    @Test+    fun sameSeedLaysTheSameField() {+        val blank = MinesweeperGameState.empty(GameConfig(BoardSize.SMALL, Difficulty.MEDIUM))+        val first = FieldGenerator.lay(blank, safeIndex = 12, rng = Random(2026))+        val second = FieldGenerator.lay(blank, safeIndex = 12, rng = Random(2026))+        assertEquals(first.mines, second.mines)+    }++    @Test+    fun layingMarksTheFieldStarted() {+        val blank = MinesweeperGameState.empty(GameConfig())+        assertFalse(blank.started)+        assertTrue(FieldGenerator.lay(blank, 0, Random(1)).started)+    }++    @Test+    fun densityAlwaysLeavesRoomForTheOpeningArea() {+        // mineCount is clamped so a field can never be so dense that the safe zone cannot fit.+        for (size in BoardSize.entries) {+            for (difficulty in Difficulty.entries) {+                assertTrue(+                    difficulty.mineCount(size) <= size.cellCount - 9,+                    "${size.name}/${difficulty.name}",+                )+            }+        }+    }++    /**+     * A cell with all eight neighbours on the board.+     *+     * `cellCount / 2` is not it: with an even column count that lands on column 0, an edge cell with+     * only five neighbours, which quietly weakens every assertion about the opening area.+     */+    private fun interiorIndex(size: BoardSize): Int = (size.rows / 2) * size.cols + size.cols / 2+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/MinesweeperRulesTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/MinesweeperRulesTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/MinesweeperRulesTest.ktnew file mode 100644index 0000000000..ff74d93785--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/MinesweeperRulesTest.kt@@ -0,0 +1,232 @@+package com.vayunmathur.games.minesweeper.domain++import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import com.vayunmathur.games.minesweeper.data.neighbourIndices+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class MinesweeperRulesTest {++    @Test+    fun revealingAMineLosesAndRecordsWhere() {+        val state = field(+            """+            .*.+            ...+            ...+            """+        )+        val next = MinesweeperRules.reveal(state, 1)+        assertEquals(GameOutcome.LOST, next.outcome)+        assertEquals(1, next.explodedAt)+    }++    @Test+    fun revealingAZeroCascadesToTheNumbersAroundIt() {+        // The single mine is in the far corner, so tapping the opposite corner opens almost all of it.+        val state = field(+            """+            ....+            ....+            ....+            ...*+            """+        )+        val next = MinesweeperRules.reveal(state, 0)+        val hidden = next.revealed.indices.filterNot { next.revealed[it] }+        // Only the mine itself stays covered; every safe cell is reachable through the zeroes.+        assertEquals(listOf(15), hidden)+        assertEquals(GameOutcome.WON, next.outcome)+    }++    @Test+    fun cascadeStopsAtNumberedCells() {+        val state = field(+            """+            ...*+            ....+            ....+            ....+            """+        )+        val next = MinesweeperRules.reveal(state, 12)+        // Cells touching the mine are revealed but do not themselves spread.+        assertTrue(next.revealed[2], "the 1 next to the mine should be uncovered")+        assertFalse(next.revealed[3], "the mine itself stays covered")+    }++    @Test+    fun cascadeDoesNotOpenFlaggedCells() {+        val state = field(+            """+            ....+            ....+            ....+            ...*+            """+        )+        // A flag mid-field is a claim the player made; a cascade must not overrule it.+        val flagged = MinesweeperRules.toggleFlag(state, 5)+        val next = MinesweeperRules.reveal(flagged, 0)+        assertFalse(next.revealed[5], "flagged cell should stay covered")+    }++    @Test+    fun flaggingIsAToggleAndOnlyAppliesToCoveredCells() {+        val state = field(+            """+            .*.+            ...+            ...+            """+        )+        val once = MinesweeperRules.toggleFlag(state, 0)+        assertTrue(once.flagged[0])+        assertEquals(0, MinesweeperRules.toggleFlag(once, 0).flagged.count { it })++        val revealed = MinesweeperRules.reveal(state, 8)+        assertFalse(+            MinesweeperRules.toggleFlag(revealed, 8).flagged[8],+            "a revealed cell cannot be flagged",+        )+    }++    @Test+    fun chordNeedsTheFlagCountToMatch() {+        val state = field(+            """+            *..+            ...+            ...+            """+        )+        // Cell 1 sees exactly one mine. With no flag placed, chording it must do nothing.+        val revealed = MinesweeperRules.reveal(state, 1)+        assertEquals(revealed, MinesweeperRules.chord(revealed, 1))++        val flagged = MinesweeperRules.toggleFlag(revealed, 0)+        val chorded = MinesweeperRules.chord(flagged, 1)+        assertTrue(chorded.revealed[2], "chord should have opened the unflagged neighbours")+    }++    @Test+    fun chordOnAWrongFlagLosesTheGame() {+        val state = field(+            """+            *..+            ...+            ...+            """+        )+        val revealed = MinesweeperRules.reveal(state, 1)+        // Flagging the wrong cell satisfies the count but points at a safe square.+        val misflagged = MinesweeperRules.toggleFlag(revealed, 2)+        val chorded = MinesweeperRules.chord(misflagged, 1)+        assertEquals(GameOutcome.LOST, chorded.outcome)+    }++    @Test+    fun chordDoesNothingOnAZeroOrACoveredCell() {+        val state = field(+            """+            *..+            ...+            ...+            """+        )+        assertEquals(state, MinesweeperRules.chord(state, 1), "covered cell")+        val revealed = MinesweeperRules.reveal(state, 8)+        assertEquals(revealed, MinesweeperRules.chord(revealed, 8), "zero cell")+    }++    @Test+    fun winningFlagsEveryRemainingMine() {+        val state = field(+            """+            *..+            ...+            ...+            """+        )+        val next = MinesweeperRules.reveal(state, 8)+        assertEquals(GameOutcome.WON, next.outcome)+        assertEquals(listOf(0), next.flagged.indices.filter { next.flagged[it] })+        assertEquals(0, next.minesRemaining)+    }++    @Test+    fun aFinishedGameIgnoresFurtherInput() {+        val state = field(+            """+            .*.+            ...+            ...+            """+        )+        val lost = MinesweeperRules.reveal(state, 1)+        assertEquals(lost, MinesweeperRules.reveal(lost, 4))+        assertEquals(lost, MinesweeperRules.toggleFlag(lost, 4))+        assertEquals(lost, MinesweeperRules.chord(lost, 4))+    }++    @Test+    fun neighbourCountsMatchTheLayout() {+        val state = field(+            """+            *.*+            ...+            *.*+            """+        )+        // The centre touches all four corners.+        assertEquals(4, state.neighbourCounts[4])+        // The top middle touches the two mines beside it.+        assertEquals(2, state.neighbourCounts[1])+    }++    @Test+    fun edgeCellsHaveNoNeighboursOffTheBoard() {+        val size = BoardSize.SMALL+        val cols = size.cols+        val rows = size.rows+        assertEquals(3, neighbourIndices(cols, rows, 0).size, "top-left corner")+        assertEquals(+            3,+            neighbourIndices(cols, rows, size.cellCount - 1).size,+            "bottom-right corner",+        )+        assertEquals(5, neighbourIndices(cols, rows, 1).size, "top edge")+        assertEquals(8, neighbourIndices(cols, rows, cols + 1).size, "interior")+    }++    /**+     * Builds a state from an ASCII field where `*` is a mine, so a test reads as the board it means.+     *+     * The grid must be rectangular. Dimensions come from the literal rather than a [BoardSize], since+     * these tests care about layouts far smaller than any the picker offers.+     */+    private fun field(layout: String): MinesweeperGameState {+        val rows = layout.trimIndent().lines().map { it.trim() }.filter { it.isNotEmpty() }+        val cols = rows.first().length+        require(rows.all { it.length == cols }) { "field must be rectangular" }++        val mines = rows.flatMap { row -> row.map { it == '*' } }+        val counts = mines.indices.map { index ->+            if (mines[index]) 0 else neighbourIndices(cols, rows.size, index).count { mines[it] }+        }+        return MinesweeperGameState(+            cols = cols,+            rows = rows.size,+            mineCount = mines.count { it },+            mines = mines,+            neighbourCounts = counts,+            revealed = List(mines.size) { false },+            flagged = List(mines.size) { false },+            started = true,+        )+    }+}
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 a5d8ac4df7..46c94eabdd 100644--- a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt+++ b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt@@ -38,6 +38,7 @@ private fun resolveGameMetadata(             "wordmaker" -> "Wordmaker"             "logicgate" -> "Logic Gates"             "sudoku" -> "Sudoku"+            "minesweeper" -> "Minesweeper"             else -> gameId.replaceFirstChar { it.uppercase() }         },         description = null,
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex b169475c84..569d7717ef 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -9,6 +9,8 @@ import androidx.compose.material.icons.filled.PersonAdd import androidx.compose.material.icons.filled.HealthAndSafety import androidx.compose.material.icons.filled.Medication import androidx.compose.material.icons.filled.MonitorHeart+import androidx.compose.material.icons.filled.Flag+import androidx.compose.material.icons.filled.Brightness7 import androidx.compose.material.icons.filled.DeliveryDining import androidx.compose.material.icons.filled.Explore import androidx.compose.material.icons.filled.Restaurant@@ -1357,3 +1359,19 @@ fun IconMedication(modifier: Modifier = Modifier, tint: Color = LocalContentColo @Composable fun IconMonitorHeart(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =     AppIcon(Icons.Filled.MonitorHeart, "Medical records", modifier, tint)++/** Flag planted on a cell — marking a suspected mine in Minesweeper. */+@Composable+fun IconFlag(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.Flag, "Flag", modifier, tint)++/**+ * A mine — the spiked disc the classic Minesweeper glyph uses.+ *+ * Material has no bomb, and `Brightness7` is a filled circle with eight rays, which is exactly that+ * shape. Named for what it means here rather than what it is called upstream, as `IconFire`+ * (Whatshot) and `IconEraser` (Backspace) already are.+ */+@Composable+fun IconMine(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.Brightness7, "Mine", modifier, tint)
metadata_data/games-minesweeper.md
diff --git a/metadata_data/games-minesweeper.md b/metadata_data/games-minesweeper.mdnew file mode 100644index 0000000000..dc4a297bba--- /dev/null+++ b/metadata_data/games-minesweeper.md@@ -0,0 +1,6 @@+A classic mine-clearing puzzle, generated fresh every game++Pick a field size and a mine density and play a field generated on the spot. The+first tap is always safe and always opens an area, so no game is lost to a guess+on move one. Tap to open, long press to flag, and tap a satisfied number to clear+around it.
metadata_data/photos/games-minesweeper/1.png
diff --git a/metadata_data/photos/games-minesweeper/1.png b/metadata_data/photos/games-minesweeper/1.pngnew file mode 100644index 0000000000..91d42a8bd0Binary files /dev/null and b/metadata_data/photos/games-minesweeper/1.png differ
metadata_data/photos/games-minesweeper/2.png
diff --git a/metadata_data/photos/games-minesweeper/2.png b/metadata_data/photos/games-minesweeper/2.pngnew file mode 100644index 0000000000..03da1533beBinary files /dev/null and b/metadata_data/photos/games-minesweeper/2.png differ
metadata_data/photos/games-minesweeper/3.png
diff --git a/metadata_data/photos/games-minesweeper/3.png b/metadata_data/photos/games-minesweeper/3.pngnew file mode 100644index 0000000000..d6013304ffBinary files /dev/null and b/metadata_data/photos/games-minesweeper/3.png differ
metadata_data/photos/games-minesweeper/4.png
diff --git a/metadata_data/photos/games-minesweeper/4.png b/metadata_data/photos/games-minesweeper/4.pngnew file mode 100644index 0000000000..b1ab4622a8Binary files /dev/null and b/metadata_data/photos/games-minesweeper/4.png differ
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 024f1d9c1a..bb2b5e0e08 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -79,6 +79,7 @@ include(":games:solitaire") include(":games:logicgate") include(":games:voxels") include(":games:sudoku")+include(":games:minesweeper") include(":games:hub") include(":email") include(":weather")