Modern Apps git

← Modern-Apps.git

solitaire: drop saved games with duplicated or missing cards

Commit
f45e4cc7d5b002d2ee581b8c94cadcd06637c800
Author
Vayun Mathur <[email protected]>
When
2026-12-01 20:24 UTC (4 days ago)
Parents
781ec29
Bug: SolitaireProgressCodec validated a restored game only by its
card count. A Klondike or FreeCell save could total 52 cards while
duplicating one card and dropping another, a Pyramid save could do
the same below 52 after removed pairs, and a Spider save could hold
more copies of a card than its 104-card deck deals. Such a position
cannot occur in legal play and may be unwinnable, yet decode
returned it and ensureMode restored it instead of dealing a fresh
game.

Fix: on decode, validate card identity as well as count. Klondike,
FreeCell and Pyramid remaining cards must be distinct (one physical
deck; Pyramid removed pairs are simply absent). Spider visible
cards must use only the suits of its deck, appear no more often
than that deck deals them (8/4/2 copies per card for 1/2/4 suits),
and carry a completed-suit count in range. Applied in the per-mode
decoders, so undo-history snapshots restored from the same save
are held to the same checks.

Tests: four new SolitaireProgressCodecTest cases build corrupted
saves from real proven deals (one per mode) and require decode to
drop them; all four failed before the fix. The targeted class then
passes, and the full :games:solitaire:testDevUnitTest suite passes
(194 tests, 0 failures).

Diff

games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.ktindex 432be58007..a7c2b0a4e7 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/InProgressGame.kt@@ -129,6 +129,49 @@ object SolitaireProgressCodec {         s.tableauPiles.sumOf { it.size } + s.freeCells.count { it != null } +             s.foundations.sumOf { it.size } +    // A count alone is not a deck: a corrupted save can still total 52 (or+    // 104) cards while duplicating one card and dropping another, which no+    // legal game can contain and which may be unwinnable. The cards that+    // remain must be the cards the mode's physical deck can actually deal.++    private fun klondikeCards(s: KlondikeState): List<Card> =+        s.stock + s.waste + s.foundations.flatten() ++            s.tableauPiles.flatMap { it.faceDown + it.faceUp }++    private fun freeCellCards(s: FreeCellState): List<Card> =+        s.tableauPiles.flatten() + s.freeCells.filterNotNull() + s.foundations.flatten()++    private fun spiderCards(s: SpiderState): List<Card> =+        s.tableauPiles.flatMap { it.faceDown + it.faceUp } + s.stockGroups.flatten()++    private fun pyramidCards(s: PyramidState): List<Card> =+        s.pyramid.flatten().filterNotNull() + s.stock + s.waste++    /** Every card distinct, as a single 52-card deck requires. */+    private fun isSingleDeck(cards: List<Card>): Boolean = cards.size == cards.toSet().size++    /**+     * Spider deals a 104-card deck built from [SpiderState.suitCount] suits+     * (8 copies of each rank of one suit, 4 each across two suits, or 2 full+     * decks), so no card may appear more often than that, in a suit the deck+     * does not use, or alongside a completed-suit count the deck cannot have.+     * Completed runs are counted, not stored, so copies already cleared are+     * simply absent from [spiderCards]; the per-card cap is what remains+     * checkable, and totalSpider already accounts for their 13 cards each.+     */+    private fun isPhysicalSpiderDeck(s: SpiderState): Boolean {+        val suits = when (s.suitCount) {+            1 -> listOf(Suit.SPADES)+            2 -> listOf(Suit.SPADES, Suit.HEARTS)+            else -> Suit.entries+        }+        val copiesPerCard = SPIDER_CARDS / (suits.size * Rank.entries.size)+        val cards = spiderCards(s)+        return s.completedSuits in 0..TOTAL_SPIDER_SUITS &&+            cards.all { it.suit in suits } &&+            cards.groupingBy { it }.eachCount().values.all { it <= copiesPerCard }+    }+     // -- per-mode states --      private fun encodeAny(state: Any): JsonObject = when (state) {@@ -173,7 +216,10 @@ object SolitaireProgressCodec {             usedUndo = obj.getValue("usedUndo").jsonPrimitive.content.toBooleanStrict(),             isWon = obj.getValue("won").jsonPrimitive.content.toBooleanStrict(),         )-        return state.takeIf { totalKlondike(it) == DECK_CARDS && it.moveCount >= 0 && it.elapsedSeconds >= 0 }+        return state.takeIf {+            totalKlondike(it) == DECK_CARDS && isSingleDeck(klondikeCards(it)) &&+                it.moveCount >= 0 && it.elapsedSeconds >= 0+        }     }      private fun encodeSpider(s: SpiderState): JsonObject = buildJsonObject {@@ -204,7 +250,7 @@ object SolitaireProgressCodec {         )         return state.takeIf {             it.suitCount in setOf(1, 2, 4) && totalSpider(it) == SPIDER_CARDS &&-                it.moveCount >= 0 && it.elapsedSeconds >= 0+                isPhysicalSpiderDeck(it) && it.moveCount >= 0 && it.elapsedSeconds >= 0         }     } @@ -233,7 +279,10 @@ object SolitaireProgressCodec {             usedUndo = obj.getValue("usedUndo").jsonPrimitive.content.toBooleanStrict(),             isWon = obj.getValue("won").jsonPrimitive.content.toBooleanStrict(),         )-        return state.takeIf { totalFreeCell(it) == DECK_CARDS && it.moveCount >= 0 && it.elapsedSeconds >= 0 }+        return state.takeIf {+            totalFreeCell(it) == DECK_CARDS && isSingleDeck(freeCellCards(it)) &&+                it.moveCount >= 0 && it.elapsedSeconds >= 0+        }     }      private fun encodePyramid(s: PyramidState): JsonObject = buildJsonObject {@@ -271,7 +320,10 @@ object SolitaireProgressCodec {         )         val total = state.pyramid.sumOf { row -> row.count { it != null } } +             state.stock.size + state.waste.size-        return state.takeIf { total in 1..DECK_CARDS && it.moveCount >= 0 && it.elapsedSeconds >= 0 }+        return state.takeIf {+            total in 1..DECK_CARDS && isSingleDeck(pyramidCards(it)) &&+                it.moveCount >= 0 && it.elapsedSeconds >= 0+        }     } } 
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.ktindex be0a425c34..a68869ccae 100644--- a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.kt+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/SolitaireProgressCodecTest.kt@@ -75,6 +75,70 @@ class SolitaireProgressCodecTest {         assertNull(SolitaireProgressCodec.decode("""{"v":2}""", GameMode.KLONDIKE))     } +    @Test+    fun savedKlondikeWithDuplicatedCardIsDropped() {+        // Still 52 cards in total, but the stock's first card is duplicated+        // onto the first tableau column and that column's own card is gone:+        // no legal single-deck game can contain this position, and the+        // missing card can make the restored game unwinnable.+        val dealt = SolitaireDeals.klondike(12345L, GameConfig())+        val duplicated = dealt.stock.first()+        val corrupted = dealt.copy(+            tableauPiles = dealt.tableauPiles.mapIndexed { i, pile ->+                if (i == 0) pile.copy(faceUp = listOf(duplicated)) else pile+            },+        )+        val state = SolitaireUiState(gameMode = GameMode.KLONDIKE, klondike = corrupted)+        assertNull(+            SolitaireProgressCodec.decode(SolitaireProgressCodec.encode(state), GameMode.KLONDIKE),+        )+    }++    @Test+    fun savedFreeCellWithDuplicatedCardIsDropped() {+        val dealt = SolitaireDeals.freeCell(777L)+        val duplicated = dealt.tableauPiles[1].first()+        val corrupted = dealt.copy(+            tableauPiles = dealt.tableauPiles.mapIndexed { i, pile ->+                if (i == 0) listOf(duplicated) + pile.drop(1) else pile+            },+        )+        val state = SolitaireUiState(gameMode = GameMode.FREECELL, freeCell = corrupted)+        assertNull(+            SolitaireProgressCodec.decode(SolitaireProgressCodec.encode(state), GameMode.FREECELL),+        )+    }++    @Test+    fun savedPyramidWithDuplicatedCardIsDropped() {+        // Removed pairs legitimately shrink the remaining card count, but+        // the cards that remain still come from one deck: no duplicates.+        val dealt = SolitaireDeals.pyramid(4242L, GameConfig())+        val duplicated = dealt.pyramid[0][0]!!+        val corrupted = dealt.copy(stock = listOf(duplicated) + dealt.stock.drop(1))+        val state = SolitaireUiState(gameMode = GameMode.PYRAMID, pyramid = corrupted)+        assertNull(+            SolitaireProgressCodec.decode(SolitaireProgressCodec.encode(state), GameMode.PYRAMID),+        )+    }++    @Test+    fun savedSpiderWithTooManyCopiesOfACardIsDropped() {+        // A four-suit Spider deck holds exactly two copies of each card;+        // a third copy of the second column's top card cannot be in play.+        val dealt = SolitaireDeals.spider(99L, GameConfig(spiderSuits = 4))+        val duplicated = dealt.tableauPiles[1].faceUp.first()+        val corrupted = dealt.copy(+            tableauPiles = dealt.tableauPiles.mapIndexed { i, pile ->+                if (i == 0) pile.copy(faceUp = listOf(duplicated)) else pile+            },+        )+        val state = SolitaireUiState(gameMode = GameMode.SPIDER, spider = corrupted)+        assertNull(+            SolitaireProgressCodec.decode(SolitaireProgressCodec.encode(state), GameMode.SPIDER),+        )+    }+     @Test     fun midGameRoundTripsThroughStore() {         val store = InProgressGame(app)