games-solitaire: animate autocomplete as rapid cascade
- Commit
cf0a1e38d933d633d2bcc06920298185998d7334- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 20:12 UTC (28 days ago)
- Parents
e9d283e
Request: Klondike autocomplete jumped instantly to the finished state. It now plays as a super-fast cascade: each card visibly flies to its foundation in rapid sequence (70 ms flight + 15 ms gap), fast enough to read as a completion sweep rather than one-by-one play. Design: the greedy autocomplete was refactored into a pure simulation, simulateKlondikeAutoComplete, which returns the ordered single-card steps (card, source pile id, foundation index, state after the step) plus the final state, using the same move choice as before (waste first, then tableau tops, foundations in index order, drawing one stock card when stalled). The instant klondikeAutoComplete applies the final state directly and is unchanged in result; the new animated path triggered by the Auto-complete button plays the steps back: each step sets an AnimatedMove flight from the source card's registered rectangle to its foundation, applies that step's state as the flight lands, and moves on. No illegal intermediate states are possible: every applied state is a prefix of the simulated legal sequence. Undo behaviour (chosen and deliberate): history is saved once before the cascade, so the whole completion is a single undo step, exactly like the instant autocomplete before it. While the cascade runs, other animated moves, drags, stock draws and undo are ignored so state cannot change mid-flight. If no card can fly (only stock left to cycle), it completes instantly as before. Verification: SolitaireAnimationTest gains autoCompleteSimulationIsLegalStepSequence (steps chain, each adds exactly one foundation card, simulation matches the instant completion's end state and win) and animatedAutoCompleteCascadesAndUndoesAsOneStep (flights run, game wins, one history entry, one undo restores the pre-autocomplete board). Full :games:solitaire:testDevUnitTest, :games:solitaire:compileDevKotlin and :games:solitaire:metadata (screenshot previews; no golden changes, static UI is unchanged) pass.
Diff
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.ktindex 5e5d29cd12..e08fa23502 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireKlondikeOps.kt@@ -186,20 +186,102 @@ internal fun SolitaireViewModel.klondikeMoveTableauToTableauImpl(fromColumn: Int } } +/**+ * Animated autocomplete: play the completion computed by+ * [simulateKlondikeAutoComplete] as a rapid cascade of flights to the+ * foundations (one short flight per card, back to back), applying each+ * step's state as its flight lands. History is saved once up front, so+ * the whole cascade stays a single undo step — the same undo behaviour+ * as the instant completion. While the cascade runs, other animated+ * moves, drags, stock draws and undo are ignored (see+ * [SolitaireViewModel.isMoveAnimating]). With no flight geometry+ * available for a step (pile off screen) that step still applies on+ * schedule, just without a visible flight.+ */ internal fun SolitaireViewModel.klondikeAutoCompleteAnimatedImpl() {- klondikeAutoCompleteImpl()+ if (isMoveAnimating()) return+ val state = uiStateInternal.value.klondike ?: return+ if (!canKlondikeAutoComplete(state)) return+ val (steps, finalState) = simulateKlondikeAutoComplete(state)+ if (steps.isEmpty()) {+ // Nothing can fly (e.g. only stock to cycle): complete instantly.+ klondikeAutoCompleteImpl()+ return+ }+ saveHistory()+ launchMoveAnimation {+ for (step in steps) {+ val fromRect = cardPositions[step.sourceId]+ val destRect = dropTargets["foundation_${step.foundationIndex}"]+ if (fromRect != null && destRect != null) {+ animatedMoveInternal.value = AnimatedMove(+ id = nextAnimationId(),+ cards = listOf(step.card),+ sourceId = step.sourceId,+ targetId = "foundation_${step.foundationIndex}",+ from = fromRect,+ to = destRect,+ durationMillis = AUTO_COMPLETE_STEP_MILLIS,+ )+ }+ kotlinx.coroutines.delay(AUTO_COMPLETE_STEP_MILLIS.toLong())+ uiStateInternal.update { it.copy(klondike = step.stateAfter) }+ animatedMoveInternal.value = null+ kotlinx.coroutines.delay(AUTO_COMPLETE_GAP_MILLIS.toLong())+ }+ uiStateInternal.update { it.copy(klondike = finalState) }+ checkKlondikeWin()+ } } internal fun SolitaireViewModel.klondikeAutoCompleteImpl() { val state = uiStateInternal.value.klondike ?: return if (!canKlondikeAutoComplete(state)) return saveHistory()- var current = state+ val (_, finalState) = simulateKlondikeAutoComplete(state)+ uiStateInternal.update { it.copy(klondike = finalState) }+ checkKlondikeWin()+}++/** One card's journey in an autocomplete: from [sourceId] to a foundation. */+internal data class KlondikeAutoCompleteStep(+ val card: Card,+ val sourceId: String,+ val foundationIndex: Int,+ val stateAfter: KlondikeState,+)++/**+ * The full autocomplete for [start], as the ordered single-card moves to+ * the foundations plus the resulting final state. Pure simulation on+ * state values (no UI state is touched), which keeps the sequencing+ * unit-testable; the instant completion applies [Pair.second] directly+ * and the animated one plays [Pair.first] back step by step. Move choice+ * matches the original greedy drain: waste top first, then tableau tops+ * in column order, foundations in index order, drawing one stock card+ * whenever the board stalls (draws are folded into the following step's+ * state, and into the final state when nothing follows them).+ */+internal fun SolitaireViewModel.simulateKlondikeAutoComplete(+ start: KlondikeState,+): Pair<List<KlondikeAutoCompleteStep>, KlondikeState> {+ var current = start+ val steps = mutableListOf<KlondikeAutoCompleteStep>() var madeProgress = true while (madeProgress) { madeProgress = false- current = drainToFoundations(current) { current = it; madeProgress = true }- // Draw one stock card and try again+ var moved = true+ while (moved) {+ moved = false+ val step = wasteFoundationStep(current) ?: tableauFoundationStep(current)+ if (step != null) {+ steps += step+ current = step.stateAfter+ moved = true+ madeProgress = true+ }+ }+ // Draw one stock card and try again. if (current.stock.isNotEmpty()) { current = current.copy( stock = current.stock.dropLast(1),@@ -208,52 +290,31 @@ internal fun SolitaireViewModel.klondikeAutoCompleteImpl() { madeProgress = true } }- uiStateInternal.update { it.copy(klondike = current) }- checkKlondikeWin()-}--private fun SolitaireViewModel.drainToFoundations(- start: KlondikeState,- onMove: (KlondikeState) -> Unit,-): KlondikeState {- var current = start- var moved = true- while (moved) {- moved = false- val afterWaste = moveWasteToFoundation(current)- if (afterWaste != null) {- current = afterWaste- moved = true- onMove(current)- continue- }- val afterTableau = moveTableauToFoundation(current)- if (afterTableau != null) {- current = afterTableau- moved = true- onMove(current)- }- }- return current+ return steps to current } -private fun SolitaireViewModel.moveWasteToFoundation(current: KlondikeState): KlondikeState? {+private fun SolitaireViewModel.wasteFoundationStep(current: KlondikeState): KlondikeAutoCompleteStep? { if (current.waste.isEmpty()) return null val card = current.waste.last() for (fi in current.foundations.indices) { if (!canPlaceOnFoundation(card, current.foundations[fi], fi)) continue val newFoundations = current.foundations.toMutableList() newFoundations[fi] = newFoundations[fi] + card- return current.copy(- waste = current.waste.dropLast(1),- foundations = newFoundations,- moveCount = current.moveCount + 1+ return KlondikeAutoCompleteStep(+ card = card,+ sourceId = "waste",+ foundationIndex = fi,+ stateAfter = current.copy(+ waste = current.waste.dropLast(1),+ foundations = newFoundations,+ moveCount = current.moveCount + 1+ ), ) } return null } -private fun SolitaireViewModel.moveTableauToFoundation(current: KlondikeState): KlondikeState? {+private fun SolitaireViewModel.tableauFoundationStep(current: KlondikeState): KlondikeAutoCompleteStep? { for (i in current.tableauPiles.indices) { val pile = current.tableauPiles[i] if (pile.faceUp.isEmpty()) continue@@ -264,10 +325,15 @@ private fun SolitaireViewModel.moveTableauToFoundation(current: KlondikeState): newFoundations[fi] = newFoundations[fi] + card val newPiles = current.tableauPiles.toMutableList() newPiles[i] = autoFlip(pile.copy(faceUp = pile.faceUp.dropLast(1)))- return current.copy(- tableauPiles = newPiles,- foundations = newFoundations,- moveCount = current.moveCount + 1+ return KlondikeAutoCompleteStep(+ card = card,+ sourceId = "tableau_${i}_${pile.faceUp.size - 1}",+ foundationIndex = fi,+ stateAfter = current.copy(+ tableauPiles = newPiles,+ foundations = newFoundations,+ moveCount = current.moveCount + 1+ ), ) } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.ktindex b11385330f..54d28bdf8f 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.kt@@ -77,7 +77,7 @@ fun GameBoardScreen(state: SolitaireUiState, mode: GameMode, actions: SolitaireA GameMode.KLONDIKE -> state.klondike?.let { KlondikeBoard(it, actions, Modifier.align(Alignment.CenterHorizontally).widthIn(max = boardMaxWidth).fillMaxWidth()) if (canKlondikeAutoComplete(it)) {- Button(onClick = { actions.klondikeAutoComplete() }, Modifier.align(Alignment.CenterHorizontally)) { Text(stringResource(R.string.auto_complete)) }+ Button(onClick = { actions.klondikeAutoCompleteAnimated() }, Modifier.align(Alignment.CenterHorizontally)) { Text(stringResource(R.string.auto_complete)) } } } GameMode.SPIDER -> state.spider?.let { SpiderBoard(it, actions, Modifier.align(Alignment.CenterHorizontally).widthIn(max = boardMaxWidth).fillMaxWidth()) }
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAnimationTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAnimationTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAnimationTest.ktindex 97e28531b6..cf8815cdb4 100644--- a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAnimationTest.kt+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAnimationTest.kt@@ -155,6 +155,89 @@ class SolitaireAnimationTest { } } + /** Foundations one king short per suit, kings in stock/waste/tableau. */+ private fun almostWonState(): KlondikeState {+ val foundations = Suit.entries.map { suit ->+ Rank.entries.filter { it != Rank.KING }.map { Card(suit, it) }+ }+ return KlondikeState(+ stock = listOf(c(Suit.SPADES, Rank.KING)),+ waste = listOf(c(Suit.HEARTS, Rank.KING)),+ tableauPiles = sevenPiles(+ TableauPile(faceUp = listOf(c(Suit.DIAMONDS, Rank.KING))),+ TableauPile(faceUp = listOf(c(Suit.CLUBS, Rank.KING))),+ ),+ foundations = foundations,+ elapsedSeconds = 42,+ )+ }++ @Test fun autoCompleteSimulationIsLegalStepSequence() {+ val vm = vm()+ val state = almostWonState()+ setK(vm, state)+ val (steps, finalState) = vm.simulateKlondikeAutoComplete(state)+ // Four kings fly: waste hearts, two tableau kings, then the stock spade.+ assertEquals(4, steps.size)+ assertEquals(listOf("waste", "tableau_0_0", "tableau_1_0", "waste"), steps.map { it.sourceId })+ assertEquals(listOf(0, 1, 3, 2), steps.map { it.foundationIndex })+ // Every step moves exactly the foundation count up by one and+ // chains: each step starts where the previous one ended.+ var previous = state+ for (step in steps) {+ val before = previous.foundations.sumOf { it.size }+ val after = step.stateAfter.foundations.sumOf { it.size }+ assertEquals(before + 1, after)+ assertEquals(step.card, step.stateAfter.foundations[step.foundationIndex].last())+ previous = step.stateAfter+ }+ assertTrue(finalState.foundations.all { it.size == 13 })+ assertTrue(finalState.stock.isEmpty() && finalState.waste.isEmpty())+ // The simulation agrees with the instant completion's end state.+ vm.klondikeAutoComplete()+ val instant = vm.uiState.value.klondike!!+ assertEquals(finalState.foundations, instant.foundations)+ assertEquals(finalState.moveCount, instant.moveCount)+ assertTrue(instant.isWon)+ }++ @Test fun animatedAutoCompleteCascadesAndUndoesAsOneStep() = runTest {+ val dispatcher = StandardTestDispatcher(testScheduler)+ Dispatchers.setMain(dispatcher)+ try {+ val vm = vm()+ val state = almostWonState()+ setK(vm, state)+ vm.cardPositions["waste"] = Rect(0f, 0f, 60f, 84f)+ vm.cardPositions["tableau_0_0"] = Rect(100f, 200f, 160f, 284f)+ vm.cardPositions["tableau_1_0"] = Rect(200f, 200f, 260f, 284f)+ for (fi in 0 until 4) vm.dropTargets["foundation_$fi"] = Rect(300f + fi * 70f, 0f, 360f + fi * 70f, 84f)+ vm.klondikeAutoCompleteAnimated()+ runCurrent()+ // First flight is up; nothing has landed yet, one history entry.+ assertNotNull(vm.animatedMove.value)+ assertEquals(12, vm.uiState.value.klondike!!.foundations[0].size)+ assertEquals(1, vm.uiState.value.history.size)+ // Let the whole cascade play out.+ advanceTimeBy((AUTO_COMPLETE_STEP_MILLIS + AUTO_COMPLETE_GAP_MILLIS) * 10L)+ runCurrent()+ val k = vm.uiState.value.klondike!!+ assertNull(vm.animatedMove.value)+ assertTrue(k.isWon)+ assertTrue(k.foundations.all { it.size == 13 })+ assertEquals(1, vm.uiState.value.history.size)+ // The cascade is a single undo step, like the instant completion.+ vm.undo()+ val restored = vm.uiState.value.klondike!!+ assertFalse(restored.isWon)+ assertEquals(state.foundations, restored.foundations)+ assertEquals(state.waste, restored.waste)+ assertTrue(restored.usedUndo)+ } finally {+ Dispatchers.resetMain()+ }+ }+ @Test fun animatedTapMoveWithoutGeometryAppliesInstantly() { val vm = vm() val ace = c(Suit.HEARTS, Rank.ACE)