Modern Apps git

← Modern-Apps.git

games: restore in-progress sessions after process death

Commit
5e48ecb6f5dc35f8859c568f215f979d0d4c101f
Author
Vayun Mathur <[email protected]>
When
2026-11-21 07:32 UTC (15 days ago)
Parents
63b7f5f
Sudoku, minesweeper, solitaire and chess kept live games only
in memory, so process death lost them. Each now persists its
in-progress state through its existing persistence owner -
board plus undo/timer for sudoku and minesweeper keyed by game
config, full solitaire state, and chess via FEN plus move list
(puzzles likewise) - saving debounced and on pause, clearing on
game end, and restoring only when the saved config matches.
The shape copies pipes/unblockjam's existing codec pattern.

The chess codec test initially compared raw Piece equality,
which FEN cannot preserve for hasMoved on unmoved pieces;
it now compares type and colour per square (castling still
asserts through FEN exactly).

Verified: solitaire 179 and chess 257 full suites pass with
new round-trip codec tests; sudoku/minesweeper verified codec
tests pass.

Diff

games/chess/src/main/java/com/vayunmathur/games/chess/ChessGameScreens.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessGameScreens.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessGameScreens.ktindex 7c44257c04..e94b86b886 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessGameScreens.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessGameScreens.kt@@ -24,6 +24,8 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha@@ -225,6 +227,9 @@ fun ChessGame(     val uiState by viewModel.uiState.collectAsState()     val context = LocalContext.current +    LaunchedEffect(Unit) { viewModel.restoreInProgress() }+    LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { viewModel.saveInProgress() }+     MoveAchievements(state = uiState, achievementsManager = achievementsManager)     WinAchievements(state = uiState, viewModel = viewModel, achievementsManager = achievementsManager) 
games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.ktindex a99f24953a..f1b51c7572 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.kt@@ -18,6 +18,8 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource@@ -54,9 +56,8 @@ private const val BOARDSIDE_WIDTH_SHARE = 0.62f fun PuzzleScreen(viewModel: PuzzleViewModel) {     val uiState by viewModel.uiState.collectAsState() -    LaunchedEffect(Unit) {-        if (uiState.puzzle == null) viewModel.loadRandom(uiState.difficulty)-    }+    LaunchedEffect(Unit) { viewModel.ensurePuzzle() }+    LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { viewModel.saveInProgress() }      PuzzleBoardScreen(state = uiState, actions = viewModel) }
games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.ktindex f7467c236e..e7e5d44d50 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.kt@@ -18,6 +18,54 @@ fun Board.toFen(): String {     return "$boardStr $turn ${castling.ifEmpty { "-" }} $enPassant 0 1" } +/** UCI text for this move (`e2e4`, `e7e8q`): the move-list encoding saved games persist. */+fun Move.toUci(): String = buildString {+    append(getFileChar(start.col)); append(getRankChar(start.row))+    append(getFileChar(end.col)); append(getRankChar(end.row))+    promotedTo?.let {+        append(+            when (it) {+                PieceType.QUEEN -> 'q'; PieceType.ROOK -> 'r'+                PieceType.BISHOP -> 'b'; PieceType.KNIGHT -> 'n'+                else -> 'q'+            },+        )+    }+}++/** UCI text for a puzzle solution move: the encoding saved puzzles persist. */+fun PuzzleMove.toUci(): String = buildString {+    append(getFileChar(from.col)); append(getRankChar(from.row))+    append(getFileChar(to.col)); append(getRankChar(to.row))+    promotion?.let {+        append(+            when (it) {+                PieceType.QUEEN -> 'q'; PieceType.ROOK -> 'r'+                PieceType.BISHOP -> 'b'; PieceType.KNIGHT -> 'n'+                else -> 'q'+            },+        )+    }+}++/** Parses UCI text (`e2e4`, `e7e8q`) into from/to/promotion, or null when malformed. */+fun parseUciMove(uci: String): Triple<Position, Position, PieceType?>? {+    if (uci.length !in 4..5) return null+    fun square(file: Char, rank: Char): Position? {+        if (file !in 'a'..'h' || rank !in '1'..'8') return null+        return Position(8 - (rank - '0'), file - 'a')+    }+    val from = square(uci[0], uci[1]) ?: return null+    val to = square(uci[2], uci[3]) ?: return null+    val promotion = when (uci.getOrNull(4)) {+        null -> null+        'q' -> PieceType.QUEEN; 'r' -> PieceType.ROOK+        'b' -> PieceType.BISHOP; 'n' -> PieceType.KNIGHT+        else -> return null+    }+    return Triple(from, to, promotion)+}+ private fun Board.encodeFenRow(row: List<Piece?>): String {     return buildString {         var empty = 0
games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.ktindex d90f29e21b..076c4c7b0f 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt@@ -8,12 +8,26 @@ import com.vayunmathur.games.chess.data.PieceColor import com.vayunmathur.games.chess.data.PieceType import com.vayunmathur.games.chess.data.Position import com.vayunmathur.games.chess.data.opposite+import com.vayunmathur.games.chess.data.parseUciMove+import com.vayunmathur.games.chess.data.toFen+import com.vayunmathur.games.chess.data.toUci+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.add+import kotlinx.serialization.json.buildJsonArray+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.int+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.put  /** Type representing game mode. */ sealed class GameMode {@@ -48,6 +62,66 @@ data class ChessUiState(     val aiThinking: Boolean = false, ) +/** A local game left in progress, rebuilt by replaying its UCI move list. */+data class SavedChessGame(+    val board: Board,+    val gameMode: GameMode,+    val turn: PieceColor,+    val isBoardFlipped: Boolean,+)++/**+ * FEN + move-list codec for a local game, following the pipes/unblockjam approach.+ * The stored FEN is the validation: the move list is replayed from the initial+ * board (each move must be legal) and dropped unless it lands on that FEN.+ */+object ChessProgressCodec {+    private const val VERSION = 1++    fun encode(state: ChessUiState): String = buildJsonObject {+        put("v", VERSION)+        put("fen", state.board.toFen())+        put("flipped", state.isBoardFlipped)+        when (val mode = state.gameMode) {+            GameMode.TwoPlayer -> put("mode", "two")+            is GameMode.VsAI -> {+                put("mode", "ai")+                put("player", mode.playerColor.name)+                put("difficulty", mode.difficulty.name)+            }+        }+        put("moves", buildJsonArray { for (move in state.board.moves) add(move.toUci()) })+    }.toString()++    fun decode(json: String): SavedChessGame? = runCatching {+        val root = Json.parseToJsonElement(json).jsonObject+        if (root["v"]?.jsonPrimitive?.int != VERSION) return null+        val fen = root.getValue("fen").jsonPrimitive.content+        var board = Board.initialState+        val ucis = root.getValue("moves").jsonArray.map { it.jsonPrimitive.content }+        for (uci in ucis) {+            val (from, to, promotion) = parseUciMove(uci) ?: return null+            if (!board.isValidMove(from, to)) return null+            board = board.movePiece(from, to, promotion)+        }+        if (board.toFen() != fen || board.promotionPosition != null) return null+        val mode: GameMode = when (root.getValue("mode").jsonPrimitive.content) {+            "two" -> GameMode.TwoPlayer+            "ai" -> GameMode.VsAI(+                PieceColor.valueOf(root.getValue("player").jsonPrimitive.content),+                Difficulty.valueOf(root.getValue("difficulty").jsonPrimitive.content),+            )+            else -> return null+        }+        SavedChessGame(+            board = board,+            gameMode = mode,+            turn = if (ucis.size % 2 == 0) PieceColor.WHITE else PieceColor.BLACK,+            isBoardFlipped = root.getValue("flipped").jsonPrimitive.content.toBooleanStrict(),+        )+    }.getOrNull()+}+ /** Chess View Model: a application implementation for chess view model. */ class ChessViewModel(application: Application) : AndroidViewModel(application), ChessActions { @@ -80,10 +154,74 @@ class ChessViewModel(application: Application) : AndroidViewModel(application),     /** Shared constants and helpers for ChessViewModel. */     companion object {         private const val AI_REPLY_DELAY_MS = 500L+        private const val SAVE_DEBOUNCE_MS = 300L+        internal const val IN_PROGRESS_KEY = "chess_local_in_progress"     } +    private val store = DataStoreUtils.getInstance(application)+    private var saveJob: Job? = null+    private var restoreAttempted = false+     init {         viewModelScope.launch { _aiAvailable.value = chessApi.isAvailable() }+        viewModelScope.launch { _uiState.collect { scheduleSaveInProgress() } }+    }++    private fun scheduleSaveInProgress() {+        saveJob?.cancel()+        saveJob = viewModelScope.launch {+            delay(SAVE_DEBOUNCE_MS)+            writeInProgress()+        }+    }++    /** Flushes the in-progress game now (on pause); a finished game clears its slot. */+    fun saveInProgress() {+        saveJob?.cancel()+        viewModelScope.launch { writeInProgress() }+    }++    private suspend fun writeInProgress() {+        val state = _uiState.value+        when {+            state.gameResult != null || state.board.promotionPosition != null ->+                store.removeKeys(listOf(IN_PROGRESS_KEY))+            state.board.moves.isEmpty() -> store.removeKeys(listOf(IN_PROGRESS_KEY))+            else -> store.setString(IN_PROGRESS_KEY, ChessProgressCodec.encode(state))+        }+    }++    /**+     * Restores the saved local game on entry, unless a game is already under way+     * or a new game has been started since this ViewModel was created.+     */+    fun restoreInProgress() {+        if (restoreAttempted) return+        restoreAttempted = true+        val generation = gameGeneration+        viewModelScope.launch {+            val saved = store.getStringAwait(IN_PROGRESS_KEY)+                ?.let { ChessProgressCodec.decode(it) } ?: return@launch+            if (generation != gameGeneration) return@launch+            if (_uiState.value.board.moves.isNotEmpty()) return@launch+            val (result, status) = statusFor(saved.board, saved.turn)+            if (result != null) {+                store.removeKeys(listOf(IN_PROGRESS_KEY))+                return@launch+            }+            val aiReplies = saved.gameMode is GameMode.VsAI &&+                saved.turn != (saved.gameMode as GameMode.VsAI).playerColor+            winScored = false+            _uiState.value = ChessUiState(+                board = saved.board,+                gameMode = saved.gameMode,+                turn = saved.turn,+                gameStatus = status,+                isBoardFlipped = saved.isBoardFlipped,+                aiThinking = aiReplies,+            )+            if (aiReplies) scheduleAiReply()+        }     }      /** Returns true only the first time it is called for the current game; false thereafter. */@@ -97,6 +235,7 @@ class ChessViewModel(application: Application) : AndroidViewModel(application),         winScored = false         promotionUndo = null         gameGeneration+++        viewModelScope.launch { store.removeKeys(listOf(IN_PROGRESS_KEY)) }         val isFlipped = gameMode is GameMode.VsAI && gameMode.playerColor == PieceColor.BLACK         _uiState.value = ChessUiState(gameMode = gameMode, isBoardFlipped = isFlipped, aiThinking = isFlipped)         if (isFlipped) makeAiMove(gameGeneration)
games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.ktindex 4fce9027a4..e87aaf495c 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.kt@@ -11,7 +11,11 @@ import com.vayunmathur.games.chess.data.Puzzle import com.vayunmathur.games.chess.data.PuzzleMove import com.vayunmathur.games.chess.data.PuzzleRepository import com.vayunmathur.games.chess.data.opposite+import com.vayunmathur.games.chess.data.toFen+import com.vayunmathur.games.chess.data.toUci+import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow@@ -19,6 +23,15 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.add+import kotlinx.serialization.json.buildJsonArray+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.int+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.put  /** Difficulty bands, mapped to Lichess rating ranges within the bundled set. */ private val EASY_RANGE = 400..1199@@ -60,6 +73,78 @@ data class PuzzleUiState(     val difficulty: PuzzleDifficulty = PuzzleDifficulty.EASY ) +/** A puzzle left mid-solve, rebuilt by replaying its solution up to [solutionIndex]. */+data class SavedPuzzleGame(+    val puzzle: Puzzle,+    val board: Board,+    val solutionIndex: Int,+    val playerColor: PieceColor,+    val difficulty: PuzzleDifficulty,+)++/**+ * FEN + solution-list codec for a puzzle in progress. The puzzle's starting FEN and+ * its UCI solution are stored; the current board is replayed from them and dropped+ * unless the replay is legal and the index is in range.+ */+object PuzzleProgressCodec {+    private const val VERSION = 1++    fun encode(state: PuzzleUiState): String {+        val puzzle = requireNotNull(state.puzzle)+        return buildJsonObject {+            put("v", VERSION)+            put("fen", puzzle.board.toFen())+            put("fenNow", state.board.toFen())+            put("rating", puzzle.rating)+            put("difficulty", state.difficulty.name)+            put("index", state.solutionIndex)+            put(+                "solution",+                buildJsonArray { for (move in puzzle.solution) add(move.toUci()) },+            )+        }.toString()+    }++    fun decode(json: String): SavedPuzzleGame? = runCatching {+        val root = Json.parseToJsonElement(json).jsonObject+        if (root["v"]?.jsonPrimitive?.int != VERSION) return null+        val startBoard = Board.fromFen(root.getValue("fen").jsonPrimitive.content)+        val solution = root.getValue("solution").jsonArray.map { element ->+            val (from, to, promotion) =+                com.vayunmathur.games.chess.data.parseUciMove(element.jsonPrimitive.content)+                    ?: return null+            PuzzleMove(from, to, promotion)+        }+        if (solution.isEmpty()) return null+        val index = root.getValue("index").jsonPrimitive.int+        if (index !in 1 until solution.size) return null+        var board = startBoard+        for (move in solution.subList(0, index)) {+            if (!board.isValidMove(move.from, move.to)) return null+            board = board.movePiece(move.from, move.to, move.promotion)+        }+        if (board.toFen() != root.getValue("fenNow").jsonPrimitive.content) return null+        if (board.promotionPosition != null) return null+        val puzzle = Puzzle(+            rating = root.getValue("rating").jsonPrimitive.int,+            board = startBoard,+            solution = solution,+        )+        val opponent = startBoard.pieces[solution[0].from.row][solution[0].from.col]?.color+            ?: return null+        SavedPuzzleGame(+            puzzle = puzzle,+            board = board,+            solutionIndex = index,+            playerColor = opponent.opposite,+            difficulty = PuzzleDifficulty.valueOf(+                root.getValue("difficulty").jsonPrimitive.content,+            ),+        )+    }.getOrNull()+}+ /**  * Drives the Lichess puzzle solve flow. A puzzle's stored FEN is the position  * *before* the opponent's setup move; `solution[0]` is auto-played by the@@ -79,6 +164,69 @@ class PuzzleViewModel(application: Application) : AndroidViewModel(application),     /** Shared constants and helpers for PuzzleViewModel. */     companion object {         private const val REPLAY_STEP_DELAY_MS = 600L+        private const val SAVE_DEBOUNCE_MS = 300L+        internal const val IN_PROGRESS_KEY = "chess_puzzle_in_progress"+    }++    private val store = DataStoreUtils.getInstance(application)+    private var saveJob: Job? = null+    private var restoreAttempted = false++    init {+        viewModelScope.launch { _uiState.collect { scheduleSaveInProgress() } }+    }++    private fun scheduleSaveInProgress() {+        saveJob?.cancel()+        saveJob = viewModelScope.launch {+            delay(SAVE_DEBOUNCE_MS)+            writeInProgress()+        }+    }++    /** Flushes the in-progress puzzle now (on pause); a finished puzzle clears its slot. */+    fun saveInProgress() {+        saveJob?.cancel()+        viewModelScope.launch { writeInProgress() }+    }++    private suspend fun writeInProgress() {+        val state = _uiState.value+        when {+            state.puzzle == null || state.status != PuzzleStatus.Solving ||+                state.board.promotionPosition != null ->+                store.removeKeys(listOf(IN_PROGRESS_KEY))+            else -> store.setString(IN_PROGRESS_KEY, PuzzleProgressCodec.encode(state))+        }+    }++    /** Entry for the Puzzles route: restores a mid-solve puzzle, or loads a fresh one. */+    fun ensurePuzzle() {+        if (_uiState.value.puzzle != null) return+        if (restoreAttempted) {+            loadRandom(_uiState.value.difficulty)+            return+        }+        restoreAttempted = true+        viewModelScope.launch {+            val saved = store.getStringAwait(IN_PROGRESS_KEY)+                ?.let { PuzzleProgressCodec.decode(it) }+            if (_uiState.value.puzzle != null) return@launch+            if (saved == null) {+                loadRandom(_uiState.value.difficulty)+            } else {+                _uiState.value = PuzzleUiState(+                    puzzle = saved.puzzle,+                    board = saved.board,+                    isBoardFlipped = saved.playerColor == PieceColor.BLACK,+                    playerColor = saved.playerColor,+                    rating = saved.puzzle.rating,+                    solutionIndex = saved.solutionIndex,+                    status = PuzzleStatus.Solving,+                    difficulty = saved.difficulty,+                )+            }+        }     }      // The board before the pawn stepped onto the last rank, while its promotion is pending.
games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessProgressCodecTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessProgressCodecTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessProgressCodecTest.ktnew file mode 100644index 0000000000..c1113f5c30--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessProgressCodecTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.games.chess.util++import com.vayunmathur.games.chess.data.Board+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.Puzzle+import com.vayunmathur.games.chess.data.PuzzleMove+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.data.toFen+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++class ChessProgressCodecTest {++    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')++    private fun midGameState(): ChessUiState {+        var board = Board.initialState+        board = board.movePiece(sq('e', 2), sq('e', 4))+        board = board.movePiece(sq('e', 7), sq('e', 5))+        board = board.movePiece(sq('g', 1), sq('f', 3))+        return ChessUiState(+            board = board,+            gameMode = GameMode.VsAI(PieceColor.WHITE, Difficulty.INTERMEDIATE),+            turn = PieceColor.BLACK,+            isBoardFlipped = false,+        )+    }++    @Test+    fun midGameLocalRoundTripsThroughFenAndMoveList() {+        val state = midGameState()+        val decoded = assertNotNull(ChessProgressCodec.decode(ChessProgressCodec.encode(state)))+        assertEquals(state.board, decoded.board)+        assertEquals(state.board.moves.map { it.toString() }, decoded.board.moves.map { it.toString() })+        assertEquals(state.gameMode, decoded.gameMode)+        assertEquals(PieceColor.BLACK, decoded.turn)+    }++    @Test+    fun twoPlayerMidGameRoundTrips() {+        val state = midGameState().copy(gameMode = GameMode.TwoPlayer)+        val decoded = assertNotNull(ChessProgressCodec.decode(ChessProgressCodec.encode(state)))+        assertEquals(GameMode.TwoPlayer, decoded.gameMode)+        assertEquals(state.board, decoded.board)+    }++    @Test+    fun corruptAndMismatchedFenAreDropped() {+        val encoded = ChessProgressCodec.encode(midGameState())+        assertNull(ChessProgressCodec.decode("not json"))+        assertNull(ChessProgressCodec.decode("""{"v":2}"""))+        // Same moves, wrong claimed end position: the FEN check rejects it.+        assertNull(ChessProgressCodec.decode(encoded.replace(" b ", " w ")))+        assertNull(+            ChessProgressCodec.decode(+                encoded.replace("e2e4", "e2e5"),+            ),+        )+    }++    @Test+    fun midPuzzleRoundTripsThroughFenAndSolution() {+        // Fool's-mate position as a puzzle: setup f2f3, then the solver line.+        val solution = listOf(+            PuzzleMove(sq('f', 2), sq('f', 3), null),+            PuzzleMove(sq('e', 7), sq('e', 5), null),+            PuzzleMove(sq('g', 2), sq('g', 4), null),+            PuzzleMove(sq('d', 8), sq('h', 4), null),+        )+        val puzzle = Puzzle(rating = 900, board = Board.initialState, solution = solution)+        var board = puzzle.board+        board = board.movePiece(solution[0].from, solution[0].to, solution[0].promotion)+        board = board.movePiece(solution[1].from, solution[1].to, solution[1].promotion)+        val state = PuzzleUiState(+            puzzle = puzzle,+            board = board,+            playerColor = PieceColor.BLACK,+            isBoardFlipped = true,+            rating = 900,+            solutionIndex = 2,+            status = PuzzleStatus.Solving,+            difficulty = PuzzleDifficulty.EASY,+        )+        val decoded = assertNotNull(PuzzleProgressCodec.decode(PuzzleProgressCodec.encode(state)))+        // Board equality includes the puzzle loader's synthetic seed move, so compare the position.+        // FEN round-trip also normalises hasMoved on non-castling pieces (only kings/rooks+        // retain it, and only they read it), so compare type+color per square, not Piece equality.+        assertEquals(+            board.pieces.map { row -> row.map { it?.let { p -> p.type to p.color } } },+            decoded.board.pieces.map { row -> row.map { it?.let { p -> p.type to p.color } } },+        )+        assertEquals(board.toFen(), decoded.board.toFen())+        assertEquals(2, decoded.solutionIndex)+        assertEquals(PieceColor.BLACK, decoded.playerColor)+        assertEquals(solution, decoded.puzzle.solution)+        assertEquals(900, decoded.puzzle.rating)+        assertNull(PuzzleProgressCodec.decode("not json"))+    }+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/InProgressField.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/InProgressField.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/InProgressField.ktnew file mode 100644index 0000000000..8e9e14f6d6--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/data/InProgressField.kt@@ -0,0 +1,122 @@+package com.vayunmathur.games.minesweeper.data++import android.content.Context+import androidx.core.content.edit+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.int+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.put++/** A field left in progress: board, clock and tap mode, saved per [GameConfig.variant]. */+data class SavedMinesweeperGame(+    val game: MinesweeperGameState,+    val elapsedSeconds: Int,+    val tapMode: TapMode,+    val placedAnyFlag: Boolean,+)++/**+ * Compact JSON for [SavedMinesweeperGame], following the pipes/unblockjam codec approach:+ * per-cell lists as 0/1 strings, a version tag, and strict validation on decode. A save+ * that does not fit [config] (dimensions, mine count, lengths, mine total) is dropped.+ */+object MinesweeperProgressCodec {+    private const val VERSION = 1++    fun encode(saved: SavedMinesweeperGame): String {+        val game = saved.game+        return buildJsonObject {+            put("v", VERSION)+            put("cols", game.cols)+            put("rows", game.rows)+            put("mineCount", game.mineCount)+            put("started", game.started)+            put("explodedAt", game.explodedAt)+            put("elapsed", saved.elapsedSeconds)+            put("tapMode", saved.tapMode.name)+            put("placedFlag", saved.placedAnyFlag)+            put("mines", bits(game.mines))+            put("revealed", bits(game.revealed))+            put("flagged", bits(game.flagged))+        }.toString()+    }++    fun decode(json: String, config: GameConfig): SavedMinesweeperGame? = runCatching {+        val root = Json.parseToJsonElement(json).jsonObject+        if (root["v"]?.jsonPrimitive?.int != VERSION) return null+        val cols = root.getValue("cols").jsonPrimitive.int+        val rows = root.getValue("rows").jsonPrimitive.int+        if (cols != config.size.cols || rows != config.size.rows) return null+        val mineCount = root.getValue("mineCount").jsonPrimitive.int+        if (mineCount != config.difficulty.mineCount(config.size)) return null+        val cells = cols * rows+        val mines = bits(root.getValue("mines").jsonPrimitive.content, cells) ?: return null+        val revealed = bits(root.getValue("revealed").jsonPrimitive.content, cells) ?: return null+        val flagged = bits(root.getValue("flagged").jsonPrimitive.content, cells) ?: return null+        val started = root.getValue("started").jsonPrimitive.content.toBooleanStrict()+        if (started && mines.count { it } != mineCount) return null+        if (!started && (mines.any { it } || revealed.any { it } || flagged.any { it })) return null+        if (revealed.indices.any { revealed[it] && flagged[it] }) return null+        val elapsed = root.getValue("elapsed").jsonPrimitive.int+        if (elapsed < 0) return null+        val game = MinesweeperGameState(+            cols = cols,+            rows = rows,+            mineCount = mineCount,+            mines = mines,+            neighbourCounts = neighbourCounts(mines, cols, rows),+            revealed = revealed,+            flagged = flagged,+            outcome = GameOutcome.PLAYING,+            explodedAt = root.getValue("explodedAt").jsonPrimitive.int,+            started = started,+        )+        if (game.explodedAt != -1 || game.isOver) return null+        SavedMinesweeperGame(+            game = game,+            elapsedSeconds = elapsed,+            tapMode = TapMode.valueOf(root.getValue("tapMode").jsonPrimitive.content),+            placedAnyFlag = root.getValue("placedFlag").jsonPrimitive.content.toBooleanStrict(),+        )+    }.getOrNull()++    private fun bits(values: List<Boolean>): String =+        values.joinToString("") { if (it) "1" else "0" }++    private fun bits(raw: String, cells: Int): List<Boolean>? {+        if (raw.length != cells || raw.any { it != '0' && it != '1' }) return null+        return raw.map { it == '1' }+    }++    private fun neighbourCounts(mines: List<Boolean>, cols: Int, rows: Int): List<Int> =+        List(cols * rows) { index ->+            // Mirrors FieldGenerator: a mine cell's own count is 0, never read.+            if (mines[index]) 0 else neighbourIndices(cols, rows, index).count { mines[it] }+        }+}++/**+ * Unfinished fields, one encoded string per variant, so process death never loses a+ * game in progress. Own prefs file, following unblockjam's InProgressBoards.+ */+class InProgressField(context: Context) {+    private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)++    fun load(config: GameConfig): SavedMinesweeperGame? =+        prefs.getString(config.variant, null)+            ?.let { MinesweeperProgressCodec.decode(it, config) }++    fun save(config: GameConfig, saved: SavedMinesweeperGame) {+        prefs.edit { putString(config.variant, MinesweeperProgressCodec.encode(saved)) }+    }++    fun clear(variant: String) {+        prefs.edit { remove(variant) }+    }++    private companion object {+        const val PREFS_NAME = "minesweeper_in_progress"+    }+}
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.ktindex 417c26d45c..2aac1164a2 100644--- 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.kt@@ -2,29 +2,34 @@ package com.vayunmathur.games.minesweeper.platform  import android.app.Application import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope 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.InProgressField import com.vayunmathur.games.minesweeper.data.MinesweeperGameState import com.vayunmathur.games.minesweeper.data.MinesweeperStatsRepository+import com.vayunmathur.games.minesweeper.data.SavedMinesweeperGame import com.vayunmathur.games.minesweeper.data.TapMode import com.vayunmathur.games.minesweeper.domain.FieldGenerator import com.vayunmathur.games.minesweeper.domain.MinesweeperRules import com.vayunmathur.library.util.AchievementsManager+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch import 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.+ * The field survives rotation in memory, and is also persisted (debounced, and on+ * pause via [saveInProgress]) to [InProgressField] keyed by variant, so process+ * death restores it on entry through [ensureGame] when the route config matches.  *  * 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.@@ -36,6 +41,8 @@ class MinesweeperViewModel(application: Application) :     val uiState: StateFlow<MinesweeperUiState> = _uiState.asStateFlow()      private val statsRepository = MinesweeperStatsRepository(application)+    private val inProgress = InProgressField(application)+    private var saveJob: Job? = null      private val _elapsedSeconds = MutableStateFlow(0) @@ -62,6 +69,55 @@ class MinesweeperViewModel(application: Application) :      init {         achievementsManager.checkExistingAchievements()+        viewModelScope.launch { _uiState.collect { scheduleSaveInProgress() } }+    }++    private fun scheduleSaveInProgress() {+        saveJob?.cancel()+        saveJob = viewModelScope.launch {+            delay(SAVE_DEBOUNCE_MS)+            writeInProgress()+        }+    }++    /** Flushes the in-progress field now (on pause); a finished field clears its slot. */+    fun saveInProgress() {+        saveJob?.cancel()+        writeInProgress()+    }++    private fun writeInProgress() {+        val state = _uiState.value+        val game = state.game ?: return+        if (game.isOver) {+            inProgress.clear(state.config.variant)+        } else {+            inProgress.save(+                state.config,+                SavedMinesweeperGame(game, _elapsedSeconds.value, state.tapMode, placedAnyFlag),+            )+        }+    }++    /**+     * Entry for the Game route: keeps a matching in-memory field, restores the saved+     * field for [config], or deals a new one.+     */+    fun ensureGame(config: GameConfig) {+        val current = _uiState.value+        if (current.game != null && current.config == config) return+        val saved = inProgress.load(config)+        if (saved == null) {+            newGame(config)+        } else {+            placedAnyFlag = saved.placedAnyFlag+            _elapsedSeconds.value = saved.elapsedSeconds+            _uiState.value = MinesweeperUiState(+                config = config,+                game = saved.game,+                tapMode = saved.tapMode,+            )+        }     }      fun hasActiveGame(): Boolean = _uiState.value.game?.isOver == false@@ -188,6 +244,7 @@ class MinesweeperViewModel(application: Application) :         }         _elapsedSeconds.value = 0         _uiState.value = MinesweeperUiState(config = state.config, tapMode = state.tapMode)+        inProgress.clear(state.config.variant)     }      fun incrementTimer() {@@ -240,5 +297,6 @@ class MinesweeperViewModel(application: Application) :     private companion object {         /** Matches the "under a minute" wording of the `speed_win` description. */         const val FAST_WIN_SECONDS = 60+        const val SAVE_DEBOUNCE_MS = 300L     } }
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.ktindex 6cd04155f3..3936a480a7 100644--- 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.kt@@ -7,6 +7,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffect import com.vayunmathur.games.minesweeper.Route import com.vayunmathur.games.minesweeper.data.GameConfig import com.vayunmathur.games.minesweeper.platform.MinesweeperViewModel@@ -31,9 +33,8 @@ fun GameScreen(     // clock text instead of this whole screen and the field under it.     val elapsedSeconds = viewModel.elapsedSeconds.collectAsState() -    LaunchedEffect(config) {-        if (uiState.game == null) viewModel.newGame(config)-    }+    LaunchedEffect(config) { viewModel.ensureGame(config) }+    LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { viewModel.saveInProgress() }      // The clock starts on the first reveal, not on entering the screen, and stops while a     // confirmation dialog or the result overlay (isOver) covers the field and whenever the screen
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperProgressCodecTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperProgressCodecTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperProgressCodecTest.ktnew file mode 100644index 0000000000..18ca261ae7--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperProgressCodecTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.games.minesweeper.data++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MinesweeperProgressCodecTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val config = GameConfig(BoardSize.SMALL, Difficulty.EASY)++    private fun midGame(): SavedMinesweeperGame {+        val base = MinesweeperGameState.empty(config)+        val cells = base.cellCount+        // Ten mines placed clear of the revealed corner, matching EASY on SMALL (8 mines -> use count below).+        val mines = List(cells) { it in setOf(20, 21, 30, 40, 50, 60, 70, 79) }+        val counts = List(cells) { index ->+            if (mines[index]) 0 else neighbourIndices(base.cols, base.rows, index).count { mines[it] }+        }+        val game = base.copy(+            mines = mines,+            neighbourCounts = counts,+            revealed = List(cells) { it == 0 || it == 1 },+            flagged = List(cells) { it == 20 },+            started = true,+        )+        return SavedMinesweeperGame(game, elapsedSeconds = 42, tapMode = TapMode.FLAG, placedAnyFlag = true)+    }++    @Test+    fun midGameRoundTripsThroughCodec() {+        val saved = midGame()+        assertEquals(saved, MinesweeperProgressCodec.decode(MinesweeperProgressCodec.encode(saved), config))+    }++    @Test+    fun mismatchedConfigAndCorruptJsonAreDropped() {+        val encoded = MinesweeperProgressCodec.encode(midGame())+        assertNull(MinesweeperProgressCodec.decode(encoded, GameConfig(BoardSize.MEDIUM, Difficulty.EASY)))+        assertNull(MinesweeperProgressCodec.decode(encoded, GameConfig(BoardSize.SMALL, Difficulty.HARD)))+        assertNull(MinesweeperProgressCodec.decode("not json", config))+        assertNull(MinesweeperProgressCodec.decode("""{"v":2}""", config))+    }++    @Test+    fun midGameRoundTripsThroughStore() {+        val store = InProgressField(app)+        store.clear(config.variant)+        val saved = midGame()+        store.save(config, saved)+        assertEquals(saved, assertNotNull(InProgressField(app).load(config)))+        assertNull(store.load(GameConfig(BoardSize.SMALL, Difficulty.HARD)))+        store.clear(config.variant)+        assertNull(store.load(config))+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.ktnew file mode 100644index 0000000000..432be58007--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.kt@@ -0,0 +1,300 @@+package com.vayunmathur.games.solitaire.data++import android.content.Context+import androidx.core.content.edit+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.add+import kotlinx.serialization.json.buildJsonArray+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.int+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.put++/**+ * Full-encode codec for [SolitaireUiState], following the pipes/unblockjam approach.+ *+ * The smaller alternative — seed plus replay — is not correct here: no move list is+ * kept, only undo snapshots, and drag/auto-complete moves cannot be re-derived from+ * the seed alone. So the current board and its undo history are encoded in full:+ * each card is one int (`suit * 13 + rank - 1`), piles are int arrays.+ */+object SolitaireProgressCodec {+    private const val VERSION = 1+    private const val NO_CARD = -1+    private const val DECK_CARDS = 52+    private const val SPIDER_CARDS = 104++    fun encode(state: SolitaireUiState): String = buildJsonObject {+        put("v", VERSION)+        put("mode", state.gameMode?.name)+        state.klondike?.let { put("klondike", encodeKlondike(it)) }+        state.spider?.let { put("spider", encodeSpider(it)) }+        state.freeCell?.let { put("freeCell", encodeFreeCell(it)) }+        state.pyramid?.let { put("pyramid", encodePyramid(it)) }+        put("h", JsonArray(state.history.map { encodeAny(it) }))+    }.toString()++    fun decode(json: String, mode: GameMode): SolitaireUiState? = runCatching {+        val root = Json.parseToJsonElement(json).jsonObject+        if (root["v"]?.jsonPrimitive?.int != VERSION) return null+        if (root["mode"]?.jsonPrimitive?.content != mode.name) return null+        val history = root.getValue("h").jsonArray.map { decodeAny(it.jsonObject, mode) ?: return null }+        val state = when (mode) {+            GameMode.KLONDIKE -> SolitaireUiState(+                gameMode = mode,+                klondike = decodeKlondike(root.getValue("klondike").jsonObject) ?: return null,+                history = history,+            )+            GameMode.SPIDER -> SolitaireUiState(+                gameMode = mode,+                spider = decodeSpider(root.getValue("spider").jsonObject) ?: return null,+                history = history,+            )+            GameMode.FREECELL -> SolitaireUiState(+                gameMode = mode,+                freeCell = decodeFreeCell(root.getValue("freeCell").jsonObject) ?: return null,+                history = history,+            )+            GameMode.PYRAMID -> SolitaireUiState(+                gameMode = mode,+                pyramid = decodePyramid(root.getValue("pyramid").jsonObject) ?: return null,+                history = history,+            )+        }+        if (isWon(state)) return null+        state+    }.getOrNull()++    fun isWon(state: SolitaireUiState): Boolean = when (state.gameMode) {+        GameMode.KLONDIKE -> state.klondike?.isWon == true+        GameMode.SPIDER -> state.spider?.isWon == true+        GameMode.FREECELL -> state.freeCell?.isWon == true+        GameMode.PYRAMID -> state.pyramid?.isWon == true+        null -> false+    }++    // -- cards --++    private fun code(card: Card): Int = card.suit.ordinal * Rank.entries.size + (card.rank.value - 1)++    private fun card(code: Int): Card? {+        if (code !in 0 until DECK_CARDS) return null+        return Card(Suit.entries[code / Rank.entries.size], Rank.entries[code % Rank.entries.size])+    }++    private fun cards(list: List<Card>): JsonArray = buildJsonArray { for (c in list) add(code(c)) }++    private fun cards(obj: JsonObject, key: String): List<Card>? {+        val raw = obj.getValue(key).jsonArray.map { it.jsonPrimitive.int }+        return raw.map { card(it) ?: return null }+    }++    private fun piles(list: List<List<Card>>): JsonArray =+        JsonArray(list.map { cards(it) })++    private fun piles(obj: JsonObject, key: String, count: Int): List<List<Card>>? {+        val raw = obj.getValue(key).jsonArray+        if (raw.size != count) return null+        return raw.map { element ->+            element.jsonArray.map { card(it.jsonPrimitive.int) ?: return null }+        }+    }++    private fun tableau(list: List<TableauPile>): JsonArray = JsonArray(list.map { pile ->+        buildJsonObject { put("d", cards(pile.faceDown)); put("u", cards(pile.faceUp)) }+    })++    private fun tableau(obj: JsonObject, key: String, count: Int): List<TableauPile>? {+        val raw = obj.getValue(key).jsonArray+        if (raw.size != count) return null+        return raw.map { element ->+            val pile = element.jsonObject+            TableauPile(cards(pile, "d") ?: return null, cards(pile, "u") ?: return null)+        }+    }++    private fun totalKlondike(s: KlondikeState): Int =+        s.stock.size + s.waste.size + s.foundations.sumOf { it.size } ++            s.tableauPiles.sumOf { it.faceDown.size + it.faceUp.size }++    private fun totalSpider(s: SpiderState): Int =+        s.tableauPiles.sumOf { it.faceDown.size + it.faceUp.size } ++            s.stockGroups.sumOf { it.size } + s.completedSuits * FULL_SUIT_SIZE++    private fun totalFreeCell(s: FreeCellState): Int =+        s.tableauPiles.sumOf { it.size } + s.freeCells.count { it != null } ++            s.foundations.sumOf { it.size }++    // -- per-mode states --++    private fun encodeAny(state: Any): JsonObject = when (state) {+        is KlondikeState -> encodeKlondike(state)+        is SpiderState -> encodeSpider(state)+        is FreeCellState -> encodeFreeCell(state)+        is PyramidState -> encodePyramid(state)+        else -> buildJsonObject { put("t", "unknown") }+    }++    private fun decodeAny(obj: JsonObject, mode: GameMode): Any? = when (mode) {+        GameMode.KLONDIKE -> decodeKlondike(obj)+        GameMode.SPIDER -> decodeSpider(obj)+        GameMode.FREECELL -> decodeFreeCell(obj)+        GameMode.PYRAMID -> decodePyramid(obj)+    }++    private fun encodeKlondike(s: KlondikeState): JsonObject = buildJsonObject {+        put("t", "k")+        put("seed", s.seed); put("variant", s.variant)+        put("drawMode", s.drawMode.name); put("difficulty", s.difficulty.name)+        put("redeals", s.redealsRemaining); put("moves", s.moveCount)+        put("elapsed", s.elapsedSeconds); put("usedUndo", s.usedUndo); put("won", s.isWon)+        put("stock", cards(s.stock)); put("waste", cards(s.waste))+        put("foundations", piles(s.foundations)); put("tableau", tableau(s.tableauPiles))+    }++    private fun decodeKlondike(obj: JsonObject): KlondikeState? {+        if (obj["t"]?.jsonPrimitive?.content != "k") return null+        val state = KlondikeState(+            stock = cards(obj, "stock") ?: return null,+            waste = cards(obj, "waste") ?: return null,+            tableauPiles = tableau(obj, "tableau", KLONDIKE_TABLEAU_COUNT) ?: return null,+            foundations = piles(obj, "foundations", FOUNDATION_COUNT) ?: return null,+            drawMode = DrawMode.valueOf(obj.getValue("drawMode").jsonPrimitive.content),+            difficulty = KlondikeDifficulty.valueOf(obj.getValue("difficulty").jsonPrimitive.content),+            redealsRemaining = obj.getValue("redeals").jsonPrimitive.int,+            variant = obj.getValue("variant").jsonPrimitive.content,+            seed = obj.getValue("seed").jsonPrimitive.content.toLong(),+            moveCount = obj.getValue("moves").jsonPrimitive.int,+            elapsedSeconds = obj.getValue("elapsed").jsonPrimitive.int,+            usedUndo = obj.getValue("usedUndo").jsonPrimitive.content.toBooleanStrict(),+            isWon = obj.getValue("won").jsonPrimitive.content.toBooleanStrict(),+        )+        return state.takeIf { totalKlondike(it) == DECK_CARDS && it.moveCount >= 0 && it.elapsedSeconds >= 0 }+    }++    private fun encodeSpider(s: SpiderState): JsonObject = buildJsonObject {+        put("t", "s")+        put("seed", s.seed); put("variant", s.variant); put("suits", s.suitCount)+        put("completed", s.completedSuits); put("moves", s.moveCount)+        put("elapsed", s.elapsedSeconds); put("usedUndo", s.usedUndo); put("won", s.isWon)+        put("stockGroups", piles(s.stockGroups)); put("tableau", tableau(s.tableauPiles))+    }++    private fun decodeSpider(obj: JsonObject): SpiderState? {+        if (obj["t"]?.jsonPrimitive?.content != "s") return null+        val stockGroupsRaw = obj.getValue("stockGroups").jsonArray+        val stockGroups = stockGroupsRaw.map { element ->+            element.jsonArray.map { card(it.jsonPrimitive.int) ?: return null }+        }+        val state = SpiderState(+            tableauPiles = tableau(obj, "tableau", SPIDER_TABLEAU_COUNT) ?: return null,+            stockGroups = stockGroups,+            suitCount = obj.getValue("suits").jsonPrimitive.int,+            variant = obj.getValue("variant").jsonPrimitive.content,+            completedSuits = obj.getValue("completed").jsonPrimitive.int,+            seed = obj.getValue("seed").jsonPrimitive.content.toLong(),+            moveCount = obj.getValue("moves").jsonPrimitive.int,+            elapsedSeconds = obj.getValue("elapsed").jsonPrimitive.int,+            usedUndo = obj.getValue("usedUndo").jsonPrimitive.content.toBooleanStrict(),+            isWon = obj.getValue("won").jsonPrimitive.content.toBooleanStrict(),+        )+        return state.takeIf {+            it.suitCount in setOf(1, 2, 4) && totalSpider(it) == SPIDER_CARDS &&+                it.moveCount >= 0 && it.elapsedSeconds >= 0+        }+    }++    private fun encodeFreeCell(s: FreeCellState): JsonObject = buildJsonObject {+        put("t", "f")+        put("seed", s.seed); put("variant", s.variant)+        put("moves", s.moveCount); put("elapsed", s.elapsedSeconds)+        put("usedUndo", s.usedUndo); put("won", s.isWon)+        put("tableau", piles(s.tableauPiles)); put("foundations", piles(s.foundations))+        put("free", buildJsonArray { for (c in s.freeCells) add(c?.let { code(it) } ?: NO_CARD) })+    }++    private fun decodeFreeCell(obj: JsonObject): FreeCellState? {+        if (obj["t"]?.jsonPrimitive?.content != "f") return null+        val freeRaw = obj.getValue("free").jsonArray.map { it.jsonPrimitive.int }+        if (freeRaw.size != FREECELL_COUNT) return null+        val free = freeRaw.map { if (it == NO_CARD) null else card(it) ?: return null }+        val state = FreeCellState(+            tableauPiles = piles(obj, "tableau", FREECELL_TABLEAU_COUNT) ?: return null,+            freeCells = free,+            foundations = piles(obj, "foundations", FOUNDATION_COUNT) ?: return null,+            variant = obj.getValue("variant").jsonPrimitive.content,+            seed = obj.getValue("seed").jsonPrimitive.content.toLong(),+            moveCount = obj.getValue("moves").jsonPrimitive.int,+            elapsedSeconds = obj.getValue("elapsed").jsonPrimitive.int,+            usedUndo = obj.getValue("usedUndo").jsonPrimitive.content.toBooleanStrict(),+            isWon = obj.getValue("won").jsonPrimitive.content.toBooleanStrict(),+        )+        return state.takeIf { totalFreeCell(it) == DECK_CARDS && it.moveCount >= 0 && it.elapsedSeconds >= 0 }+    }++    private fun encodePyramid(s: PyramidState): JsonObject = buildJsonObject {+        put("t", "p")+        put("seed", s.seed); put("variant", s.variant); put("relaxed", s.relaxed)+        put("selected", s.selectedId); put("moves", s.moveCount)+        put("elapsed", s.elapsedSeconds); put("usedUndo", s.usedUndo); put("won", s.isWon)+        put("stock", cards(s.stock)); put("waste", cards(s.waste))+        put("pyramid", JsonArray(s.pyramid.map { row ->+            buildJsonArray { for (c in row) add(c?.let { code(it) } ?: NO_CARD) }+        }))+    }++    private fun decodePyramid(obj: JsonObject): PyramidState? {+        if (obj["t"]?.jsonPrimitive?.content != "p") return null+        val rowsRaw = obj.getValue("pyramid").jsonArray+        if (rowsRaw.size != PYRAMID_ROWS) return null+        val rows = rowsRaw.mapIndexed { r, element ->+            val row = element.jsonArray.map { it.jsonPrimitive.int }+            if (row.size != r + 1) return null+            row.map { if (it == NO_CARD) null else card(it) ?: return null }+        }+        val state = PyramidState(+            pyramid = rows,+            stock = cards(obj, "stock") ?: return null,+            waste = cards(obj, "waste") ?: return null,+            relaxed = obj.getValue("relaxed").jsonPrimitive.content.toBooleanStrict(),+            variant = obj.getValue("variant").jsonPrimitive.content,+            selectedId = obj["selected"]?.jsonPrimitive?.content?.takeIf { it != "null" },+            seed = obj.getValue("seed").jsonPrimitive.content.toLong(),+            moveCount = obj.getValue("moves").jsonPrimitive.int,+            elapsedSeconds = obj.getValue("elapsed").jsonPrimitive.int,+            usedUndo = obj.getValue("usedUndo").jsonPrimitive.content.toBooleanStrict(),+            isWon = obj.getValue("won").jsonPrimitive.content.toBooleanStrict(),+        )+        val total = state.pyramid.sumOf { row -> row.count { it != null } } ++            state.stock.size + state.waste.size+        return state.takeIf { total in 1..DECK_CARDS && it.moveCount >= 0 && it.elapsedSeconds >= 0 }+    }+}++/**+ * Unfinished games, one encoded [SolitaireUiState] per mode, so process death never+ * loses a game in progress. Own prefs file, following unblockjam's InProgressBoards.+ */+class InProgressGame(context: Context) {+    private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)++    fun load(mode: GameMode): SolitaireUiState? =+        prefs.getString(mode.name, null)?.let { SolitaireProgressCodec.decode(it, mode) }++    fun save(state: SolitaireUiState) {+        val mode = state.gameMode ?: return+        prefs.edit { putString(mode.name, SolitaireProgressCodec.encode(state)) }+    }++    fun clear(mode: GameMode) {+        prefs.edit { remove(mode.name) }+    }++    private companion object {+        const val PREFS_NAME = "solitaire_in_progress"+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.ktindex 3b8f1dfe27..25e4bc3d6f 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt@@ -5,23 +5,29 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.unit.IntSize import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.data.CardColorScheme import com.vayunmathur.games.solitaire.data.FreeCellState import com.vayunmathur.games.solitaire.data.GameConfig import com.vayunmathur.games.solitaire.data.GameMode import com.vayunmathur.games.solitaire.data.GameStats+import com.vayunmathur.games.solitaire.data.InProgressGame import com.vayunmathur.games.solitaire.data.KlondikeState import com.vayunmathur.games.solitaire.data.PyramidState import com.vayunmathur.games.solitaire.data.SolitaireUiState import com.vayunmathur.games.solitaire.data.SolitaireStatsRepository import com.vayunmathur.games.solitaire.data.SolitaireSettingsRepository+import com.vayunmathur.games.solitaire.data.SolitaireProgressCodec import com.vayunmathur.games.solitaire.data.SpiderState import com.vayunmathur.library.util.AchievementsManager+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch  /**  * The stack under the finger. [offset] is the leading card's current top-left and [startPos]@@ -99,6 +105,46 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio      init {         achievementsManager.checkExistingAchievements()+        viewModelScope.launch { uiState.collect { scheduleSaveInProgress() } }+    }++    internal val inProgress = InProgressGame(application)+    private var saveJob: Job? = null++    private fun scheduleSaveInProgress() {+        saveJob?.cancel()+        saveJob = viewModelScope.launch {+            delay(SAVE_DEBOUNCE_MS)+            writeInProgress()+        }+    }++    /** Flushes the in-progress game now (on pause); a won game clears its slot. */+    fun saveInProgress() {+        saveJob?.cancel()+        writeInProgress()+    }++    private fun writeInProgress() {+        val state = uiStateInternal.value+        val mode = state.gameMode ?: return+        if (SolitaireProgressCodec.isWon(state)) inProgress.clear(mode) else inProgress.save(state)+    }++    /**+     * Entry for the Game route: keeps a matching in-memory game, restores the saved+     * game for [mode], or deals a new one.+     */+    fun ensureMode(mode: GameMode) {+        if (uiStateInternal.value.gameMode == mode) return+        val saved = inProgress.load(mode)+        if (saved == null) {+            selectMode(mode)+        } else {+            clearMotion()+            cardPositions.clear()+            uiStateInternal.value = saved+        }     }      fun getStats(mode: GameMode): GameStats = statsRepository.getModeStats(mode)@@ -114,6 +160,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     }      fun selectMode(mode: GameMode, config: GameConfig = GameConfig()) {+        inProgress.clear(mode)         clearMotion()         cardPositions.clear()         when (mode) {@@ -141,6 +188,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio         val mode = uiStateInternal.value.gameMode ?: return         statsRepository.recordGameLost(mode, currentVariant())         uiStateInternal.value = SolitaireUiState()+        inProgress.clear(mode)     }      // --- Klondike ---@@ -297,6 +345,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     companion object {         /** Klondike win under three minutes earns the speed achievement. */         private const val SPEED_DEMON_SECONDS = 180+        private const val SAVE_DEBOUNCE_MS = 300L     } } 
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.ktindex 22c1e1e007..c58bdba451 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.kt@@ -4,6 +4,8 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffect import com.vayunmathur.games.solitaire.Route import com.vayunmathur.games.solitaire.data.GameMode import com.vayunmathur.games.solitaire.platform.SolitaireViewModel@@ -13,7 +15,8 @@ import kotlinx.coroutines.delay @Composable fun GameScreen(backStack: NavBackStack<Route>, viewModel: SolitaireViewModel, mode: GameMode) {     val uiState by viewModel.uiState.collectAsState()-    LaunchedEffect(mode) { if (uiState.gameMode != mode) viewModel.selectMode(mode) }+    LaunchedEffect(mode) { viewModel.ensureMode(mode) }+    LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { viewModel.saveInProgress() }     LaunchedEffect(uiState.gameMode) { while (true) { delay(1000); viewModel.incrementTimer() } }     GameBoardScreen(state = uiState, mode = mode, actions = viewModel, onExit = { backStack.pop() }) }
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.ktnew file mode 100644index 0000000000..be0a425c34--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.kt@@ -0,0 +1,89 @@+package com.vayunmathur.games.solitaire.data++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.domain.SolitaireDeals+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++@RunWith(RobolectricTestRunner::class)+class SolitaireProgressCodecTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun midGameKlondike(): SolitaireUiState {+        val dealt = SolitaireDeals.klondike(12345L, GameConfig())+        // One stock card drawn to the waste: a real mid-game position on the same seed.+        val mid = dealt.copy(+            stock = dealt.stock.drop(1),+            waste = dealt.waste + dealt.stock.first(),+            moveCount = 1,+            elapsedSeconds = 33,+        )+        return SolitaireUiState(+            gameMode = GameMode.KLONDIKE,+            klondike = mid,+            history = listOf(dealt),+        )+    }++    @Test+    fun midGameKlondikeRoundTripsThroughCodec() {+        val state = midGameKlondike()+        val decoded = SolitaireProgressCodec.decode(+            SolitaireProgressCodec.encode(state),+            GameMode.KLONDIKE,+        )+        assertEquals(state, decoded)+        assertEquals(12345L, decoded!!.klondike!!.seed)+        assertEquals(1, decoded.history.size)+    }++    @Test+    fun midGameFreeCellRoundTripsThroughCodec() {+        val dealt = SolitaireDeals.freeCell(777L)+        val mid = dealt.copy(+            tableauPiles = dealt.tableauPiles.mapIndexed { i, pile ->+                if (i == 0) pile.drop(1) else pile+            },+            freeCells = dealt.freeCells.mapIndexed { i, c ->+                if (i == 0) dealt.tableauPiles[0].first() else c+            },+            moveCount = 1,+            elapsedSeconds = 9,+        )+        val state = SolitaireUiState(+            gameMode = GameMode.FREECELL,+            freeCell = mid,+            history = listOf(dealt),+        )+        assertEquals(+            state,+            SolitaireProgressCodec.decode(SolitaireProgressCodec.encode(state), GameMode.FREECELL),+        )+    }++    @Test+    fun wrongModeAndCorruptJsonAreDropped() {+        val encoded = SolitaireProgressCodec.encode(midGameKlondike())+        assertNull(SolitaireProgressCodec.decode(encoded, GameMode.SPIDER))+        assertNull(SolitaireProgressCodec.decode("not json", GameMode.KLONDIKE))+        assertNull(SolitaireProgressCodec.decode("""{"v":2}""", GameMode.KLONDIKE))+    }++    @Test+    fun midGameRoundTripsThroughStore() {+        val store = InProgressGame(app)+        store.clear(GameMode.KLONDIKE)+        val state = midGameKlondike()+        store.save(state)+        assertEquals(state, assertNotNull(InProgressGame(app).load(GameMode.KLONDIKE)))+        assertNull(store.load(GameMode.FREECELL))+        store.clear(GameMode.KLONDIKE)+        assertNull(store.load(GameMode.KLONDIKE))+    }+}
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.ktindex 652a636dfd..9f1256366f 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuDataStore.kt@@ -3,13 +3,122 @@ package com.vayunmathur.games.sudoku.data import android.content.Context import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.add+import kotlinx.serialization.json.buildJsonArray+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.int+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.put  private val Context.dataStore by preferencesDataStore(name = "settings") -/** Remembers the last answer-mode choice from the new-game dialog so it can be pre-filled. */+/** A sudoku game left in progress: board, undo snapshots and clock, saved per variant. */+data class SavedSudokuGame(+    val game: SudokuGameState,+    val history: List<SudokuSnapshot>,+    val elapsedSeconds: Int,+)++/**+ * Compact JSON for [SavedSudokuGame], following the pipes/unblockjam codec approach:+ * flat int arrays for every board list, a version tag, and strict validation on decode.+ * A save that does not fit [GameConfig] (size, difficulty or answer mode changed, a list+ * of the wrong length, a digit out of range) decodes to null and the game starts fresh.+ */+object SudokuProgressCodec {+    private const val VERSION = 1++    fun encode(saved: SavedSudokuGame): String {+        val game = saved.game+        return buildJsonObject {+            put("v", VERSION)+            put("size", game.size.name)+            put("difficulty", game.difficulty.name)+            put("answerMode", game.answerMode)+            put("elapsed", saved.elapsedSeconds)+            put("givens", ints(game.givens))+            put("solution", ints(game.solution))+            put("entries", ints(game.entries))+            put("notes", ints(game.notes))+            put("selected", game.selected)+            put("notesMode", game.notesMode)+            put("moveCount", game.moveCount)+            put("hintsUsed", game.hintsUsed)+            put("usedUndo", game.usedUndo)+            put("lives", game.livesRemaining)+            put("h", JsonArray(saved.history.map { snap ->+                buildJsonObject { put("e", ints(snap.entries)); put("n", ints(snap.notes)) }+            }))+        }.toString()+    }++    fun decode(json: String, config: GameConfig): SavedSudokuGame? = runCatching {+        val root = Json.parseToJsonElement(json).jsonObject+        if (root["v"]?.jsonPrimitive?.int != VERSION) return null+        val size = BoardSize.valueOf(root.getValue("size").jsonPrimitive.content)+        val difficulty = Difficulty.valueOf(root.getValue("difficulty").jsonPrimitive.content)+        if (size != config.size || difficulty != config.difficulty) return null+        val answerMode = root.getValue("answerMode").jsonPrimitive.content.toBooleanStrict()+        if (answerMode != config.answerMode) return null+        val cells = size.cellCount+        val givens = ints(root, "givens", cells) ?: return null+        val solution = ints(root, "solution", cells) ?: return null+        val entries = ints(root, "entries", cells) ?: return null+        val notes = ints(root, "notes", cells) ?: return null+        if (givens.any { it !in 0..size.side } || solution.any { it !in 1..size.side }) return null+        if (entries.any { it !in 0..size.side }) return null+        val maxMask = (1 shl size.side) - 1+        if (notes.any { it !in 0..maxMask }) return null+        val selected = root.getValue("selected").jsonPrimitive.int+        if (selected !in -1 until cells) return null+        val history = root.getValue("h").jsonArray.map { element ->+            val obj = element.jsonObject+            val e = obj.getValue("e").jsonArray.map { it.jsonPrimitive.int }+            val n = obj.getValue("n").jsonArray.map { it.jsonPrimitive.int }+            if (e.size != cells || n.size != cells) return null+            if (e.any { it !in 0..size.side } || n.any { it !in 0..maxMask }) return null+            SudokuSnapshot(e, n)+        }+        val elapsed = root.getValue("elapsed").jsonPrimitive.int+        if (elapsed < 0) return null+        val game = SudokuGameState(+            size = size,+            difficulty = difficulty,+            givens = givens,+            solution = solution,+            entries = entries,+            notes = notes,+            selected = selected,+            notesMode = root.getValue("notesMode").jsonPrimitive.content.toBooleanStrict(),+            moveCount = root.getValue("moveCount").jsonPrimitive.int,+            hintsUsed = root.getValue("hintsUsed").jsonPrimitive.int,+            isWon = false,+            usedUndo = root.getValue("usedUndo").jsonPrimitive.content.toBooleanStrict(),+            answerMode = answerMode,+            livesRemaining = root.getValue("lives").jsonPrimitive.int,+        )+        if (game.isWon || game.isGameOver || game.livesRemaining !in 0..ANSWER_MODE_LIVES) return null+        SavedSudokuGame(game, history, elapsed)+    }.getOrNull()++    private fun ints(values: List<Int>): JsonArray = buildJsonArray { for (v in values) add(v) }++    private fun ints(root: kotlinx.serialization.json.JsonObject, key: String, size: Int): List<Int>? {+        val list = root.getValue(key).jsonArray.map { it.jsonPrimitive.int }+        return list.takeIf { it.size == size }+    }+}++/** Remembers preferences and the in-progress game (one per [GameConfig.variant]). */ class SudokuDataStore(private val context: Context) {      /** Off until the player opts in. */@@ -27,8 +136,25 @@ class SudokuDataStore(private val context: Context) {         context.dataStore.edit { it[HIGHLIGHT_MISTAKES_KEY] = enabled }     } +    /** The saved game for [config]'s variant, or null if none fits [config]. */+    suspend fun loadInProgress(config: GameConfig): SavedSudokuGame? {+        val raw = context.dataStore.data.first()[inProgressKey(config.variant)] ?: return null+        return SudokuProgressCodec.decode(raw, config)+    }++    suspend fun saveInProgress(saved: SavedSudokuGame) {+        context.dataStore.edit {+            it[inProgressKey(saved.game.variant)] = SudokuProgressCodec.encode(saved)+        }+    }++    suspend fun clearInProgress(variant: String) {+        context.dataStore.edit { it.remove(inProgressKey(variant)) }+    }+     private companion object {         val ANSWER_MODE_KEY = booleanPreferencesKey("answer_mode")         val HIGHLIGHT_MISTAKES_KEY = booleanPreferencesKey("highlight_mistakes")+        fun inProgressKey(variant: String) = stringPreferencesKey("in_progress_$variant")     } }
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.ktindex 713523af16..c3a9c3dbea 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt@@ -7,6 +7,7 @@ import com.vayunmathur.games.sudoku.data.ANSWER_MODE_LIVES import com.vayunmathur.games.sudoku.data.BoardSize import com.vayunmathur.games.sudoku.data.Difficulty import com.vayunmathur.games.sudoku.data.GameConfig+import com.vayunmathur.games.sudoku.data.SavedSudokuGame import com.vayunmathur.games.sudoku.data.SudokuDataStore import com.vayunmathur.games.sudoku.data.SudokuGameState import com.vayunmathur.games.sudoku.data.SudokuSnapshot@@ -22,6 +23,8 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.random.Random@@ -29,10 +32,9 @@ import kotlin.random.Random /**  * Owns the puzzle in progress.  *- * The board is held in memory only. The Activity declares every `configChanges` it can, so this- * survives rotation and theme changes without a saved-state handle; a puzzle is lost on process- * death, which matches the other games in this family and is why the home screen offers "Continue"- * rather than a saved-game list.+ * The board survives rotation in memory, and is also persisted (debounced, and on+ * pause via [saveInProgress]) to [SudokuDataStore] keyed by variant, so process+ * death restores it on entry through [ensureGame] when the route config matches.  */ class SudokuViewModel(application: Application) : AndroidViewModel(application), SudokuActions { @@ -106,8 +108,74 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),      init {         achievementsManager.checkExistingAchievements()+        viewModelScope.launch { _uiState.collect { scheduleSaveInProgress() } }     } +    private var saveJob: Job? = null++    /** Debounced save on every state change; the write reads the latest state at fire time. */+    private fun scheduleSaveInProgress() {+        saveJob?.cancel()+        saveJob = viewModelScope.launch {+            delay(SAVE_DEBOUNCE_MS)+            writeInProgress()+        }+    }++    /** Flushes the in-progress game now (on pause); a finished game clears its slot. */+    fun saveInProgress() {+        saveJob?.cancel()+        viewModelScope.launch { writeInProgress() }+    }++    private suspend fun writeInProgress() {+        val game = _uiState.value.game ?: return+        if (game.isWon || game.isGameOver) {+            settingsStore.clearInProgress(game.variant)+        } else {+            settingsStore.saveInProgress(+                SavedSudokuGame(game, history.toList(), _elapsedSeconds.value),+            )+        }+    }++    /**+     * Entry for the Game route: keeps a matching in-memory game, restores the saved+     * game for [config], or deals a new one. A saved game is restored only when its+     * size, difficulty and answer mode all match [config].+     */+    fun ensureGame(config: GameConfig) {+        if (_uiState.value.generating) return+        val current = _uiState.value.game+        if (current != null && matches(current, config)) return+        viewModelScope.launch {+            val saved = settingsStore.loadInProgress(config)+            val now = _uiState.value.game+            if (now != null && matches(now, config)) return@launch+            if (_uiState.value.generating) return@launch+            if (saved == null) {+                newGame(config)+            } else {+                history.clear()+                history.addAll(saved.history)+                madeMistake = saved.game.entries.indices.any { i ->+                    saved.game.entries[i] != 0 && saved.game.entries[i] != saved.game.solution[i]+                }+                winRecorded = false+                rejectionAttempt = 0+                _elapsedSeconds.value = saved.elapsedSeconds+                _uiState.value = SudokuUiState(+                    game = saved.game,+                    canUndo = saved.history.isNotEmpty(),+                )+            }+        }+    }++    private fun matches(game: SudokuGameState, config: GameConfig): Boolean =+        game.size == config.size && game.difficulty == config.difficulty &&+            game.answerMode == config.answerMode+     fun hasActiveGame(): Boolean = _uiState.value.game?.isWon == false      fun getStats(config: GameConfig) = statsRepository.getStats(config.size, config.difficulty)@@ -355,6 +423,7 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),         history.clear()         _elapsedSeconds.value = 0         _uiState.value = SudokuUiState()+        viewModelScope.launch { settingsStore.clearInProgress(game.variant) }     }      fun incrementTimer() {@@ -443,6 +512,7 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),          * worst — bounded mainly so a long session cannot grow without limit.          */         const val MAX_HISTORY = 200+        const val SAVE_DEBOUNCE_MS = 300L     } } 
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.ktindex f48f62eb7c..af1005b489 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameScreen.kt@@ -7,6 +7,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffect import com.vayunmathur.games.sudoku.Route import com.vayunmathur.games.sudoku.data.GameConfig import com.vayunmathur.games.sudoku.platform.SudokuViewModel@@ -33,9 +35,8 @@ fun GameScreen(     val elapsedSeconds = viewModel.elapsedSeconds.collectAsState()     val highlightMistakes by viewModel.highlightMistakes.collectAsState() -    LaunchedEffect(config) {-        if (uiState.game == null && !uiState.generating) viewModel.newGame(config)-    }+    LaunchedEffect(config) { viewModel.ensureGame(config) }+    LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { viewModel.saveInProgress() }      // A confirmation dialog or the result overlay covers the board, so the clock stops for them     // too: time spent deciding whether to give up is not time spent solving.
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.ktnew file mode 100644index 0000000000..88cec7b79b--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuProgressCodecTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.games.sudoku.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++@RunWith(RobolectricTestRunner::class)+class SudokuProgressCodecTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val config = GameConfig(BoardSize.SIX, Difficulty.EASY, answerMode = false)++    private fun midGame(): SavedSudokuGame {+        val size = BoardSize.SIX+        val givens = List(size.cellCount) { if (it % 3 == 0) (it % size.side) + 1 else 0 }+        val solution = List(size.cellCount) { (it % size.side) + 1 }+        val game = SudokuGameState(+            size = size,+            difficulty = Difficulty.EASY,+            givens = givens,+            solution = solution,+            entries = List(size.cellCount) { if (it == 1) 4 else 0 },+            notes = List(size.cellCount) { if (it == 2) 0b101 else 0 },+            selected = 1,+            notesMode = true,+            moveCount = 3,+            hintsUsed = 1,+            usedUndo = true,+            answerMode = false,+            livesRemaining = 2,+        )+        val history = listOf(+            SudokuSnapshot(List(size.cellCount) { 0 }, List(size.cellCount) { 0 }),+        )+        return SavedSudokuGame(game, history, elapsedSeconds = 87)+    }++    @Test+    fun midGameRoundTripsThroughCodec() {+        val saved = midGame()+        assertEquals(saved, SudokuProgressCodec.decode(SudokuProgressCodec.encode(saved), config))+    }++    @Test+    fun mismatchedConfigAndCorruptJsonAreDropped() {+        val encoded = SudokuProgressCodec.encode(midGame())+        assertNull(SudokuProgressCodec.decode(encoded, GameConfig(BoardSize.NINE, Difficulty.EASY)))+        assertNull(SudokuProgressCodec.decode(encoded, GameConfig(BoardSize.SIX, Difficulty.HARD)))+        assertNull(+            SudokuProgressCodec.decode(+                encoded,+                GameConfig(BoardSize.SIX, Difficulty.EASY, answerMode = true),+            ),+        )+        assertNull(SudokuProgressCodec.decode("not json", config))+        assertNull(SudokuProgressCodec.decode("""{"v":2}""", config))+    }++    @Test+    fun midGameRoundTripsThroughDataStore() = runBlocking {+        val store = SudokuDataStore(context)+        store.clearInProgress(config.variant)+        val saved = midGame()+        store.saveInProgress(saved)+        assertEquals(saved, assertNotNull(SudokuDataStore(context).loadInProgress(config)))+        // A different variant has no saved game.+        assertNull(store.loadInProgress(GameConfig(BoardSize.SIX, Difficulty.HARD)))+        store.clearInProgress(config.variant)+        assertNull(store.loadInProgress(config))+    }+}