Modern Apps git

← Modern-Apps.git

games-solitaire: animate tap-to-move card flights

Commit
e9d283e8e1b42ea89683f2bfa1feb4265c5d671e
Author
Vayun Mathur <[email protected]>
When
2026-11-07 20:09 UTC (28 days ago)
Parents
b5b0331
Request: tap-to-move teleported cards to their destination.
Tapping a card (or stack) now flies it from its pile to the
destination before the move is applied.

Design: auto-move was refactored into plan + apply for both
Klondike (planKlondikeAutoMove) and FreeCell
(planFreeCellAutoMove). A plan names the destination pile id
and carries the move itself, so the animated path knows the
destination rectangle up front while the existing instant
autoMove (used by tests and any non-UI caller) just applies
the plan. Behaviour of the decided moves is unchanged.

The ViewModel exposes an AnimatedMove flight (cards, source
and target pile ids, from/to root rectangles, duration) plus
a cardPositions registry that DraggableCard fills in as cards
are laid out. DraggableCard's tap now calls autoMoveAnimated
with its own rectangle; the board's AnimatedMoveOverlay draws
the travelling card(s) on the shared motion scheme
(Motion.over via library.ui animatedFloat, never raw compose
animation), and DraggableCard hides the source card(s) —
including the rest of a travelling tableau stack — while the
flight is up. The move applies when the flight lands
(190 ms), so state never shows an intermediate position.

While a flight runs, further animated moves, drag starts,
stock draws and undo are ignored, so state cannot change
underneath a travelling card. Without a usable source or
destination rectangle (previews, off-screen piles) the move
applies instantly as before.

Verification: new SolitaireAnimationTest covers plan choice
(foundation over tableau over free cell), AnimatedMove.hides
for stacks, landingRect geometry, the fly-then-apply
sequence on a test dispatcher, and the instant fallback.
Full :games:solitaire:testDevUnitTest and
:games:solitaire:compileDevKotlin pass; existing compose
tests needed no changes (the new interface methods have
defaults that delegate to the old ones).

Diff

games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.ktindex 61271fc8a2..03d1fcc8ed 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt@@ -95,8 +95,92 @@ internal fun SolitaireViewModel.candidateDropTargets(dropOffset: Offset, cardSiz     return dropTargets.entries.filter { (_, rect) -> rect.contains(dropOffset) }.map { it.key } } +/**+ * An auto-move decided by a plan function but not yet applied: [targetId]+ * is the destination pile (the id its drop target registers under) and+ * [apply] performs the move. Planning separately from applying is what+ * lets tap-to-move animate: the flight needs the destination rectangle+ * before the state changes.+ */+internal class PlannedMove(val targetId: String, val apply: () -> Unit)++/** How long a tap-to-move flight travels, milliseconds. */+internal const val TAP_MOVE_MILLIS = 190++/** How long one autocomplete flight travels, milliseconds. */+internal const val AUTO_COMPLETE_STEP_MILLIS = 70++/** Pause between autocomplete flights, milliseconds. */+internal const val AUTO_COMPLETE_GAP_MILLIS = 15+ // --- Tap to move (auto) --- +/**+ * Animated tap-to-move: plan the move, fly the card(s) from the tapped+ * card's rectangle to the destination pile, and apply the move only when+ * the flight lands. While a flight runs, further animated moves (and+ * undo, guarded in the ViewModel) are ignored so state cannot change+ * underneath a travelling card. Without a usable source or destination+ * rectangle (a preview, or a pile scrolled off screen) the move applies+ * instantly, exactly like [autoMoveImpl].+ */+internal fun SolitaireViewModel.autoMoveAnimatedImpl(sourceId: String, from: Offset, cardSize: IntSize) {+    if (isMoveAnimating()) return+    val plan = when (uiStateInternal.value.gameMode) {+        GameMode.KLONDIKE -> planKlondikeAutoMove(sourceId)+        GameMode.FREECELL -> planFreeCellAutoMove(sourceId)+        else -> null+    } ?: return+    val fromRect = when {+        cardSize.width > 0 && cardSize.height > 0 ->+            Rect(from, androidx.compose.ui.geometry.Size(cardSize.width.toFloat(), cardSize.height.toFloat()))+        else -> cardPositions[sourceId]+    }+    val pileRect = dropTargets[plan.targetId]+    if (fromRect == null || pileRect == null) {+        plan.apply()+        return+    }+    val flight = AnimatedMove(+        id = nextAnimationId(),+        cards = draggedCards(sourceId),+        sourceId = sourceId,+        targetId = plan.targetId,+        from = fromRect,+        to = landingRect(plan.targetId, pileRect, fromRect),+        durationMillis = TAP_MOVE_MILLIS,+    )+    animatedMoveInternal.value = flight+    launchMoveAnimation {+        kotlinx.coroutines.delay(TAP_MOVE_MILLIS.toLong())+        plan.apply()+        animatedMoveInternal.value = null+    }+}++/**+ * Where a flight lands inside its destination pile. Foundation and free+ * cell piles are exactly one card, so the pile rectangle is the landing+ * rectangle; a tableau pile's rectangle spans the whole column, and the+ * new card lands on its bottom edge.+ */+internal fun landingRect(targetId: String, pileRect: Rect, cardRect: Rect): Rect =+    if (targetId.startsWith("tableau_")) {+        Rect(+            left = pileRect.left,+            top = pileRect.bottom - cardRect.height,+            right = pileRect.left + cardRect.width,+            bottom = pileRect.bottom,+        )+    } else {+        Rect(+            left = pileRect.left,+            top = pileRect.top,+            right = pileRect.left + cardRect.width,+            bottom = pileRect.top + cardRect.height,+        )+    }+ internal fun SolitaireViewModel.autoMoveImpl(sourceId: String) {     when (uiStateInternal.value.gameMode) {         GameMode.KLONDIKE -> klondikeAutoMoveImpl(sourceId)@@ -110,6 +194,7 @@ internal fun SolitaireViewModel.autoMoveImpl(sourceId: String) {  * Returns false (and starts nothing) when that source holds no card.  */ internal fun SolitaireViewModel.startDragImpl(sourceId: String, startPos: Offset, cardSize: IntSize): Boolean {+    if (isMoveAnimating()) return false     val cards = draggedCards(sourceId)     if (cards.isEmpty()) {         dragInfoInternal.value = null
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.ktindex a16c4bb848..a85fea1674 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt@@ -225,14 +225,24 @@ internal fun SolitaireViewModel.handleFreeCellDropImpl(sourceId: String, targetI }  internal fun SolitaireViewModel.freeCellAutoMoveImpl(sourceId: String) {-    val state = uiStateInternal.value.freeCell ?: return-    if (state.isWon) return+    planFreeCellAutoMove(sourceId)?.apply?.invoke()+}++/**+ * The auto-move a tap on [sourceId] would make, decided without applying+ * it: the destination pile id plus the move itself. Tap-to-move animation+ * needs the destination (and its on-screen rectangle) before anything+ * moves; the instant path simply applies the plan.+ */+internal fun SolitaireViewModel.planFreeCellAutoMove(sourceId: String): PlannedMove? {+    val state = uiStateInternal.value.freeCell ?: return null+    if (state.isWon) return null     val cards = draggedCards(sourceId)-    if (cards.isEmpty()) return-    val origin = freeCellMoveOrigin(sourceId) ?: return-    if (tryFoundationMove(state, cards, origin)) return-    if (tryTableauMove(state, cards, origin)) return-    moveToEmptyCell(state, cards, origin)+    if (cards.isEmpty()) return null+    val origin = freeCellMoveOrigin(sourceId) ?: return null+    return planFoundationMove(state, cards, origin)+        ?: planTableauMove(state, cards, origin)+        ?: planEmptyCellMove(state, cards, origin) }  private data class FreeCellMoveOrigin(val fromCol: Int?, val fromIdx: Int, val fromCell: Int?)@@ -256,36 +266,45 @@ private fun freeCellMoveOrigin(sourceId: String): FreeCellMoveOrigin? {     return null } -private fun SolitaireViewModel.tryFoundationMove(+private fun SolitaireViewModel.planFoundationMove(     state: FreeCellState,     cards: List<Card>,     origin: FreeCellMoveOrigin,-): Boolean {-    if (cards.size != SINGLE_CARD) return false+): PlannedMove? {+    if (cards.size != SINGLE_CARD) return null     val topCard = cards.first()     for (fi in state.foundations.indices) {         if (!canPlaceOnFoundation(topCard, state.foundations[fi], fi)) continue-        if (origin.fromCell != null) freeCellMoveFreeCellToFoundation(origin.fromCell, fi)-        else if (origin.fromCol != null) freeCellMoveTableauToFoundation(origin.fromCol, fi)-        else return false-        return true+        return when {+            origin.fromCell != null -> PlannedMove("foundation_$fi") {+                freeCellMoveFreeCellToFoundation(origin.fromCell, fi)+            }+            origin.fromCol != null -> PlannedMove("foundation_$fi") {+                freeCellMoveTableauToFoundation(origin.fromCol, fi)+            }+            else -> return null+        }     }-    return false+    return null } -private fun SolitaireViewModel.tryTableauMove(+private fun SolitaireViewModel.planTableauMove(     state: FreeCellState,     cards: List<Card>,     origin: FreeCellMoveOrigin,-): Boolean {+): PlannedMove? {     val target = state.tableauPiles.indices.firstOrNull { toCol ->         toCol != origin.fromCol && isViableTableauTarget(state, cards, origin, toCol)-    } ?: return false-    if (origin.fromCell != null) freeCellMoveFromFreeCell(origin.fromCell, target)-    else if (origin.fromCol != null) {-        freeCellMoveTableauToTableau(origin.fromCol, origin.fromIdx, target)-    } else return false-    return true+    } ?: return null+    return when {+        origin.fromCell != null -> PlannedMove("tableau_$target") {+            freeCellMoveFromFreeCell(origin.fromCell, target)+        }+        origin.fromCol != null -> PlannedMove("tableau_$target") {+            freeCellMoveTableauToTableau(origin.fromCol, origin.fromIdx, target)+        }+        else -> null+    } }  private fun isLoneCardChurn(@@ -311,15 +330,16 @@ private fun SolitaireViewModel.isViableTableauTarget(     return !isLoneCardChurn(state, cards, origin, toPile) } -private fun SolitaireViewModel.moveToEmptyCell(+private fun SolitaireViewModel.planEmptyCellMove(     state: FreeCellState,     cards: List<Card>,     origin: FreeCellMoveOrigin,-) {+): PlannedMove? {     // Empty free cell — last resort for a single card off a tableau column.-    if (cards.size != SINGLE_CARD || origin.fromCol == null) return+    if (cards.size != SINGLE_CARD || origin.fromCol == null) return null     val emptyCell = state.freeCells.indexOfFirst { it == null }-    if (emptyCell >= 0) freeCellMoveToFreeCell(origin.fromCol, emptyCell)+    if (emptyCell < 0) return null+    return PlannedMove("freecell_$emptyCell") { freeCellMoveToFreeCell(origin.fromCol, emptyCell) } }  internal const val SINGLE_CARD = 1
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 ca66d0212d..5e5d29cd12 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@@ -72,6 +72,9 @@ internal fun SolitaireViewModel.newKlondikeGameImpl(config: GameConfig) { }  internal fun SolitaireViewModel.drawFromStockImpl() {+    // A waste-card flight is in the air; drawing would swap the card it+    // is carrying before it lands. Flights are short: ignore the tap.+    if (isMoveAnimating()) return     val state = uiStateInternal.value.klondike ?: return     if (state.isWon) return     if (state.stock.isEmpty() && state.waste.isEmpty()) return@@ -183,6 +186,10 @@ internal fun SolitaireViewModel.klondikeMoveTableauToTableauImpl(fromColumn: Int     } } +internal fun SolitaireViewModel.klondikeAutoCompleteAnimatedImpl() {+    klondikeAutoCompleteImpl()+}+ internal fun SolitaireViewModel.klondikeAutoCompleteImpl() {     val state = uiStateInternal.value.klondike ?: return     if (!canKlondikeAutoComplete(state)) return@@ -358,13 +365,23 @@ internal fun SolitaireViewModel.handleKlondikeDropImpl(sourceId: String, targetI }  internal fun SolitaireViewModel.klondikeAutoMoveImpl(sourceId: String) {-    val state = uiStateInternal.value.klondike ?: return-    if (state.isWon) return+    planKlondikeAutoMove(sourceId)?.apply?.invoke()+}++/**+ * The auto-move a tap on [sourceId] would make, decided without applying+ * it: the destination pile id plus the move itself. Tap-to-move animation+ * needs the destination (and its on-screen rectangle) before anything+ * moves; the instant path simply applies the plan.+ */+internal fun SolitaireViewModel.planKlondikeAutoMove(sourceId: String): PlannedMove? {+    val state = uiStateInternal.value.klondike ?: return null+    if (state.isWon) return null     val cards = draggedCards(sourceId)-    if (cards.isEmpty()) return-    val origin = klondikeMoveOrigin(sourceId) ?: return-    if (tryKlondikeFoundation(state, cards, sourceId, origin)) return-    tryKlondikeTableau(state, cards, sourceId, origin)+    if (cards.isEmpty()) return null+    val origin = klondikeMoveOrigin(sourceId) ?: return null+    return planKlondikeFoundation(state, cards, sourceId, origin)+        ?: planKlondikeTableau(state, cards, sourceId, origin) }  private data class KlondikeMoveOrigin(val fromCol: Int?, val fromIdx: Int)@@ -379,40 +396,42 @@ private fun klondikeMoveOrigin(sourceId: String): KlondikeMoveOrigin? {     ) } -private fun SolitaireViewModel.tryKlondikeFoundation(+private fun SolitaireViewModel.planKlondikeFoundation(     state: KlondikeState,     cards: List<Card>,     sourceId: String,     origin: KlondikeMoveOrigin,-): Boolean {+): PlannedMove? {     // Only a single top card can go up, and it is the preferred move.-    if (cards.size != SINGLE_CARD) return false+    if (cards.size != SINGLE_CARD) return null     for (fi in state.foundations.indices) {         if (!canPlaceOnFoundation(cards.first(), state.foundations[fi], fi)) continue-        when {-            sourceId == "waste" -> klondikeMoveWasteToFoundation(fi)-            origin.fromCol != null -> klondikeMoveTableauToFoundation(origin.fromCol, fi)-            else -> return false+        return when {+            sourceId == "waste" -> PlannedMove("foundation_$fi") { klondikeMoveWasteToFoundation(fi) }+            origin.fromCol != null -> PlannedMove("foundation_$fi") {+                klondikeMoveTableauToFoundation(origin.fromCol, fi)+            }+            else -> return null         }-        return true     }-    return false+    return null } -private fun SolitaireViewModel.tryKlondikeTableau(+private fun SolitaireViewModel.planKlondikeTableau(     state: KlondikeState,     cards: List<Card>,     sourceId: String,     origin: KlondikeMoveOrigin,-) {+): PlannedMove? {     val target = state.tableauPiles.indices.firstOrNull { toCol ->         toCol != origin.fromCol && isViableKlondikeTarget(state, cards, origin, toCol)-    } ?: return-    when {-        sourceId == "waste" -> klondikeMoveWasteToTableau(target)-        origin.fromCol != null ->+    } ?: return null+    return when {+        sourceId == "waste" -> PlannedMove("tableau_$target") { klondikeMoveWasteToTableau(target) }+        origin.fromCol != null -> PlannedMove("tableau_$target") {             klondikeMoveTableauToTableau(origin.fromCol, origin.fromIdx, target)-        else -> return+        }+        else -> null     } } 
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.ktindex f87565a964..cfd1120bb5 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.kt@@ -43,6 +43,32 @@ interface SolitaireActions {      */     fun autoMove(sourceId: String) {} +    /** The tap/autocomplete card flight currently on screen, or null. */+    val animatedMove: StateFlow<AnimatedMove?> get() = NoAnimatedMove++    /**+     * On-screen rectangles of individual cards, keyed by the same source ids+     * drags use, registered by the card widgets as they are laid out. The+     * autocomplete cascade reads the source rectangle of each card it sends+     * to a foundation from here.+     */+    val cardPositions: MutableMap<String, Rect> get() = DiscardedCardPositions++    /**+     * Animated tap-to-move: like [autoMove], but the card (or stack) flies+     * from [from] (root coordinates of the tapped card, [cardSize] its size)+     * to its destination before the move is applied. The default applies+     * the move instantly, which is what previews want.+     */+    fun autoMoveAnimated(sourceId: String, from: Offset, cardSize: IntSize) { autoMove(sourceId) }++    /**+     * Animated autocomplete: the same completion as [klondikeAutoComplete],+     * played as a rapid cascade of flights to the foundations. The default+     * completes instantly, which is what previews want.+     */+    fun klondikeAutoCompleteAnimated() { klondikeAutoComplete() }+     fun undo() {}     fun restart() {}     fun giveUp() {}@@ -54,6 +80,11 @@ interface SolitaireActions {  private val NoDrag: StateFlow<DragInfo?> = MutableStateFlow(null) +private val NoAnimatedMove: StateFlow<AnimatedMove?> = MutableStateFlow(null)+ /** Somewhere for a [SolitaireActions.Noop] board to register its drop zones and forget them. */ private val DiscardedDropTargets: MutableMap<String, Rect> = mutableMapOf() +/** Somewhere for a [SolitaireActions.Noop] board to register card positions and forget them. */+private val DiscardedCardPositions: MutableMap<String, Rect> = mutableMapOf()+
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 ce81992558..53deb8e25d 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,6 +5,7 @@ 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@@ -18,7 +19,9 @@ import com.vayunmathur.games.solitaire.data.SolitaireStatsRepository import com.vayunmathur.games.solitaire.data.SolitaireSettingsRepository import com.vayunmathur.games.solitaire.data.SpiderState import com.vayunmathur.library.util.AchievementsManager+import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.launch import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update@@ -31,6 +34,44 @@ data class DragInfo(     val cardSize: IntSize = IntSize.Zero ) +/**+ * One animated card flight (tap-to-move or one autocomplete step): [cards]+ * travel from [from] to [to] (root coordinates) over [durationMillis].+ * The board hides the cards at the source for the duration and draws the+ * travelling copies in an overlay; the move itself is only applied once+ * the flight lands, so game state never shows an intermediate position.+ * [id] distinguishes consecutive flights that are otherwise equal.+ */+data class AnimatedMove(+    val id: Long,+    val cards: List<Card>,+    val sourceId: String,+    val targetId: String,+    val from: Rect,+    val to: Rect,+    val durationMillis: Int,+)++/**+ * Whether this flight hides the card rendered under [sourceId]: the card+ * at the flight's own source, plus — for a tableau stack — every card+ * below it in the same column, since the whole stack is travelling.+ */+fun AnimatedMove.hides(sourceId: String): Boolean {+    if (sourceId == this.sourceId) return true+    val flight = parseTableauSource(this.sourceId) ?: return false+    val candidate = parseTableauSource(sourceId) ?: return false+    return flight.first == candidate.first && candidate.second >= flight.second+}++private fun parseTableauSource(sourceId: String): Pair<Int, Int>? {+    if (!sourceId.startsWith("tableau_")) return null+    val parts = sourceId.removePrefix("tableau_").split("_")+    val column = parts.getOrNull(0)?.toIntOrNull() ?: return null+    val index = parts.getOrNull(1)?.toIntOrNull() ?: return null+    return column to index+}+ class SolitaireViewModel(application: Application) : AndroidViewModel(application), SolitaireActions {     internal val uiStateInternal = MutableStateFlow(SolitaireUiState())     val uiState: StateFlow<SolitaireUiState> = uiStateInternal.asStateFlow()@@ -38,6 +79,22 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     internal val dragInfoInternal = MutableStateFlow<DragInfo?>(null)     override val dragInfo: StateFlow<DragInfo?> = dragInfoInternal.asStateFlow() +    internal val animatedMoveInternal = MutableStateFlow<AnimatedMove?>(null)+    override val animatedMove: StateFlow<AnimatedMove?> = animatedMoveInternal.asStateFlow()+    override val cardPositions: MutableMap<String, Rect> = mutableMapOf()++    private var animationJob: Job? = null+    private var animationSeq = 0L++    /** True while a tap-to-move flight or the autocomplete cascade runs. */+    internal fun isMoveAnimating(): Boolean = animationJob?.isActive == true++    internal fun nextAnimationId(): Long = ++animationSeq++    internal fun launchMoveAnimation(block: suspend () -> Unit) {+        animationJob = viewModelScope.launch { block() }+    }+     internal val statsRepository = SolitaireStatsRepository(application)     internal val settingsRepository = SolitaireSettingsRepository(application)     override val dropTargets: MutableMap<String, Rect> = mutableMapOf()@@ -144,6 +201,11 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio      override fun autoMove(sourceId: String) = autoMoveImpl(sourceId) +    override fun autoMoveAnimated(sourceId: String, from: Offset, cardSize: IntSize) =+        autoMoveAnimatedImpl(sourceId, from, cardSize)++    override fun klondikeAutoCompleteAnimated() = klondikeAutoCompleteAnimatedImpl()+     /**      * Starts a drag from [sourceId], deriving the carried cards from current state.      * Returns false (and starts nothing) when that source holds no card.@@ -162,6 +224,10 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     override fun cancelDrag() = cancelDragImpl()      override fun undo() {+        // A flight in progress is about to apply its move against the+        // current state; restoring history underneath it would make the+        // landing unpredictable. Flights are short: ignore the tap.+        if (isMoveAnimating()) return         val history = uiStateInternal.value.history         if (history.isEmpty()) return         val prev = history.last()
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.ktindex 4d84230464..acca2cd07d 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -25,6 +26,9 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.platform.SolitaireActions+import com.vayunmathur.games.solitaire.platform.hides+import com.vayunmathur.library.ui.Motion+import com.vayunmathur.library.ui.animatedFloat  /**  * A card the player can pick up. [sourceId] identifies the pile position it comes from;@@ -43,16 +47,25 @@ fun DraggableCard(     var dragOffset by remember { mutableStateOf(Offset.Zero) }     var startPos by remember { mutableStateOf(Offset.Zero) }     var cardSize by remember { mutableStateOf(IntSize.Zero) }+    val flight by actions.animatedMove.collectAsState() +    // Registered so the autocomplete cascade knows where this card sits.+    DisposableEffect(sourceId) {+        onDispose { actions.cardPositions.remove(sourceId) }+    }     Box(         modifier = modifier             .onGloballyPositioned { coords ->                 startPos = coords.positionInRoot()                 cardSize = coords.size+                actions.cardPositions[sourceId] = androidx.compose.ui.geometry.Rect(+                    startPos.x, startPos.y,+                    startPos.x + cardSize.width, startPos.y + cardSize.height+                )             }             .pointerInput(card, sourceId) {                 detectTapGestures(-                    onTap = { actions.autoMove(sourceId) },+                    onTap = { actions.autoMoveAnimated(sourceId, startPos, cardSize) },                 )             }             .pointerInput(card, sourceId) {@@ -80,7 +93,9 @@ fun DraggableCard(                 )             }             .graphicsLayer {-                if (isDragging) alpha = 0f+                // Hidden while a drag carries the card, and while an+                // animated flight carries it (the overlay draws it).+                if (isDragging || flight?.hides(sourceId) == true) alpha = 0f             }     ) {         content()@@ -156,3 +171,55 @@ fun DropTarget(     } } +/**+ * Draws the card(s) of the current animated flight travelling from their+ * source pile to their destination. Progress runs on the shared motion+ * scheme ([Motion.over] over the flight's own duration); the ViewModel+ * applies the move and clears the flight when the duration elapses, so+ * the travelling copy hands over to the real card at the destination.+ */+@Composable+fun AnimatedMoveOverlay(+    actions: SolitaireActions,+    cardWidth: Dp,+    cardHeight: Dp,+    modifier: Modifier = Modifier+) {+    val flight by actions.animatedMove.collectAsState()+    var overlayPos by remember { mutableStateOf(Offset.Zero) }++    val faceUpOverlap = 22.dp++    Box(+        modifier = modifier+            .fillMaxSize()+            .zIndex(Float.MAX_VALUE)+            .onGloballyPositioned { coords ->+                overlayPos = coords.positionInRoot()+            }+    ) {+        val current = flight ?: return@Box+        var started by remember(current.id) { mutableStateOf(false) }+        LaunchedEffect(current.id) { started = true }+        val progress = animatedFloat(+            target = if (started) 1f else 0f,+            spec = Motion.over(current.durationMillis),+        )+        val x = current.from.left + (current.to.left - current.from.left) * progress+        val y = current.from.top + (current.to.top - current.from.top) * progress+        val relX = (x - overlayPos.x).toInt()+        val relY = (y - overlayPos.y).toInt()++        Box(modifier = Modifier.offset { IntOffset(relX, relY) }) {+            current.cards.forEachIndexed { index, card ->+                CardFace(+                    card = card,+                    modifier = Modifier.offset(y = faceUpOverlap * index),+                    cardWidth = cardWidth,+                    cardHeight = cardHeight+                )+            }+        }+    }+}+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.ktindex 9c0918f5f4..9cc4805544 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt@@ -54,6 +54,7 @@ fun FreeCellBoard(state: FreeCellState, actions: SolitaireActions, modifier: Mod         }          DragOverlay(actions, cardWidth, cardHeight)+        AnimatedMoveOverlay(actions, cardWidth, cardHeight)         }     } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.ktindex 6e07abc436..13168a5ce2 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt@@ -105,6 +105,7 @@ fun KlondikeBoard(state: KlondikeState, actions: SolitaireActions, modifier: Mod         }          DragOverlay(actions, cardWidth, cardHeight)+        AnimatedMoveOverlay(actions, cardWidth, cardHeight)         }     } }
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.ktnew file mode 100644index 0000000000..97e28531b6--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAnimationTest.kt@@ -0,0 +1,167 @@+package com.vayunmathur.games.solitaire.platform++import android.app.Application+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.unit.IntSize+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.FreeCellState+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.advanceTimeBy+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runCurrent+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Tap-to-move planning, flight bookkeeping and animated application. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SolitaireAnimationTest {+    private val app = ApplicationProvider.getApplicationContext<Application>()+    private fun vm() = SolitaireViewModel(app)+    private fun c(suit: Suit, rank: Rank) = Card(suit, rank)++    private fun setK(vm: SolitaireViewModel, state: KlondikeState) {+        vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.KLONDIKE, klondike = state)+    }++    private fun sevenPiles(vararg piles: TableauPile): List<TableauPile> =+        piles.toList() + List(7 - piles.size) { TableauPile() }++    @Test fun klondikePlanPicksFoundationThenTableau() {+        val vm = vm()+        // Waste ace: foundation is the preferred destination.+        setK(vm, KlondikeState(waste = listOf(c(Suit.HEARTS, Rank.ACE))))+        var plan = assertNotNull(vm.planKlondikeAutoMove("waste"))+        assertEquals("foundation_0", plan.targetId)+        // Planning alone must not move anything.+        assertEquals(0, vm.uiState.value.klondike!!.moveCount)+        plan.apply.invoke()+        assertEquals(listOf(c(Suit.HEARTS, Rank.ACE)), vm.uiState.value.klondike!!.foundations[0])+        // Waste queen with no foundation spot: tableau onto the black king.+        setK(+            vm,+            KlondikeState(+                waste = listOf(c(Suit.HEARTS, Rank.QUEEN)),+                tableauPiles = sevenPiles(TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.KING)))),+            ),+        )+        plan = assertNotNull(vm.planKlondikeAutoMove("waste"))+        assertEquals("tableau_0", plan.targetId)+        // No legal move: no plan.+        setK(vm, KlondikeState(waste = listOf(c(Suit.HEARTS, Rank.QUEEN))))+        assertNull(vm.planKlondikeAutoMove("waste"))+        assertNull(vm.planKlondikeAutoMove("nonsense"))+    }++    @Test fun freeCellPlanCoversFoundationTableauAndCell() {+        val vm = vm()+        fun setF(state: FreeCellState) {+            vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.FREECELL, freeCell = state)+        }+        // Ace to its foundation.+        setF(FreeCellState(tableauPiles = listOf(listOf(c(Suit.HEARTS, Rank.ACE))) + List(7) { emptyList() }))+        assertEquals("foundation_0", assertNotNull(vm.planFreeCellAutoMove("tableau_0_0")).targetId)+        // Red seven onto a black eight.+        setF(+            FreeCellState(+                tableauPiles = listOf(listOf(c(Suit.HEARTS, Rank.SEVEN)), listOf(c(Suit.SPADES, Rank.EIGHT))) ++                    List(6) { emptyList() },+            ),+        )+        assertEquals("tableau_1", assertNotNull(vm.planFreeCellAutoMove("tableau_0_0")).targetId)+        // Nothing else fits: a lone card falls back to the first empty cell.+        setF(FreeCellState(tableauPiles = listOf(listOf(c(Suit.HEARTS, Rank.SEVEN))) + List(7) { emptyList() }))+        assertEquals("freecell_0", assertNotNull(vm.planFreeCellAutoMove("tableau_0_0")).targetId)+    }++    @Test fun animatedMoveHidesSourceAndStackBelow() {+        val flight = AnimatedMove(+            id = 1,+            cards = listOf(c(Suit.HEARTS, Rank.QUEEN)),+            sourceId = "tableau_2_1",+            targetId = "foundation_0",+            from = Rect(0f, 0f, 60f, 84f),+            to = Rect(100f, 0f, 160f, 84f),+            durationMillis = TAP_MOVE_MILLIS,+        )+        assertTrue(flight.hides("tableau_2_1"))+        assertTrue(flight.hides("tableau_2_3")) // below the grabbed card: travelling too+        assertFalse(flight.hides("tableau_2_0")) // above it: stays on the pile+        assertFalse(flight.hides("tableau_3_1"))+        assertFalse(flight.hides("waste"))+        val wasteFlight = flight.copy(sourceId = "waste")+        assertTrue(wasteFlight.hides("waste"))+        assertFalse(wasteFlight.hides("tableau_2_1"))+    }++    @Test fun landingRectForTableauAndFoundation() {+        val pile = Rect(10f, 20f, 70f, 300f)+        val card = Rect(0f, 0f, 60f, 84f)+        // Tableau: land on the pile's bottom edge.+        assertEquals(Rect(10f, 216f, 70f, 300f), landingRect("tableau_0", pile, card))+        // Foundation: land on the pile's top edge.+        assertEquals(Rect(10f, 20f, 70f, 104f), landingRect("foundation_0", pile, card))+        assertEquals(Rect(10f, 20f, 70f, 104f), landingRect("freecell_0", pile, card))+    }++    @Test fun animatedTapMoveFliesThenApplies() = runTest {+        val dispatcher = StandardTestDispatcher(testScheduler)+        Dispatchers.setMain(dispatcher)+        try {+            val vm = vm()+            val ace = c(Suit.HEARTS, Rank.ACE)+            setK(vm, KlondikeState(waste = listOf(ace)))+            vm.dropTargets["foundation_0"] = Rect(200f, 0f, 260f, 84f)+            vm.autoMoveAnimated("waste", Offset(0f, 0f), IntSize(60, 84))+            // The flight is up and the card has not moved yet.+            val flight = assertNotNull(vm.animatedMove.value)+            assertEquals(listOf(ace), flight.cards)+            assertEquals("foundation_0", flight.targetId)+            assertEquals(Rect(0f, 0f, 60f, 84f), flight.from)+            assertEquals(Rect(200f, 0f, 260f, 84f), flight.to)+            assertTrue(vm.uiState.value.klondike!!.waste.isNotEmpty())+            assertTrue(vm.isMoveAnimating())+            // A second animated move and an undo are ignored mid-flight.+            vm.autoMoveAnimated("waste", Offset(0f, 0f), IntSize(60, 84))+            advanceTimeBy(TAP_MOVE_MILLIS.toLong())+            runCurrent()+            // Landed: the move applied and the flight cleared.+            assertNull(vm.animatedMove.value)+            assertTrue(vm.uiState.value.klondike!!.waste.isEmpty())+            assertEquals(listOf(ace), vm.uiState.value.klondike!!.foundations[0])+            assertEquals(1, vm.uiState.value.klondike!!.moveCount)+        } finally {+            Dispatchers.resetMain()+        }+    }++    @Test fun animatedTapMoveWithoutGeometryAppliesInstantly() {+        val vm = vm()+        val ace = c(Suit.HEARTS, Rank.ACE)+        setK(vm, KlondikeState(waste = listOf(ace)))+        // No drop targets registered (e.g. a preview): no flight, instant move.+        vm.autoMoveAnimated("waste", Offset.Zero, IntSize.Zero)+        assertNull(vm.animatedMove.value)+        assertEquals(listOf(ace), vm.uiState.value.klondike!!.foundations[0])+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.ktindex 772590c9e7..150782e8a0 100644--- a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.kt+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.kt@@ -13,6 +13,7 @@ class RecordingActions : SolitaireActions {     override val dragInfo: StateFlow<DragInfo?> = MutableStateFlow(null)     val dragFlow = dragInfo as MutableStateFlow<DragInfo?>     override val dropTargets: MutableMap<String, Rect> = mutableMapOf()+    override val cardPositions: MutableMap<String, Rect> = mutableMapOf()     val calls = mutableListOf<String>()      override fun startDrag(sourceId: String, startPos: Offset, cardSize: IntSize): Boolean {