Modern Apps git

← Modern-Apps.git

sudoku: stop the clock from recomposing the whole grid every second (#ux-audit)

Commit
11148408731583aff9adb40bbdd49a552d81effc
Author
Vayun Mathur <[email protected]>
When
2026-11-13 01:11 UTC (23 days ago)
Parents
8c7501e
Symptom: while a puzzle was open, the entire board - every one of the
36/81/144 cells, plus the number pad - recomposed once a second, and
each recomposition re-ran the O(n^2) duplicate scan. Wasted work on
every tick, noticeable as jank/battery on low-end devices.

Root cause: elapsedSeconds lived in SudokuGameState, so each 1 Hz
incrementTimer() produced a new game instance. SudokuGrid and every
SudokuCell take that instance (its List fields make it unstable for
Compose), so all of them recomposed; and SudokuGrid called
game.conflictingIndices() directly in composition.

Fix:
- Removed elapsedSeconds from SudokuGameState. SudokuViewModel now
  owns the clock as its own StateFlow (elapsedSeconds), reset by
  newGame, restart and giveUp; checkWin reads it for stats and the
  speed achievement exactly as before.
- GameBoardScreen takes the clock as a lazily-read
  `elapsedSeconds: () -> Int` (default { 0 } for previews/tests) and
  renders it in a small private ClockText composable, so a tick
  invalidates only that text. GameScreen collects the flow without
  delegating, so reading happens inside the lambda, not at the screen.
- SudokuGrid memoises conflictingIndices() with
  remember(size, givens, entries): it now runs only when digits change,
  not on ticks or selection moves.
- Store-listing previews pass their fixed times through the new
  parameter (screenshots are not regenerated in this commit).

User-visible effect: none visually - the clock still ticks and the
win overlay still shows the time - but the board no longer redraws
every second.

Verification: SudokuViewModelTest asserts incrementTimer() leaves the
game state instance untouched (assertSame) and that the clock lives in
vm.elapsedSeconds, stops after a win and resets on restart;
SudokuScreensTest checks the win overlay and app bar both show the
time passed in; :games:sudoku:testDevUnitTest in the toolchain
container.

Diff

games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.ktindex da7f413017..7e0abe8517 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/data/SudokuModels.kt@@ -112,7 +112,8 @@ data class SudokuGameState(     val selected: Int = -1,     val notesMode: Boolean = false,     val moveCount: Int = 0,-    val elapsedSeconds: Int = 0,+    // The clock is deliberately not here: it ticks every second, and every tick would hand the+    // grid a new state and redraw all 81-144 cells. SudokuViewModel.elapsedSeconds owns it.     val hintsUsed: Int = 0,     val isWon: Boolean = false,     val usedUndo: Boolean = false,
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/platform/SudokuViewModel.ktindex 4732dd3e9c..713523af16 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@@ -69,6 +69,16 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),         viewModelScope.launch { settingsStore.setHighlightMistakes(enabled) }     } +    private val _elapsedSeconds = MutableStateFlow(0)++    /**+     * Seconds on the clock for the game in progress.+     *+     * Its own flow rather than a field of [SudokuGameState]: the game state feeds the whole grid,+     * so a 1 Hz tick inside it recomposed every cell every second. Only the clock text reads this.+     */+    val elapsedSeconds: StateFlow<Int> = _elapsedSeconds.asStateFlow()+     /** Undo snapshots, oldest first. Cleared whenever a new puzzle is dealt. */     private val history = ArrayDeque<SudokuSnapshot>() @@ -115,6 +125,7 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),         madeMistake = false         winRecorded = false         rejectionAttempt = 0+        _elapsedSeconds.value = 0         _uiState.value = SudokuUiState(generating = true)         viewModelScope.launch {             val puzzle = withContext(Dispatchers.Default) {@@ -308,13 +319,13 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),         history.clear()         madeMistake = false         rejectionAttempt = 0+        _elapsedSeconds.value = 0         _uiState.value = SudokuUiState(             game = game.copy(                 entries = List(game.size.cellCount) { 0 },                 notes = List(game.size.cellCount) { 0 },                 selected = -1,                 moveCount = 0,-                elapsedSeconds = 0,                 hintsUsed = 0,                 isWon = false,                 usedUndo = false,@@ -342,13 +353,14 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),         val game = _uiState.value.game ?: return         if (!game.isWon) statsRepository.recordGameLost(game.size, game.difficulty)         history.clear()+        _elapsedSeconds.value = 0         _uiState.value = SudokuUiState()     }      fun incrementTimer() {         val game = _uiState.value.game ?: return         if (game.isWon || game.isGameOver) return-        mutate { it.copy(elapsedSeconds = it.elapsedSeconds + 1) }+        _elapsedSeconds.update { it + 1 }     }      fun dismissAchievementNotification() = achievementsManager.dismissNotification()@@ -365,13 +377,14 @@ class SudokuViewModel(application: Application) : AndroidViewModel(application),         // The board still shows its win on a restart replay; only the recording is once-only.         if (winRecorded) return         winRecorded = true-        statsRepository.recordGameWon(game.size, game.difficulty, game.elapsedSeconds)+        val elapsed = _elapsedSeconds.value+        statsRepository.recordGameWon(game.size, game.difficulty, elapsed)         val manager = achievementsManager         manager.onAchievementUnlocked("first_win")         if (game.size == BoardSize.NINE) {             manager.onAchievementUnlocked("win_nine")             if (game.hintsUsed == 0) manager.onAchievementUnlocked("no_hints")-            if (game.elapsedSeconds < SudokuAchievementsManager.SPEED_SECONDS) {+            if (elapsed < SudokuAchievementsManager.SPEED_SECONDS) {                 manager.onAchievementUnlocked("speed_nine")             }         }
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.ktindex 0b4eb609da..7b6c63d003 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameBoardScreen.kt@@ -57,6 +57,9 @@ private val BoardMaxWidth = 520.dp /**  * The board, with no dependency on the ViewModel so it can be rendered from a `@Preview` — see  * `src/screenshotTest`.+ *+ * @param elapsedSeconds the clock, read lazily so a 1 Hz tick recomposes only the text that+ * shows it rather than the grid and pad.  */ @Composable fun GameBoardScreen(@@ -64,6 +67,7 @@ fun GameBoardScreen(     actions: SudokuActions,     onExit: () -> Unit,     highlightMistakes: Boolean = true,+    elapsedSeconds: () -> Int = { 0 }, ) {     val game = state.game     AppScaffold(@@ -72,13 +76,7 @@ fun GameBoardScreen(         onNavigateBack = onExit,         alignment = AppBarAlignment.Center,         actions = {-            if (game != null) {-                Text(-                    formatDuration(game.elapsedSeconds),-                    style = MaterialTheme.typography.titleMedium,-                    modifier = Modifier.padding(end = Spacing.lg),-                )-            }+            if (game != null) ClockText(elapsedSeconds)         },         scrollBehavior = appBarScrollBehavior(),     ) { padding ->@@ -182,7 +180,7 @@ fun GameBoardScreen(                     onPlayAgain = { actions.playAgain() },                     onBack = onExit,                 ) {-                    Text("${stringResource(UiR.string.game_time)}: ${formatDuration(game.elapsedSeconds)}")+                    Text("${stringResource(UiR.string.game_time)}: ${formatDuration(elapsedSeconds())}")                     if (game.hintsUsed > 0) {                         Text(                             "${stringResource(R.string.hints_used)}: ${game.hintsUsed}",@@ -210,6 +208,16 @@ fun GameBoardScreen(     } } +/** Its own restart scope, so the per-second tick recomposes this text and nothing else. */+@Composable+private fun ClockText(elapsedSeconds: () -> Int) {+    Text(+        formatDuration(elapsedSeconds()),+        style = MaterialTheme.typography.titleMedium,+        modifier = Modifier.padding(end = Spacing.lg),+    )+}+ @Composable private fun HintsUsed(hintsUsed: Int) {     if (hintsUsed > 0) {
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 cfd69d2368..dd72a980f3 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@@ -25,6 +25,9 @@ fun GameScreen(     config: GameConfig, ) {     val uiState by viewModel.uiState.collectAsState()+    // Not delegated: the State is read inside the lambda below, so a tick recomposes only the+    // clock text instead of this whole screen and the grid under it.+    val elapsedSeconds = viewModel.elapsedSeconds.collectAsState()     val highlightMistakes by viewModel.highlightMistakes.collectAsState()      LaunchedEffect(config) {@@ -44,5 +47,6 @@ fun GameScreen(         actions = viewModel,         onExit = { backStack.pop() },         highlightMistakes = highlightMistakes,+        elapsedSeconds = { elapsedSeconds.value },     ) }
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.ktindex 939037287e..a9f27c17e8 100644--- a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/components/SudokuGrid.kt@@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind@@ -52,8 +53,10 @@ fun SudokuGrid(     val selected = game.selected     val selectedValue = if (selected >= 0) game.valueAt(selected) else 0     // Digits repeated within a row, column or box. Computable from the board alone, so-    // marking them shows the player a mistake without revealing the solution.-    val conflicts = game.conflictingIndices()+    // marking them shows the player a mistake without revealing the solution. The scan is+    // quadratic in the cell count, so it reruns only when the digits change — not on every+    // selection move.+    val conflicts = remember(game.size, game.givens, game.entries) { game.conflictingIndices() }      BoxWithConstraints(modifier.aspectRatio(1f)) {         val cell: Dp = maxWidth / side
games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.kt
diff --git a/games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.kt b/games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.ktindex 5a1f26eafd..8543c05b62 100644--- a/games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.kt+++ b/games/sudoku/src/screenshotTest/kotlin/com/vayunmathur/games/sudoku/MetadataPreviews.kt@@ -41,8 +41,8 @@ class MetadataPreviews {                 seed = 20260824,                 filled = 14,                 selected = 40,-                elapsed = 232,-            )+            ),+            elapsed = 232,         )     } @@ -56,9 +56,8 @@ class MetadataPreviews {             seed = 4711,             filled = 6,             selected = 30,-            elapsed = 96,         )-        Board(base.copy(notesMode = true, notes = pencilMarks(base)))+        Board(base.copy(notesMode = true, notes = pencilMarks(base)), elapsed = 96)     }      @PreviewTest@@ -73,8 +72,8 @@ class MetadataPreviews {                 seed = 1212,                 filled = 18,                 selected = 40,-                elapsed = 604,-            )+            ),+            elapsed = 604,         )     } @@ -89,8 +88,8 @@ class MetadataPreviews {                 seed = 991,                 filled = 5,                 selected = 20,-                elapsed = 41,-            )+            ),+            elapsed = 41,         )     } @@ -98,18 +97,19 @@ class MetadataPreviews {     @Preview(name = "5-solved", device = PHONE, group = "phone", showSystemUi = true)     @Composable     fun Preview5Solved() {-        val base = game(BoardSize.NINE, Difficulty.EXPERT, seed = 2024, filled = 0, elapsed = 511)-        Board(base.copy(entries = base.blanksFilled(), isWon = true))+        val base = game(BoardSize.NINE, Difficulty.EXPERT, seed = 2024, filled = 0)+        Board(base.copy(entries = base.blanksFilled(), isWon = true), elapsed = 511)     }      @Composable-    private fun Board(game: SudokuGameState) {+    private fun Board(game: SudokuGameState, elapsed: Int) {         // Layoutlib has no wallpaper to sample, so Material You falls back to the default palette.         DynamicTheme(darkTheme = true) {             GameBoardScreen(                 state = SudokuUiState(game = game, canUndo = game.moveCount > 0),                 actions = SudokuActions.Noop,                 onExit = {},+                elapsedSeconds = { elapsed },             )         }     }@@ -125,7 +125,6 @@ class MetadataPreviews {         seed: Int,         filled: Int,         selected: Int = -1,-        elapsed: Int = 0,     ): SudokuGameState {         val puzzle = SudokuGenerator.generate(size, difficulty, Random(seed))         val state = SudokuGameState.from(puzzle)@@ -135,7 +134,6 @@ class MetadataPreviews {         return state.copy(             entries = entries,             selected = selected,-            elapsedSeconds = elapsed,             moveCount = filled,         )     }
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.ktindex ed49f8ebc9..9fac01b545 100644--- a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.kt+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/data/SudokuModelsTest.kt@@ -80,7 +80,6 @@ class SudokuModelsTest {         assertEquals(-1, state.selected)         assertFalse(state.notesMode)         assertEquals(0, state.moveCount)-        assertEquals(0, state.elapsedSeconds)         assertEquals(0, state.hintsUsed)         assertFalse(state.isWon)         assertFalse(state.usedUndo)
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.ktindex 0920175231..d725ac604c 100644--- a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.kt+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/platform/SudokuViewModelTest.kt@@ -25,6 +25,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull+import kotlin.test.assertSame import kotlin.test.assertTrue  @OptIn(ExperimentalCoroutinesApi::class)@@ -281,8 +282,10 @@ class SudokuViewModelTest {         val original = vm.uiState.value.game!!         vm.selectCell(cell)         vm.enterDigit(original.solution[cell])+        val beforeTicks = vm.uiState.value.game!!         vm.incrementTimer(); vm.incrementTimer()-        assertEquals(2, vm.uiState.value.game!!.elapsedSeconds)+        assertEquals(2, vm.elapsedSeconds.value)+        assertSame(beforeTicks, vm.uiState.value.game!!, "a tick must not hand the grid a new state")          vm.restart()         val after = vm.uiState.value.game!!@@ -290,7 +293,7 @@ class SudokuViewModelTest {         assertEquals(original.solution, after.solution)         assertEquals(List(after.size.cellCount) { 0 }, after.entries)         assertEquals(0, after.moveCount)-        assertEquals(0, after.elapsedSeconds)+        assertEquals(0, vm.elapsedSeconds.value)         assertEquals(0, after.hintsUsed)         assertEquals(-1, after.selected)         assertFalse(after.isWon)@@ -326,9 +329,10 @@ class SudokuViewModelTest {         assertEquals(-1, won.selected)         assertFalse(vm.hasActiveGame())         assertEquals(1, stats.getStats(BoardSize.SIX, Difficulty.EASY).gamesWon)-        val elapsed = won.elapsedSeconds+        val elapsed = vm.elapsedSeconds.value+        assertEquals(1, elapsed)         vm.incrementTimer()-        assertEquals(elapsed, vm.uiState.value.game!!.elapsedSeconds, "timer stops after win")+        assertEquals(elapsed, vm.elapsedSeconds.value, "timer stops after win")         // Further digits are ignored on a won game.         vm.selectCell(0)         val entries = vm.uiState.value.game!!.entries@@ -462,7 +466,7 @@ class SudokuViewModelTest {         assertEquals(0, stats.getStats(BoardSize.SIX, Difficulty.EASY).currentWinStreak,             "losing the last life records a loss")         vm.incrementTimer()-        assertEquals(0, after.elapsedSeconds)+        assertEquals(0, vm.elapsedSeconds.value)          // Correct digits still place in answer mode (before game over this is the path); after         // game over input is ignored, verified by unchanged entries.
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.ktindex 9b6df5b275..128282ad08 100644--- a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.kt+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/SudokuScreensTest.kt@@ -146,11 +146,17 @@ class SudokuScreensTest {         val actions = RecordingActions()         val base = freshGame()         val entries = List(base.size.cellCount) { if (base.isGiven(it)) 0 else base.solution[it] }-        val won = base.copy(entries = entries, isWon = true, hintsUsed = 2, elapsedSeconds = 65)+        val won = base.copy(entries = entries, isWon = true, hintsUsed = 2)         rule.setContent {-            GameBoardScreen(state = SudokuUiState(game = won), actions = actions, onExit = {})+            GameBoardScreen(+                state = SudokuUiState(game = won),+                actions = actions,+                onExit = {},+                elapsedSeconds = { 65 },+            )         }         rule.onNodeWithText(str(R.string.congratulations)).assertExists()+        rule.onAllNodesWithText("1:05", substring = true).assertCountEquals(2)         rule.onAllNodesWithText("${str(R.string.hints_used)}: 2").assertCountEquals(2)         rule.onNodeWithText("Play Again").performClick()         assertEquals(1, actions.playAgains)@@ -215,7 +221,7 @@ class SudokuScreensTest {             val base = freshGame(size, Difficulty.MEDIUM)             val blank = base.givens.indices.first { base.givens[it] == 0 }             val notes = base.notes.toMutableList().also { it[blank] = 0b101 }-            val styled = base.copy(notes = notes, selected = blank, elapsedSeconds = 3661)+            val styled = base.copy(notes = notes, selected = blank)             current = SudokuUiState(game = styled)             rule.onNodeWithText(str(R.string.hint)).assertExists()         }