Modern Apps git

← Modern-Apps.git

solitaire: autocomplete recycles the stock; offer only winnable (#owner-report)

Commit
eba1bda8c5fc2f6d01438b910c2a78bfd1894198
Author
Vayun Mathur <[email protected]>
When
2026-11-12 20:51 UTC (23 days ago)
Parents
7b5580f
Symptom (owner report): "autocomplete should be able to reload the
deck if needed instead of getting stuck when reaching the end".

Root cause: the auto-complete loop (runAutoCompleteLoop and the
animated advanceAutoComplete) only ever moved cards to foundations
and drew ONE stock card at a time. It never recycled the waste, so
once the stock ran dry with a needed card buried in the waste the run
just ended mid-game. It also ignored draw-three (always drew one).
And canKlondikeAutoComplete offered the button whenever any card
could move or the stock was non-empty ("drawing always makes
progress"), so it offered boards the run could not finish.

Fix: new pure planner in platform/KlondikeAutoComplete.kt.
- nextKlondikeAutoCompleteStep(state) plays as a player would with
  foundation moves only: waste top up, else the first tableau top
  that fits, else draw (one or three, per the deal's draw mode, the
  same way the stock tap draws), else recycle the waste if a pass is
  left (unlimited stays unlimited). Steps are ToFoundation / Draw /
  Recycle, each carrying the board it leaves.
- planKlondikeAutoComplete(state) chains steps to a finished board or
  returns null: face-down cards or a won game -> null; out of moves
  and passes -> null; a full pass with no foundation move between two
  recycles -> null (the next pass would be identical, so unlimited
  passes would cycle forever); hard step cap as a backstop.
- canKlondikeAutoComplete = plan != null. The offer therefore already
  accounts for the pass limit, so a started run can never run out of
  passes mid-way.
- The animated run, the Skip button and the instant path all use the
  same step function, so they cannot disagree with the offer. Draws
  and recycles are not counted as moves (as before for draws); each
  foundation move counts one. Recycled cards drop their stale
  positions, so their later hops apply instantly instead of flying
  from where they used to be. A hop whose card is still in the air
  from a player's move waits for that flight to land.
- GameBoardScreen remembers the offer per board, not per timer tick.

User-visible effect: Auto-complete is only offered when it will win,
and it turns the stock over (within the pass limit) instead of
stopping at the end of the stock; draw-three games draw in threes.

Verification: new KlondikeAutoCompletePlanTest (tableau/waste/stock
finish order, recycle with one pass vs none, unlimited stays
unlimited, draw-three triplets incl. cycle detection and a lined-up
finish, face-down/won never offered, stuck board, step priority);
SolitaireAutoCompleteTest: animated, instant and skipped runs recycle
to a win, not offered/started with no passes left;
SolitaireRulesTest.autoCompleteVisibility updated to the finish-only
semantics. :games:solitaire:testDevUnitTest in the container build.

Detekt (kept the touched files clean): the view-model side of the run
moves to platform/KlondikeAutoCompleteRun.kt (SolitaireKlondikeOps.kt
was over the 30-functions-per-file limit already on main) and
advanceAutoComplete is split into takeAutoCompleteStep/flyHop;
currentVariant becomes an extension (SolitaireViewModel was over the
25-functions limit on main); SolitaireFlight's landingSlot and queued
tap replay are split to stay under the complexity/jump limits.

Diff

games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoComplete.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoComplete.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoComplete.ktnew file mode 100644index 0000000000..6c4ae1f9ce--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoComplete.kt@@ -0,0 +1,162 @@+package com.vayunmathur.games.solitaire.platform++import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.DrawMode+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import com.vayunmathur.games.solitaire.data.isOneHigherThan++// ---- Klondike auto-complete planning (pure) ----+// The run, the skip and the offer all derive from these functions, so the button is only+// offered for a board the run will actually finish, and the run can never strand itself.++/** One move of a Klondike auto-complete, with the board it leaves behind. */+sealed interface AutoCompleteStep {+    val after: KlondikeState++    /** [card] goes from [sourceId] (`waste` or `tableau_<col>_<index>`) up to foundation [foundationIndex]. */+    data class ToFoundation(+        val card: Card,+        val sourceId: String,+        val foundationIndex: Int,+        override val after: KlondikeState,+    ) : AutoCompleteStep++    /** Draws from the stock onto the waste: one card or three, as the deal's draw mode says. */+    data class Draw(override val after: KlondikeState) : AutoCompleteStep++    /** Turns the waste back over into the stock, spending one of the deal's passes. */+    data class Recycle(override val after: KlondikeState) : AutoCompleteStep+}++/**+ * The move auto-complete makes next from [state], playing as a player would with only+ * foundation moves: the waste top to its foundation, else the first tableau top that fits,+ * else draw (respecting draw-one/draw-three), else recycle the waste if a pass is left.+ * Null when none of those is possible. Moving a card up never removes an option, so taking+ * any fitting card before drawing is safe.+ */+fun nextKlondikeAutoCompleteStep(state: KlondikeState): AutoCompleteStep? =+    wasteToFoundation(state)+        ?: tableauToFoundation(state)+        ?: drawStep(state)+        ?: recycleStep(state)++/**+ * Every step auto-complete takes from [state] to a finished board, or null when it cannot+ * finish under the deal's draw mode and pass limit (or must not be offered: a face-down+ * card is still on the tableau, or the game is already won).+ *+ * A pass that turns over the whole stock without a single foundation move leaves the board+ * exactly as it was, so a second recycle with no progress since the first means the run+ * would cycle forever with unlimited passes; that board cannot finish either.+ */+fun planKlondikeAutoComplete(state: KlondikeState): List<AutoCompleteStep>? {+    if (state.isWon || state.tableauPiles.any { it.faceDown.isNotEmpty() }) return null+    val steps = mutableListOf<AutoCompleteStep>()+    var current = state+    var recycled = false+    var progressSinceRecycle = false+    while (!current.allOnFoundations()) {+        val step = nextKlondikeAutoCompleteStep(current) ?: return null+        when (step) {+            is AutoCompleteStep.ToFoundation -> progressSinceRecycle = true+            is AutoCompleteStep.Recycle -> {+                if (recycled && !progressSinceRecycle) return null+                recycled = true+                progressSinceRecycle = false+            }+            is AutoCompleteStep.Draw -> Unit+        }+        steps += step+        current = step.after+        if (steps.size > MAX_PLAN_STEPS) return null+    }+    return steps+}++/** Whether auto-complete may be offered: only when [planKlondikeAutoComplete] finishes. */+fun canKlondikeAutoComplete(state: KlondikeState): Boolean = planKlondikeAutoComplete(state) != null++/** The board a finished auto-complete leaves, or [state] itself when it cannot finish. */+internal fun finishedKlondikeAutoComplete(state: KlondikeState): KlondikeState =+    planKlondikeAutoComplete(state)?.lastOrNull()?.after ?: state++private fun KlondikeState.allOnFoundations(): Boolean =+    foundations.sumOf { it.size } == Suit.entries.size * Rank.entries.size++private fun wasteToFoundation(state: KlondikeState): AutoCompleteStep? {+    val card = state.waste.lastOrNull() ?: return null+    val fi = fittingFoundation(state, card) ?: return null+    return AutoCompleteStep.ToFoundation(+        card = card,+        sourceId = WASTE,+        foundationIndex = fi,+        after = state.copy(+            waste = state.waste.dropLast(1),+            foundations = state.foundations.withCardOn(fi, card),+            moveCount = state.moveCount + 1,+        ),+    )+}++private fun tableauToFoundation(state: KlondikeState): AutoCompleteStep? {+    val (col, fi) = state.tableauPiles.withIndex().firstNotNullOfOrNull { (c, pile) ->+        pile.faceUp.lastOrNull()?.let { fittingFoundation(state, it) }?.let { c to it }+    } ?: return null+    val pile = state.tableauPiles[col]+    val card = pile.faceUp.last()+    val piles = state.tableauPiles.toMutableList()+    piles[col] = flipped(pile.copy(faceUp = pile.faceUp.dropLast(1)))+    return AutoCompleteStep.ToFoundation(+        card = card,+        sourceId = "$TABLEAU_PREFIX${col}_${pile.faceUp.lastIndex}",+        foundationIndex = fi,+        after = state.copy(+            tableauPiles = piles,+            foundations = state.foundations.withCardOn(fi, card),+            moveCount = state.moveCount + 1,+        ),+    )+}++/** Draws like the stock tap does (the drawn cards' last ends up on top); not counted as a move. */+private fun drawStep(state: KlondikeState): AutoCompleteStep? {+    if (state.stock.isEmpty()) return null+    val count = if (state.drawMode == DrawMode.DRAW_THREE) DRAW_THREE_COUNT else 1+    val drawn = state.stock.takeLast(count).reversed()+    return AutoCompleteStep.Draw(state.copy(stock = state.stock.dropLast(count), waste = state.waste + drawn))+}++/** Recycles like the empty-stock tap does; unlimited passes stay unlimited. */+private fun recycleStep(state: KlondikeState): AutoCompleteStep? {+    if (state.waste.isEmpty() || state.redealsRemaining <= 0) return null+    val remaining = if (state.redealsRemaining == Int.MAX_VALUE) Int.MAX_VALUE else state.redealsRemaining - 1+    return AutoCompleteStep.Recycle(+        state.copy(stock = state.waste.reversed(), waste = emptyList(), redealsRemaining = remaining),+    )+}++private fun fittingFoundation(state: KlondikeState, card: Card): Int? =+    state.foundations.indices.firstOrNull { fi ->+        val pile = state.foundations[fi]+        if (pile.isEmpty()) card.rank == Rank.ACE && card.suit == Suit.entries[fi]+        else card.suit == pile.last().suit && card.isOneHigherThan(pile.last())+    }++private fun List<List<Card>>.withCardOn(index: Int, card: Card): List<List<Card>> =+    mapIndexed { i, pile -> if (i == index) pile + card else pile }++private fun flipped(pile: TableauPile): TableauPile =+    if (pile.faceUp.isEmpty() && pile.faceDown.isNotEmpty()) {+        pile.copy(faceDown = pile.faceDown.dropLast(1), faceUp = listOf(pile.faceDown.last()))+    } else {+        pile+    }++private const val DRAW_THREE_COUNT = 3++/** Far above any real plan (52 foundation moves plus at most a stock's worth of draws per productive pass). */+private const val MAX_PLAN_STEPS = 5_000
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoCompleteRun.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoCompleteRun.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoCompleteRun.ktnew file mode 100644index 0000000000..25c8b1d8fe--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoCompleteRun.kt@@ -0,0 +1,116 @@+package com.vayunmathur.games.solitaire.platform++import com.vayunmathur.games.solitaire.data.KlondikeState+import kotlinx.coroutines.flow.update++// ---- Klondike auto-complete: the run on the view model ----+// Planning is pure and lives in KlondikeAutoComplete.kt; this drives it on live state.++/** Instant auto-complete: applies the whole plan in one step (one history entry). */+internal fun SolitaireViewModel.klondikeAutoCompleteImpl() {+    val state = uiStateInternal.value.klondike ?: return+    val finished = planKlondikeAutoComplete(state)?.lastOrNull()?.after ?: return+    saveHistory()+    uiStateInternal.update { it.copy(klondike = finished) }+    checkKlondikeWin()+}++/**+ * Animated auto-complete entry: the button tap (and re-tap) lands here. Merely+ * offering the button locks nothing; only a started run pauses board input, and+ * board input then stops the run ([stopAutoComplete]). Re-tapping the button+ * mid-run skips straight to the finished board. The run is only started for a+ * board [planKlondikeAutoComplete] finishes, so it can never strand itself at the+ * end of the stock. 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+    saveHistory()+    queuedTaps.clear()+    autoCompleteRunningInternal.value = true+    advanceAutoComplete()+}++/**+ * Steps the run forward from the live state with [nextKlondikeAutoCompleteStep] — the+ * same function the plan behind the offer is made of — applying each step to game state+ * at once. A foundation hop whose card has a known position launches a fast flight and+ * the run waits for its landing; draws, recycles and hops of never-laid-out cards apply+ * instantly. A hop whose card is still in the air from a player's move waits for that+ * flight to land first, so the card is never drawn twice.+ */+internal fun SolitaireViewModel.advanceAutoComplete() {+    while (autoCompleteRunningInternal.value) {+        when (takeAutoCompleteStep()) {+            StepOutcome.APPLIED -> Unit+            StepOutcome.WAITING -> return+            StepOutcome.DONE -> break+        }+    }+    autoCompleteRunningInternal.value = false+    autoCompleteFlightId = null+    checkKlondikeWin()+}++private enum class StepOutcome { APPLIED, WAITING, DONE }++/** Applies the next step to game state, flying it when it is a hop of a laid-out card. */+private fun SolitaireViewModel.takeAutoCompleteStep(): StepOutcome {+    val current = uiStateInternal.value.klondike+    val step = current?.let { nextKlondikeAutoCompleteStep(it) } ?: return StepOutcome.DONE+    if (step is AutoCompleteStep.ToFoundation && isAirborne(hopSource(current, step))) return StepOutcome.WAITING+    uiStateInternal.update { it.copy(klondike = step.after) }+    // Turned face down: their laid-out positions no longer mean anything.+    if (step is AutoCompleteStep.Recycle) current.waste.forEach { cardPositions.remove(it) }+    return if (step is AutoCompleteStep.ToFoundation && flyHop(step)) StepOutcome.WAITING else StepOutcome.APPLIED+}++/** Launches the fast flight for [step]; false when its card was never laid out. */+private fun SolitaireViewModel.flyHop(step: AutoCompleteStep.ToFoundation): Boolean {+    val from = cardPositions[step.card] ?: return false+    val flight = launchFlight(+        cards = listOf(step.card),+        from = from,+        targetId = "$FOUNDATION_PREFIX${step.foundationIndex}",+        cardSize = lastCardSize,+        fast = true,+    ) ?: return false+    autoCompleteFlightId = flight.id+    return true+}++/** Where a hop's card sits before the hop, as a pile range. */+private fun hopSource(state: KlondikeState, step: AutoCompleteStep.ToFoundation): PileRange =+    if (step.sourceId == WASTE) {+        PileRange(WASTE, state.waste.lastIndex, listOf(step.card))+    } else {+        val col = step.sourceId.removePrefix(TABLEAU_PREFIX).substringBefore("_")+        PileRange("$TABLEAU_PREFIX$col", step.sourceId.substringAfterLast("_").toInt(), listOf(step.card))+    }++/**+ * Stops a running auto-complete where it is: every step taken so far stays applied (one+ * undo still restores the pre-run board), the hop in the air lands, and the board is+ * playable again with the offer back if it can still finish. A tap, drag or stock tap+ * on the board mid-run lands here.+ */+internal fun SolitaireViewModel.stopAutoComplete() {+    autoCompleteRunningInternal.value = false+    autoCompleteFlightId = null+}++/**+ * Skips the animation: applies the rest of the plan on the live state at once. Hops+ * already in the air are left to land — their moves are applied already.+ */+internal fun SolitaireViewModel.skipAutoCompleteToEnd() {+    autoCompleteRunningInternal.value = false+    autoCompleteFlightId = null+    val state = uiStateInternal.value.klondike ?: return+    uiStateInternal.update { it.copy(klondike = finishedKlondikeAutoComplete(state)) }+    checkKlondikeWin()+}
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 24f405cbf7..3701bf6daa 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@@ -196,56 +196,63 @@ internal fun SolitaireViewModel.launchReturnFlight(range: PileRange, from: Offse  * 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.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+internal fun SolitaireViewModel.landingSlot(targetId: String, cards: List<Card>): FlightTarget.Slot? = when {+    targetId.startsWith(FOUNDATION_PREFIX) -> {+        val fi = targetId.removePrefix(FOUNDATION_PREFIX).toIntOrNull()+        currentFoundations()?.getOrNull(fi ?: -1)?.let { pile ->             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     }+    targetId.startsWith(FREECELL_PREFIX) -> FlightTarget.Slot(targetId, 0, 0)+    targetId.startsWith(TABLEAU_PREFIX) -> tableauLandingSlot(targetId, cards)+    else -> null+}++private fun SolitaireViewModel.tableauLandingSlot(targetId: String, cards: List<Card>): FlightTarget.Slot? {+    val col = targetId.removePrefix(TABLEAU_PREFIX).toIntOrNull() ?: return null+    val state = uiStateInternal.value+    // (face-down count, face-up count) of the column after the move.+    val counts = 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+    return FlightTarget.Slot(targetId, counts.first, (counts.second - cards.size).coerceAtLeast(0)) }  /**  * 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.+ * replayed against the live state (not mid-run: a run owns the board until it stops).  */ 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()+    if (id == autoCompleteFlightId) autoCompleteFlightId = null+    // The run continues when its own hop lands, or — while it waits on a card a player's+    // move still has in the air — when that flight does.+    if (autoCompleteRunningInternal.value && autoCompleteFlightId == null) advanceAutoComplete()+    if (!autoCompleteRunningInternal.value) replayQueuedTaps() }  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)+    pending.forEach { replayQueuedTap(it) }+}++private fun SolitaireViewModel.replayQueuedTap(tap: QueuedTap) {+    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) return+    if (isAirborne(range)) {+        queuedTaps.addLast(tap)+        return     }+    val targetId = resolveAutoMoveTarget(tap.sourceId) ?: return+    flyMove(tap.sourceId, targetId, range.cards, cardPositions[tap.card], lastCardSize) }  /** Drops every flight and queued tap: undo, restart, mode switch and give-up replace the board. */
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 f5cfea5c26..067b3ac49f 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@@ -214,189 +214,6 @@ fun canMoveKlondikeFoundationToTableau(state: KlondikeState, foundationIndex: In     return canPlaceCardOnKlondikeTableau(card, pile) } -internal fun SolitaireViewModel.klondikeAutoCompleteImpl() {-    val state = uiStateInternal.value.klondike ?: return-    if (!canKlondikeAutoComplete(state)) return-    saveHistory()-    uiStateInternal.update { it.copy(klondike = runAutoCompleteLoop(state)) }-    checkKlondikeWin()-}--/**- * The drain-and-draw loop both the instant auto-complete and the skip path share:- * move every fitting waste/tableau top to its foundation, draw one stock card when- * stuck, repeat until the stock is spent and nothing moves. Pure, so the animated- * run stages the same transitions one flight at a time.- */-internal fun SolitaireViewModel.runAutoCompleteLoop(start: KlondikeState): KlondikeState {-    var current = start-    var madeProgress = true-    while (madeProgress) {-        madeProgress = false-        current = drainToFoundations(current) { current = it; madeProgress = true }-        // Draw one stock card and try again-        if (current.stock.isNotEmpty()) {-            current = current.copy(-                stock = current.stock.dropLast(1),-                waste = current.waste + current.stock.last()-            )-            madeProgress = true-        }-    }-    return current-}--/**- * Animated auto-complete entry: the button tap (and re-tap) lands here. Merely- * offering the button locks nothing; only a started run pauses board input, and- * board input then stops the run ([stopAutoComplete]). Re-tapping the button- * 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-    saveHistory()-    autoCompleteRunningInternal.value = true-    advanceAutoComplete()-}--/**- * 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() {-    while (autoCompleteRunningInternal.value) {-        val current = uiStateInternal.value.klondike ?: break-        val after = moveWasteToFoundation(current) ?: moveTableauToFoundation(current)-        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()-                ))-            }-            continue-        }-        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 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, 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) }--/**- * Stops a running auto-complete where it is: every step taken so far stays applied (one- * undo still restores the pre-run board), the hop in the air lands, and the board is- * playable again with the offer back if it can still finish. A tap, drag or stock tap- * on the board mid-run lands here.- */-internal fun SolitaireViewModel.stopAutoComplete() {-    autoCompleteRunningInternal.value = false-    autoCompleteFlightId = null-}--/**- * 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.skipAutoCompleteToEnd() {-    autoCompleteRunningInternal.value = false-    autoCompleteFlightId = null-    val state = uiStateInternal.value.klondike ?: return-    uiStateInternal.update { it.copy(klondike = runAutoCompleteLoop(state)) }-    checkKlondikeWin()-}--private fun SolitaireViewModel.drainToFoundations(-    start: KlondikeState,-    onMove: (KlondikeState) -> Unit,-): KlondikeState {-    var current = start-    var moved = true-    while (moved) {-        moved = false-        val afterWaste = moveWasteToFoundation(current)-        if (afterWaste != null) {-            current = afterWaste-            moved = true-            onMove(current)-            continue-        }-        val afterTableau = moveTableauToFoundation(current)-        if (afterTableau != null) {-            current = afterTableau-            moved = true-            onMove(current)-        }-    }-    return current-}--private fun SolitaireViewModel.moveWasteToFoundation(current: KlondikeState): KlondikeState? {-    if (current.waste.isEmpty()) return null-    val card = current.waste.last()-    for (fi in current.foundations.indices) {-        if (!canPlaceOnFoundation(card, current.foundations[fi], fi)) continue-        val newFoundations = current.foundations.toMutableList()-        newFoundations[fi] = newFoundations[fi] + card-        return current.copy(-            waste = current.waste.dropLast(1),-            foundations = newFoundations,-            moveCount = current.moveCount + 1-        )-    }-    return null-}--private fun SolitaireViewModel.moveTableauToFoundation(current: KlondikeState): KlondikeState? {-    for (i in current.tableauPiles.indices) {-        val pile = current.tableauPiles[i]-        if (pile.faceUp.isEmpty()) continue-        val card = pile.faceUp.last()-        for (fi in current.foundations.indices) {-            if (!canPlaceOnFoundation(card, current.foundations[fi], fi)) continue-            val newFoundations = current.foundations.toMutableList()-            newFoundations[fi] = newFoundations[fi] + card-            val newPiles = current.tableauPiles.toMutableList()-            newPiles[i] = autoFlip(pile.copy(faceUp = pile.faceUp.dropLast(1)))-            return current.copy(-                tableauPiles = newPiles,-                foundations = newFoundations,-                moveCount = current.moveCount + 1-            )-        }-    }-    return null-}- /** One fewer recycle left; unlimited (RELAXED) stays unlimited. */ private fun remainingAfterRecycle(redealsRemaining: Int): Int =     if (redealsRemaining == Int.MAX_VALUE) Int.MAX_VALUE else redealsRemaining - 1@@ -417,29 +234,6 @@ internal fun SolitaireViewModel.canPlaceOnFoundation(     foundationIndex: Int, ): Boolean = canPlaceCardOnFoundation(card, foundation, foundationIndex) -/**- * Whether the Auto-complete button should show for [state] (issue #730).- *- * The button used to appear whenever every tableau card was face-up, even when- * [klondikeAutoCompleteImpl] could not move a single card: stock exhausted with- * neither the waste top nor any tableau top fitting its foundation. Drawing- * from the stock always makes progress, so only a stock-empty, move-less board- * hides the button.- */-fun canKlondikeAutoComplete(state: KlondikeState): Boolean {-    if (state.isWon) return false-    if (state.tableauPiles.any { it.faceDown.isNotEmpty() }) return false-    if (state.stock.isNotEmpty()) return true-    val wasteTop = state.waste.lastOrNull()-    if (wasteTop != null && state.foundations.indices.any { fi ->-        canPlaceCardOnFoundation(wasteTop, state.foundations[fi], fi)-    }) return true-    return state.tableauPiles.any { pile ->-        val top = pile.faceUp.lastOrNull() ?: return@any false-        state.foundations.indices.any { fi -> canPlaceCardOnFoundation(top, state.foundations[fi], fi) }-    }-}- /** Foundation rule without a ViewModel receiver, so the board can preview it. */ private fun canPlaceCardOnFoundation(     card: Card,
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 8144485699..bb73925047 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@@ -135,16 +135,6 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio         } ?: GameConfig()     } -    internal fun currentVariant(): String = with(uiStateInternal.value) {-        when (gameMode) {-            GameMode.KLONDIKE -> klondike?.variant-            GameMode.SPIDER -> spider?.variant-            GameMode.FREECELL -> freeCell?.variant-            GameMode.PYRAMID -> pyramid?.variant-            null -> null-        } ?: ""-    }-     override fun giveUp() {         clearMotion()         val mode = uiStateInternal.value.gameMode ?: return@@ -308,3 +298,13 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio     } } +/** The stats variant key of the active game ("" without one). */+internal fun SolitaireViewModel.currentVariant(): String = with(uiStateInternal.value) {+    when (gameMode) {+        GameMode.KLONDIKE -> klondike?.variant+        GameMode.SPIDER -> spider?.variant+        GameMode.FREECELL -> freeCell?.variant+        GameMode.PYRAMID -> pyramid?.variant+        null -> null+    } ?: ""+}
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 cf21efa7ec..6f5370ae2a 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@@ -82,7 +82,14 @@ fun GameBoardScreen(state: SolitaireUiState, mode: GameMode, actions: SolitaireA                         // foundations can otherwise hide it under the player's tap),                         // and any tap on the board mid-run stops the run instead.                         val autoCompleteRunning by actions.autoCompleteRunning.collectAsState()-                        if (canKlondikeAutoComplete(it) || autoCompleteRunning) {+                        // Offered only when the run can actually finish (stock draws and+                        // recycles under the pass limit included); keyed on the board, not+                        // the ticking timer.+                        val canAutoComplete = remember(+                            it.stock, it.waste, it.tableauPiles, it.foundations,+                            it.redealsRemaining, it.drawMode, it.isWon,+                        ) { canKlondikeAutoComplete(it) }+                        if (canAutoComplete || autoCompleteRunning) {                             Button(onClick = { actions.klondikeAutoComplete() }, Modifier.align(Alignment.CenterHorizontally)) {                                 Text(stringResource(if (autoCompleteRunning) R.string.skip else R.string.auto_complete))                             }
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoCompletePlanTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoCompletePlanTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoCompletePlanTest.ktnew file mode 100644index 0000000000..243ab301f3--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/KlondikeAutoCompletePlanTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.games.solitaire.platform++import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.DrawMode+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.Rank+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.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** The pure "can auto-complete finish" plan: foundation moves, draws, recycles, pass limits. */+class KlondikeAutoCompletePlanTest {++    private fun hearts(rank: Rank) = Card(Suit.HEARTS, rank)++    /** Spades, diamonds and clubs complete; hearts up to (not including) [nextHeart]. */+    private fun foundationsUpTo(nextHeart: Rank): List<List<Card>> = Suit.entries.map { suit ->+        if (suit == Suit.HEARTS) Rank.entries.filter { it.value < nextHeart.value }.map { hearts(it) }+        else Rank.entries.map { Card(suit, it) }+    }++    private fun piles(vararg piles: TableauPile) = piles.toList() + List(7 - piles.size) { TableauPile() }++    private fun KlondikeState.finish(): KlondikeState? = planKlondikeAutoComplete(this)?.lastOrNull()?.after++    private fun KlondikeState.isComplete() = foundations.all { it.size == 13 }++    @Test fun finishesFromTableauWasteAndStock() {+        val state = KlondikeState(+            stock = listOf(hearts(Rank.KING)),+            waste = listOf(hearts(Rank.JACK)),+            tableauPiles = piles(TableauPile(faceUp = listOf(hearts(Rank.QUEEN), hearts(Rank.TEN)))),+            foundations = foundationsUpTo(Rank.TEN),+        )+        val plan = assertNotNull(planKlondikeAutoComplete(state))+        assertTrue(plan.last().after.isComplete())+        assertTrue(canKlondikeAutoComplete(state))+        // The tableau ten, the waste jack, the tableau queen, then the stock king.+        val flown = plan.filterIsInstance<AutoCompleteStep.ToFoundation>()+        assertEquals(listOf(Rank.TEN, Rank.JACK, Rank.QUEEN, Rank.KING), flown.map { it.card.rank })+        assertEquals(listOf("tableau_0_1", "waste", "tableau_0_0", "waste"), flown.map { it.sourceId })+    }++    @Test fun recyclesTheStockWhenAPassIsLeft() {+        // The waste top (K) is buried on top of the Q it needs: only a recycle reaches the Q.+        val state = KlondikeState(+            waste = listOf(hearts(Rank.QUEEN), hearts(Rank.KING)),+            foundations = foundationsUpTo(Rank.QUEEN),+            redealsRemaining = 1,+        )+        val plan = assertNotNull(planKlondikeAutoComplete(state))+        assertIs<AutoCompleteStep.Recycle>(plan.first())+        val end = plan.last().after+        assertTrue(end.isComplete())+        assertEquals(0, end.redealsRemaining)+        // Out of passes, the same board cannot finish, so it is not offered.+        assertNull(planKlondikeAutoComplete(state.copy(redealsRemaining = 0)))+        assertFalse(canKlondikeAutoComplete(state.copy(redealsRemaining = 0)))+    }++    @Test fun unlimitedPassesStayUnlimited() {+        val state = KlondikeState(+            waste = listOf(hearts(Rank.QUEEN), hearts(Rank.KING)),+            foundations = foundationsUpTo(Rank.QUEEN),+            redealsRemaining = Int.MAX_VALUE,+        )+        assertEquals(Int.MAX_VALUE, state.finish()!!.redealsRemaining)+    }++    @Test fun drawThreeRespectsItsTripletsAndPassLimit() {+        // Stock top is the ten: drawing one at a time reaches 10, J, Q, K in order.+        val stock = listOf(hearts(Rank.KING), hearts(Rank.QUEEN), hearts(Rank.JACK), hearts(Rank.TEN))+        val base = KlondikeState(stock = stock, foundations = foundationsUpTo(Rank.TEN), redealsRemaining = 0)+        assertTrue(base.copy(drawMode = DrawMode.DRAW_ONE).finish()!!.isComplete())+        // Drawing three puts the queen on top of the ten: no single pass can finish...+        val drawThree = base.copy(drawMode = DrawMode.DRAW_THREE)+        assertNull(planKlondikeAutoComplete(drawThree))+        val firstDraw = assertIs<AutoCompleteStep.Draw>(nextKlondikeAutoCompleteStep(drawThree))+        assertEquals(hearts(Rank.QUEEN), firstDraw.after.waste.last())+        assertEquals(listOf(hearts(Rank.KING)), firstDraw.after.stock)+        // ...and every pass deals the same triplets, so even unlimited passes would cycle.+        assertNull(planKlondikeAutoComplete(drawThree.copy(redealsRemaining = Int.MAX_VALUE)))+        assertNull(planKlondikeAutoComplete(drawThree.copy(redealsRemaining = 5)))+    }++    @Test fun drawThreeFinishesWhenTheTripletsLineUp() {+        // Draw-three order: the third card from the top surfaces first.+        val stock = listOf(hearts(Rank.KING), hearts(Rank.TEN), hearts(Rank.JACK), hearts(Rank.QUEEN))+        val state = KlondikeState(+            stock = stock,+            drawMode = DrawMode.DRAW_THREE,+            foundations = foundationsUpTo(Rank.TEN),+            redealsRemaining = 1,+        )+        val plan = assertNotNull(planKlondikeAutoComplete(state))+        assertTrue(plan.last().after.isComplete())+    }++    @Test fun neverOfferedWithFaceDownCardsOrWhenWon() {+        val faceDown = KlondikeState(+            tableauPiles = piles(TableauPile(faceDown = listOf(hearts(Rank.KING)), faceUp = listOf(hearts(Rank.QUEEN)))),+            foundations = foundationsUpTo(Rank.QUEEN),+        )+        assertNull(planKlondikeAutoComplete(faceDown))+        val won = KlondikeState(foundations = foundationsUpTo(Rank.KING).let { f ->+            f.mapIndexed { i, pile -> if (i == 0) pile + hearts(Rank.KING) else pile }+        }, isWon = true)+        assertNull(planKlondikeAutoComplete(won))+        assertFalse(canKlondikeAutoComplete(won))+    }++    @Test fun stuckBoardWithEmptyStockIsNotOffered() {+        // Hearts need the ten, but only J..K are left, so nothing can ever move.+        val state = KlondikeState(+            waste = listOf(hearts(Rank.JACK)),+            tableauPiles = piles(TableauPile(faceUp = listOf(hearts(Rank.KING), hearts(Rank.QUEEN)))),+            foundations = foundationsUpTo(Rank.TEN),+            redealsRemaining = Int.MAX_VALUE,+        )+        assertNull(planKlondikeAutoComplete(state))+    }++    @Test fun nextStepPrefersWasteThenTableauThenDrawThenRecycle() {+        val f = foundationsUpTo(Rank.TEN)+        val waste = KlondikeState(+            waste = listOf(hearts(Rank.TEN)),+            tableauPiles = piles(TableauPile(faceUp = listOf(hearts(Rank.TEN)))),+            foundations = f,+        )+        assertEquals("waste", assertIs<AutoCompleteStep.ToFoundation>(nextKlondikeAutoCompleteStep(waste)).sourceId)+        val draw = KlondikeState(stock = listOf(hearts(Rank.JACK)), waste = listOf(hearts(Rank.KING)), foundations = f)+        assertIs<AutoCompleteStep.Draw>(nextKlondikeAutoCompleteStep(draw))+        val recycle = KlondikeState(waste = listOf(hearts(Rank.KING)), foundations = f, redealsRemaining = 1)+        assertIs<AutoCompleteStep.Recycle>(nextKlondikeAutoCompleteStep(recycle))+        assertNull(nextKlondikeAutoCompleteStep(recycle.copy(redealsRemaining = 0)))+    }+}
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 5c0a3914a9..126701368b 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@@ -184,6 +184,67 @@ class SolitaireAutoCompleteTest {         assertTrue(vm.uiState.value.klondike!!.isWon)     } +    /**+     * The waste King sits on the Queen it needs, the stock is empty and one pass is left:+     * finishing takes a recycle. The old loop drew the stock dry and stalled here.+     */+    private fun needsRecycle() = KlondikeState(+        waste = listOf(Card(Suit.HEARTS, Rank.QUEEN), Card(Suit.HEARTS, Rank.KING)),+        tableauPiles = sevenPiles(TableauPile(faceUp = listOf(Card(Suit.CLUBS, Rank.KING)))),+        foundations = Suit.entries.map { suit ->+            val top = if (suit == Suit.HEARTS) Rank.JACK else if (suit == Suit.CLUBS) Rank.QUEEN else Rank.KING+            Rank.entries.filter { it.value <= top.value }.map { Card(suit, it) }+        },+        redealsRemaining = 1,+    )++    @Test fun animatedRunRecyclesTheStockInsteadOfStalling() {+        val vm = vm()+        setK(vm, needsRecycle())+        vm.registerCardPosition(Card(Suit.CLUBS, Rank.KING), Offset(30f, 30f))+        vm.registerCardPosition(Card(Suit.HEARTS, Rank.KING), Offset(10f, 10f))+        vm.registerCardPosition(Card(Suit.HEARTS, Rank.QUEEN), Offset(10f, 10f))+        vm.klondikeAutoComplete()+        val flown = mutableListOf<Card>()+        var guard = 0+        while (vm.autoCompleteRunning.value) {+            if (guard++ > 10) fail("run did not finish")+            val flight = vm.flights.value.singleOrNull() ?: fail("running without a hop in the air")+            flown += flight.cards+            vm.landFlight(flight.id)+        }+        // The recycled cards' old positions are stale (they went face down), so their+        // hops after the recycle apply instantly rather than flying from the old spot.+        assertEquals(listOf(Card(Suit.CLUBS, Rank.KING)), flown)+        val k = vm.uiState.value.klondike!!+        assertTrue(k.isWon, "state=$k")+        assertEquals(0, k.redealsRemaining)+        assertEquals(1, vm.uiState.value.history.size)+    }++    @Test fun instantAndSkippedRunsRecycleToo() {+        val instant = vm()+        setK(instant, needsRecycle())+        instant.klondikeAutoComplete()+        assertTrue(instant.uiState.value.klondike!!.isWon)+        val skipped = vm()+        setK(skipped, needsRecycle())+        skipped.registerCardPosition(Card(Suit.CLUBS, Rank.KING), Offset(30f, 30f))+        skipped.klondikeAutoComplete()+        assertTrue(skipped.autoCompleteRunning.value)+        skipped.klondikeAutoComplete() // the Skip button+        assertTrue(skipped.uiState.value.klondike!!.isWon)+    }++    @Test fun notOfferedNorStartedWhenPassesRunOut() {+        val vm = vm()+        setK(vm, needsRecycle().copy(redealsRemaining = 0))+        assertFalse(canKlondikeAutoComplete(vm.uiState.value.klondike!!))+        vm.klondikeAutoComplete()+        assertFalse(vm.autoCompleteRunning.value)+        assertTrue(vm.uiState.value.history.isEmpty())+    }+     @Test fun undoRestoresPreRunBoard() {         val vm = vm()         setK(vm, almostWon())
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireRulesTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireRulesTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireRulesTest.ktindex 377748de41..130598fd40 100644--- a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireRulesTest.kt+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolitaireRulesTest.kt@@ -195,21 +195,29 @@ class SolitaireRulesTest {      @Test     fun autoCompleteVisibility() {+        // Offered only when the run can actually finish (see KlondikeAutoCompletePlanTest).         val aceHearts = Card(Suit.HEARTS, Rank.ACE)-        val base = KlondikeState(-            stock = emptyList(), waste = listOf(aceHearts),-            tableauPiles = listOf(TableauPile(faceUp = listOf(Card(Suit.SPADES, Rank.TWO)))) + List(6) { TableauPile() },+        val almostDone = KlondikeState(+            stock = emptyList(), waste = listOf(Card(Suit.HEARTS, Rank.KING)),+            foundations = Suit.entries.map { suit ->+                Rank.entries.filter { suit != Suit.HEARTS || it != Rank.KING }.map { Card(suit, it) }+            },         )-        assertTrue(canKlondikeAutoComplete(base))+        assertTrue(canKlondikeAutoComplete(almostDone))         // Face-down cards hide the button even with stock remaining.-        val withDown = base.copy(+        val withDown = almostDone.copy(             stock = listOf(aceHearts),             tableauPiles = listOf(TableauPile(faceDown = listOf(aceHearts), faceUp = listOf(aceHearts))) + List(6) { TableauPile() },         )         assertFalse(canKlondikeAutoComplete(withDown))-        assertFalse(canKlondikeAutoComplete(base.copy(isWon = true)))-        // Stock present (and no face-down) always shows it.-        assertTrue(canKlondikeAutoComplete(base.copy(stock = listOf(aceHearts), waste = emptyList())))+        assertFalse(canKlondikeAutoComplete(almostDone.copy(isWon = true)))+        // A board that could make a move or two but never finish is no longer offered+        // (it used to be, and the run then stalled at the end of the stock).+        val partial = KlondikeState(+            stock = emptyList(), waste = listOf(aceHearts),+            tableauPiles = listOf(TableauPile(faceUp = listOf(Card(Suit.SPADES, Rank.TWO)))) + List(6) { TableauPile() },+        )+        assertFalse(canKlondikeAutoComplete(partial))     }      @Test