games: one shared game-stats store for sudoku, minesweeper, solitaire
- Commit
4c0b5aa8cd2d01a73fb4ea469d675265d911c4e4- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-19 15:53 UTC (16 days ago)
- Parents
086ec10
The three games each carried a ~100-line stats repository: the same @Serializable GameStats record, SharedPreferences + JSON encoding, corrupt-value tolerance, and played/won/lost bookkeeping, differing only in prefs file name and enum-to-key mapping. GameStatsStore in library/util owns the storage now. File names (sudoku_stats, minesweeper_stats, solitaire_stats), key strings and JSON shape are unchanged, so existing installs and backup restores read identically. Each game keeps a thin repository with its typed API and key mapping, plus a typealias so GameStats keeps its old per-game package for UI and tests. Verified: full testDevUnitTest for all three games.
Diff
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.ktindex ad959e704b..c87266ee80 100644--- 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.kt@@ -1,23 +1,10 @@ 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+import com.vayunmathur.library.util.GameStatsStore -/**- * 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,-)+/** Minesweeper's stats record; the shared store's record under its old name. */+typealias GameStats = com.vayunmathur.library.util.GameStats /** * Played/won/streak/best-time records, kept per field size and mine density.@@ -26,70 +13,33 @@ data class GameStats( * 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.+ * Storage lives in the shared [GameStatsStore] (`minesweeper_stats` file, same keys and JSON as+ * before); this class owns only the size/difficulty key mapping. */ class MinesweeperStatsRepository(context: Context) {- private val prefs: SharedPreferences =- context.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE)- private val json = Json { ignoreUnknownKeys = true }+ private val store = GameStatsStore(context, "minesweeper_stats") private fun key(size: BoardSize, difficulty: Difficulty) = "stats_${size.name}__${difficulty.name}" - // The prefs file is backup-restored, so a corrupt or cross-version- // value must read as "no record" instead of crash-looping at startup.- private fun readKey(key: String): GameStats? =- prefs.getString(key, null)?.let {- runCatching { json.decodeFromString<GameStats>(it) }.getOrNull()- }- fun getStats(size: BoardSize, difficulty: Difficulty): GameStats =- readKey(key(size, difficulty)) ?: GameStats()+ store.read(key(size, difficulty)) /** 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)) }- }+ fun getSizeStats(size: BoardSize): GameStats =+ GameStatsStore.aggregate(Difficulty.entries.mapNotNull { store.readOrNull(key(size, it)) }) /** * 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 recordGamePlayed(size: BoardSize, difficulty: Difficulty) =+ store.recordPlayed(key(size, difficulty)) - 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 recordGameWon(size: BoardSize, difficulty: Difficulty, timeSeconds: Int) =+ store.recordWon(key(size, difficulty), timeSeconds) - fun recordGameLost(size: BoardSize, difficulty: Difficulty) {- val stats = getStats(size, difficulty)- save(size, difficulty, stats.copy(currentWinStreak = 0))- }+ fun recordGameLost(size: BoardSize, difficulty: Difficulty) =+ store.recordLost(key(size, difficulty)) fun getTotalGamesWon(): Int = BoardSize.entries.sumOf { size -> Difficulty.entries.sumOf { getStats(size, it).gamesWon } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/SolitaireStatsRepository.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/SolitaireStatsRepository.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/SolitaireStatsRepository.ktindex e0150fd2ea..2acde7f073 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/SolitaireStatsRepository.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/SolitaireStatsRepository.kt@@ -1,97 +1,53 @@ package com.vayunmathur.games.solitaire.data import android.content.Context-import android.content.SharedPreferences-import androidx.core.content.edit-import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json-import kotlinx.serialization.encodeToString+import com.vayunmathur.library.util.GameStatsStore -/** Persisted play and win statistics for one variant. */-@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-)+/** Solitaire's stats record; the shared store's record under its old name. */+typealias GameStats = com.vayunmathur.library.util.GameStats /** * Stores stats per (mode, variant) so difficulty variants are tracked * separately, while [getModeStats] aggregates all variants of a mode for the * grouped per-mode display. Keys look like `stats_KLONDIKE__DRAW_ONE_RELAXED`; * a legacy `stats_KLONDIKE` key (no variant) is still folded into the totals.+ *+ * Storage lives in the shared [GameStatsStore] (`solitaire_stats` file, same keys and JSON as+ * before); this class owns only the mode/variant key mapping. */ class SolitaireStatsRepository(context: Context) {- private val prefs: SharedPreferences =- context.getSharedPreferences("solitaire_stats", Context.MODE_PRIVATE)- private val json = Json { ignoreUnknownKeys = true }+ private val store = GameStatsStore(context, "solitaire_stats") private fun key(mode: GameMode, variant: String) = "stats_${mode.name}__$variant" private fun modePrefix(mode: GameMode) = "stats_${mode.name}" - // The prefs file is backup-restored, so a corrupt or cross-version- // value must read as "no record" instead of crash-looping at startup.- private fun readKey(key: String): GameStats? =- prefs.getString(key, null)?.let {- runCatching { json.decodeFromString<GameStats>(it) }.getOrNull()- }- /** Stats for one specific variant of a mode. */ fun getStats(mode: GameMode, variant: String): GameStats =- readKey(key(mode, variant)) ?: GameStats()+ store.read(key(mode, variant)) /** All stat records belonging to [mode] (every variant + any legacy record). */ private fun modeRecords(mode: GameMode): List<GameStats> { val prefix = modePrefix(mode)- return prefs.all.keys+ return store.keys() .filter { it == prefix || it.startsWith("${prefix}__") }- .mapNotNull { readKey(it) }+ .mapNotNull { store.readOrNull(it) } } /** Aggregated stats for a mode, for the grouped per-mode card. */- fun getModeStats(mode: GameMode): GameStats {- val records = modeRecords(mode)- 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 }- )- }+ fun getModeStats(mode: GameMode): GameStats =+ GameStatsStore.aggregate(modeRecords(mode)) - private fun saveStats(mode: GameMode, variant: String, stats: GameStats) {- prefs.edit { putString(key(mode, variant), json.encodeToString(stats)) }- }+ fun recordGamePlayed(mode: GameMode, variant: String) =+ store.recordPlayed(key(mode, variant)) - fun recordGamePlayed(mode: GameMode, variant: String) {- val stats = getStats(mode, variant)- saveStats(mode, variant, stats.copy(gamesPlayed = stats.gamesPlayed + 1))- }+ fun recordGameWon(mode: GameMode, variant: String, timeSeconds: Int) =+ store.recordWon(key(mode, variant), timeSeconds) - fun recordGameWon(mode: GameMode, variant: String, timeSeconds: Int) {- val stats = getStats(mode, variant)- val newStreak = stats.currentWinStreak + 1- saveStats(- mode, variant, stats.copy(- gamesWon = stats.gamesWon + 1,- currentWinStreak = newStreak,- bestWinStreak = maxOf(stats.bestWinStreak, newStreak),- bestTimeSeconds = minOf(stats.bestTimeSeconds, timeSeconds)- )- )- }-- fun recordGameLost(mode: GameMode, variant: String) {- val stats = getStats(mode, variant)- saveStats(mode, variant, stats.copy(currentWinStreak = 0))- }+ fun recordGameLost(mode: GameMode, variant: String) =+ store.recordLost(key(mode, variant)) private fun allRecords(): List<GameStats> =- prefs.all.keys.filter { it.startsWith("stats_") }.mapNotNull { readKey(it) }+ store.keys().filter { it.startsWith("stats_") }.mapNotNull { store.readOrNull(it) } fun getTotalGamesWon(): Int = allRecords().sumOf { it.gamesWon }
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.ktindex 8df193510a..fcd4692723 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuStatsRepository.kt@@ -1,23 +1,10 @@ package com.vayunmathur.games.sudoku.data import android.content.Context-import android.content.SharedPreferences-import androidx.core.content.edit-import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json+import com.vayunmathur.library.util.GameStatsStore -/**- * 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,-)+/** Sudoku's stats record; the shared store's record under its old name. */+typealias GameStats = com.vayunmathur.library.util.GameStats /** * Played/won/streak/best-time records, kept per board size and difficulty.@@ -27,70 +14,33 @@ data class GameStats( * home screen still wants a single figure per size, so [getSizeStats] aggregates by key prefix * instead of keeping a second denormalised record that could drift. *- * Reads are synchronous and happen during composition. That is fine for SharedPreferences, which is- * an in-memory map after the first load, and is the reason this is not a DataStore.+ * Storage lives in the shared [GameStatsStore] (`sudoku_stats` file, same keys and JSON as+ * before); this class owns only the size/difficulty key mapping. */ class SudokuStatsRepository(context: Context) {- private val prefs: SharedPreferences =- context.getSharedPreferences("sudoku_stats", Context.MODE_PRIVATE)- private val json = Json { ignoreUnknownKeys = true }+ private val store = GameStatsStore(context, "sudoku_stats") private fun key(size: BoardSize, difficulty: Difficulty) = "${sizePrefix(size)}__${difficulty.name}" private fun sizePrefix(size: BoardSize) = "stats_${size.name}" - // The prefs file is backup-restored, so a corrupt or cross-version- // value must read as "no record" instead of crash-looping at startup.- private fun readKey(key: String): GameStats? =- prefs.getString(key, null)?.let {- runCatching { json.decodeFromString<GameStats>(it) }.getOrNull()- }- fun getStats(size: BoardSize, difficulty: Difficulty): GameStats =- readKey(key(size, difficulty)) ?: GameStats()+ store.read(key(size, difficulty)) /** Every difficulty's record for [size], summed for played/won and best-of for the rest. */- fun getSizeStats(size: BoardSize): GameStats {- val records = Difficulty.entries.mapNotNull { readKey(key(size, it)) }- if (records.isEmpty()) return GameStats()- return GameStats(- gamesPlayed = records.sumOf { it.gamesPlayed },- gamesWon = records.sumOf { it.gamesWon },- currentWinStreak = records.maxOf { it.currentWinStreak },- bestWinStreak = records.maxOf { it.bestWinStreak },- bestTimeSeconds = records.minOf { it.bestTimeSeconds },- )- }-- private fun save(size: BoardSize, difficulty: Difficulty, stats: GameStats) {- prefs.edit { putString(key(size, difficulty), json.encodeToString(stats)) }- }+ fun getSizeStats(size: BoardSize): GameStats =+ GameStatsStore.aggregate(Difficulty.entries.mapNotNull { store.readOrNull(key(size, it)) }) /** Counted when the puzzle is dealt, so an abandoned game still shows up as played. */- fun recordGamePlayed(size: BoardSize, difficulty: Difficulty) {- val stats = getStats(size, difficulty)- save(size, difficulty, stats.copy(gamesPlayed = stats.gamesPlayed + 1))- }+ fun recordGamePlayed(size: BoardSize, difficulty: Difficulty) =+ store.recordPlayed(key(size, difficulty)) - 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 recordGameWon(size: BoardSize, difficulty: Difficulty, timeSeconds: Int) =+ store.recordWon(key(size, difficulty), timeSeconds) - fun recordGameLost(size: BoardSize, difficulty: Difficulty) {- val stats = getStats(size, difficulty)- save(size, difficulty, stats.copy(currentWinStreak = 0))- }+ fun recordGameLost(size: BoardSize, difficulty: Difficulty) =+ store.recordLost(key(size, difficulty)) fun getTotalGamesWon(): Int = BoardSize.entries.sumOf { size -> Difficulty.entries.sumOf { getStats(size, it).gamesWon } }
library/src/main/java/com/vayunmathur/library/util/GameStatsStore.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/GameStatsStore.kt b/library/src/main/java/com/vayunmathur/library/util/GameStatsStore.ktnew file mode 100644index 0000000000..41f701e5a5--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/util/GameStatsStore.kt@@ -0,0 +1,110 @@+package com.vayunmathur.library.util++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 game 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 over SharedPreferences, shared by+ * the games that track them.+ *+ * sudoku, minesweeper and solitaire each carried a ~100-line copy of+ * this store (same `@Serializable` record, same JSON-in-prefs encoding,+ * same corrupt-value tolerance, same played/won/lost bookkeeping),+ * differing only in the prefs file name and in how their enum types map+ * to record keys. The file names, key strings and JSON shape are+ * unchanged, so existing installs and backup restores read identically;+ * each game keeps a thin repository that owns only its key mapping and+ * exposes `GameStats` under its old package via a typealias.+ *+ * Reads are synchronous. 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 GameStatsStore(context: Context, prefsName: String) {++ private val prefs: SharedPreferences =+ context.getSharedPreferences(prefsName, Context.MODE_PRIVATE)+ private val json = Json { ignoreUnknownKeys = true }++ /**+ * The record at [key], or null when absent or unreadable. The prefs+ * file is backup-restored, so a corrupt or cross-version value must+ * read as "no record" instead of crash-looping at startup.+ */+ fun readOrNull(key: String): GameStats? =+ prefs.getString(key, null)?.let {+ runCatching { json.decodeFromString<GameStats>(it) }.getOrNull()+ }++ /** The record at [key], or a fresh record when there is none. */+ fun read(key: String): GameStats = readOrNull(key) ?: GameStats()++ /** Every key currently stored (solitaire aggregates over these). */+ fun keys(): Set<String> = prefs.all.keys++ private fun save(key: String, stats: GameStats) {+ prefs.edit { putString(key, json.encodeToString(stats)) }+ }++ /** Count a dealt/played game at [key]. */+ fun recordPlayed(key: String) {+ val stats = read(key)+ save(key, stats.copy(gamesPlayed = stats.gamesPlayed + 1))+ }++ /** Count a win at [key] in [timeSeconds], updating streaks and best time. */+ fun recordWon(key: String, timeSeconds: Int) {+ val stats = read(key)+ val streak = stats.currentWinStreak + 1+ save(+ key,+ stats.copy(+ gamesWon = stats.gamesWon + 1,+ currentWinStreak = streak,+ bestWinStreak = maxOf(stats.bestWinStreak, streak),+ bestTimeSeconds = minOf(stats.bestTimeSeconds, timeSeconds),+ ),+ )+ }++ /** Count a loss at [key], resetting the current streak. */+ fun recordLost(key: String) {+ val stats = read(key)+ save(key, stats.copy(currentWinStreak = 0))+ }++ companion object {+ /**+ * Sum played/won over [records] and take the best of the streak+ * and time fields — the per-variant aggregate each game's home+ * screen shows.+ */+ fun aggregate(records: List<GameStats>): GameStats {+ 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 },+ )+ }+ }+}