sudoku: pause the clock in the background and behind dialogs (#ux-audit)
- Commit
5a31c7a9c614c633b6a16614379cd3df338e3fab- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 01:12 UTC (23 days ago)
- Parents
1114840
Symptom: the game clock kept counting while the app was in the background, behind the recents switcher or under the notification shade, and while the give-up confirmation covered the board. Times recorded in stats were inflated and the under-N-seconds speed achievement could be lost to time the player was not playing. Root cause: GameScreen drove the clock with a LaunchedEffect loop keyed only on "not won". A composition outlives the screen being visible, so the loop ran whenever the Activity was alive, regardless of lifecycle; and nothing told it about dialogs. Fix: - New internal GameClock composable (ui/GameClock.kt): ticks once a second only while `running` and the LocalLifecycleOwner is at least RESUMED (lifecycle-runtime-compose currentStateAsState(), already on the classpath via Compose UI). ON_PAUSE stops the loop, ON_RESUME restarts it; a partial second is dropped, in the player's favour. - GameBoardScreen gains onDialogShownChange (no-op default). ActionBar reports the give-up confirmation opening and closing; GameScreen folds that into `running`, together with not won and not out of lives (the result overlay states), so the clock stops whenever the board is covered. User-visible effect: leaving the app, pulling down the shade or opening the give-up dialog freezes the timer; it continues from the same value on return. Verification: new GameClockTest - with a test LifecycleOwner and a paused main clock, it ticks 3 times in 3.5 s while RESUMED, not at all for 10 s at STARTED, resumes at RESUMED, and stops when not running; and the give-up dialog reports true on open / false on cancel. :games:sudoku:testDevUnitTest in the toolchain container.
Diff
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 7b6c63d003..5b1b337fb5 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@@ -14,9 +14,11 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -60,6 +62,8 @@ private val BoardMaxWidth = 520.dp * * @param elapsedSeconds the clock, read lazily so a 1 Hz tick recomposes only the text that * shows it rather than the grid and pad.+ * @param onDialogShownChange told whenever a dialog over the board opens or closes, so the+ * stateful caller can pause the clock while the board is covered. */ @Composable fun GameBoardScreen(@@ -68,6 +72,7 @@ fun GameBoardScreen( onExit: () -> Unit, highlightMistakes: Boolean = true, elapsedSeconds: () -> Int = { 0 },+ onDialogShownChange: (Boolean) -> Unit = {}, ) { val game = state.game AppScaffold(@@ -129,7 +134,7 @@ fun GameBoardScreen( rejected = state.rejectedDigit, ) - ActionBar(state, actions, onExit)+ ActionBar(state, actions, onExit, onDialogShownChange) } // Height-sized square: the board is what the height allows. // Capped at a share of the width so a narrow-but-short window@@ -168,7 +173,7 @@ fun GameBoardScreen( rejected = state.rejectedDigit, ) - ActionBar(state, actions, onExit)+ ActionBar(state, actions, onExit, onDialogShownChange) } } @@ -267,9 +272,12 @@ private fun ActionBar( state: SudokuUiState, actions: SudokuActions, onExit: () -> Unit,+ onDialogShownChange: (Boolean) -> Unit, ) { val game = state.game ?: return var confirmGiveUp by remember { mutableStateOf(false) }+ val dialogShownChange by rememberUpdatedState(onDialogShownChange)+ LaunchedEffect(confirmGiveUp) { dialogShownChange(confirmGiveUp) } // Won or out of lives: the board takes no more input, so erase, undo and hint go quiet too. // Undo in particular would otherwise restore pre-win entries under a board still marked won. val ended = game.isWon || game.isGameOver
games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameClock.kt
diff --git a/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameClock.kt b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameClock.ktnew file mode 100644index 0000000000..8cc6ed5c80--- /dev/null+++ b/games/sudoku/src/main/java/com/vayunmathur/games/sudoku/ui/GameClock.kt@@ -0,0 +1,35 @@+package com.vayunmathur.games.sudoku.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberUpdatedState+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LocalLifecycleOwner+import androidx.lifecycle.compose.currentStateAsState+import kotlinx.coroutines.delay++/**+ * Calls [onTick] once a second while [running] is true and the screen is RESUMED.+ *+ * A plain `LaunchedEffect` loop keeps going for as long as the composition exists, and the+ * composition outlives the screen being visible: with the app in the background, behind the+ * recents switcher or under the notification shade the clock kept counting, inflating times and+ * costing the speed achievement. Keying the loop on the lifecycle stops it at ON_PAUSE and starts+ * it again at ON_RESUME. A partial second is dropped on each pause, which errs in the player's+ * favour.+ */+@Composable+internal fun GameClock(running: Boolean, onTick: () -> Unit) {+ val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState()+ val ticking = running && lifecycleState.isAtLeast(Lifecycle.State.RESUMED)+ val tick by rememberUpdatedState(onTick)+ LaunchedEffect(ticking) {+ while (ticking) {+ delay(TICK_MILLIS)+ tick()+ }+ }+}++private const val TICK_MILLIS = 1_000L
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 dd72a980f3..f48f62eb7c 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@@ -4,17 +4,20 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import com.vayunmathur.games.sudoku.Route import com.vayunmathur.games.sudoku.data.GameConfig import com.vayunmathur.games.sudoku.platform.SudokuViewModel import com.vayunmathur.library.util.NavBackStack-import kotlinx.coroutines.delay /** * The only place the board touches the ViewModel. * * It deals a puzzle if there is not one already โ reached by entering this route after process- * death, when the route survived but the in-memory grid did not โ and drives the 1 Hz clock.+ * death, when the route survived but the in-memory grid did not โ and drives the 1 Hz clock,+ * which runs only while the screen is resumed and the player can actually play. * Everything else is handed to the stateless [GameBoardScreen], which is what the store-listing * previews render. */@@ -34,13 +37,12 @@ fun GameScreen( if (uiState.game == null && !uiState.generating) viewModel.newGame(config) } - val running = uiState.game?.isWon == false- LaunchedEffect(running) {- while (running) {- delay(1000)- viewModel.incrementTimer()- }- }+ // 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.+ var dialogShown by remember { mutableStateOf(false) }+ val game = uiState.game+ val running = game != null && !game.isWon && !game.isGameOver && !dialogShown+ GameClock(running = running, onTick = viewModel::incrementTimer) GameBoardScreen( state = uiState,@@ -48,5 +50,6 @@ fun GameScreen( onExit = { backStack.pop() }, highlightMistakes = highlightMistakes, elapsedSeconds = { elapsedSeconds.value },+ onDialogShownChange = { dialogShown = it }, ) }
games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/GameClockTest.kt
diff --git a/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/GameClockTest.kt b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/GameClockTest.ktnew file mode 100644index 0000000000..fc8e6f7bc9--- /dev/null+++ b/games/sudoku/src/test/java/com/vayunmathur/games/sudoku/ui/GameClockTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.games.sudoku.ui++import android.content.Context+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleOwner+import androidx.lifecycle.LifecycleRegistry+import androidx.lifecycle.compose.LocalLifecycleOwner+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.sudoku.R+import com.vayunmathur.games.sudoku.data.BoardSize+import com.vayunmathur.games.sudoku.data.Difficulty+import com.vayunmathur.games.sudoku.data.SudokuGameState+import com.vayunmathur.games.sudoku.domain.SudokuGenerator+import com.vayunmathur.games.sudoku.platform.SudokuActions+import com.vayunmathur.games.sudoku.platform.SudokuUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals++/** The 1 Hz clock only ticks while the screen is resumed, running, and not covered by a dialog. */+@RunWith(RobolectricTestRunner::class)+class GameClockTest {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private class TestOwner : LifecycleOwner {+ val registry = LifecycleRegistry.createUnsafe(this)+ override val lifecycle: Lifecycle get() = registry+ }++ @Test+ fun ticksOnlyWhileResumedAndRunning() {+ val owner = TestOwner().apply { registry.currentState = Lifecycle.State.RESUMED }+ var running by mutableStateOf(true)+ var ticks = 0+ rule.mainClock.autoAdvance = false+ rule.setContent {+ CompositionLocalProvider(LocalLifecycleOwner provides owner) {+ GameClock(running = running, onTick = { ticks++ })+ }+ }++ rule.mainClock.advanceTimeBy(3_500)+ rule.waitForIdle()+ assertEquals(3, ticks, "ticks once a second while resumed")++ // Backgrounded (or behind a system dialog): ON_PAUSE drops the state to STARTED.+ rule.runOnIdle { owner.registry.currentState = Lifecycle.State.STARTED }+ rule.mainClock.advanceTimeBy(10_000)+ rule.waitForIdle()+ assertEquals(3, ticks, "no ticks while paused")++ rule.runOnIdle { owner.registry.currentState = Lifecycle.State.RESUMED }+ rule.mainClock.advanceTimeBy(1_500)+ rule.waitForIdle()+ assertEquals(4, ticks, "resumes after ON_RESUME")++ // The flag reaches the clock on the next frame; count from there.+ rule.runOnIdle { running = false }+ rule.mainClock.advanceTimeByFrame()+ rule.waitForIdle()+ val stoppedAt = ticks+ rule.mainClock.advanceTimeBy(5_000)+ rule.waitForIdle()+ assertEquals(stoppedAt, ticks, "a finished game does not tick")+ }++ @Test+ fun giveUpDialogReportsItselfSoTheClockCanPause() {+ val puzzle = SudokuGenerator.generate(BoardSize.SIX, Difficulty.EASY, Random(1))+ val game = SudokuGameState.from(puzzle)+ val reports = mutableListOf<Boolean>()+ rule.setContent {+ GameBoardScreen(+ state = SudokuUiState(game = game),+ actions = SudokuActions.Noop,+ onExit = {},+ onDialogShownChange = { reports += it },+ )+ }+ rule.onNodeWithText(ctx.getString(R.string.give_up)).performClick()+ rule.waitForIdle()+ assertEquals(true, reports.last(), "opening the dialog pauses the clock")+ rule.onNodeWithText(ctx.getString(com.vayunmathur.library.ui.R.string.cancel)).performClick()+ rule.waitForIdle()+ assertEquals(false, reports.last(), "dismissing it resumes the clock")+ rule.onAllNodesWithText(ctx.getString(R.string.confirm_give_up_title)).fetchSemanticsNodes()+ .let { assertEquals(0, it.size) }+ }+}