Modern Apps git

← Modern-Apps.git

solitaire: deal every new game from the solver-proven tables (#owner-report)

Commit
2e8a6cbea17ea7b09c5ec43added6ad114b528b6
Author
Vayun Mathur <[email protected]>
When
2026-11-12 21:50 UTC (23 days ago)
Parents
a44bcff
Switches all four modes onto the shipped seed tables, so every new deal
in every mode and option is provably winnable (owner: "guarantee the
solvability of a solitaire game").

Before: new*GameImpl shuffled with java.util.Random(currentTimeMillis)
and dealt inline; the seed was thrown away.

Now:
- New game (New Game dialog, mode select, and the win screen's "New
  game", which calls restart()): SolitaireDealSource picks a uniformly
  random seed from the table for the exact config (mode + draw + passes,
  suits, relaxed) and deals it through domain/SolitaireDeals, the same
  code that dealt it for the solver. The asset (141 KB, 14 x 10,000
  seeds) is decoded once per process; a pick is one array read, so
  nothing is solved on the device: no main-thread work beyond a tiny
  one-off asset read, no battery cost. The four new*GameImpl bodies
  shrink to one call each.
- The per-mode deal code moved verbatim into SolitaireDeals; for any
  seed it deals byte-for-byte what the old code dealt (tested).
- States keep their `seed`; new restartDeal() re-deals it (same board,
  timer/moves/undo reset, no extra game counted). Nothing in the UI
  calls it yet: there is no restart-same-deal button today (restart()
  is the win screen's "New game" and keeps dealing a fresh table seed),
  and the UI belongs to the fix/solitaire-ui work.
- Stats: same keys (stats_<MODE>__<variant>); the table keys are those
  variants, and recordGamePlayed is called exactly as before.
- Saved games / daily deals: none exist, so nothing to migrate.
  SolvableDealTables.seedForDay already maps a date to the same proven
  seed on every device should a daily deal be added.
- Fallback: every dialog config has a table (asserted by tests); only
  an unknown config (none exists) would fall back to a clock seed.

Guarantee per mode: Klondike (all 8 draw x pass configs), FreeCell,
Spider (1/2/4 suits) and Pyramid (relaxed and single pass) only ever
deal seeds the matching solver won outright. The seed tables commit has
the per-config solvable rates.

Tests:
- SolverReplayTest now samples table seeds for every config (4 each,
  2 for Spider), re-proves them and replays each line action by action
  through the ViewModel ops to a won game: the solver/rules drift
  guard. If it fails after a rules change, regenerate the tables
  (AGENTS.md, "Solvable deals").
- SolvableDealTablesTest: every config has a sorted table of >= 5,000
  seeds; new games and restart() only deal table seeds with the right
  stats variant; a picked seed deals exactly SolitaireDeals of it;
  restartDeal restores the identical fresh board and counts no extra
  game; picks spread over the table; the daily mapping is
  deterministic and lands in the table.

AGENTS.md documents the domain/ package, the tables, and the
regeneration command.

Diff

games/solitaire/AGENTS.md
diff --git a/games/solitaire/AGENTS.md b/games/solitaire/AGENTS.mdindex 2103be8d91..1ba691bafa 100644--- a/games/solitaire/AGENTS.md+++ b/games/solitaire/AGENTS.md@@ -3,9 +3,9 @@ > Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `games/solitaire/` + allowed shared modules. Do not root-scan.  _Install: ./install games/solitaire (dev by default)._-<!-- last-reviewed: 2026-10-16 -->+<!-- last-reviewed: 2026-11-12 --> - Gradle: :games:solitaire / dir: games/solitaire/-- Package roots present: ui, data, platform+- Package roots present: ui, data, domain, platform - Entry files: MainActivity.kt, Route.kt, Navigation.kt - Deps: :sdk:games - Metadata: metadata_data/games-solitaire.md (present)@@ -15,7 +15,7 @@ _Install: ./install games/solitaire (dev by default)._ **Purpose:** Multi-variant solitaire — Klondike, FreeCell, Spider (+ Pyramid ops present), on-device deals, undo, win overlay. 100% offline. **Game shape:** Per-variant boards (`KlondikeBoard`, `FreeCellBoard`, `SpiderBoard`, `PyramidBoard`) over shared card/drag components → `platform/SolitaireViewModel` + per-variant `*Ops` → `data/` game state + stats; achievements → `:sdk:games` → hub. **Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/GameBoardScreen.kt` → `platform/SolitaireViewModel.kt` → `data/GameState.kt`.-**Gotchas:** Variant rules live in `platform/Solitaire*Ops` — shared board components must stay variant-agnostic.+**Gotchas:** Variant rules live in `platform/Solitaire*Ops` — shared board components must stay variant-agnostic. Every new deal comes from a table of solver-proven seeds, so **any rule change in the `*Ops` files means regenerating the tables** (see "Solvable deals").  ## Key files ### Root — entry + navigation@@ -28,6 +28,12 @@ _Install: ./install games/solitaire (dev by default)._ - com/vayunmathur/games/solitaire/data/CardColorScheme.kt - com/vayunmathur/games/solitaire/data/SolitaireStatsRepository.kt - com/vayunmathur/games/solitaire/data/SolitaireSettingsRepository.kt+### domain/ — pure Kotlin: deals, solvers, seed tables (no Android)+- com/vayunmathur/games/solitaire/domain/SolitaireDeals.kt (seed → starting board; the only deal code)+- com/vayunmathur/games/solitaire/domain/SolvableDeals.kt (table keys, `solvable_deals.bin` format, pick / daily mapping)+- com/vayunmathur/games/solitaire/domain/DealProofs.kt (what "proven" means: solver + pass-limit ladder)+- com/vayunmathur/games/solitaire/domain/SolverSearch.kt (DFS / beam / portfolio search engine)+- com/vayunmathur/games/solitaire/domain/KlondikeSolver.kt, FreeCellSolver.kt, SpiderSolver.kt, PyramidSolver.kt ### platform/ — ViewModel + per-variant rules - com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt - com/vayunmathur/games/solitaire/platform/SolitaireUiContract.kt@@ -35,6 +41,7 @@ _Install: ./install games/solitaire (dev by default)._ - com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt - com/vayunmathur/games/solitaire/platform/SolitaireSpiderOps.kt - com/vayunmathur/games/solitaire/platform/SolitairePyramidOps.kt+- com/vayunmathur/games/solitaire/platform/SolitaireDealSource.kt (new game = random table seed; `restartDeal()`) - com/vayunmathur/games/solitaire/platform/SolitaireDragOps.kt - com/vayunmathur/games/solitaire/platform/SolitaireFlight.kt — in-flight moves (visual only; game state updates first) - com/vayunmathur/games/solitaire/platform/SolitaireAchievementsManager.kt@@ -68,3 +75,39 @@ _Install: ./install games/solitaire (dev by default)._ ./gradlew :games:solitaire:lint ./gradlew :games:solitaire:checkMetadata ```++## Solvable deals+Every new game deals a seed from `src/main/assets/solvable_deals.bin`: one sorted+table per mode × option (8 Klondike draw/pass configs, Spider 1/2/4 suits,+FreeCell, Pyramid relaxed/single-pass), keyed by the stats variant+(`KLONDIKE__DRAW_THREE_HARD`, ...). Each seed was solved to a full win offline+by `domain/DealProofs` (the mode's solver, climbing the pass-limit ladder:+a win with fewer passes is a win with more). Seeds deal through+`createShuffledDeck(seed)` / `createSpiderDeck(suits, seed)` exactly as before,+so a seed deals the same board everywhere; the state keeps it (`seed`), and+`restartDeal()` replays it.++`SolverReplayTest` / `SolvableDealTablesTest` replay solver lines from table+seeds through the real ViewModel ops. If they fail after a rules change (or a+solver change), regenerate:++```+./gradlew :games:solitaire:testDevUnitTest \+  --tests 'com.vayunmathur.games.solitaire.domain.SolvableSeedTableGenerator' \+  -PsolitaireSeedGen=$PWD/analysis/soldeal -PsolitaireSeedGenThreads=64+cp analysis/soldeal/solvable_deals.bin games/solitaire/src/main/assets/+```+Optional: `-PsolitaireSeedGenTarget=10000` (seeds per config),+`-PsolitaireSeedGenGroups=klondike-draw1,klondike-draw3,pyramid,freecell,spider1,spider2,spider4`+(subset; merge by hand), `-PsolitaireSeedGenHeap=40g` (test JVM heap).+`analysis/soldeal/solvable_deals_report.txt` has per-config solvable rates+(last run: Klondike draw-1 86% unlimited .. 19% one pass, draw-3 79% .. 2.6%,+FreeCell 99.9%, Pyramid 83% relaxed / 12.8% single pass, Spider 84/83/71% for+1/2/4 suits; proven within budget).+Output is deterministic for a given solver and budget (any thread count).+It is CPU-heavy (about 25 min on 64 cores at 10 000 per config; the build+hook turns off coverage and -ea for it, which otherwise make it ~10x slower):+on the shared build box run it in the toolchain container under+the heavy-build lock, e.g.+`MEM_CAP=60g GEXCL="" ~/release-opt2/gbuild.sh soldeal-gen ~/code/Modern-Apps <branch> ":games:solitaire:testDevUnitTest --tests com.vayunmathur.games.solitaire.domain.SolvableSeedTableGenerator -PsolitaireSeedGen=/work/out -PsolitaireSeedGenThreads=64 -PsolitaireSeedGenHeap=44g"`+(output in `~/release-opt2/runs/soldeal-gen/work/out/`).
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDealSource.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDealSource.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDealSource.ktnew file mode 100644index 0000000000..49f7d5493d--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireDealSource.kt@@ -0,0 +1,81 @@+package com.vayunmathur.games.solitaire.platform++import android.app.Application+import android.content.Context+import com.vayunmathur.games.solitaire.data.GameConfig+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.domain.SolitaireDeals+import com.vayunmathur.games.solitaire.domain.SolvableDealTables+import com.vayunmathur.games.solitaire.domain.SolvableDeals+import kotlin.random.Random++/**+ * Where new deals come from: a uniformly random seed from the shipped table of+ * solver-proven seeds for the chosen mode and options (assets/solvable_deals.bin,+ * see domain/SolvableDeals), so every new game is winnable. The tables are a+ * 141 KB asset (14 configs x 10,000 seeds) decoded once per process; picking+ * is a single array read, so nothing is solved on the device.+ */+internal object SolitaireDealSource {+    @Volatile+    private var tables: SolvableDealTables? = null++    fun tables(context: Context): SolvableDealTables? = tables ?: synchronized(this) {+        tables ?: load(context)?.also { tables = it }+    }++    private fun load(context: Context): SolvableDealTables? =+        runCatching {+            context.assets.open(SolvableDeals.ASSET_NAME).use { SolvableDealTables.decode(it.readBytes()) }+        }.getOrNull()++    /**+     * A proven seed for [mode] + [config]. Every config the New Game dialog can+     * produce has a table (enforced by SolvableDealTablesTest); the clock seed+     * is only a last resort for a config outside that set.+     */+    fun pickSeed(context: Context, mode: GameMode, config: GameConfig, random: Random = Random.Default): Long =+        tables(context)?.pick(mode, config, random) ?: System.currentTimeMillis()+}++/** Starts a new game of [mode] with a fresh proven deal for [config]. */+internal fun SolitaireViewModel.startNewDeal(mode: GameMode, config: GameConfig) =+    startDeal(mode, config, SolitaireDealSource.pickSeed(getApplication<Application>(), mode, config))++/**+ * Deals [seed] for [mode] + [config] and starts it as a new game: clears+ * history and records a game played under the stats variant (unchanged keys).+ */+internal fun SolitaireViewModel.startDeal(mode: GameMode, config: GameConfig, seed: Long) {+    uiStateInternal.value = dealtState(mode, config, seed)+    statsRepository.recordGamePlayed(mode, SolvableDeals.variant(mode, config))+}++/**+ * Restarts the current game on the same deal: the board returns to its first+ * position, with the timer, moves and undo history reset. It is the same+ * game, so no extra game is counted in the stats. (`restart()` is different:+ * it is the win screen's "New game" and deals a new seed for the same options.)+ */+fun SolitaireViewModel.restartDeal() {+    val ui = uiStateInternal.value+    val mode = ui.gameMode ?: return+    val seed = when (mode) {+        GameMode.KLONDIKE -> ui.klondike?.seed+        GameMode.SPIDER -> ui.spider?.seed+        GameMode.FREECELL -> ui.freeCell?.seed+        GameMode.PYRAMID -> ui.pyramid?.seed+    } ?: return+    clearMotion()+    cardPositions.clear()+    uiStateInternal.value = dealtState(mode, currentConfig(), seed)+}++/** A fresh game state (empty history) holding the deal of [seed]. */+private fun dealtState(mode: GameMode, config: GameConfig, seed: Long): SolitaireUiState = when (mode) {+    GameMode.KLONDIKE -> SolitaireUiState(gameMode = mode, klondike = SolitaireDeals.klondike(seed, config))+    GameMode.SPIDER -> SolitaireUiState(gameMode = mode, spider = SolitaireDeals.spider(seed, config))+    GameMode.FREECELL -> SolitaireUiState(gameMode = mode, freeCell = SolitaireDeals.freeCell(seed))+    GameMode.PYRAMID -> SolitaireUiState(gameMode = mode, pyramid = SolitaireDeals.pyramid(seed, config))+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.ktindex fd81010a11..b153196e24 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireFreeCellOps.kt@@ -1,15 +1,11 @@ package com.vayunmathur.games.solitaire.platform  import com.vayunmathur.games.solitaire.data.Card-import com.vayunmathur.games.solitaire.data.FOUNDATION_COUNT-import com.vayunmathur.games.solitaire.data.FREECELL_COUNT-import com.vayunmathur.games.solitaire.data.FREECELL_TABLEAU_COUNT import com.vayunmathur.games.solitaire.data.FreeCellState+import com.vayunmathur.games.solitaire.data.GameConfig import com.vayunmathur.games.solitaire.data.GameMode import com.vayunmathur.games.solitaire.data.Rank-import com.vayunmathur.games.solitaire.data.SolitaireUiState import com.vayunmathur.games.solitaire.data.alternatesColorWith-import com.vayunmathur.games.solitaire.data.createShuffledDeck import com.vayunmathur.games.solitaire.data.isOneHigherThan import kotlinx.coroutines.flow.update @@ -33,24 +29,8 @@ fun SolitaireViewModel.freeCellMoveTableauToFoundation(fromColumn: Int, foundati fun SolitaireViewModel.freeCellMoveTableauToTableau(fromColumn: Int, cardIndex: Int, toColumn: Int) =     freeCellMoveTableauToTableauImpl(fromColumn, cardIndex, toColumn) -internal fun SolitaireViewModel.newFreeCellGameImpl() {-    val deck = createShuffledDeck()-    val piles = List(FREECELL_TABLEAU_COUNT) { mutableListOf<Card>() }-    for (i in deck.indices) {-        piles[i % FREECELL_TABLEAU_COUNT].add(deck[i])-    }-    uiStateInternal.value = SolitaireUiState(-        gameMode = GameMode.FREECELL,-        freeCell = FreeCellState(-            tableauPiles = piles.map { it.toList() },-            freeCells = List(FREECELL_COUNT) { null },-            foundations = List(FOUNDATION_COUNT) { emptyList() },-            variant = "STANDARD"-        ),-        history = emptyList()-    )-    statsRepository.recordGamePlayed(GameMode.FREECELL, "STANDARD")-}+/** A new game on a solver-proven deal (see SolitaireDealSource). */+internal fun SolitaireViewModel.newFreeCellGameImpl() = startNewDeal(GameMode.FREECELL, GameConfig())  internal fun SolitaireViewModel.freeCellMoveToFreeCellImpl(fromColumn: Int, cellIndex: Int) {     val state = uiStateInternal.value.freeCell ?: return
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 067b3ac49f..cd86bc0b07 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@@ -3,19 +3,14 @@ package com.vayunmathur.games.solitaire.platform import androidx.compose.ui.geometry.Rect import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.data.DrawMode-import com.vayunmathur.games.solitaire.data.FOUNDATION_COUNT import com.vayunmathur.games.solitaire.data.GameConfig import com.vayunmathur.games.solitaire.data.GameMode-import com.vayunmathur.games.solitaire.data.KLONDIKE_TABLEAU_COUNT import com.vayunmathur.games.solitaire.data.KlondikeState import com.vayunmathur.games.solitaire.data.Rank-import com.vayunmathur.games.solitaire.data.SolitaireUiState import com.vayunmathur.games.solitaire.data.Suit import com.vayunmathur.games.solitaire.data.TableauPile import com.vayunmathur.games.solitaire.data.alternatesColorWith-import com.vayunmathur.games.solitaire.data.createShuffledDeck import com.vayunmathur.games.solitaire.data.isOneHigherThan-import com.vayunmathur.games.solitaire.data.redeals import kotlinx.coroutines.flow.update  // ---- Klondike ----@@ -41,35 +36,8 @@ fun SolitaireViewModel.tryMoveByDrag(     cardSize: androidx.compose.ui.unit.IntSize = androidx.compose.ui.unit.IntSize.Zero, ): String? = tryMoveByDragImpl(sourceId, dropOffset, cardSize) -internal fun SolitaireViewModel.newKlondikeGameImpl(config: GameConfig) {-    val deck = createShuffledDeck()-    val tableauPiles = mutableListOf<TableauPile>()-    var index = 0-    for (i in 0 until KLONDIKE_TABLEAU_COUNT) {-        val faceDown = deck.subList(index, index + i)-        index += i-        val faceUp = listOf(deck[index])-        index++-        tableauPiles.add(TableauPile(faceDown, faceUp))-    }-    val stock = deck.subList(index, deck.size)-    val variant = "${config.drawMode.name}_${config.klondikeDifficulty.name}"-    uiStateInternal.value = SolitaireUiState(-        gameMode = GameMode.KLONDIKE,-        klondike = KlondikeState(-            stock = stock,-            waste = emptyList(),-            tableauPiles = tableauPiles,-            foundations = List(FOUNDATION_COUNT) { emptyList() },-            drawMode = config.drawMode,-            difficulty = config.klondikeDifficulty,-            redealsRemaining = config.klondikeDifficulty.redeals(),-            variant = variant-        ),-        history = emptyList()-    )-    statsRepository.recordGamePlayed(GameMode.KLONDIKE, variant)-}+/** A new game on a solver-proven deal for [config] (see SolitaireDealSource). */+internal fun SolitaireViewModel.newKlondikeGameImpl(config: GameConfig) = startNewDeal(GameMode.KLONDIKE, config)  internal fun SolitaireViewModel.drawFromStockImpl() {     val state = uiStateInternal.value.klondike ?: return
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitairePyramidOps.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitairePyramidOps.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitairePyramidOps.ktindex e0b384144c..233265f856 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitairePyramidOps.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitairePyramidOps.kt@@ -3,12 +3,9 @@ package com.vayunmathur.games.solitaire.platform import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.data.GameConfig import com.vayunmathur.games.solitaire.data.GameMode-import com.vayunmathur.games.solitaire.data.PYRAMID_ROWS import com.vayunmathur.games.solitaire.data.PAIR_TARGET import com.vayunmathur.games.solitaire.data.PyramidState import com.vayunmathur.games.solitaire.data.Rank-import com.vayunmathur.games.solitaire.data.SolitaireUiState-import com.vayunmathur.games.solitaire.data.createShuffledDeck import kotlinx.coroutines.flow.update  // ---- Pyramid ----@@ -16,32 +13,8 @@ import kotlinx.coroutines.flow.update  fun SolitaireViewModel.newPyramidGame(config: GameConfig) = newPyramidGameImpl(config) -internal fun SolitaireViewModel.newPyramidGameImpl(config: GameConfig) {-    val deck = createShuffledDeck()-    var index = 0-    val rows = mutableListOf<List<Card?>>()-    for (r in 0 until PYRAMID_ROWS) {-        val row = mutableListOf<Card?>()-        for (c in 0..r) {-            row.add(deck[index]); index++-        }-        rows.add(row)-    }-    val stock = deck.subList(index, deck.size).toList()-    val variant = if (config.relaxed) "RELAXED" else "ORIGINAL"-    uiStateInternal.value = SolitaireUiState(-        gameMode = GameMode.PYRAMID,-        pyramid = PyramidState(-            pyramid = rows,-            stock = stock,-            waste = emptyList(),-            relaxed = config.relaxed,-            variant = variant-        ),-        history = emptyList()-    )-    statsRepository.recordGamePlayed(GameMode.PYRAMID, variant)-}+/** A new game on a solver-proven deal for [config] (see SolitaireDealSource). */+internal fun SolitaireViewModel.newPyramidGameImpl(config: GameConfig) = startNewDeal(GameMode.PYRAMID, config)  /** A pyramid card is exposed when both cards resting on it have been removed. */ internal fun SolitaireViewModel.isPyramidCardExposed(state: PyramidState, row: Int, col: Int): Boolean {
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireSpiderOps.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireSpiderOps.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireSpiderOps.ktindex 46ceb60213..9aa9d48b6c 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireSpiderOps.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireSpiderOps.kt@@ -6,14 +6,8 @@ import com.vayunmathur.games.solitaire.data.FULL_SUIT_SIZE import com.vayunmathur.games.solitaire.data.GameMode import com.vayunmathur.games.solitaire.data.Rank import com.vayunmathur.games.solitaire.data.SPIDER_TABLEAU_COUNT-import com.vayunmathur.games.solitaire.data.SPIDER_COLUMN_CARDS-import com.vayunmathur.games.solitaire.data.SPIDER_TALL_COLUMN_CARDS-import com.vayunmathur.games.solitaire.data.SPIDER_TALL_COLUMN_COUNT-import com.vayunmathur.games.solitaire.data.SolitaireUiState import com.vayunmathur.games.solitaire.data.TOTAL_SPIDER_SUITS-import com.vayunmathur.games.solitaire.data.SpiderState import com.vayunmathur.games.solitaire.data.TableauPile-import com.vayunmathur.games.solitaire.data.createSpiderDeck import com.vayunmathur.games.solitaire.data.isOneHigherThan import kotlinx.coroutines.flow.update @@ -25,34 +19,8 @@ fun SolitaireViewModel.newSpiderGame(config: GameConfig) = newSpiderGameImpl(con fun SolitaireViewModel.spiderMoveCards(fromColumn: Int, cardIndex: Int, toColumn: Int) =     spiderMoveCardsImpl(fromColumn, cardIndex, toColumn) -internal fun SolitaireViewModel.newSpiderGameImpl(config: GameConfig) {-    val suitCount = config.spiderSuits-    val deck = createSpiderDeck(suitCount)-    val tableauPiles = mutableListOf<TableauPile>()-    var index = 0-    for (i in 0 until SPIDER_TABLEAU_COUNT) {-        val count = if (i < SPIDER_TALL_COLUMN_COUNT) SPIDER_TALL_COLUMN_CARDS else SPIDER_COLUMN_CARDS-        val faceDown = deck.subList(index, index + count - 1)-        index += count - 1-        val faceUp = listOf(deck[index])-        index++-        tableauPiles.add(TableauPile(faceDown, faceUp))-    }-    val remaining = deck.subList(index, deck.size)-    val stockGroups = remaining.chunked(SPIDER_TABLEAU_COUNT)-    val variant = "${suitCount}SUIT"-    uiStateInternal.value = SolitaireUiState(-        gameMode = GameMode.SPIDER,-        spider = SpiderState(-            tableauPiles = tableauPiles,-            stockGroups = stockGroups,-            suitCount = suitCount,-            variant = variant-        ),-        history = emptyList()-    )-    statsRepository.recordGamePlayed(GameMode.SPIDER, variant)-}+/** A new game on a solver-proven deal for [config] (see SolitaireDealSource). */+internal fun SolitaireViewModel.newSpiderGameImpl(config: GameConfig) = startNewDeal(GameMode.SPIDER, config)  internal fun SolitaireViewModel.dealSpiderStockImpl() {     val state = uiStateInternal.value.spider ?: return
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolvableDealTablesTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolvableDealTablesTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolvableDealTablesTest.ktnew file mode 100644index 0000000000..f0dd5f66c5--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolvableDealTablesTest.kt@@ -0,0 +1,119 @@+package com.vayunmathur.games.solitaire.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.GameConfig+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.domain.SolvableDealTables+import com.vayunmathur.games.solitaire.domain.SolvableDeals+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** The shipped seed tables and how new games, restarts and replays use them. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SolvableDealTablesTest {++    private val app = ApplicationProvider.getApplicationContext<Application>()++    private val tables: SolvableDealTables by lazy {+        app.assets.open(SolvableDeals.ASSET_NAME).use { SolvableDealTables.decode(it.readBytes()) }+    }++    private fun seedOf(vm: SolitaireViewModel): Long = with(vm.uiState.value) {+        klondike?.seed ?: spider?.seed ?: freeCell?.seed ?: pyramid?.seed ?: error("no game")+    }++    @Test fun everyDialogConfigHasAFullSortedTable() {+        for ((mode, config) in SolvableDeals.allConfigs) {+            val seeds = assertNotNull(tables.seeds(mode, config), "$mode $config has no table")+            assertTrue(seeds.size >= MIN_TABLE, "$mode $config: only ${seeds.size} seeds")+            assertTrue(seeds.first() > 0 && (1 until seeds.size).all { seeds[it] > seeds[it - 1] })+        }+    }++    @Test fun newGamesOnlyDealTableSeedsForEveryConfig() {+        val vm = SolutionReplay.vm()+        for ((mode, config) in SolvableDeals.allConfigs) {+            val table = tables.seeds(mode, config)!!.toSet()+            repeat(PICKS) {+                vm.selectMode(mode, config)+                val seed = seedOf(vm)+                assertTrue(seed.toInt() in table, "$mode $config dealt $seed, not a table seed")+                assertEquals(SolvableDeals.variant(mode, config), currentVariantOf(vm))+            }+            // The win screen's "New game" (restart) also deals from the same table.+            vm.restart()+            assertTrue(seedOf(vm).toInt() in table)+        }+    }++    private fun currentVariantOf(vm: SolitaireViewModel): String = vm.currentVariant()++    @Test fun pickedSeedDealsExactlyTheProvenBoard() {+        // A new game is exactly SolitaireDeals of its seed: the board the solver proved.+        val vm = SolutionReplay.vm()+        val config = GameConfig()+        vm.selectMode(GameMode.KLONDIKE, config)+        val state: KlondikeState = vm.uiState.value.klondike!!+        assertEquals(com.vayunmathur.games.solitaire.domain.SolitaireDeals.klondike(state.seed, config), state)+    }++    @Test fun restartDealKeepsTheSameDeal() {+        val vm = SolutionReplay.vm()+        for ((mode, config) in SolvableDeals.allConfigs) {+            vm.selectMode(mode, config)+            val fresh = vm.uiState.value+            when (mode) {+                GameMode.KLONDIKE -> vm.drawFromStock()+                GameMode.SPIDER -> vm.dealSpiderStock()+                GameMode.FREECELL -> vm.freeCellMoveToFreeCell(0, 0)+                GameMode.PYRAMID -> vm.pyramidDealStock()+            }+            vm.incrementTimer()+            assertNotEquals(fresh, vm.uiState.value, "$mode $config: the setup move did nothing")+            vm.restartDeal()+            assertEquals(fresh, vm.uiState.value, "$mode $config: restartDeal changed the deal")+        }+    }++    @Test fun restartDealDoesNotCountAnotherGame() {+        val vm = SolutionReplay.vm()+        vm.selectMode(GameMode.FREECELL, GameConfig())+        val played = vm.getStats(GameMode.FREECELL).gamesPlayed+        vm.restartDeal()+        assertEquals(played, vm.getStats(GameMode.FREECELL).gamesPlayed)+    }++    @Test fun pickIsUniformOverTheTable() {+        // Not stuck on a few entries: many draws spread over many distinct seeds.+        val config = GameConfig()+        val random = Random(SAMPLE_SEED)+        val seen = (1..2000).map { tables.pick(GameMode.FREECELL, config, random) }.toSet()+        assertTrue(seen.size > 1500, "only ${seen.size} distinct of 2000 picks")+    }++    @Test fun dailyDealIsDeterministicAndProven() {+        for ((mode, config) in SolvableDeals.allConfigs) {+            val table = tables.seeds(mode, config)!!.toSet()+            val day = tables.seedForDay(mode, config, DAY)!!+            assertEquals(day, tables.seedForDay(mode, config, DAY))+            assertTrue(day.toInt() in table)+        }+    }++    private companion object {+        const val MIN_TABLE = 5_000+        const val PICKS = 5+        const val SAMPLE_SEED = 20_261_112L+        const val DAY = 20_769L+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolverReplayTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolverReplayTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolverReplayTest.ktindex 7cb0138f28..24e1e1f9b9 100644--- a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolverReplayTest.kt+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolverReplayTest.kt@@ -1,35 +1,47 @@ package com.vayunmathur.games.solitaire.platform -import com.vayunmathur.games.solitaire.domain.DealProofs+import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.domain.SolvableDealTables import com.vayunmathur.games.solitaire.domain.SolvableDeals+import kotlin.random.Random import kotlin.test.Test-import kotlin.test.assertEquals import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config  /**- * For every mode × option, the solver's winning lines on real deals replay- * through the ViewModel's rules to a won game (see [SolutionReplay]).+ * For every mode × option, a sample of shipped table seeds is re-proven and+ * the solver's winning line replays through the ViewModel's rules to a won+ * game (see [SolutionReplay]). A failure here means the rules or a solver+ * drifted from the tables: regenerate them (AGENTS.md, "Solvable deals").  */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class SolverReplayTest { +    private val tables: SolvableDealTables by lazy {+        ApplicationProvider.getApplicationContext<Application>().assets.open(SolvableDeals.ASSET_NAME)+            .use { SolvableDealTables.decode(it.readBytes()) }+    }+     @Test-    fun solverLinesWinUnderTheGameRulesForEveryConfig() {+    fun tableSeedsWinUnderTheGameRulesForEveryConfig() {+        // Fixed sample so failures reproduce; Spider solves are the slow ones (seconds each).+        val random = Random(SAMPLE_SEED)         for ((mode, config) in SolvableDeals.allConfigs) {-            val proven = (1L..MAX_SCAN).asSequence()-                .filter { DealProofs.prove(mode, config, it) != null }-                .take(SAMPLES)-                .toList()-            assertEquals(SAMPLES, proven.size, "$mode $config: fewer than $SAMPLES proven seeds in 1..$MAX_SCAN")-            proven.forEach { SolutionReplay.proveAndReplay(mode, config, it) }+            val seeds = tables.seeds(mode, config)!!+            val samples = if (mode == GameMode.SPIDER) SPIDER_SAMPLES else SAMPLES+            repeat(samples) {+                SolutionReplay.proveAndReplay(mode, config, seeds[random.nextInt(seeds.size)].toLong())+            }         }     }      private companion object {-        const val SAMPLES = 2-        const val MAX_SCAN = 400L+        const val SAMPLES = 4+        const val SPIDER_SAMPLES = 2+        const val SAMPLE_SEED = 914L     } }