minesweeper: pause the clock in the background and behind dialogs (#ux-audit)
- Commit
cf04808e3b6ed80c7eb679c22f1beccfcc073fe6- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 01:19 UTC (23 days ago)
- Parents
c0ce392
Symptom: once the first cell was opened the clock kept counting while the app was backgrounded, behind the recents switcher or under the notification shade, and while the New Field / Give Up confirmation covered the field. Win times in stats were inflated and the under-a-minute speed_win achievement could be lost to time the player was not playing. Root cause: GameScreen drove the clock with a LaunchedEffect loop keyed only on "started and not over". The composition outlives the screen being visible, so the loop ignored the lifecycle, and nothing told it about the dialogs that live inside GameBoardScreen. Fix (same approach as sudoku): - 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(), on the classpath via Compose UI). ON_PAUSE stops it, ON_RESUME restarts it. - GameBoardScreen gains onDialogShownChange (no-op default) and reports whenever either confirmation dialog opens or closes; GameScreen folds that into `running` alongside started && !isOver (isOver is when the result overlay shows). User-visible effect: leaving the app, pulling down the shade, or opening a confirmation 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; the Give Up and New Field dialogs report true on open and false on cancel. :games:minesweeper:testDevUnitTest in the toolchain container.
Diff
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.ktindex d896ba7dc1..38c7c29327 100644--- a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.kt+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreen.kt@@ -11,9 +11,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@@ -54,6 +56,8 @@ private val FieldMaxWidth = 480.dp * * @param elapsedSeconds the clock, read lazily so a 1 Hz tick recomposes only the text that * shows it rather than the field.+ * @param onDialogShownChange told whenever a confirmation dialog opens or closes, so the stateful+ * caller can pause the clock while the field is covered. */ @Composable fun GameBoardScreen(@@ -61,6 +65,7 @@ fun GameBoardScreen( actions: MinesweeperActions, onExit: () -> Unit, elapsedSeconds: () -> Int = { 0 },+ onDialogShownChange: (Boolean) -> Unit = {}, ) { val game = state.game val mineCount = state.config.difficulty.mineCount(state.config.size)@@ -70,6 +75,9 @@ fun GameBoardScreen( val hasProgress = game?.let { it.started && !it.isOver } == true var confirmRestart by remember { mutableStateOf(false) } var confirmGiveUp by remember { mutableStateOf(false) }+ val dialogShownChange by rememberUpdatedState(onDialogShownChange)+ val dialogShown = confirmRestart || confirmGiveUp+ LaunchedEffect(dialogShown) { dialogShownChange(dialogShown) } AppScaffold( // Size name plus the mine count rather than size plus density name: the two enums share // labels ("Medium" and "Medium"), and the raw count is what a player actually wants to know.
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameClock.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameClock.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameClock.ktnew file mode 100644index 0000000000..c4829aab6a--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/ui/GameClock.kt@@ -0,0 +1,35 @@+package com.vayunmathur.games.minesweeper.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 under-a-minute 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/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 8fa25fd39a..6cd04155f3 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@@ -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.minesweeper.Route import com.vayunmathur.games.minesweeper.data.GameConfig import com.vayunmathur.games.minesweeper.platform.MinesweeperViewModel import com.vayunmathur.library.util.NavBackStack-import kotlinx.coroutines.delay /** * The only place the board touches the ViewModel. * * It deals a field if there is not one already — reached by entering this route after process death,- * when the route survived but the in-memory field did not — and drives the 1 Hz clock. Everything+ * when the route survived but the in-memory field did not — and drives the 1 Hz clock, which+ * runs only while the screen is resumed and the field is actually playable. Everything * else is handed to the stateless [GameBoardScreen], which is what the store-listing previews render. */ @Composable@@ -32,19 +35,18 @@ fun GameScreen( if (uiState.game == null) viewModel.newGame(config) } - // The clock starts on the first reveal, not on entering the screen.- val running = uiState.game?.let { it.started && !it.isOver } == true- LaunchedEffect(running) {- while (running) {- delay(1000)- viewModel.incrementTimer()- }- }+ // 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+ // is not resumed — see GameClock.+ var dialogShown by remember { mutableStateOf(false) }+ val running = uiState.game?.let { it.started && !it.isOver } == true && !dialogShown+ GameClock(running = running, onTick = viewModel::incrementTimer) GameBoardScreen( state = uiState, actions = viewModel, onExit = { backStack.pop() }, elapsedSeconds = { elapsedSeconds.value },+ onDialogShownChange = { dialogShown = it }, ) }
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameClockTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameClockTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameClockTest.ktnew file mode 100644index 0000000000..e0aa08d1c7--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameClockTest.kt@@ -0,0 +1,108 @@+package com.vayunmathur.games.minesweeper.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.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.minesweeper.R+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import com.vayunmathur.games.minesweeper.domain.FieldGenerator+import com.vayunmathur.games.minesweeper.domain.MinesweeperRules+import com.vayunmathur.games.minesweeper.platform.MinesweeperActions+import com.vayunmathur.games.minesweeper.platform.MinesweeperUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+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)+@Config(sdk = [34])+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")++ 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 field does not tick")+ }++ @Test+ fun confirmationDialogsReportThemselvesSoTheClockCanPause() {+ val config = GameConfig(BoardSize.SMALL, Difficulty.EASY)+ val blank = MinesweeperGameState.empty(config)+ val safe = 4 * config.size.cols + 4+ val game = MinesweeperRules.reveal(FieldGenerator.lay(blank, safe, Random(1)), safe)+ val reports = mutableListOf<Boolean>()+ rule.setContent {+ GameBoardScreen(+ state = MinesweeperUiState(config = config, game = game),+ actions = MinesweeperActions.Noop,+ onExit = {},+ onDialogShownChange = { reports += it },+ )+ }+ rule.onNodeWithText(ctx.getString(R.string.give_up)).performClick()+ rule.waitForIdle()+ assertEquals(true, reports.last(), "the give-up 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.onNodeWithText(ctx.getString(R.string.new_field)).performClick()+ rule.waitForIdle()+ assertEquals(true, reports.last(), "the new-field dialog pauses it too")+ }+}