Modern Apps git

← Modern-Apps.git

solitaire: concurrent tap-to-move flights landing on exact slot (#owner-report)

Commit
811fc6a18cce472cd2fab72ff5117453de7a013a
Author
Vayun Mathur <[email protected]>
When
2026-11-12 20:40 UTC (23 days ago)
Parents
d8fc1d2
Symptom (owner report): tap-to-move flew the card to the wrong spot
and it then snapped into place; tapping another card while one was
still moving cancelled or blocked the second move; the flying stack
was clipped at the bottom of the screen.

Root causes:
- Wrong landing spot: CardFlightOverlay aimed at the destination's
  drop rectangle as `bottom - cardHeight`. A tableau column's rect
  ends at its current last card, so the flight landed ON that card,
  one fan step (22dp) short of the slot the card is drawn at after
  the move; the commit then re-laid the pile and the card jumped.
- No concurrency: there was a single nullable flight, the move only
  committed on landing, and requestFlight/startDrag refused while
  any flight was staged, so a second tap was dropped and logical
  state lagged behind the animation.
- Clipping: the overlays lived inside each board, i.e. inside the
  screen's verticalScroll column, whose viewport clips its content.

Fix:
- Flights are visual only. A tap resolves its target, applies the
  move to game state immediately through the same drop handler a
  drag ends in, then launches a CardFlight keyed by a fresh id. Any
  number fly at once (StateFlow<List<CardFlight>>), each on its own
  clock via library/ui travelledOffset; the layer reports landings
  through SolitaireActions.landFlight(id).
- Each flight targets a FlightTarget.Slot (pile, face-down count,
  index) read from the post-move state. The new ui/PileLayout.kt
  holds tableauCardOffset/pileSlotOffset, which the columns now use
  to draw every card and the motion layer uses to land flights, so
  the two cannot disagree; card size comes from the laid-out card.
- While a card flies, the board hides it in its new slot (PileRange
  matched on pile, index and card, so Spider's duplicate cards and
  stale ranges are safe), so each card is drawn exactly once. The
  foundation, waste (draw-one) and free cell draw the card beneath,
  or the empty outline, under a hidden top.
- A tap on cards still in the air is queued and replayed against the
  live state when they land; a drag of airborne cards is refused.
  Unrelated taps and drags proceed while others fly.
- New top-level CardMotionLayer in GameBoardScreen (outside the
  scroll column, zIndex above the board) replaces the per-board
  CardFlightOverlay; flying cards are drawn opaque.
- Auto-complete hops follow the same model: each step is applied,
  then flown; the run continues when its hop lands.
- One public composable per touched file: FreeCellTableauColumn,
  FreeCellSlot and DropTarget move to their own files;
  FoundationView.kt is renamed FoundationSlot.kt (AGENTS.md updated).

User-visible effect: a tapped card or run flies once, lands exactly
where it stays, and quick successive taps all play out.

Verification: SolitaireFlightTest rewritten (move applied at once,
exact slot for foundation/tableau-past-face-down/run/FreeCell,
second tap keeps the first move and flight, queued tap replay,
airborne drag refused); SolitaireAutoCompleteTest adapted.
:games:solitaire:testDevUnitTest in the container build.

Diff

games/solitaire/AGENTS.md
diff --git a/games/solitaire/AGENTS.md b/games/solitaire/AGENTS.mdindex 763abe8969..7b5a5b5b58 100644--- a/games/solitaire/AGENTS.md+++ b/games/solitaire/AGENTS.md@@ -47,7 +47,8 @@ _Install: ./install games/solitaire (dev by default)._ - com/vayunmathur/games/solitaire/ui/SpiderBoard.kt - com/vayunmathur/games/solitaire/ui/PyramidBoard.kt - com/vayunmathur/games/solitaire/ui/TableauColumn.kt-- com/vayunmathur/games/solitaire/ui/FoundationView.kt+- com/vayunmathur/games/solitaire/ui/FoundationSlot.kt+- com/vayunmathur/games/solitaire/ui/FreeCellSlot.kt - com/vayunmathur/games/solitaire/ui/CardView.kt - com/vayunmathur/games/solitaire/ui/DragAndDrop.kt - com/vayunmathur/games/solitaire/ui/GameActionBar.kt
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 1be9fbf120..1ec5d00967 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@@ -110,15 +110,14 @@ 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 {-    // No drag may start under a travelling flight: the cards live in game-    // state until the flight lands, so a mid-flight drag would corrupt both.-    if (flightInfoInternal.value != null) return false-    val cards = draggedCards(sourceId)-    if (cards.isEmpty()) {+    val range = sourceRange(sourceId)+    // Cards still in the air cannot be picked up: the hand would grab cards the+    // player cannot see where they are drawn. Other flights keep flying.+    if (range == null || isAirborne(range)) {         dragInfoInternal.value = null         return false     }-    dragInfoInternal.value = DragInfo(cards, sourceId, startPos, startPos, cardSize)+    dragInfoInternal.value = DragInfo(range.cards, sourceId, startPos, startPos, cardSize)     return true } 
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFlight.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFlight.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFlight.ktindex 533f441fb8..24f405cbf7 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFlight.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFlight.kt@@ -1,76 +1,265 @@ package com.vayunmathur.games.solitaire.platform  import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.unit.IntSize import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.data.GameMode+import kotlinx.coroutines.flow.update  /**- * A tap-to-move travelling to its destination.+ * A run of [cards] starting at [start] in pile [pileId].  *- * The cards keep living in game state until the flight lands: [commitFlightImpl]- * performs the move through the same drop handlers a drag ends in, so legality is- * re-validated at landing and a stale flight (state moved on underneath it) is a- * no-op rather than a corrupt move. [from] is the tap point in root coordinates;- * the overlay translates it into its own frame and derives the landing point from- * the target's registered drop rectangle.+ * Index semantics follow the drag source ids: a Klondike/Spider tableau index counts face-up+ * cards only, a FreeCell column is flat, the waste and a foundation index their own lists, and a+ * free cell is always 0. Matching on the card as well as the slot keeps a stale range (the state+ * moved on underneath it) from hiding whatever card now sits in that slot — and keeps Spider's+ * duplicate cards apart, which identity alone cannot.+ */+data class PileRange(val pileId: String, val start: Int, val cards: List<Card>) {++    /** Whether the card drawn at [index] of [pileId] is [card] and part of this run. */+    fun covers(pileId: String, index: Int, card: Card): Boolean =+        pileId == this.pileId && (index - start) in cards.indices && cards[index - start] == card++    /** Whether the two runs share a slot. */+    fun overlaps(other: PileRange): Boolean =+        pileId == other.pileId && start < other.start + other.cards.size && other.start < start + cards.size+}++/** Where a flight lands. */+sealed interface FlightTarget {++    /**+     * The slot the leading card occupies in its pile once the move has been applied. The board+     * turns it into a position with the same layout function it draws that slot with, so a+     * flight cannot land somewhere the card is not then drawn.+     */+    data class Slot(val pileId: String, val faceDownCount: Int, val index: Int) : FlightTarget++    /** A fixed root position: a rejected drag going back to where it was picked up. */+    data class Point(val position: Offset) : FlightTarget+}++/**+ * Cards travelling across the board. Purely visual: the move a flight shows has already been+ * applied to game state when the flight is launched, so the logical board never waits on an+ * animation and several flights can be in the air at once, each keyed by [id].+ *+ * While it flies, the board hides the cards in [hides] — where they now live in game state — so+ * each card is drawn exactly once: by the flight until it lands, then by its pile. [from] is the+ * leading card's top-left in root coordinates.  */ data class CardFlight(+    val id: Long,     val cards: List<Card>,-    val sourceId: String,-    val targetId: String,     val from: Offset,-    /** Fast auto-complete hops fly shorter than a tap-to-move. */+    val target: FlightTarget,+    val hides: PileRange,+    val cardSize: IntSize = IntSize.Zero,+    /** Auto-complete hops fly shorter than a tap-to-move. */     val fast: Boolean = false, ) +/** A tap on cards that were still in the air, replayed once they land. */+internal data class QueuedTap(val sourceId: String, val card: Card)+ /**- * Stages a flight for the card (or valid run) at [sourceId], resolving the same- * destination [autoMoveImpl] would take it to. False when there is no legal move,- * when [sourceId] holds no card, or when a flight is already in the air.+ * The run a tap or drag on [sourceId] would carry, located in its pile; null when the source+ * holds no card.  */-internal fun SolitaireViewModel.requestFlightImpl(sourceId: String, startPos: Offset): Boolean {-    if (flightInfoInternal.value != null) return false-    val targetId = when (uiStateInternal.value.gameMode) {+internal fun SolitaireViewModel.sourceRange(sourceId: String): PileRange? {+    val cards = draggedCards(sourceId)+    if (cards.isEmpty()) return null+    val state = uiStateInternal.value+    return when {+        sourceId == WASTE -> state.klondike?.waste?.let { PileRange(WASTE, it.lastIndex, cards) }+        sourceId.startsWith(FREECELL_PREFIX) -> PileRange(sourceId, 0, cards)+        sourceId.startsWith(FOUNDATION_PREFIX) -> {+            val fi = sourceId.removePrefix(FOUNDATION_PREFIX).toIntOrNull()+            currentFoundations()?.getOrNull(fi ?: -1)?.let { PileRange(sourceId, it.lastIndex, cards) }+        }+        sourceId.startsWith(TABLEAU_PREFIX) -> {+            val parts = sourceId.removePrefix(TABLEAU_PREFIX).split("_")+            val col = parts.getOrNull(0)?.toIntOrNull()+            val idx = parts.getOrNull(1)?.toIntOrNull()+            if (col == null || idx == null) null else PileRange("$TABLEAU_PREFIX$col", idx, cards)+        }+        else -> null+    }+}++/** Whether any card of [range] is still in the air. */+internal fun SolitaireViewModel.isAirborne(range: PileRange): Boolean =+    flightsInternal.value.any { it.hides.overlaps(range) }++private fun SolitaireViewModel.currentFoundations(): List<List<Card>>? = with(uiStateInternal.value) {+    when (gameMode) {+        GameMode.KLONDIKE -> klondike?.foundations+        GameMode.FREECELL -> freeCell?.foundations+        else -> null+    }+}++/**+ * Tap-to-move: resolves the destination [autoMoveImpl] would take [sourceId] to, applies the+ * move at once and launches its flight from [startPos]. A tap on cards still in the air is+ * queued and replayed when they land, so it can neither jump nor cancel the flight carrying+ * them. False when there is no legal move or [sourceId] holds no card.+ */+internal fun SolitaireViewModel.requestFlightImpl(sourceId: String, startPos: Offset, cardSize: IntSize): Boolean {+    val range = sourceRange(sourceId) ?: return false+    if (isAirborne(range)) {+        val tap = QueuedTap(sourceId, range.cards.first())+        if (tap !in queuedTaps) queuedTaps.addLast(tap)+        return true+    }+    val targetId = resolveAutoMoveTarget(sourceId) ?: return false+    return flyMove(sourceId, targetId, range.cards, startPos, cardSize)+}++private fun SolitaireViewModel.resolveAutoMoveTarget(sourceId: String): String? =+    when (uiStateInternal.value.gameMode) {         GameMode.KLONDIKE -> resolveKlondikeAutoMoveTarget(sourceId)         GameMode.FREECELL -> resolveFreeCellAutoMoveTarget(sourceId)         else -> null // Spider has no foundations; Pyramid is already tap-based.-    } ?: return false-    val cards = draggedCards(sourceId)-    if (cards.isEmpty()) return false-    flightInfoInternal.value = CardFlight(cards, sourceId, targetId, startPos)+    }++/**+ * Applies the move of [cards] from [sourceId] onto [targetId] through the same drop handler a+ * drag ends in, then — if it was legal — launches a flight from [from] (no flight when the+ * position is unknown). Returns whether the move was applied.+ */+internal fun SolitaireViewModel.flyMove(+    sourceId: String,+    targetId: String,+    cards: List<Card>,+    from: Offset?,+    cardSize: IntSize,+): Boolean {+    val before = uiStateInternal.value+    applyDrop(sourceId, targetId)+    if (uiStateInternal.value === before) return false+    if (from != null) launchFlight(cards, from, targetId, cardSize)     return true } +/** Dispatches a move to the current mode's drop handler; illegal moves leave state untouched. */+internal fun SolitaireViewModel.applyDrop(sourceId: String, targetId: String) {+    when (uiStateInternal.value.gameMode) {+        GameMode.KLONDIKE -> handleKlondikeDropImpl(sourceId, targetId)+        GameMode.SPIDER -> handleSpiderDropImpl(sourceId, targetId)+        GameMode.FREECELL -> handleFreeCellDropImpl(sourceId, targetId)+        GameMode.PYRAMID, null -> {}+    }+}++/**+ * Launches a flight of [cards] — already moved onto [targetId] in game state — from [from] to+ * the slot they now occupy there. Returns the flight, or null when the target is not a pile.+ */+internal fun SolitaireViewModel.launchFlight(+    cards: List<Card>,+    from: Offset,+    targetId: String,+    cardSize: IntSize,+    fast: Boolean = false,+): CardFlight? {+    val slot = landingSlot(targetId, cards) ?: return null+    val flight = CardFlight(+        id = nextFlightId++,+        cards = cards,+        from = from,+        target = slot,+        hides = PileRange(slot.pileId, slot.index, cards),+        cardSize = if (cardSize.width > 0 && cardSize.height > 0) cardSize else lastCardSize,+        fast = fast,+    )+    flightsInternal.update { it + flight }+    return flight+}++/** Launches a flight returning [cards] (never moved) from [from] to [home], hidden at [range]. */+internal fun SolitaireViewModel.launchReturnFlight(range: PileRange, from: Offset, home: Offset, cardSize: IntSize) {+    val flight = CardFlight(+        id = nextFlightId++,+        cards = range.cards,+        from = from,+        target = FlightTarget.Point(home),+        hides = range,+        cardSize = if (cardSize.width > 0 && cardSize.height > 0) cardSize else lastCardSize,+    )+    flightsInternal.update { it + flight }+}+ /**- * Lands the staged flight. Clears it first so the overlay lifts the moment the- * move commits; a flight whose source or target no longer applies is refused by- * the move functions themselves. A fast flight landing mid-run advances the- * auto-complete instead of going through the drop handlers.+ * The slot the leading card of [cards] occupies on [targetId] in the current (post-move) state.+ * A pile that no longer ends with the cards (a Spider run that completed and cleared) still+ * yields its next slot, and the flight's hidden range then matches nothing.  */-internal fun SolitaireViewModel.commitFlightImpl() {-    val flight = flightInfoInternal.value ?: return-    flightInfoInternal.value = null-    if (flight.fast && autoCompleteRunningInternal.value &&-        uiStateInternal.value.gameMode == GameMode.KLONDIKE-    ) {-        landAutoCompleteStep(flight)-        return+internal fun SolitaireViewModel.landingSlot(targetId: String, cards: List<Card>): FlightTarget.Slot? {+    val state = uiStateInternal.value+    return when {+        targetId.startsWith(FOUNDATION_PREFIX) -> {+            val fi = targetId.removePrefix(FOUNDATION_PREFIX).toIntOrNull() ?: return null+            val pile = currentFoundations()?.getOrNull(fi) ?: return null+            FlightTarget.Slot(targetId, 0, (pile.size - cards.size).coerceAtLeast(0))+        }+        targetId.startsWith(FREECELL_PREFIX) -> FlightTarget.Slot(targetId, 0, 0)+        targetId.startsWith(TABLEAU_PREFIX) -> {+            val col = targetId.removePrefix(TABLEAU_PREFIX).toIntOrNull() ?: return null+            val (faceDown, faceUp) = when (state.gameMode) {+                GameMode.KLONDIKE -> state.klondike?.tableauPiles?.getOrNull(col)?.let { it.faceDown.size to it.faceUp.size }+                GameMode.SPIDER -> state.spider?.tableauPiles?.getOrNull(col)?.let { it.faceDown.size to it.faceUp.size }+                GameMode.FREECELL -> state.freeCell?.tableauPiles?.getOrNull(col)?.let { 0 to it.size }+                else -> null+            } ?: return null+            FlightTarget.Slot(targetId, faceDown, (faceUp - cards.size).coerceAtLeast(0))+        }+        else -> null     }-    when (uiStateInternal.value.gameMode) {-        GameMode.KLONDIKE -> handleKlondikeDropImpl(flight.sourceId, flight.targetId)-        GameMode.FREECELL -> handleFreeCellDropImpl(flight.sourceId, flight.targetId)-        else -> {}+}++/**+ * A flight reached its destination: the board draws its cards in their pile again. The landing+ * of the auto-complete's current hop advances the run; queued taps whose cards are now down are+ * replayed against the live state.+ */+internal fun SolitaireViewModel.landFlightImpl(id: Long) {+    if (flightsInternal.value.none { it.id == id }) return+    flightsInternal.update { flights -> flights.filterNot { it.id == id } }+    if (id == autoCompleteFlightId) {+        autoCompleteFlightId = null+        if (autoCompleteRunningInternal.value) advanceAutoComplete()     }+    replayQueuedTaps() } -internal fun SolitaireViewModel.cancelFlightImpl() {-    flightInfoInternal.value = null+private fun SolitaireViewModel.replayQueuedTaps() {+    if (queuedTaps.isEmpty()) return+    val pending = queuedTaps.toList()+    queuedTaps.clear()+    for (tap in pending) {+        val range = sourceRange(tap.sourceId)+        // The state moved on under the queued tap: the card it was aimed at is gone.+        if (range == null || range.cards.first() != tap.card) continue+        if (isAirborne(range)) { queuedTaps.addLast(tap); continue }+        val targetId = resolveAutoMoveTarget(tap.sourceId) ?: continue+        flyMove(tap.sourceId, targetId, range.cards, cardPositions[tap.card], lastCardSize)+    } } -/** Drops any staged flight: undo, restart, mode switch and give-up all strand it. */-internal fun SolitaireViewModel.clearFlight() {-    flightInfoInternal.value = null+/** Drops every flight and queued tap: undo, restart, mode switch and give-up replace the board. */+internal fun SolitaireViewModel.clearMotion() {+    flightsInternal.value = emptyList()+    queuedTaps.clear()+    dragInfoInternal.value = null+    autoCompleteFlightId = null     // An abandoned run strands nothing: undo/give-up/mode-switch restore or     // replace the board, and the single pre-run history entry covers undo.     autoCompleteRunningInternal.value = false }++internal const val WASTE = "waste"+internal const val TABLEAU_PREFIX = "tableau_"+internal const val FOUNDATION_PREFIX = "foundation_"+internal const val FREECELL_PREFIX = "freecell_"
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 a552dc9ec5..d08f74210b 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@@ -217,114 +217,75 @@ internal fun SolitaireViewModel.runAutoCompleteLoop(start: KlondikeState): Klond  /**  * Animated auto-complete entry: the button tap (and re-tap) lands here. A tap- * mid-run skips straight to the finished board; otherwise the run stages one fast- * flight per step, suspending on each landing until the overlay commits it back- * through [landAutoCompleteStep]. One history entry covers the whole run, so a- * single undo restores the pre-run board, and the win is checked once at the end- * so the overlay cannot pop mid-flight.+ * mid-run skips straight to the finished board; otherwise the run applies one+ * step at a time and flies each foundation hop, continuing when that hop lands+ * ([landFlightImpl]). One history entry covers the whole run, so a single undo+ * restores the pre-run board, and the win is checked once at the end so the+ * overlay cannot pop mid-flight. Flights already in the air keep flying.  */ internal fun SolitaireViewModel.requestAutoCompleteImpl() {     if (autoCompleteRunningInternal.value) { skipAutoCompleteToEnd(); return }     val state = uiStateInternal.value.klondike ?: return     if (!canKlondikeAutoComplete(state)) return-    // A staged tap-to-move stays where it is; the run covers its card anyway.-    cancelFlightImpl()     saveHistory()     autoCompleteRunningInternal.value = true-    advanceAutoComplete(state)+    advanceAutoComplete() }  /**- * Steps the run forward from [start], staging one fast flight when the moving- * card's position is known and applying the step instantly otherwise. Publishes- * at the top of every iteration so the landing re-derives from exactly the- * staged state — an unpublished instant draw ahead of a staged flight would- * otherwise make the landing recompute the wrong move from stale live state.+ * Steps the run forward from the live state. Each step is applied to game state+ * at once (logical state is authoritative); a foundation hop whose card has a+ * known position launches a fast flight and the run waits for its landing,+ * every other step applies instantly and the loop continues.  */-internal fun SolitaireViewModel.advanceAutoComplete(start: KlondikeState) {-    var current = start-    while (true) {-        uiStateInternal.update { it.copy(klondike = current) }+internal fun SolitaireViewModel.advanceAutoComplete() {+    while (autoCompleteRunningInternal.value) {+        val current = uiStateInternal.value.klondike ?: break         val after = moveWasteToFoundation(current) ?: moveTableauToFoundation(current)-        if (after != null) {-            val step = autoCompleteStep(current, after)-            val from = step?.let { cardPositions[it.card] }-            if (step != null && from != null) {-                flightInfoInternal.value = CardFlight(-                    cards = listOf(step.card),-                    sourceId = step.sourceId,-                    targetId = "foundation_${step.foundationIndex}",-                    from = from,-                    fast = true,-                )-                return+        if (after == null && current.stock.isEmpty()) break+        if (after == null) {+            uiStateInternal.update {+                it.copy(klondike = current.copy(+                    stock = current.stock.dropLast(1),+                    waste = current.waste + current.stock.last()+                ))             }-            current = after-            continue-        }-        if (current.stock.isNotEmpty()) {-            current = current.copy(-                stock = current.stock.dropLast(1),-                waste = current.waste + current.stock.last()-            )             continue         }-        autoCompleteRunningInternal.value = false-        checkKlondikeWin()+        val step = autoCompleteStep(current, after)+        uiStateInternal.update { it.copy(klondike = after) }+        val from = step?.let { cardPositions[it.card] } ?: continue+        val flight = launchFlight(+            cards = listOf(step.card),+            from = from,+            targetId = "foundation_${step.foundationIndex}",+            cardSize = lastCardSize,+            fast = true,+        ) ?: continue+        autoCompleteFlightId = flight.id         return     }+    autoCompleteRunningInternal.value = false+    autoCompleteFlightId = null+    checkKlondikeWin() } -/** One staged step: which card moved, where it came from, which foundation it took. */-private data class AutoCompleteStep(val card: Card, val sourceId: String, val foundationIndex: Int)+/** One flown step: which card moved and which foundation it took. */+private data class AutoCompleteStep(val card: Card, val foundationIndex: Int) -/**- * Diffs the grown foundation between [before] and [after] into its step. Cards are- * unique, so the waste top decides "waste" and the matching tableau top decides- * its column unambiguously; null means the transition moved nothing recognisable.- */-private fun autoCompleteStep(before: KlondikeState, after: KlondikeState): AutoCompleteStep? {-    for (fi in before.foundations.indices) {-        if (after.foundations[fi].size != before.foundations[fi].size + 1) continue-        val card = after.foundations[fi].last()-        val sourceId = if (before.waste.lastOrNull() == card) {-            "waste"-        } else {-            val col = before.tableauPiles.indexOfFirst { it.faceUp.lastOrNull() == card }-            if (col < 0) return null-            "tableau_${col}_${before.tableauPiles[col].faceUp.lastIndex}"-        }-        return AutoCompleteStep(card, sourceId, fi)-    }-    return null-}+/** Diffs the grown foundation between [before] and [after] into its step, or null. */+private fun autoCompleteStep(before: KlondikeState, after: KlondikeState): AutoCompleteStep? =+    before.foundations.indices.firstOrNull { fi ->+        after.foundations[fi].size == before.foundations[fi].size + 1+    }?.let { fi -> AutoCompleteStep(after.foundations[fi].last(), fi) }  /**- * Continues the run after a fast flight lands. Re-runs the pure transition for the- * flight's source kind on the unchanged live state — deterministic first-fit, so it- * yields the same state the staging step computed — then advances from there. A- * null (unreachable: the flight was staged from this exact state) finishes- * conservatively rather than stranding the run.+ * Skips the animation: runs the shared loop to the end on the live state. Hops+ * already in the air are left to land — their moves are applied already.  */-internal fun SolitaireViewModel.landAutoCompleteStep(flight: CardFlight) {-    val current = uiStateInternal.value.klondike-    val after = when {-        current == null -> null-        flight.sourceId == "waste" -> moveWasteToFoundation(current)-        flight.sourceId.startsWith("tableau_") -> moveTableauToFoundation(current)-        else -> null-    }-    if (after == null) {-        autoCompleteRunningInternal.value = false-        checkKlondikeWin()-        return-    }-    advanceAutoComplete(after)-}--/** Skips the animation: drops any staged flight and runs the shared loop to the end. */ internal fun SolitaireViewModel.skipAutoCompleteToEnd() {-    clearFlight()+    autoCompleteRunningInternal.value = false+    autoCompleteFlightId = null     val state = uiStateInternal.value.klondike ?: return     uiStateInternal.update { it.copy(klondike = runAutoCompleteLoop(state)) }     checkKlondikeWin()
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 5f0b2f42e0..7703c1ab7c 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@@ -23,10 +23,11 @@ interface SolitaireActions {     val dragInfo: StateFlow<DragInfo?> get() = NoDrag      /**-     * A tap-to-move travelling to its destination, or null. The overlay animates it;-     * the move itself commits only when the flight lands.+     * Cards in the air, each flight independent and keyed by its id. Visual only: the move a+     * flight shows is already applied to game state, and the board hides the flying cards in+     * their new pile until the motion layer reports the landing through [landFlight].      */-    val flightInfo: StateFlow<CardFlight?> get() = NoFlight+    val flights: StateFlow<List<CardFlight>> get() = NoFlights      /** Drop zones, registered by the piles as they are laid out. */     val dropTargets: MutableMap<String, Rect> get() = DiscardedDropTargets@@ -37,9 +38,10 @@ interface SolitaireActions {     /**      * Records where [card] was last laid out in root coordinates, so the animated      * auto-complete can fly it from there. Positions for cards never laid out (in-     * the stock) are simply absent, and those steps apply instantly.+     * the stock) are simply absent, and those steps apply instantly. [size] is the+     * laid-out card size, which flights without a gesture of their own are drawn at.      */-    fun registerCardPosition(card: Card, position: Offset) {}+    fun registerCardPosition(card: Card, position: Offset, size: IntSize = IntSize.Zero) {}      fun startDrag(sourceId: String, startPos: Offset, cardSize: IntSize = IntSize.Zero): Boolean = false     fun updateDrag(offset: Offset) {}@@ -61,18 +63,16 @@ interface SolitaireActions {     fun autoMove(sourceId: String) {}      /**-     * Animated tap-to-move: resolves the best legal destination for [sourceId] and-     * stages the flight from [startPos], which the overlay animates before committing.-     * Returns false (and stages nothing) when there is no legal move or a flight is-     * already active. Klondike and FreeCell only, like [autoMove].+     * Animated tap-to-move: resolves the best legal destination for [sourceId], applies+     * the move at once and launches a flight from [startPos] (the tapped card's top-left,+     * [cardSize] its laid-out size) to the exact slot the cards now occupy. Other flights+     * keep flying; a tap on cards still in the air is queued until they land. Returns+     * false when there is no legal move. Klondike and FreeCell only, like [autoMove].      */-    fun requestAutoMove(sourceId: String, startPos: Offset): Boolean = false+    fun requestAutoMove(sourceId: String, startPos: Offset, cardSize: IntSize = IntSize.Zero): Boolean = false -    /** Lands the staged flight, performing its move. A no-op without one. */-    fun commitFlight() {}--    /** Drops the staged flight without moving anything. */-    fun cancelFlight() {}+    /** The motion layer finished drawing flight [id]; its cards show in their pile again. */+    fun landFlight(id: Long) {}      fun undo() {}     fun restart() {}@@ -84,7 +84,7 @@ interface SolitaireActions { }  private val NoDrag: StateFlow<DragInfo?> = MutableStateFlow(null)-private val NoFlight: StateFlow<CardFlight?> = MutableStateFlow(null)+private val NoFlights: StateFlow<List<CardFlight>> = MutableStateFlow(emptyList()) private val NoAutoComplete: StateFlow<Boolean> = MutableStateFlow(false)  /** Somewhere for a [SolitaireActions.Noop] board to register its drop zones and forget them. */
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 f9e1d64b8b..e312a4af7e 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@@ -38,8 +38,20 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     internal val dragInfoInternal = MutableStateFlow<DragInfo?>(null)     override val dragInfo: StateFlow<DragInfo?> = dragInfoInternal.asStateFlow() -    internal val flightInfoInternal = MutableStateFlow<CardFlight?>(null)-    override val flightInfo: StateFlow<CardFlight?> = flightInfoInternal.asStateFlow()+    internal val flightsInternal = MutableStateFlow<List<CardFlight>>(emptyList())+    override val flights: StateFlow<List<CardFlight>> = flightsInternal.asStateFlow()++    /** Ids for [flights]; never reused, so a late landing can never touch a newer flight. */+    internal var nextFlightId = 0L++    /** The auto-complete hop the run is waiting on, or null. */+    internal var autoCompleteFlightId: Long? = null++    /** Taps on cards that were still in the air, replayed as their flights land. */+    internal val queuedTaps = ArrayDeque<QueuedTap>()++    /** Card size last laid out, for flights launched without a gesture (auto-complete). */+    internal var lastCardSize: IntSize = IntSize.Zero      internal val autoCompleteRunningInternal = MutableStateFlow(false)     override val autoCompleteRunning: StateFlow<Boolean> = autoCompleteRunningInternal.asStateFlow()@@ -50,8 +62,9 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio      * re-registered as piles lay out, so a stale entry never survives a new game.      */     internal val cardPositions = mutableMapOf<Card, Offset>()-    override fun registerCardPosition(card: Card, position: Offset) {+    override fun registerCardPosition(card: Card, position: Offset, size: IntSize) {         cardPositions[card] = position+        if (size.width > 0 && size.height > 0) lastCardSize = size     }      internal val statsRepository = SolitaireStatsRepository(application)@@ -89,7 +102,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     }      fun selectMode(mode: GameMode, config: GameConfig = GameConfig()) {-        clearFlight()+        clearMotion()         cardPositions.clear()         when (mode) {             GameMode.KLONDIKE -> newKlondikeGame(config)@@ -122,7 +135,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     }      override fun giveUp() {-        clearFlight()+        clearMotion()         val mode = uiStateInternal.value.gameMode ?: return         statsRepository.recordGameLost(mode, currentVariant())         uiStateInternal.value = SolitaireUiState()@@ -167,14 +180,12 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio      override fun autoMove(sourceId: String) = autoMoveImpl(sourceId) -    override fun requestAutoMove(sourceId: String, startPos: Offset): Boolean {+    override fun requestAutoMove(sourceId: String, startPos: Offset, cardSize: IntSize): Boolean {         if (autoCompleteRunningInternal.value) { skipAutoCompleteToEnd(); return false }-        return requestFlightImpl(sourceId, startPos)+        return requestFlightImpl(sourceId, startPos, cardSize)     } -    override fun commitFlight() = commitFlightImpl()--    override fun cancelFlight() = cancelFlightImpl()+    override fun landFlight(id: Long) = landFlightImpl(id)      /**      * Starts a drag from [sourceId], deriving the carried cards from current state.@@ -197,7 +208,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     override fun cancelDrag() = cancelDragImpl()      override fun undo() {-        clearFlight()+        clearMotion()         val history = uiStateInternal.value.history         if (history.isEmpty()) return         val prev = history.last()
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardFlightOverlay.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardFlightOverlay.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardFlightOverlay.ktdeleted file mode 100644index ece74a6249..0000000000--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardFlightOverlay.kt+++ /dev/null@@ -1,104 +0,0 @@-package com.vayunmathur.games.solitaire.ui--import androidx.compose.animation.core.Animatable-import androidx.compose.animation.core.AnimationVector2D-import androidx.compose.animation.core.TwoWayConverter-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.offset-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 androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.graphics.graphicsLayer-import androidx.compose.ui.layout.onGloballyPositioned-import androidx.compose.ui.layout.positionInRoot-import androidx.compose.ui.platform.LocalDensity-import androidx.compose.ui.unit.Dp-import androidx.compose.ui.unit.IntOffset-import androidx.compose.ui.unit.dp-import androidx.compose.ui.zIndex-import com.vayunmathur.games.solitaire.platform.SolitaireActions-import com.vayunmathur.library.ui.Motion-import kotlin.math.roundToInt--private val OffsetConverter = TwoWayConverter<Offset, AnimationVector2D>(-    convertToVector = { AnimationVector2D(it.x, it.y) },-    convertFromVector = { Offset(it.v1, it.v2) }-)--/** One auto-complete hop: snappy enough to stagger, slow enough to follow. */-private const val FastFlightMillis = 110--/**- * Flies a staged tap-to-move from its tap point to its destination, then lands it.- *- * The flight carries root-frame coordinates; the overlay translates both ends into- * its own frame, deriving the landing point from the target's registered drop- * rectangle so the card arrives exactly on the pile. When the target is not laid- * out (a stale flight after a mode switch), the move commits instantly instead of- * stranding the cards mid-air. Stacking and translucency mirror [DragOverlay].- */-@Composable-fun CardFlightOverlay(-    actions: SolitaireActions,-    cardWidth: Dp,-    cardHeight: Dp,-    modifier: Modifier = Modifier-) {-    val flight by actions.flightInfo.collectAsState()-    var overlayPos by remember { mutableStateOf(Offset.Zero) }-    val cardHeightPx = with(LocalDensity.current) { cardHeight.toPx() }--    val faceUpOverlap = 22.dp--    Box(-        modifier = modifier-            .fillMaxSize()-            .zIndex(Float.MAX_VALUE)-            .onGloballyPositioned { coords ->-                overlayPos = coords.positionInRoot()-            }-    ) {-        val current = flight ?: return@Box-        val target = actions.dropTargets[current.targetId]-        if (target == null) {-            LaunchedEffect(current) { actions.commitFlight() }-            return@Box-        }-        val from = Offset(current.from.x - overlayPos.x, current.from.y - overlayPos.y)-        val to = Offset(-            target.left - overlayPos.x,-            target.bottom - overlayPos.y - cardHeightPx-        )-        val position: Animatable<Offset, AnimationVector2D> =-            remember(current) { Animatable(from, OffsetConverter) }-        LaunchedEffect(current) {-            position.animateTo(-                to,-                if (current.fast) Motion.over<Offset>(FastFlightMillis) else Motion.drop<Offset>()-            )-            actions.commitFlight()-        }--        Box(-            modifier = Modifier-                .offset { IntOffset(position.value.x.roundToInt(), position.value.y.roundToInt()) }-                .graphicsLayer { alpha = 0.9f }-        ) {-            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/CardMotionLayer.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardMotionLayer.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardMotionLayer.ktnew file mode 100644index 0000000000..648e9e7111--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/CardMotionLayer.kt@@ -0,0 +1,106 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.offset+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInRoot+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.round+import androidx.compose.ui.zIndex+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.platform.CardFlight+import com.vayunmathur.games.solitaire.platform.FlightTarget+import com.vayunmathur.games.solitaire.platform.SolitaireActions+import com.vayunmathur.library.ui.Motion+import com.vayunmathur.library.ui.travelledOffset++/** One auto-complete hop: snappy enough to stagger, slow enough to follow. */+private const val FAST_FLIGHT_MILLIS = 110++/** Above every pile, the board's controls and the scrolling column that holds them. */+private const val MOTION_LAYER_Z = 1f++/**+ * Every card in motion, drawn in one layer laid over the whole game screen.+ *+ * It lives outside the board's scrolling column rather than inside a pile, so nothing in motion+ * is clipped by a pile's bounds or by the scroll viewport, and it works in root coordinates so a+ * card can travel between any two piles. Each flight is keyed by its id and runs on its own+ * clock: a new flight never restarts or jumps one already in the air. A flight lands on the slot+ * its card now occupies, positioned by [pileSlotPosition] — the same layout the piles draw+ * with — and is reported back through [SolitaireActions.landFlight] so the pile shows the card+ * again. A flight whose target pile is not laid out (a stale flight after a mode switch) lands+ * at once instead of stranding cards mid-air.+ */+@Composable+fun CardMotionLayer(actions: SolitaireActions, modifier: Modifier = Modifier) {+    val flights by actions.flights.collectAsState()+    var origin by remember { mutableStateOf(Offset.Zero) }+    Box(+        modifier = modifier+            .fillMaxSize()+            .zIndex(MOTION_LAYER_Z)+            .onGloballyPositioned { origin = it.positionInRoot() }+    ) {+        flights.forEach { flight ->+            key(flight.id) { FlyingCards(flight, actions) { origin } }+        }+    }+}++@Composable+private fun FlyingCards(flight: CardFlight, actions: SolitaireActions, origin: () -> Offset) {+    val density = LocalDensity.current+    val to = when (val target = flight.target) {+        is FlightTarget.Point -> target.position+        is FlightTarget.Slot -> actions.dropTargets[target.pileId]?.let { pile ->+            with(density) { pileSlotPosition(pile.topLeft, target) }+        }+    }+    if (to == null) {+        LaunchedEffect(flight.id) { actions.landFlight(flight.id) }+        return+    }+    val spec = if (flight.fast) Motion.over<Offset>(FAST_FLIGHT_MILLIS) else Motion.drop()+    val position = travelledOffset(flight.id, flight.from, to, spec) { actions.landFlight(flight.id) }+    CarriedCards(+        cards = flight.cards,+        cardSize = flight.cardSize,+        modifier = Modifier.offset { (position.value - origin()).round() },+    )+}++/** A carried run, fanned like a tableau column, each card drawn exactly once. */+@Composable+private fun CarriedCards(cards: List<Card>, cardSize: IntSize, modifier: Modifier) {+    val density = LocalDensity.current+    val (width, height) = with(density) {+        if (cardSize.width > 0 && cardSize.height > 0) {+            cardSize.width.toDp() to cardSize.height.toDp()+        } else {+            CARD_WIDTH to CARD_HEIGHT+        }+    }+    Box(modifier) {+        cards.forEachIndexed { index, card ->+            CardFace(+                card = card,+                modifier = Modifier.offset(y = tableauCardOffset(0, index)),+                cardWidth = width,+                cardHeight = height,+            )+        }+    }+}
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 24061238a6..9cf0c1c740 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@@ -6,7 +6,6 @@ import androidx.compose.foundation.layout.Box 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@@ -36,6 +35,8 @@ import com.vayunmathur.games.solitaire.platform.SolitaireActions fun DraggableCard(     card: Card,     sourceId: String,+    pileId: String,+    index: Int,     actions: SolitaireActions,     modifier: Modifier = Modifier,     content: @Composable () -> Unit@@ -44,14 +45,14 @@ fun DraggableCard(     var dragOffset by remember { mutableStateOf(Offset.Zero) }     var startPos by remember { mutableStateOf(Offset.Zero) }     var cardSize by remember { mutableStateOf(IntSize.Zero) }-    // Hidden while a staged flight covers this card, so the flight — not a-    // duplicate underneath — is what the player sees travelling.-    val flight by actions.flightInfo.collectAsState()-    val isFlying = flight?.cards?.contains(card) == true+    // Hidden while a flight carries this card into (or back to) this slot, so the+    // flight — not a copy underneath — is what the player sees travelling.+    val flights by actions.flights.collectAsState()+    val isFlying = flights.any { it.hides.covers(pileId, index, card) }     // Feeds the animated auto-complete its launch points; unlaid cards (the stock)     // stay absent and fly instantly instead.-    LaunchedEffect(card, startPos) {-        if (startPos != Offset.Zero) actions.registerCardPosition(card, startPos)+    LaunchedEffect(card, startPos, cardSize) {+        if (startPos != Offset.Zero) actions.registerCardPosition(card, startPos, cardSize)     }      Box(@@ -62,7 +63,7 @@ fun DraggableCard(             }             .pointerInput(card, sourceId) {                 detectTapGestures(-                    onTap = { actions.requestAutoMove(sourceId, startPos) },+                    onTap = { actions.requestAutoMove(sourceId, startPos, cardSize) },                 )             }             .pointerInput(card, sourceId) {@@ -137,32 +138,3 @@ fun DragOverlay(         }     } }--@Composable-fun DropTarget(-    targetId: String,-    actions: SolitaireActions,-    modifier: Modifier = Modifier,-    content: @Composable () -> Unit-) {-    // The map outlives the board — it hangs off the view model, which is scoped to the-    // activity. A pile that leaves the composition has to take its rectangle with it, or a-    // mode with fewer piles (or piles somewhere else) keeps resolving drops against the-    // previous mode's geometry.-    DisposableEffect(targetId) {-        onDispose { actions.dropTargets.remove(targetId) }-    }-    Box(-        modifier = modifier.onGloballyPositioned { coords ->-            val pos = coords.positionInRoot()-            val size = coords.size-            actions.dropTargets[targetId] = androidx.compose.ui.geometry.Rect(-                pos.x, pos.y,-                pos.x + size.width, pos.y + size.height-            )-        }-    ) {-        content()-    }-}-
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DropTarget.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DropTarget.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DropTarget.ktnew file mode 100644index 0000000000..b96b033f3f--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DropTarget.kt@@ -0,0 +1,43 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInRoot+import com.vayunmathur.games.solitaire.platform.SolitaireActions++/**+ * A pile's drop zone. Its laid-out rectangle (root coordinates) is what drops resolve against,+ * and its top-left is the pile origin the motion layer lands flights relative to.+ */+@Composable+fun DropTarget(+    targetId: String,+    actions: SolitaireActions,+    modifier: Modifier = Modifier,+    content: @Composable () -> Unit+) {+    // The map outlives the board — it hangs off the view model, which is scoped to the+    // activity. A pile that leaves the composition has to take its rectangle with it, or a+    // mode with fewer piles (or piles somewhere else) keeps resolving drops against the+    // previous mode's geometry.+    DisposableEffect(targetId) {+        onDispose { actions.dropTargets.remove(targetId) }+    }+    Box(+        modifier = modifier.onGloballyPositioned { coords ->+            val pos = coords.positionInRoot()+            val size = coords.size+            actions.dropTargets[targetId] = Rect(+                pos.x, pos.y,+                pos.x + size.width, pos.y + size.height+            )+        }+    ) {+        content()+    }+}+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationSlot.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationSlot.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationSlot.ktnew file mode 100644index 0000000000..4270d8b3e3--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationSlot.kt@@ -0,0 +1,55 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.Dp+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.platform.SolitaireActions++/**+ * A foundation pile. The top card is a [DraggableCard] so the board can hide it while it flies+ * in (or, where the variant allows, is carried back out); the card beneath — or the suit+ * watermark — is drawn under it so a hidden top never leaves a hole.+ */+@Composable+fun FoundationSlot(+    cards: List<Card>,+    index: Int,+    actions: SolitaireActions,+    modifier: Modifier = Modifier,+    cardWidth: Dp = CARD_WIDTH,+    cardHeight: Dp = CARD_HEIGHT+) {+    val pileId = "foundation_$index"+    DropTarget(pileId, actions, modifier) {+        Box {+            val beneath = cards.getOrNull(cards.size - 2)+            if (beneath != null) {+                CardFace(beneath, cardWidth = cardWidth, cardHeight = cardHeight)+            } else {+                val suit = Suit.entries.getOrNull(index)+                EmptySlot(+                    label = suit?.symbol ?: "",+                    labelColor = suit?.let { LocalCardColorScheme.current.colorFor(it).copy(alpha = 0.5f) }+                        ?: Color.Gray,+                    cardWidth = cardWidth,+                    cardHeight = cardHeight+                )+            }+            cards.lastOrNull()?.let { top ->+                DraggableCard(+                    card = top,+                    sourceId = pileId,+                    pileId = pileId,+                    index = cards.lastIndex,+                    actions = actions,+                ) {+                    CardFace(top, cardWidth = cardWidth, cardHeight = cardHeight)+                }+            }+        }+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.ktdeleted file mode 100644index 9fc16afae8..0000000000--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt+++ /dev/null@@ -1,59 +0,0 @@-package com.vayunmathur.games.solitaire.ui--import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.unit.Dp-import com.vayunmathur.games.solitaire.data.Card-import com.vayunmathur.games.solitaire.data.Suit-import com.vayunmathur.games.solitaire.platform.SolitaireActions--@Composable-fun FoundationSlot(-    cards: List<Card>,-    index: Int,-    actions: SolitaireActions,-    modifier: Modifier = Modifier,-    cardWidth: Dp = CARD_WIDTH,-    cardHeight: Dp = CARD_HEIGHT-) {-    DropTarget("foundation_$index", actions, modifier) {-        if (cards.isNotEmpty()) {-            CardFace(cards.last(), cardWidth = cardWidth, cardHeight = cardHeight)-        } else {-            val suit = Suit.entries.getOrNull(index)-            EmptySlot(-                label = suit?.symbol ?: "",-                labelColor = suit?.let { LocalCardColorScheme.current.colorFor(it).copy(alpha = 0.5f) }-                    ?: Color.Gray,-                cardWidth = cardWidth,-                cardHeight = cardHeight-            )-        }-    }-}--@Composable-fun FreeCellSlot(-    card: Card?,-    index: Int,-    actions: SolitaireActions,-    modifier: Modifier = Modifier,-    cardWidth: Dp = CARD_WIDTH,-    cardHeight: Dp = CARD_HEIGHT-) {-    DropTarget("freecell_$index", actions, modifier) {-        if (card != null) {-            DraggableCard(-                card = card,-                sourceId = "freecell_$index",-                actions = actions,-            ) {-                CardFace(card, cardWidth = cardWidth, cardHeight = cardHeight)-            }-        } else {-            EmptySlot(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 665f791179..9c0918f5f4 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,7 +54,6 @@ fun FreeCellBoard(state: FreeCellState, actions: SolitaireActions, modifier: Mod         }          DragOverlay(actions, cardWidth, cardHeight)-        CardFlightOverlay(actions, cardWidth, cardHeight)         }     } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellSlot.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellSlot.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellSlot.ktnew file mode 100644index 0000000000..54563f2d08--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellSlot.kt@@ -0,0 +1,37 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.Dp+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.platform.SolitaireActions++/** A FreeCell cell. The empty outline stays drawn under the card, which can be hidden mid-move. */+@Composable+fun FreeCellSlot(+    card: Card?,+    index: Int,+    actions: SolitaireActions,+    modifier: Modifier = Modifier,+    cardWidth: Dp = CARD_WIDTH,+    cardHeight: Dp = CARD_HEIGHT+) {+    val pileId = "freecell_$index"+    DropTarget(pileId, actions, modifier) {+        Box {+            EmptySlot(cardWidth = cardWidth, cardHeight = cardHeight)+            if (card != null) {+                DraggableCard(+                    card = card,+                    sourceId = pileId,+                    pileId = pileId,+                    index = 0,+                    actions = actions,+                ) {+                    CardFace(card, cardWidth = cardWidth, cardHeight = cardHeight)+                }+            }+        }+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellTableauColumn.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellTableauColumn.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellTableauColumn.ktnew file mode 100644index 0000000000..290560cdd5--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellTableauColumn.kt@@ -0,0 +1,45 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.offset+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.Dp+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.platform.SolitaireActions++@Composable+fun FreeCellTableauColumn(+    pile: List<Card>,+    columnIndex: Int,+    actions: SolitaireActions,+    modifier: Modifier = Modifier,+    cardWidth: Dp = CARD_WIDTH,+    cardHeight: Dp = CARD_HEIGHT+) {+    val totalHeight = tableauCardOffset(0, maxOf(0, pile.size - 1)) + cardHeight+    val pileId = "tableau_$columnIndex"++    DropTarget(pileId, actions, modifier) {+        Box(modifier = Modifier.heightIn(min = totalHeight)) {+            EmptySlot(cardWidth = cardWidth, cardHeight = cardHeight)+            pile.forEachIndexed { index, card ->+                DraggableCard(+                    card = card,+                    sourceId = "${pileId}_$index",+                    pileId = pileId,+                    index = index,+                    actions = actions,+                    modifier = Modifier.offset(y = tableauCardOffset(0, index)),+                ) {+                    CardFace(+                        card = card,+                        cardWidth = cardWidth,+                        cardHeight = cardHeight+                    )+                }+            }+        }+    }+}
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 873408d847..0c4385b31b 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@@ -92,6 +92,8 @@ fun GameBoardScreen(state: SolitaireUiState, mode: GameMode, actions: SolitaireA                 }             }             }+            // Cards in motion draw above the board and outside its scrolling column.+            CardMotionLayer(actions)             if (isWon) { WinOverlay(elapsedSeconds = elapsed, moveCount = moveCount, onNewGame = { actions.restart() }, onBack = onExit) }             if (confirmGiveUp) {                 ConfirmDialog(
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 5de5c05b22..c669e1b2b7 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@@ -67,12 +67,19 @@ fun KlondikeBoard(state: KlondikeState, actions: SolitaireActions, modifier: Mod                     val visibleCards = state.waste.takeLast(visibleCount)                     val fanOffset = cardWidth * 0.3f                     Box(modifier = Modifier.width(cardWidth + fanOffset * (visibleCount - 1))) {+                        // Draw-one shows only the top, so the card beneath is drawn under it:+                        // the top is hidden while it is carried or flies away.+                        if (visibleCount == 1 && state.waste.size > 1) {+                            CardFace(state.waste[state.waste.size - 2], cardWidth = cardWidth, cardHeight = cardHeight)+                        }                         visibleCards.forEachIndexed { index, card ->                             val isTop = index == visibleCards.lastIndex                             if (isTop) {                                 DraggableCard(                                     card = card,                                     sourceId = "waste",+                                    pileId = "waste",+                                    index = state.waste.lastIndex,                                     actions = actions,                                     modifier = Modifier.offset(x = fanOffset * index),                                 ) {@@ -120,7 +127,6 @@ fun KlondikeBoard(state: KlondikeState, actions: SolitaireActions, modifier: Mod         }          DragOverlay(actions, cardWidth, cardHeight)-        CardFlightOverlay(actions, cardWidth, cardHeight)         }     } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/PileLayout.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/PileLayout.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/PileLayout.ktnew file mode 100644index 0000000000..237487d94a--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/PileLayout.kt@@ -0,0 +1,33 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.solitaire.platform.FlightTarget+import com.vayunmathur.games.solitaire.platform.TABLEAU_PREFIX++/** Vertical step between face-down cards in a tableau column. */+internal val FACE_DOWN_OVERLAP = 8.dp++/** Vertical step between face-up cards in a tableau column (and in a carried stack). */+internal val FACE_UP_OVERLAP = 22.dp++/**+ * Offset of a tableau card from its column's top: [faceDownCount] face-down cards, then the+ * face-up card at [faceUpIndex]. The columns draw every card with this, and the motion layer+ * lands flights with it, so a flight always ends exactly where its card is then drawn.+ */+internal fun tableauCardOffset(faceDownCount: Int, faceUpIndex: Int): Dp =+    FACE_DOWN_OVERLAP * faceDownCount + FACE_UP_OVERLAP * faceUpIndex++/**+ * Offset of [slot]'s card from its pile's laid-out origin. Tableau columns fan downwards;+ * every other pile (foundation, free cell) stacks its cards in place.+ */+internal fun pileSlotOffset(slot: FlightTarget.Slot): Dp =+    if (slot.pileId.startsWith(TABLEAU_PREFIX)) tableauCardOffset(slot.faceDownCount, slot.index) else 0.dp++/** Root position of [slot]'s card, given the root position of its pile's origin. */+internal fun Density.pileSlotPosition(pileOrigin: Offset, slot: FlightTarget.Slot): Offset =+    Offset(pileOrigin.x, pileOrigin.y + pileSlotOffset(slot).toPx())
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.ktindex 3d4370d9d0..2dd7eb36e0 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt@@ -6,14 +6,9 @@ import androidx.compose.foundation.layout.offset import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp-import androidx.compose.ui.unit.dp-import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.data.TableauPile import com.vayunmathur.games.solitaire.platform.SolitaireActions -private val FACE_DOWN_OVERLAP = 8.dp-private val FACE_UP_OVERLAP = 22.dp- @Composable fun TableauColumn(     pile: TableauPile,@@ -26,68 +21,32 @@ fun TableauColumn(     val totalHeight = if (pile.faceDown.isEmpty() && pile.faceUp.isEmpty()) {         cardHeight     } else {-        FACE_DOWN_OVERLAP * pile.faceDown.size +-        FACE_UP_OVERLAP * maxOf(0, pile.faceUp.size - 1) +-        cardHeight+        tableauCardOffset(pile.faceDown.size, maxOf(0, pile.faceUp.size - 1)) + cardHeight     }+    val pileId = "tableau_$columnIndex" -    DropTarget("tableau_$columnIndex", actions, modifier) {+    DropTarget(pileId, actions, modifier) {         Box(modifier = Modifier.heightIn(min = totalHeight)) {-            if (pile.faceDown.isEmpty() && pile.faceUp.isEmpty()) {+            // Drawn under the cards too, so a column whose every card is being carried+            // or is in the air reads as the empty column it is about to be.+            if (pile.faceDown.isEmpty()) {                 EmptySlot(cardWidth = cardWidth, cardHeight = cardHeight)             }             pile.faceDown.indices.forEach { i ->                 CardBack(-                    modifier = Modifier.offset(y = FACE_DOWN_OVERLAP * i),+                    modifier = Modifier.offset(y = tableauCardOffset(i, 0)),                     cardWidth = cardWidth,                     cardHeight = cardHeight                 )             }-            val faceDownOffset = FACE_DOWN_OVERLAP * pile.faceDown.size             pile.faceUp.forEachIndexed { index, card ->                 DraggableCard(                     card = card,-                    sourceId = "tableau_${columnIndex}_$index",-                    actions = actions,-                    modifier = Modifier.offset(y = faceDownOffset + FACE_UP_OVERLAP * index),-                ) {-                    CardFace(-                        card = card,-                        cardWidth = cardWidth,-                        cardHeight = cardHeight-                    )-                }-            }-        }-    }-}--@Composable-fun FreeCellTableauColumn(-    pile: List<Card>,-    columnIndex: Int,-    actions: SolitaireActions,-    modifier: Modifier = Modifier,-    cardWidth: Dp = CARD_WIDTH,-    cardHeight: Dp = CARD_HEIGHT-) {-    val totalHeight = if (pile.isEmpty()) {-        cardHeight-    } else {-        FACE_UP_OVERLAP * maxOf(0, pile.size - 1) + cardHeight-    }--    DropTarget("tableau_$columnIndex", actions, modifier) {-        Box(modifier = Modifier.heightIn(min = totalHeight)) {-            if (pile.isEmpty()) {-                EmptySlot(cardWidth = cardWidth, cardHeight = cardHeight)-            }-            pile.forEachIndexed { index, card ->-                DraggableCard(-                    card = card,-                    sourceId = "tableau_${columnIndex}_$index",+                    sourceId = "${pileId}_$index",+                    pileId = pileId,+                    index = index,                     actions = actions,-                    modifier = Modifier.offset(y = FACE_UP_OVERLAP * index),+                    modifier = Modifier.offset(y = tableauCardOffset(pile.faceDown.size, index)),                 ) {                     CardFace(                         card = card,@@ -99,4 +58,3 @@ fun FreeCellTableauColumn(         }     } }-
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAutoCompleteTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAutoCompleteTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAutoCompleteTest.ktindex 6f2c4559a5..821943db69 100644--- a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAutoCompleteTest.kt+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireAutoCompleteTest.kt@@ -13,7 +13,6 @@ import com.vayunmathur.games.solitaire.data.TableauPile import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse-import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.test.fail import org.junit.runner.RunWith@@ -53,18 +52,20 @@ class SolitaireAutoCompleteTest {         elapsedSeconds = 42,     ) -    @Test fun stagingLeavesStateUnchangedWithOneHistoryEntry() {+    @Test fun firstHopIsAppliedAndFlownWithOneHistoryEntry() {         val vm = vm()         setK(vm, almostWon())         val heartsK = Card(Suit.HEARTS, Rank.KING)         vm.registerCardPosition(heartsK, Offset(10f, 10f))         vm.klondikeAutoComplete()         assertTrue(vm.autoCompleteRunning.value)-        val flight = vm.flightInfo.value!!-        assertEquals("waste", flight.sourceId)+        val flight = vm.flights.value.single()+        assertEquals(listOf(heartsK), flight.cards)+        assertEquals(FlightTarget.Slot("foundation_0", 0, 12), flight.target)         assertTrue(flight.fast)-        // The staged card still lives in state until the flight lands.-        assertEquals(listOf(heartsK), vm.uiState.value.klondike!!.waste)+        // Logical state leads: the King is on its foundation while it flies.+        assertTrue(vm.uiState.value.klondike!!.waste.isEmpty())+        assertEquals(13, vm.uiState.value.klondike!!.foundations[0].size)         assertEquals(1, vm.uiState.value.history.size)     } @@ -73,7 +74,7 @@ class SolitaireAutoCompleteTest {         setK(vm, almostWon())         vm.klondikeAutoComplete()         assertFalse(vm.autoCompleteRunning.value)-        assertNull(vm.flightInfo.value)+        assertTrue(vm.flights.value.isEmpty())         val k = vm.uiState.value.klondike!!         assertTrue(k.isWon, "state=$k")         assertTrue(k.foundations.all { it.size == 13 })@@ -87,19 +88,22 @@ class SolitaireAutoCompleteTest {         vm.registerCardPosition(Card(Suit.DIAMONDS, Rank.KING), Offset(20f, 20f))         vm.registerCardPosition(Card(Suit.CLUBS, Rank.KING), Offset(30f, 30f))         vm.klondikeAutoComplete()-        val staged = mutableListOf<String>()+        val flown = mutableListOf<Card>()         var guard = 0         while (vm.autoCompleteRunning.value) {             if (guard++ > 10) fail("run did not finish")-            val flight = vm.flightInfo.value ?: fail("running without a staged flight")+            val flight = vm.flights.value.singleOrNull() ?: fail("running without a hop in the air")             assertTrue(flight.fast, "flight=$flight")-            staged += flight.sourceId-            vm.commitFlight()+            assertFalse(vm.uiState.value.klondike!!.isWon, "won before the last hop landed")+            flown += flight.cards+            vm.landFlight(flight.id)         }         // The stock spades King was never laid out, so its draw and landing apply-        // instantly between the staged flights rather than staging a fourth flight.-        // (tableau_1_0: column 1, the King at card index 0 of its pile.)-        assertEquals(listOf("waste", "tableau_0_0", "tableau_1_0"), staged)+        // instantly between the flown hops rather than flying a fourth.+        assertEquals(+            listOf(Card(Suit.HEARTS, Rank.KING), Card(Suit.DIAMONDS, Rank.KING), Card(Suit.CLUBS, Rank.KING)),+            flown,+        )         val k = vm.uiState.value.klondike!!         assertTrue(k.isWon, "state=$k")         assertTrue(k.foundations.all { it.size == 13 })@@ -113,7 +117,8 @@ class SolitaireAutoCompleteTest {         assertTrue(vm.autoCompleteRunning.value)         assertFalse(vm.requestAutoMove("waste", Offset.Zero))         assertFalse(vm.autoCompleteRunning.value)-        assertNull(vm.flightInfo.value)+        // The hop already in the air is left to land; its move is applied.+        assertEquals(1, vm.flights.value.size)         assertTrue(vm.uiState.value.klondike!!.isWon)     } @@ -147,7 +152,7 @@ class SolitaireAutoCompleteTest {         assertTrue(vm.autoCompleteRunning.value)         vm.klondikeAutoComplete()         assertFalse(vm.autoCompleteRunning.value)-        assertNull(vm.flightInfo.value)+        assertEquals(1, vm.flights.value.size)         assertTrue(vm.uiState.value.klondike!!.isWon)     } @@ -179,7 +184,7 @@ class SolitaireAutoCompleteTest {         )         vm.klondikeAutoComplete()         assertFalse(vm.autoCompleteRunning.value)-        assertNull(vm.flightInfo.value)+        assertTrue(vm.flights.value.isEmpty())         assertTrue(vm.uiState.value.history.isEmpty())     } }
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireFlightTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireFlightTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireFlightTest.ktindex 03722281cc..02144bc978 100644--- a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireFlightTest.kt+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireFlightTest.kt@@ -2,6 +2,8 @@ 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@@ -14,13 +16,15 @@ import com.vayunmathur.games.solitaire.data.TableauPile import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse-import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config -/** Tap-to-move flights: staging, landing, and refusal cases. */+/**+ * Tap-to-move flights: the move applies at once, the flight is visual, several fly at once,+ * and a card in the air cannot be grabbed in a way that corrupts state.+ */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class SolitaireFlightTest {@@ -28,6 +32,7 @@ class SolitaireFlightTest {     private fun vm() = SolitaireViewModel(app)     private fun c(suit: Suit, rank: Rank) = Card(suit, rank)     private val tap = Offset(10f, 20f)+    private val size = IntSize(60, 90)      private fun setK(vm: SolitaireViewModel, state: KlondikeState) {         vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.KLONDIKE, klondike = state)@@ -37,84 +42,197 @@ class SolitaireFlightTest {         vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.FREECELL, freeCell = state)     } -    @Test fun wasteAceStagesFoundationFlightAndLandsOnCommit() {+    private fun piles(vararg piles: TableauPile) = piles.toList() + List(7 - piles.size) { TableauPile() }++    @Test fun wasteAceMovesAtOnceAndFliesToFoundationSlot() {         val vm = vm()-        setK(vm, KlondikeState(waste = listOf(c(Suit.HEARTS, Rank.ACE))))-        assertTrue(vm.requestAutoMove("waste", tap))-        val flight = vm.flightInfo.value-        assertEquals(listOf(c(Suit.HEARTS, Rank.ACE)), flight?.cards)-        assertEquals("waste", flight?.sourceId)-        assertEquals("foundation_0", flight?.targetId)-        // Staging moves nothing: the card is still in the waste until landing.-        assertEquals(listOf(c(Suit.HEARTS, Rank.ACE)), vm.uiState.value.klondike!!.waste)-        vm.commitFlight()-        assertNull(vm.flightInfo.value)+        val ace = c(Suit.HEARTS, Rank.ACE)+        setK(vm, KlondikeState(waste = listOf(ace)))+        assertTrue(vm.requestAutoMove("waste", tap, size))+        // Logical state is authoritative: the move is applied before the flight lands.         val k = vm.uiState.value.klondike!!         assertTrue(k.waste.isEmpty())-        assertEquals(listOf(c(Suit.HEARTS, Rank.ACE)), k.foundations[0])+        assertEquals(listOf(ace), k.foundations[0])+        val flight = vm.flights.value.single()+        assertEquals(listOf(ace), flight.cards)+        assertEquals(tap, flight.from)+        assertEquals(size, flight.cardSize)+        assertEquals(FlightTarget.Slot("foundation_0", 0, 0), flight.target)+        assertEquals(PileRange("foundation_0", 0, listOf(ace)), flight.hides)+        // Landing only ends the visual.+        vm.landFlight(flight.id)+        assertTrue(vm.flights.value.isEmpty())+        assertEquals(k, vm.uiState.value.klondike)     } -    @Test fun wasteCardStagesTableauFlightWhenNoFoundationFits() {+    @Test fun tableauFlightTargetsTheNextSlotPastFaceDownCards() {         val vm = vm()-        val eightSpades = c(Suit.SPADES, Rank.EIGHT)+        val eight = c(Suit.SPADES, Rank.EIGHT)+        val seven = c(Suit.HEARTS, Rank.SEVEN)         setK(             vm,             KlondikeState(-                waste = listOf(c(Suit.HEARTS, Rank.SEVEN)),-                tableauPiles = listOf(TableauPile(faceUp = listOf(eightSpades))) +-                    List(6) { TableauPile() },+                waste = listOf(seven),+                tableauPiles = piles(+                    TableauPile(faceDown = listOf(c(Suit.CLUBS, Rank.TWO), c(Suit.CLUBS, Rank.THREE)), faceUp = listOf(eight)),+                ),             ),         )-        assertTrue(vm.requestAutoMove("waste", tap))-        assertEquals("tableau_0", vm.flightInfo.value?.targetId)-        vm.commitFlight()-        val k = vm.uiState.value.klondike!!-        assertTrue(k.waste.isEmpty())-        assertEquals(listOf(eightSpades, c(Suit.HEARTS, Rank.SEVEN)), k.tableauPiles[0].faceUp)+        assertTrue(vm.requestAutoMove("waste", tap, size))+        assertEquals(listOf(eight, seven), vm.uiState.value.klondike!!.tableauPiles[0].faceUp)+        // Two face-down cards, then the seven at face-up index 1: the slot the column draws it at.+        assertEquals(FlightTarget.Slot("tableau_0", 2, 1), vm.flights.value.single().target)+    }++    @Test fun runFlightCarriesEveryCardOnceToTheFirstSlot() {+        val vm = vm()+        val run = listOf(c(Suit.HEARTS, Rank.QUEEN), c(Suit.CLUBS, Rank.JACK))+        val king = c(Suit.SPADES, Rank.KING)+        setK(+            vm,+            KlondikeState(+                tableauPiles = piles(+                    TableauPile(faceDown = listOf(c(Suit.CLUBS, Rank.TWO)), faceUp = run),+                    TableauPile(faceUp = listOf(king)),+                ),+            ),+        )+        assertTrue(vm.requestAutoMove("tableau_0_0", tap, size))+        val flight = vm.flights.value.single()+        assertEquals(run, flight.cards)+        assertEquals(FlightTarget.Slot("tableau_1", 0, 1), flight.target)+        assertEquals(PileRange("tableau_1", 1, run), flight.hides)     } -    @Test fun requestRefusedWithoutLegalMoveOrWhileFlying() {+    @Test fun requestRefusedWithoutLegalMove() {         val vm = vm()         setK(vm, KlondikeState(waste = emptyList()))         assertFalse(vm.requestAutoMove("waste", tap))         assertFalse(vm.requestAutoMove("nope", tap))-        assertNull(vm.flightInfo.value)-        // A lone king with an empty board always has somewhere to go; the second-        // request while it is still staged is the one refused.-        setK(vm, KlondikeState(waste = listOf(c(Suit.SPADES, Rank.KING))))-        assertTrue(vm.requestAutoMove("waste", tap))-        assertFalse(vm.requestAutoMove("waste", tap))+        assertTrue(vm.flights.value.isEmpty())     } -    @Test fun commitWithoutFlightIsNoOp() {+    @Test fun secondTapDuringFlightKeepsFirstMoveAndFlight() {         val vm = vm()-        setK(vm, KlondikeState(waste = listOf(c(Suit.HEARTS, Rank.ACE))))-        vm.commitFlight()-        vm.cancelFlight()-        assertEquals(0, vm.uiState.value.klondike!!.moveCount)-        assertEquals(listOf(c(Suit.HEARTS, Rank.ACE)), vm.uiState.value.klondike!!.waste)+        val heartsAce = c(Suit.HEARTS, Rank.ACE)+        val spadesAce = c(Suit.SPADES, Rank.ACE)+        setK(vm, KlondikeState(waste = listOf(heartsAce), tableauPiles = piles(TableauPile(faceUp = listOf(spadesAce)))))+        assertTrue(vm.requestAutoMove("waste", tap, size))+        val first = vm.flights.value.single()+        assertTrue(vm.requestAutoMove("tableau_0_0", Offset(99f, 99f), size))+        // Both moves applied; both flights in the air, the first untouched.+        val k = vm.uiState.value.klondike!!+        assertEquals(listOf(heartsAce), k.foundations[0])+        assertEquals(listOf(spadesAce), k.foundations[2])+        assertEquals(2, vm.flights.value.size)+        assertEquals(first, vm.flights.value.first())+        assertEquals(2, k.moveCount)+        // Landing the second leaves the first flying.+        vm.landFlight(vm.flights.value.last().id)+        assertEquals(listOf(first), vm.flights.value)+        vm.landFlight(first.id)+        assertTrue(vm.flights.value.isEmpty())+        vm.landFlight(first.id) // a repeated landing is a no-op+        assertEquals(k, vm.uiState.value.klondike)     } -    @Test fun undoAndGiveUpClearStagedFlight() {+    @Test fun tapOnCardInTheAirIsQueuedAndReplayedWhenItLands() {+        val vm = vm()+        val seven = c(Suit.HEARTS, Rank.SEVEN)+        setK(+            vm,+            KlondikeState(+                waste = listOf(seven),+                tableauPiles = piles(+                    TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.EIGHT))),+                    TableauPile(faceUp = listOf(c(Suit.CLUBS, Rank.EIGHT))),+                ),+            ),+        )+        assertTrue(vm.requestAutoMove("waste", tap, size))+        val first = vm.flights.value.single()+        assertEquals(seven, vm.uiState.value.klondike!!.tableauPiles[0].faceUp.last())+        // Tapping the seven where it is landing: queued, nothing moves, the flight keeps going.+        val before = vm.uiState.value+        assertTrue(vm.requestAutoMove("tableau_0_1", tap, size))+        assertEquals(before, vm.uiState.value)+        assertEquals(listOf(first), vm.flights.value)+        // Once it lands the queued tap replays against the live state.+        vm.registerCardPosition(seven, Offset(5f, 5f), size)+        vm.landFlight(first.id)+        val k = vm.uiState.value.klondike!!+        assertEquals(1, k.tableauPiles[0].faceUp.size)+        assertEquals(seven, k.tableauPiles[1].faceUp.last())+        assertEquals(Offset(5f, 5f), vm.flights.value.single().from)+    }++    @Test fun dragOfCardInTheAirIsRefusedButOthersMayDrag() {+        val vm = vm()+        val seven = c(Suit.HEARTS, Rank.SEVEN)+        val king = c(Suit.CLUBS, Rank.KING)+        setK(+            vm,+            KlondikeState(+                waste = listOf(seven),+                tableauPiles = piles(TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.EIGHT))), TableauPile(faceUp = listOf(king))),+            ),+        )+        assertTrue(vm.requestAutoMove("waste", tap, size))+        assertFalse(vm.startDrag("tableau_0_0", Offset.Zero, size)) // carries the airborne seven+        assertFalse(vm.startDrag("tableau_0_1", Offset.Zero, size))+        assertTrue(vm.startDrag("tableau_1_0", Offset.Zero, size))+        assertEquals(listOf(king), vm.dragInfo.value!!.cards)+    }++    @Test fun undoAndGiveUpClearFlights() {         val vm = vm()         setK(vm, KlondikeState(waste = listOf(c(Suit.HEARTS, Rank.ACE))))         assertTrue(vm.requestAutoMove("waste", tap))         vm.undo()-        assertNull(vm.flightInfo.value)+        assertTrue(vm.flights.value.isEmpty())+        assertEquals(listOf(c(Suit.HEARTS, Rank.ACE)), vm.uiState.value.klondike!!.waste)         assertTrue(vm.requestAutoMove("waste", tap))         vm.giveUp()-        assertNull(vm.flightInfo.value)+        assertTrue(vm.flights.value.isEmpty())     } -    @Test fun freeCellAceStagesFoundationFlight() {+    @Test fun freeCellAceFliesToFoundation() {         val vm = vm()         val ace = c(Suit.HEARTS, Rank.ACE)         setF(vm, FreeCellState(tableauPiles = listOf(listOf(ace)) + List(7) { emptyList() }))         assertTrue(vm.requestAutoMove("tableau_0_0", tap))-        assertEquals("foundation_0", vm.flightInfo.value?.targetId)-        vm.commitFlight()+        assertEquals(FlightTarget.Slot("foundation_0", 0, 0), vm.flights.value.single().target)         val f = vm.uiState.value.freeCell!!         assertTrue(f.tableauPiles[0].isEmpty())         assertEquals(listOf(ace), f.foundations[0])     }++    @Test fun freeCellCardFliesToFlatColumnSlotAndCell() {+        val vm = vm()+        val six = c(Suit.HEARTS, Rank.SIX)+        setF(+            vm,+            FreeCellState(+                tableauPiles = listOf(listOf(c(Suit.CLUBS, Rank.TWO), six), listOf(c(Suit.DIAMONDS, Rank.FOUR), c(Suit.SPADES, Rank.SEVEN))) ++                    List(6) { emptyList() },+            ),+        )+        vm.dropTargets["tableau_1"] = Rect(0f, 0f, 1f, 1f)+        assertTrue(vm.requestAutoMove("tableau_0_1", tap))+        assertEquals(FlightTarget.Slot("tableau_1", 0, 2), vm.flights.value.single().target)+    }++    @Test fun pileRangeCoversOnlyItsOwnCardsAndSlots() {+        val a = c(Suit.HEARTS, Rank.ACE)+        val b = c(Suit.HEARTS, Rank.TWO)+        val range = PileRange("tableau_0", 2, listOf(a, b))+        assertTrue(range.covers("tableau_0", 2, a))+        assertTrue(range.covers("tableau_0", 3, b))+        assertFalse(range.covers("tableau_0", 3, a)) // right slot, wrong card+        assertFalse(range.covers("tableau_1", 2, a))+        assertFalse(range.covers("tableau_0", 1, a))+        assertTrue(range.overlaps(PileRange("tableau_0", 3, listOf(b))))+        assertFalse(range.overlaps(PileRange("tableau_0", 4, listOf(b))))+        assertFalse(range.overlaps(PileRange("tableau_1", 2, listOf(a))))+    } }
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 16b1246923..608654614b 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@@ -14,11 +14,11 @@ import kotlinx.coroutines.flow.StateFlow class RecordingActions : SolitaireActions {     override val dragInfo: StateFlow<DragInfo?> = MutableStateFlow(null)     val dragFlow = dragInfo as MutableStateFlow<DragInfo?>-    override val flightInfo: StateFlow<CardFlight?> = MutableStateFlow(null)-    val flightFlow = flightInfo as MutableStateFlow<CardFlight?>+    override val flights: StateFlow<List<CardFlight>> = MutableStateFlow(emptyList())+    val flightsFlow = flights as MutableStateFlow<List<CardFlight>>     override val dropTargets: MutableMap<String, Rect> = mutableMapOf()     val cardPositions: MutableMap<Card, Offset> = mutableMapOf()-    override fun registerCardPosition(card: Card, position: Offset) { cardPositions[card] = position }+    override fun registerCardPosition(card: Card, position: Offset, size: IntSize) { cardPositions[card] = position }     val calls = mutableListOf<String>()      override fun startDrag(sourceId: String, startPos: Offset, cardSize: IntSize): Boolean {@@ -35,12 +35,11 @@ class RecordingActions : SolitaireActions {     override fun pyramidTapCard(id: String) { calls += "pyramidTapCard:$id" }     override fun pyramidDealStock() { calls += "pyramidDealStock" }     override fun autoMove(sourceId: String) { calls += "autoMove:$sourceId" }-    override fun requestAutoMove(sourceId: String, startPos: Offset): Boolean {+    override fun requestAutoMove(sourceId: String, startPos: Offset, cardSize: IntSize): Boolean {         calls += "autoMove:$sourceId"         return true     }-    override fun commitFlight() { calls += "commitFlight" }-    override fun cancelFlight() { calls += "cancelFlight" }+    override fun landFlight(id: Long) { calls += "landFlight:$id" }     override fun undo() { calls += "undo" }     override fun restart() { calls += "restart" }     override fun giveUp() { calls += "giveUp" }