Modern Apps git

← Modern-Apps.git

solitaire: deal solvers and offline solvable-seed generator (#owner-report)

Commit
9156d6f29251ea43a1de76332cd16143656325c6
Author
Vayun Mathur <[email protected]>
When
2026-11-12 21:13 UTC (23 days ago)
Parents
21331e5
The owner asked to "guarantee the solvability of a solitaire game".
Today every deal is java.util.Random(System.currentTimeMillis()), so
some fraction of deals in every mode can never be won. This commit adds
the machinery to prove deals winnable; the shipped seed tables and the
switch of new games onto them follow in separate commits.

Inventory (what has to be covered):
- Klondike: draw 1 / draw 3 x passes unlimited / 3 / 2 / 1
  (KlondikeDifficulty RELAXED / REGULAR / TWO_PASSES / HARD): 8 configs.
- Spider: 1, 2, 4 suits. FreeCell: one config. Pyramid: relaxed
  (unlimited recycles) and original (single pass).
- 14 configs in all. No daily or shared deals, no saved games: the
  seed was never kept, so nothing persisted depends on it. Stats keys
  are stats_<MODE>__<variant> and are untouched.

Design, all pure Kotlin in the new domain/ package (no Android):
- SolitaireDeals: the one place a seed becomes a board. Same shuffle
  (createShuffledDeck / createSpiderDeck) and same dealing order as the
  old new*GameImpl code, so a seed deals card-for-card what it always
  dealt; states gain a `seed` field (default 0, nothing else changes).
- SolverSearch: a deterministic search engine over flat byte-array
  states with a 64-bit transposition set: ordered DFS, beam search, and
  a fixed portfolio (DFS, then beam if DFS proved nothing). A key
  collision can only prune, never fake a win: the result is a real move
  sequence from the start.
- KlondikeSolver: stock handled as macro moves (every card the stock
  can bring to the waste top, with draws and recycles folded in, using
  the game's exact draw-3 order and pass limit), safe auto-play of
  tableau cards no opposite colour can still need, column-order-free
  keys.
- FreeCellSolver: the game's own supermove limit, safe auto-play,
  cell/column-order-free keys.
- SpiderSolver: 1/2/4 suits with the game's deal and clear rules; DFS
  then a 300-wide beam (DFS alone proved ~9% of 4-suit deals, the
  portfolio ~75%). Splits a run into an empty column only in the
  deal deadlock (rows left, every column one run).
- PyramidSolver: pair removals, Kings, the game's sole-cover rule and
  stock macro moves; the talon keeps its order across recycles, so the
  whole position packs into a collision-free 57-bit key and an
  exhausted search is a real proof of unsolvability.
- DealProofs: the single definition of "proven" shared by generator
  and tests: the mode's solver at its DEFAULT_BUDGET, climbing the
  pass-limit ladder (a win with 1 pass is a win with 2, 3 or unlimited;
  a single-pass Pyramid win is a relaxed win).
- SolvableDeals / SolvableDealTables: table keys (= stats variants),
  the compact asset format (varint-delta sorted seeds), uniform pick,
  and seedForDay (a fixed 64-bit mix of the epoch day into the table)
  for any future daily or shared deal.

Generator: SolvableSeedTableGenerator (test source set, so it never
ships), skipped unless Gradle gets -PsolitaireSeedGen=<dir>. It scans
seeds 1, 2, 3, ... in fixed rounds per group of configs sharing a deal
and keeps the first N proven per config; output is identical for any
thread count. Regenerate with:

  ./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/

(options: -PsolitaireSeedGenTarget, -PsolitaireSeedGenGroups,
-PsolitaireSeedGenHeap; the build-file hook only applies with the
property set).

Tests:
- SolitaireSolversTest: known solvable and unsolvable small positions
  per solver (draw-1 vs draw-3 on the same stock, pass limits, buried
  Aces, a FreeCell spot that needs 12 free slots but has 11, Pyramid
  recycles, a Spider finish), legacy-deal equality for every mode,
  table format round trip, pick returns only table seeds, the daily
  mapping is deterministic and scattered, keys = stats variants,
  ladder order.
- SolverReplayTest (Robolectric): for every one of the 14 configs,
  solver lines on real deals replay action by action through the
  ViewModel's own *Ops to a won game, with every action accepted. That
  is the guard against solver/rules drift.

Early rates on small samples (seeds proven / scanned): Klondike draw-1
84.7% unlimited, 20.4% single pass; draw-3 77.5% unlimited, 2.6% single
pass; FreeCell 100%; Pyramid relaxed 83%, single pass 11% (the rest
proven unsolvable); Spider ~89% / 83% / 73% for 1 / 2 / 4 suits.

Diff

games/solitaire/build.gradle.kts
diff --git a/games/solitaire/build.gradle.kts b/games/solitaire/build.gradle.ktsindex 61b78707b7..07f5d8db47 100644--- a/games/solitaire/build.gradle.kts+++ b/games/solitaire/build.gradle.kts@@ -1,3 +1,5 @@+import org.gradle.testing.jacoco.plugins.JacocoTaskExtension+ plugins {     id("common-conventions-app")     // Listing screenshots come from Compose previews (src/screenshotTest), not from an@@ -18,3 +20,32 @@ android { dependencies {     implementation(project(":sdk:games")) }++// Offline generator for src/main/assets/solvable_deals.bin (AGENTS.md, "Solvable deals").+// Inert unless -PsolitaireSeedGen=<output dir> is given; then the unit-test JVM gets the+// generator's settings and a heap big enough for one solver per thread.+val solitaireSeedGen = providers.gradleProperty("solitaireSeedGen")+val solitaireSeedGenTarget = providers.gradleProperty("solitaireSeedGenTarget")+val solitaireSeedGenThreads = providers.gradleProperty("solitaireSeedGenThreads")+val solitaireSeedGenGroups = providers.gradleProperty("solitaireSeedGenGroups")+val solitaireSeedGenHeap = providers.gradleProperty("solitaireSeedGenHeap")+tasks.withType<Test>().configureEach {+    if (solitaireSeedGen.isPresent) {+        systemProperty("solitaire.seedgen.out", solitaireSeedGen.get())+        systemProperty("solitaire.seedgen.target", solitaireSeedGenTarget.getOrElse("10000"))+        systemProperty("solitaire.seedgen.threads", solitaireSeedGenThreads.getOrElse("0"))+        systemProperty("solitaire.seedgen.groups", solitaireSeedGenGroups.getOrElse(""))+        maxHeapSize = solitaireSeedGenHeap.getOrElse("40g")+        // -ea and coverage probes (below) in the solvers' hot loops, shared across+        // threads, slow the run by an order of magnitude; neither means anything here.+        enableAssertions = false+        outputs.upToDateWhen { false }+        testLogging.showStandardStreams = true+    }+}+// Registered once the coverage plugin is in, so this runs after it adds its task extension.+plugins.withId("jacoco") {+    tasks.withType<Test>().configureEach {+        if (solitaireSeedGen.isPresent) extensions.getByType(JacocoTaskExtension::class.java).isEnabled = false+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.ktindex d92cd05637..4b3860ea2d 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.kt@@ -59,6 +59,8 @@ data class KlondikeState(     val difficulty: KlondikeDifficulty = KlondikeDifficulty.REGULAR,     val redealsRemaining: Int = 2,     val variant: String = "",+    /** Deal seed (see domain/SolitaireDeals): re-dealing it reproduces this board. */+    val seed: Long = 0L,     val moveCount: Int = 0,     val elapsedSeconds: Int = 0,     val usedUndo: Boolean = false,@@ -74,6 +76,8 @@ data class SpiderState(     val suitCount: Int = 4,     val variant: String = "",     val completedSuits: Int = 0,+    /** Deal seed (see domain/SolitaireDeals): re-dealing it reproduces this board. */+    val seed: Long = 0L,     val moveCount: Int = 0,     val elapsedSeconds: Int = 0,     val usedUndo: Boolean = false,@@ -88,6 +92,8 @@ data class FreeCellState(     val freeCells: List<Card?> = List(size = FREECELL_COUNT) { null },     val foundations: List<List<Card>> = List(size = FOUNDATION_COUNT) { emptyList() },     val variant: String = "",+    /** Deal seed (see domain/SolitaireDeals): re-dealing it reproduces this board. */+    val seed: Long = 0L,     val moveCount: Int = 0,     val elapsedSeconds: Int = 0,     val usedUndo: Boolean = false,@@ -114,6 +120,8 @@ data class PyramidState(     val relaxed: Boolean = false,     val variant: String = "",     val selectedId: String? = null,+    /** Deal seed (see domain/SolitaireDeals): re-dealing it reproduces this board. */+    val seed: Long = 0L,     val moveCount: Int = 0,     val elapsedSeconds: Int = 0,     val usedUndo: Boolean = false,
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/DealProofs.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/DealProofs.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/DealProofs.ktnew file mode 100644index 0000000000..31e2147c32--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/DealProofs.kt@@ -0,0 +1,55 @@+package com.vayunmathur.games.solitaire.domain++import com.vayunmathur.games.solitaire.data.GameConfig+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.KlondikeDifficulty++/**+ * How a seed is proven winnable for a config — the single definition both the+ * offline table generator and the tests use.+ *+ * Pass limits nest: a line that wins with one pass through the stock also wins+ * with two, three or unlimited passes (unused recycles change nothing), and a+ * single-pass Pyramid win also wins relaxed. So a config's [ladder] lists the+ * configs from the strictest up to itself, and a seed belongs to the config's+ * table when the solver wins it at any rung. Trying strict rungs first is+ * also faster: their searches are smaller.+ */+object DealProofs {++    /** Klondike pass limits from 1 pass to unlimited. */+    private val PASS_LADDER = listOf(+        KlondikeDifficulty.HARD,+        KlondikeDifficulty.TWO_PASSES,+        KlondikeDifficulty.REGULAR,+        KlondikeDifficulty.RELAXED,+    )++    fun ladder(mode: GameMode, config: GameConfig): List<GameConfig> = when (mode) {+        GameMode.KLONDIKE -> PASS_LADDER+            .take(PASS_LADDER.indexOf(config.klondikeDifficulty) + 1)+            .map { config.copy(klondikeDifficulty = it) }+        GameMode.PYRAMID -> if (config.relaxed) listOf(config.copy(relaxed = false), config) else listOf(config)+        else -> listOf(config)+    }++    /** One solver run on the fresh deal of [seed] under exactly [config], at the default budget. */+    fun solve(mode: GameMode, config: GameConfig, seed: Long): SolveResult = when (mode) {+        GameMode.KLONDIKE -> KlondikeSolver.solve(SolitaireDeals.klondike(seed, config))+        GameMode.SPIDER -> SpiderSolver.solve(SolitaireDeals.spider(seed, config))+        GameMode.FREECELL -> FreeCellSolver.solve(SolitaireDeals.freeCell(seed))+        GameMode.PYRAMID -> PyramidSolver.solve(SolitaireDeals.pyramid(seed, config))+    }++    /**+     * The first ladder rung that wins [seed], with its winning line (valid as-is+     * under [config]), or null when no rung proves it.+     */+    fun prove(mode: GameMode, config: GameConfig, seed: Long): Pair<GameConfig, SolveResult>? {+        for (rung in ladder(mode, config)) {+            val result = solve(mode, rung, seed)+            if (result.status == SolveStatus.SOLVED) return rung to result+        }+        return null+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/FreeCellSolver.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/FreeCellSolver.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/FreeCellSolver.ktnew file mode 100644index 0000000000..de45fa0e87--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/FreeCellSolver.kt@@ -0,0 +1,314 @@+package com.vayunmathur.games.solitaire.domain++import com.vayunmathur.games.solitaire.data.FREECELL_COUNT+import com.vayunmathur.games.solitaire.data.FREECELL_TABLEAU_COUNT+import com.vayunmathur.games.solitaire.data.FreeCellState++/** One player action in a FreeCell winning line, in the ViewModel's own vocabulary. */+sealed interface FreeCellMove {+    /** Top of column [column] to foundation [foundation] (foundations are suit-indexed). */+    data class TableauToFoundation(val column: Int, val foundation: Int) : FreeCellMove++    /** Free cell [cell] to foundation [foundation]. */+    data class FreeCellToFoundation(val cell: Int, val foundation: Int) : FreeCellMove++    /** Moves the run starting at absolute index [cardIndex] of [from] onto [to]. */+    data class TableauToTableau(val from: Int, val cardIndex: Int, val to: Int) : FreeCellMove++    /** Free cell [cell] onto column [column]. */+    data class FreeCellToTableau(val cell: Int, val column: Int) : FreeCellMove++    /** Top of column [column] into the empty free cell [cell]. */+    data class TableauToFreeCell(val column: Int, val cell: Int) : FreeCellMove+}++/**+ * FreeCell solver using the game's own supermove limit+ * (`(1 + free cells) * 2^empty columns`, the target column excluded).+ * Columns and cells are interchangeable, so the transposition key ignores their+ * order; a card is auto-played to its foundation when no opposite-colour card+ * could still need it.+ */+class FreeCellSolver private constructor() : SearchProblem {++    override fun isWon(state: ByteArray): Boolean = (0 until SUITS).all { state[it].toInt() == RANKS }++    override fun key(state: ByteArray): Long {+        var columns = 0L+        for (c in 0 until FREECELL_TABLEAU_COUNT) {+            val base = colBase(c)+            columns += mix64(hashBytes(state, base, state[base] + 1, COLUMN_SEED))+        }+        var cells = 0L+        for (i in 0 until FREECELL_COUNT) cells += mix64(state[CELLS + i] + CELL_SEED)+        return mix64(columns xor (cells * CELL_MULT))+    }++    override fun score(state: ByteArray): Int {+        var breaks = 0+        var empty = 0+        for (c in 0 until FREECELL_TABLEAU_COUNT) {+            val base = colBase(c)+            val len = state[base].toInt()+            if (len == 0) empty+++            for (i in 1 until len) {+                if (!isNaturalChild(state[base + i].toInt(), state[base + 1 + i].toInt())) breaks+++            }+        }+        val usedCells = (0 until FREECELL_COUNT).count { state[CELLS + it] >= 0 }+        return 3 * (FULL_DECK - foundationTotal(state)) + 2 * usedCells + 2 * breaks - 2 * empty+    }++    override fun expand(state: ByteArray, sink: ChildSink) {+        if (emitSafeAutoPlay(state, sink)) return+        emitToFoundation(state, sink)+        emitRuns(state, sink, toEmpty = false)+        emitCellToColumn(state, sink, toEmpty = false)+        emitRuns(state, sink, toEmpty = true)+        emitCellToColumn(state, sink, toEmpty = true)+        emitToCell(state, sink)+    }++    private fun emitSafeAutoPlay(state: ByteArray, sink: ChildSink): Boolean {+        for (c in 0 until FREECELL_TABLEAU_COUNT) {+            val top = topCard(state, c)+            if (top >= 0 && isSafeToFoundation(state, top)) {+                sink.child(columnToFoundation(state, c, top), pack(T2F, c, codeSuit(top), 0))+                return true+            }+        }+        for (i in 0 until FREECELL_COUNT) {+            val card = state[CELLS + i].toInt()+            if (card >= 0 && isSafeToFoundation(state, card)) {+                sink.child(cellToFoundation(state, i, card), pack(C2F, i, codeSuit(card), 0))+                return true+            }+        }+        return false+    }++    private fun emitToFoundation(state: ByteArray, sink: ChildSink) {+        for (c in 0 until FREECELL_TABLEAU_COUNT) {+            val top = topCard(state, c)+            if (top >= 0 && fitsFoundation(state, top)) {+                sink.child(columnToFoundation(state, c, top), pack(T2F, c, codeSuit(top), 0))+            }+        }+        for (i in 0 until FREECELL_COUNT) {+            val card = state[CELLS + i].toInt()+            if (card >= 0 && fitsFoundation(state, card)) {+                sink.child(cellToFoundation(state, i, card), pack(C2F, i, codeSuit(card), 0))+            }+        }+    }++    /**+     * Run moves. Onto a card only the whole natural run (from the first card that+     * does not sit on its natural parent) or, for that exact target, the part of+     * it that fits; into an empty column the longest movable run, unless it is+     * already the whole column.+     */+    private fun emitRuns(state: ByteArray, sink: ChildSink, toEmpty: Boolean) {+        for (from in 0 until FREECELL_TABLEAU_COUNT) {+            val base = colBase(from)+            val len = state[base].toInt()+            if (len == 0) continue+            val runLen = naturalRunLength(state, from)+            if (toEmpty) emitRunToEmpty(state, from, runLen, sink) else emitRunToCards(state, from, runLen, sink)+        }+    }++    private fun emitRunToCards(state: ByteArray, from: Int, runLen: Int, sink: ChildSink) {+        val base = colBase(from)+        val len = state[base].toInt()+        val topRank = codeRank(state[base + len].toInt())+        for (to in 0 until FREECELL_TABLEAU_COUNT) {+            val target = topCard(state, to)+            if (to == from || target < 0) continue+            val count = codeRank(target) - topRank+            if (count < 1 || count > runLen || count > maxMove(state, from, to)) continue+            val start = len - count+            val first = state[base + 1 + start].toInt()+            if (codeIsRed(first) == codeIsRed(target)) continue+            sink.child(moveRun(state, from, start, to), pack(T2T, from, start, to))+        }+    }++    private fun emitRunToEmpty(state: ByteArray, from: Int, runLen: Int, sink: ChildSink) {+        val len = state[colBase(from)].toInt()+        val to = (0 until FREECELL_TABLEAU_COUNT).firstOrNull { state[colBase(it)].toInt() == 0 } ?: return+        val count = minOf(runLen, maxMove(state, from, to))+        if (count == len) return+        val start = len - count+        sink.child(moveRun(state, from, start, to), pack(T2T, from, start, to))+    }++    private fun emitCellToColumn(state: ByteArray, sink: ChildSink, toEmpty: Boolean) {+        val firstEmpty = (0 until FREECELL_TABLEAU_COUNT).firstOrNull { state[colBase(it)].toInt() == 0 }+        for (i in 0 until FREECELL_COUNT) {+            val card = state[CELLS + i].toInt()+            if (card < 0) continue+            if (toEmpty) {+                if (firstEmpty != null) {+                    sink.child(cellToColumn(state, i, card, firstEmpty), pack(C2T, i, firstEmpty, 0))+                }+                continue+            }+            for (to in 0 until FREECELL_TABLEAU_COUNT) {+                val target = topCard(state, to)+                if (target >= 0 && isNaturalChild(target, card)) {+                    sink.child(cellToColumn(state, i, card, to), pack(C2T, i, to, 0))+                }+            }+        }+    }++    private fun emitToCell(state: ByteArray, sink: ChildSink) {+        val cell = (0 until FREECELL_COUNT).firstOrNull { state[CELLS + it] < 0 } ?: return+        for (c in 0 until FREECELL_TABLEAU_COUNT) {+            val top = topCard(state, c)+            if (top < 0) continue+            val child = state.copyOf()+            val base = colBase(c)+            child[base] = (child[base] - 1).toByte()+            child[CELLS + cell] = top.toByte()+            sink.child(child, pack(T2C, c, cell, 0))+        }+    }++    private fun isSafeToFoundation(state: ByteArray, card: Int): Boolean {+        if (!fitsFoundation(state, card)) return false+        val rank = codeRank(card)+        if (rank <= 2) return true+        val firstOpposite = if (codeIsRed(card)) 2 else 0+        return state[firstOpposite] >= rank - 1 && state[firstOpposite + 1] >= rank - 1+    }++    companion object {+        fun solve(state: FreeCellState, budget: SolverBudget = DEFAULT_BUDGET): SolveResult =+            portfolioSearch(FreeCellSolver(), encode(state), budget)++        /** The budget the shipped table was generated with. */+        val DEFAULT_BUDGET = SolverBudget(dfsNodes = 100_000, beamWidth = 500, beamNodes = 300_000)++        fun decode(moves: IntArray): List<FreeCellMove> = moves.map { m ->+            val a = (m ushr A_SHIFT) and FIELD_MASK+            val b = (m ushr B_SHIFT) and FIELD_MASK+            when (m and TYPE_MASK) {+                T2F -> FreeCellMove.TableauToFoundation(a, b)+                C2F -> FreeCellMove.FreeCellToFoundation(a, b)+                T2T -> FreeCellMove.TableauToTableau(a, b, (m ushr C_SHIFT) and FIELD_MASK)+                C2T -> FreeCellMove.FreeCellToTableau(a, b)+                else -> FreeCellMove.TableauToFreeCell(a, b)+            }+        }++        private fun encode(state: FreeCellState): ByteArray {+            val s = ByteArray(SIZE)+            for (f in 0 until SUITS) s[f] = state.foundations[f].size.toByte()+            for (i in 0 until FREECELL_COUNT) s[CELLS + i] = (state.freeCells[i]?.code() ?: -1).toByte()+            state.tableauPiles.forEachIndexed { c, pile ->+                val base = colBase(c)+                s[base] = pile.size.toByte()+                pile.forEachIndexed { i, card -> s[base + 1 + i] = card.code().toByte() }+            }+            return s+        }++        private fun colBase(c: Int) = COLUMNS + c * COLUMN_SPAN++        private fun foundationTotal(s: ByteArray) = s[0] + s[1] + s[2] + s[3]++        private fun topCard(s: ByteArray, c: Int): Int {+            val base = colBase(c)+            val len = s[base].toInt()+            return if (len == 0) -1 else s[base + len].toInt()+        }++        private fun fitsFoundation(s: ByteArray, card: Int) = s[codeSuit(card)].toInt() == codeRank(card) - 1++        private fun isNaturalChild(parent: Int, child: Int) =+            codeIsRed(parent) != codeIsRed(child) && codeRank(parent) == codeRank(child) + 1++        private fun naturalRunLength(s: ByteArray, c: Int): Int {+            val base = colBase(c)+            val len = s[base].toInt()+            var run = 1+            while (run < len && isNaturalChild(s[base + len - run].toInt(), s[base + len - run + 1].toInt())) run+++            return run+        }++        /** The ViewModel's limit: empty columns other than source and target double it. */+        private fun maxMove(s: ByteArray, from: Int, to: Int): Int {+            val freeCells = (0 until FREECELL_COUNT).count { s[CELLS + it] < 0 }+            val emptyColumns = (0 until FREECELL_TABLEAU_COUNT).count {+                it != from && it != to && s[colBase(it)].toInt() == 0+            }+            return (1 + freeCells) shl emptyColumns+        }++        private fun moveRun(s: ByteArray, from: Int, start: Int, to: Int): ByteArray {+            val child = s.copyOf()+            val fromBase = colBase(from)+            val toBase = colBase(to)+            val len = s[fromBase].toInt()+            var toLen = s[toBase].toInt()+            for (k in start until len) {+                child[toBase + 1 + toLen] = s[fromBase + 1 + k]+                toLen+++            }+            child[toBase] = toLen.toByte()+            child[fromBase] = start.toByte()+            return child+        }++        private fun columnToFoundation(s: ByteArray, c: Int, card: Int): ByteArray {+            val child = s.copyOf()+            child[colBase(c)] = (child[colBase(c)] - 1).toByte()+            child[codeSuit(card)]+++            return child+        }++        private fun cellToFoundation(s: ByteArray, cell: Int, card: Int): ByteArray {+            val child = s.copyOf()+            child[CELLS + cell] = -1+            child[codeSuit(card)]+++            return child+        }++        private fun cellToColumn(s: ByteArray, cell: Int, card: Int, to: Int): ByteArray {+            val child = s.copyOf()+            val base = colBase(to)+            val len = s[base].toInt()+            child[base + 1 + len] = card.toByte()+            child[base] = (len + 1).toByte()+            child[CELLS + cell] = -1+            return child+        }++        private fun pack(type: Int, a: Int, b: Int, c: Int): Int =+            type or (a shl A_SHIFT) or (b shl B_SHIFT) or (c shl C_SHIFT)++        private const val T2F = 0+        private const val C2F = 1+        private const val T2T = 2+        private const val C2T = 3+        private const val T2C = 4+        private const val TYPE_MASK = 7+        private const val A_SHIFT = 3+        private const val B_SHIFT = 8+        private const val C_SHIFT = 13+        private const val FIELD_MASK = 31++        private const val SUITS = 4+        private const val FULL_DECK = 52+        private const val CELLS = 4+        private const val COLUMNS = 8+        private const val COLUMN_SPAN = 22+        private const val SIZE = COLUMNS + FREECELL_TABLEAU_COUNT * COLUMN_SPAN++        private const val COLUMN_SEED = 0x4567_89ABL+        private const val CELL_SEED = 0x5678_9ABCL+        private const val CELL_MULT = 0x9E37_79B9L+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/KlondikeSolver.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/KlondikeSolver.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/KlondikeSolver.ktnew file mode 100644index 0000000000..b676bc0bd4--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/KlondikeSolver.kt@@ -0,0 +1,330 @@+package com.vayunmathur.games.solitaire.domain++import com.vayunmathur.games.solitaire.data.KLONDIKE_TABLEAU_COUNT+import com.vayunmathur.games.solitaire.data.KlondikeState++/** One player action in a Klondike winning line, in the ViewModel's own vocabulary. */+sealed interface KlondikeMove {+    /** Tap the stock: draw (1 or 3) or, when it is empty, recycle the waste. */+    data object Draw : KlondikeMove++    /** Waste top to foundation [foundation] (foundations are suit-indexed). */+    data class WasteToFoundation(val foundation: Int) : KlondikeMove++    /** Waste top onto column [column]. */+    data class WasteToTableau(val column: Int) : KlondikeMove++    /** Top of column [column] to foundation [foundation]. */+    data class TableauToFoundation(val column: Int, val foundation: Int) : KlondikeMove++    /** Moves the face-up run starting at [faceUpIndex] of column [from] onto column [to]. */+    data class TableauToTableau(val from: Int, val faceUpIndex: Int, val to: Int) : KlondikeMove+}++/**+ * Klondike solver for every draw mode and pass limit.+ *+ * The stock is handled as macro moves: from any position it enumerates every+ * card that can reach the waste top by tapping the stock (drawing [drawCount] at+ * a time and recycling while [KlondikeState.redealsRemaining] allows), and plays+ * it in one edge with the taps folded in. Taps that play nothing are never+ * needed, so this is complete for the stock while removing its long, cyclic+ * chains from the search. Columns are interchangeable, so the transposition key+ * ignores their order. A tableau card is auto-played to its foundation when no+ * opposite-colour card could still need it; that move never costs a win.+ */+class KlondikeSolver private constructor(private val drawCount: Int) : SearchProblem {++    override fun isWon(state: ByteArray): Boolean =+        (0 until SUITS).all { state[it].toInt() == RANKS }++    override fun key(state: ByteArray): Long {+        var columns = 0L+        for (c in 0 until KLONDIKE_TABLEAU_COUNT) {+            val base = colBase(c)+            columns += mix64(hashBytes(state, base, state[base] + 2, COLUMN_SEED))+        }+        val stock = hashBytes(state, STOCK, state[STOCK_N].toInt(), STOCK_SEED)+        val waste = hashBytes(state, WASTE, state[WASTE_N].toInt(), WASTE_SEED)+        return mix64(columns xor mix64(stock + state[REDEALS]) xor (waste * WASTE_MULT))+    }++    override fun score(state: ByteArray): Int {+        var down = 0+        var buried = 0+        for (c in 0 until KLONDIKE_TABLEAU_COUNT) {+            val base = colBase(c)+            val d = state[base + 1].toInt()+            down += d+            // Face-down cards under a deep pile are slower to reach.+            if (d > 0) buried += d * (state[base].toInt() - d)+        }+        return 4 * down + 2 * (FULL_DECK - foundationTotal(state)) + buried / 2 ++            state[STOCK_N] + state[WASTE_N]+    }++    override fun expand(state: ByteArray, sink: ChildSink) {+        if (emitSafeAutoPlay(state, sink)) return+        emitTableauToTableau(state, sink, revealing = true)+        emitTableauToFoundation(state, sink)+        emitTalonPlays(state, sink)+        emitTableauToTableau(state, sink, revealing = false)+    }++    /** A tableau top that is safe to send up is the only child: no branching needed. */+    private fun emitSafeAutoPlay(state: ByteArray, sink: ChildSink): Boolean {+        for (c in 0 until KLONDIKE_TABLEAU_COUNT) {+            val top = topCard(state, c)+            if (top >= 0 && isSafeToFoundation(state, top)) {+                val child = state.copyOf()+                popFromColumn(child, c, 1)+                child[codeSuit(top)]+++                sink.child(child, pack(T2F, c, codeSuit(top), 0, 0))+                return true+            }+        }+        return false+    }++    private fun emitTableauToFoundation(state: ByteArray, sink: ChildSink) {+        for (c in 0 until KLONDIKE_TABLEAU_COUNT) {+            val top = topCard(state, c)+            if (top < 0 || !fitsFoundation(state, top)) continue+            val child = state.copyOf()+            popFromColumn(child, c, 1)+            child[codeSuit(top)]+++            sink.child(child, pack(T2F, c, codeSuit(top), 0, 0))+        }+    }++    /** Every card reachable on the waste top, played to a foundation or a column. */+    private fun emitTalonPlays(state: ByteArray, sink: ChildSink) {+        val sim = state.copyOf()+        var taps = 0+        var recycles = 0+        var seenCards = 0L+        while (true) {+            val top = if (sim[WASTE_N] > 0) sim[WASTE + sim[WASTE_N] - 1].toInt() else -1+            if (top >= 0 && (seenCards and (1L shl top)) == 0L) {+                seenCards = seenCards or (1L shl top)+                emitWastePlays(sim, top, taps, sink)+            }+            // A third pass would only repeat the second, which started from a full stock.+            if (sim[STOCK_N].toInt() == 0 && recycles == 1) return+            val recycled = sim[STOCK_N].toInt() == 0+            if (!tapStock(sim)) return+            if (recycled) recycles+++            taps+++        }+    }++    private fun emitWastePlays(atTop: ByteArray, card: Int, taps: Int, sink: ChildSink) {+        if (fitsFoundation(atTop, card)) {+            val child = atTop.copyOf()+            child[WASTE_N]--+            child[codeSuit(card)]+++            sink.child(child, pack(W2F, 0, codeSuit(card), 0, taps))+        }+        var emptyTried = false+        for (c in 0 until KLONDIKE_TABLEAU_COUNT) {+            if (!fitsColumn(atTop, card, c)) continue+            val empty = atTop[colBase(c)].toInt() == 0+            if (empty && emptyTried) continue+            emptyTried = emptyTried || empty+            val child = atTop.copyOf()+            child[WASTE_N]--+            pushToColumn(child, c, card)+            sink.child(child, pack(W2T, c, 0, 0, taps))+        }+    }++    /**+     * Run moves. [revealing] picks the whole face-up run of a column with cards+     * still face-down (always progress); otherwise it is a run that empties its+     * column, or a part-run whose removal frees a card for its foundation.+     */+    private fun emitTableauToTableau(state: ByteArray, sink: ChildSink, revealing: Boolean) {+        for (from in 0 until KLONDIKE_TABLEAU_COUNT) {+            val base = colBase(from)+            val len = state[base].toInt()+            val down = state[base + 1].toInt()+            if (len == 0) continue+            for (i in down until len) {+                if (!isUsefulRunStart(state, from, i, revealing)) continue+                emitRunTargets(state, from, i, sink)+            }+        }+    }++    private fun isUsefulRunStart(state: ByteArray, from: Int, i: Int, revealing: Boolean): Boolean {+        val base = colBase(from)+        val down = state[base + 1].toInt()+        return when {+            i == down && down > 0 -> revealing+            revealing -> false+            i == down -> true+            else -> fitsFoundation(state, state[base + 2 + i - 1].toInt())+        }+    }++    private fun emitRunTargets(state: ByteArray, from: Int, i: Int, sink: ChildSink) {+        val base = colBase(from)+        val len = state[base].toInt()+        val down = state[base + 1].toInt()+        val card = state[base + 2 + i].toInt()+        var emptyTried = false+        for (to in 0 until KLONDIKE_TABLEAU_COUNT) {+            if (to == from || !fitsColumn(state, card, to)) continue+            val empty = state[colBase(to)].toInt() == 0+            // A King run already at the bottom gains nothing by changing columns.+            val pointlessEmpty = emptyTried || (i == 0 && down == 0)+            if (empty && pointlessEmpty) continue+            emptyTried = emptyTried || empty+            val child = state.copyOf()+            for (k in i until len) pushToColumn(child, to, state[base + 2 + k].toInt())+            popFromColumn(child, from, len - i)+            sink.child(child, pack(T2T, from, i - down, to, 0))+        }+    }++    private fun isSafeToFoundation(state: ByteArray, card: Int): Boolean {+        if (!fitsFoundation(state, card)) return false+        val rank = codeRank(card)+        if (rank <= 2) return true+        val firstOpposite = if (codeIsRed(card)) 2 else 0+        return state[firstOpposite] >= rank - 1 && state[firstOpposite + 1] >= rank - 1+    }++    /** One stock tap with the ViewModel's exact semantics; false when it does nothing. */+    private fun tapStock(s: ByteArray): Boolean {+        val stockN = s[STOCK_N].toInt()+        val wasteN = s[WASTE_N].toInt()+        if (stockN > 0) {+            val n = minOf(drawCount, stockN)+            for (k in 0 until n) s[WASTE + wasteN + k] = s[STOCK + stockN - 1 - k]+            s[STOCK_N] = (stockN - n).toByte()+            s[WASTE_N] = (wasteN + n).toByte()+            return true+        }+        val redeals = s[REDEALS].toInt() and 0xFF+        if (wasteN == 0 || redeals == 0) return false+        for (k in 0 until wasteN) s[STOCK + k] = s[WASTE + wasteN - 1 - k]+        s[STOCK_N] = wasteN.toByte()+        s[WASTE_N] = 0+        if (redeals != UNLIMITED) s[REDEALS] = (redeals - 1).toByte()+        return true+    }++    companion object {+        /**+         * Solves [state] (any position, normally a fresh deal) within [budget].+         * The pass limit comes from the state's own+         * [KlondikeState.redealsRemaining].+         */+        fun solve(state: KlondikeState, budget: SolverBudget = DEFAULT_BUDGET): SolveResult =+            portfolioSearch(KlondikeSolver(state.drawMode.cardsPerDraw()), encode(state), budget)++        /** The budget the shipped tables were generated with. */+        val DEFAULT_BUDGET = SolverBudget(dfsNodes = 300_000)++        /** Expands packed codes into the taps and moves a player makes. */+        fun decode(moves: IntArray): List<KlondikeMove> = buildList {+            for (m in moves) {+                repeat(field(m, DRAWS_SHIFT, DRAWS_BITS)) { add(KlondikeMove.Draw) }+                val a = field(m, A_SHIFT, FIELD_BITS)+                val b = field(m, B_SHIFT, FIELD_BITS)+                when (m and TYPE_MASK) {+                    T2F -> add(KlondikeMove.TableauToFoundation(a, b))+                    W2F -> add(KlondikeMove.WasteToFoundation(b))+                    W2T -> add(KlondikeMove.WasteToTableau(a))+                    else -> add(KlondikeMove.TableauToTableau(a, b, field(m, C_SHIFT, FIELD_BITS)))+                }+            }+        }++        private fun encode(state: KlondikeState): ByteArray {+            val s = ByteArray(SIZE)+            for (f in 0 until SUITS) s[f] = state.foundations[f].size.toByte()+            s[REDEALS] = (if (state.redealsRemaining >= UNLIMITED) UNLIMITED else state.redealsRemaining).toByte()+            s[STOCK_N] = state.stock.size.toByte()+            state.stock.forEachIndexed { i, card -> s[STOCK + i] = card.code().toByte() }+            s[WASTE_N] = state.waste.size.toByte()+            state.waste.forEachIndexed { i, card -> s[WASTE + i] = card.code().toByte() }+            state.tableauPiles.forEachIndexed { c, pile ->+                val base = colBase(c)+                val cards = pile.faceDown + pile.faceUp+                s[base] = cards.size.toByte()+                s[base + 1] = pile.faceDown.size.toByte()+                cards.forEachIndexed { i, card -> s[base + 2 + i] = card.code().toByte() }+            }+            return s+        }++        private fun colBase(c: Int) = COLUMNS + c * COLUMN_SPAN++        private fun foundationTotal(s: ByteArray) = s[0] + s[1] + s[2] + s[3]++        private fun topCard(s: ByteArray, c: Int): Int {+            val base = colBase(c)+            val len = s[base].toInt()+            return if (len == 0) -1 else s[base + 1 + len].toInt()+        }++        private fun fitsFoundation(s: ByteArray, card: Int) = s[codeSuit(card)].toInt() == codeRank(card) - 1++        private fun fitsColumn(s: ByteArray, card: Int, c: Int): Boolean {+            val top = topCard(s, c)+            if (top < 0) return codeRank(card) == RANKS+            return codeIsRed(top) != codeIsRed(card) && codeRank(top) == codeRank(card) + 1+        }++        private fun pushToColumn(s: ByteArray, c: Int, card: Int) {+            val base = colBase(c)+            val len = s[base].toInt()+            s[base + 2 + len] = card.toByte()+            s[base] = (len + 1).toByte()+        }++        /** Removes [count] top cards, then flips the new top face-up like the game does. */+        private fun popFromColumn(s: ByteArray, c: Int, count: Int) {+            val base = colBase(c)+            val len = s[base] - count+            s[base] = len.toByte()+            if (len > 0 && s[base + 1].toInt() == len) s[base + 1] = (len - 1).toByte()+        }++        private fun pack(type: Int, a: Int, b: Int, c: Int, draws: Int): Int =+            type or (a shl A_SHIFT) or (b shl B_SHIFT) or (c shl C_SHIFT) or (draws shl DRAWS_SHIFT)++        private fun field(m: Int, shift: Int, bits: Int) = (m ushr shift) and ((1 shl bits) - 1)++        private const val T2F = 0+        private const val W2F = 1+        private const val W2T = 2+        private const val T2T = 3+        private const val TYPE_MASK = 3+        private const val A_SHIFT = 2+        private const val B_SHIFT = 7+        private const val C_SHIFT = 12+        private const val DRAWS_SHIFT = 17+        private const val FIELD_BITS = 5+        private const val DRAWS_BITS = 8++        private const val SUITS = 4+        private const val FULL_DECK = 52+        private const val UNLIMITED = 255+        private const val REDEALS = 4+        private const val STOCK_N = 5+        private const val WASTE_N = 6+        private const val STOCK = 7+        private const val WASTE = 31+        private const val COLUMNS = 55+        private const val COLUMN_SPAN = 21+        private const val SIZE = COLUMNS + KLONDIKE_TABLEAU_COUNT * COLUMN_SPAN++        private const val COLUMN_SEED = 0x1234_5678L+        private const val STOCK_SEED = 0x2345_6789L+        private const val WASTE_SEED = 0x3456_789AL+        private const val WASTE_MULT = 0x9E37_79B9L+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/PyramidSolver.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/PyramidSolver.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/PyramidSolver.ktnew file mode 100644index 0000000000..db5a23822f--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/PyramidSolver.kt@@ -0,0 +1,234 @@+package com.vayunmathur.games.solitaire.domain++import com.vayunmathur.games.solitaire.data.PAIR_TARGET+import com.vayunmathur.games.solitaire.data.PYRAMID_ROWS+import com.vayunmathur.games.solitaire.data.PyramidState++/**+ * One player action in a Pyramid winning line. Ids are the board's own+ * (`pyr_<row>_<col>` or `waste`); a pair is replayed as two taps, [first] then+ * [second], and a lone King as one tap.+ */+sealed interface PyramidMove {+    /** Tap the stock: deal one card, or recycle the waste in relaxed mode. */+    data object Deal : PyramidMove++    /** Tap the exposed King [id] (pyramid card or waste top). */+    data class RemoveKing(val id: String) : PyramidMove++    /** Tap [first] (selects it), then [second] (completes the pair of 13). */+    data class RemovePair(val first: String, val second: String) : PyramidMove+}++/**+ * Pyramid solver over pair removals, Kings, and the stock/waste with the game's+ * pass rule (single pass, or unlimited recycles when relaxed). Includes the+ * game's sole-cover variation: an exposed card may pair with the card it is the+ * last cover of.+ *+ * The talon is modelled exactly: dealing preserves card order across recycles,+ * so the talon is a fixed sequence plus a removed mask and a position. The key+ * packs the whole position into 57 bits, so it is collision-free and an+ * exhausted search is a real proof of unsolvability.+ */+class PyramidSolver private constructor(+    private val pyramid: IntArray,+    private val talon: IntArray,+    private val relaxed: Boolean,+) : SearchProblem {++    override fun isWon(state: ByteArray): Boolean = (0 until PYRAMID_CARDS).none { state[it].toInt() != 0 }++    override fun key(state: ByteArray): Long {+        var k = 0L+        for (i in 0 until PYRAMID_CARDS + talon.size) k = (k shl 1) or state[i].toLong()+        return (k shl POS_BITS) or state[posIndex()].toLong()+    }++    override fun score(state: ByteArray): Int {+        var left = 0+        for (i in 0 until PYRAMID_CARDS) left += state[i]+        return left+    }++    override fun expand(state: ByteArray, sink: ChildSink) {+        val exposed = (0 until PYRAMID_CARDS).filter { isExposed(state, it) }+        for (i in exposed) if (rankAt(i) == KING) sink.child(removed(state, i, -1), pack(KING_MOVE, i, 0, 0))+        for (x in exposed.indices) {+            for (y in x + 1 until exposed.size) {+                val a = exposed[x]+                val b = exposed[y]+                if (rankAt(a) + rankAt(b) == PAIR_TARGET) sink.child(removed(state, a, b), pack(PAIR_MOVE, a, b, 0))+            }+            emitSoleCoverPairs(state, exposed[x], sink)+        }+        emitWastePlays(state, exposed, sink)+    }++    /**+     * Stock macro moves: every card that taps on the stock can bring to the+     * waste top, removed (a King) or paired with an exposed card in the same+     * edge. Taps that remove nothing are never needed, and pyramid-only moves+     * do not depend on the stock, so this loses no wins.+     */+    private fun emitWastePlays(state: ByteArray, exposed: List<Int>, sink: ChildSink) {+        val sim = state.copyOf()+        var taps = 0+        var recycled = false+        var seenCards = 0L+        while (true) {+            val top = wasteTop(sim)+            if (top >= 0 && (seenCards and (1L shl talon[top])) == 0L) {+                seenCards = seenCards or (1L shl talon[top])+                emitWasteRemovals(sim, talon[top], exposed, taps, sink)+            }+            val stockEmpty = nextInStock(sim) == null+            // A second recycle would only repeat the full pass after the first.+            if (stockEmpty && recycled) return+            val next = dealt(sim) ?: return+            recycled = recycled || stockEmpty+            next.copyInto(sim)+            taps+++        }+    }++    private fun emitWasteRemovals(atTop: ByteArray, card: Int, exposed: List<Int>, taps: Int, sink: ChildSink) {+        if (codeRank(card) == KING) {+            sink.child(removed(atTop, WASTE_SLOT, -1), pack(KING_MOVE, WASTE_SLOT, 0, taps))+            return+        }+        for (i in exposed) {+            if (rankAt(i) + codeRank(card) == PAIR_TARGET) {+                sink.child(removed(atTop, i, WASTE_SLOT), pack(PAIR_MOVE, i, WASTE_SLOT, taps))+            }+        }+    }++    /** [cover] with the card it alone still covers (the game's partial-cover rule). */+    private fun emitSoleCoverPairs(state: ByteArray, cover: Int, sink: ChildSink) {+        val (row, col) = rowCol(cover)+        if (row == 0) return+        // Parents of (row, col) are (row-1, col-1) and (row-1, col).+        for (pc in col - 1..col) {+            if (pc < 0 || pc > row - 1) continue+            val parent = slot(row - 1, pc)+            if (state[parent].toInt() == 0) continue+            val sibling = slot(row, if (pc == col) col + 1 else col - 1)+            if (state[sibling].toInt() != 0) continue+            if (rankAt(cover) + rankAt(parent) == PAIR_TARGET) {+                sink.child(removed(state, cover, parent), pack(PAIR_MOVE, cover, parent, 0))+            }+        }+    }++    private fun isExposed(state: ByteArray, i: Int): Boolean {+        if (state[i].toInt() == 0) return false+        val (row, col) = rowCol(i)+        if (row == PYRAMID_ROWS - 1) return true+        return state[slot(row + 1, col)].toInt() == 0 && state[slot(row + 1, col + 1)].toInt() == 0+    }++    private fun wasteTop(state: ByteArray): Int {+        val pos = state[posIndex()].toInt()+        for (t in pos - 1 downTo 0) if (state[PYRAMID_CARDS + t].toInt() != 0) return t+        return -1+    }++    private fun removed(state: ByteArray, a: Int, b: Int): ByteArray {+        val child = state.copyOf()+        for (slotId in intArrayOf(a, b)) {+            when {+                slotId == WASTE_SLOT -> child[PYRAMID_CARDS + wasteTop(state)] = 0+                slotId >= 0 -> child[slotId] = 0+            }+        }+        return child+    }++    private fun nextInStock(state: ByteArray): Int? =+        (state[posIndex()].toInt() until talon.size).firstOrNull { state[PYRAMID_CARDS + it].toInt() != 0 }++    /** The stock tap: deal the next card, or recycle when relaxed; null when it does nothing. */+    private fun dealt(state: ByteArray): ByteArray? {+        val next = nextInStock(state)+        val child = state.copyOf()+        when {+            next != null -> child[posIndex()] = (next + 1).toByte()+            relaxed && wasteTop(state) >= 0 -> child[posIndex()] = 0+            else -> return null+        }+        return child+    }++    private fun rankAt(i: Int) = codeRank(pyramid[i])++    private fun posIndex() = PYRAMID_CARDS + talon.size++    companion object {+        /** The budget the shipped tables were generated with. */+        val DEFAULT_BUDGET = SolverBudget(dfsNodes = 1_000_000)++        fun solve(state: PyramidState, budget: SolverBudget = DEFAULT_BUDGET): SolveResult {+            val pyramid = IntArray(PYRAMID_CARDS)+            val start = ByteArray(PYRAMID_CARDS + state.waste.size + state.stock.size + 1)+            for (r in 0 until PYRAMID_ROWS) {+                for (c in 0..r) {+                    val card = state.pyramid.getOrNull(r)?.getOrNull(c) ?: continue+                    pyramid[slot(r, c)] = card.code()+                    start[slot(r, c)] = 1+                }+            }+            // Draw order: the waste bottom-up, then the stock top-down. Dealing and+            // recycling both preserve it, so a position is just which are gone.+            val talon = (state.waste + state.stock.asReversed()).map { it.code() }.toIntArray()+            for (t in talon.indices) start[PYRAMID_CARDS + t] = 1+            start[PYRAMID_CARDS + talon.size] = state.waste.size.toByte()+            return portfolioSearch(PyramidSolver(pyramid, talon, state.relaxed), start, budget)+        }++        /** Expands packed codes into the stock taps and removals a player makes. */+        fun decode(moves: IntArray): List<PyramidMove> = buildList {+            for (m in moves) {+                repeat((m ushr TAPS_SHIFT) and TAPS_MASK) { add(PyramidMove.Deal) }+                val a = (m ushr A_SHIFT) and FIELD_MASK+                val b = (m ushr B_SHIFT) and FIELD_MASK+                val removal = if (m and TYPE_MASK == KING_MOVE) {+                    PyramidMove.RemoveKing(idOf(a))+                } else {+                    PyramidMove.RemovePair(idOf(a), idOf(b))+                }+                add(removal)+            }+        }++        private fun idOf(slotId: Int): String {+            if (slotId == WASTE_SLOT) return "waste"+            val (r, c) = rowCol(slotId)+            return "pyr_${r}_$c"+        }++        private fun slot(row: Int, col: Int) = row * (row + 1) / 2 + col++        private fun rowCol(i: Int): Pair<Int, Int> {+            var row = 0+            while (slot(row + 1, 0) <= i) row+++            return row to i - slot(row, 0)+        }++        private fun pack(type: Int, a: Int, b: Int, taps: Int) =+            type or (a shl A_SHIFT) or (b shl B_SHIFT) or (taps shl TAPS_SHIFT)++        private const val KING_MOVE = 1+        private const val PAIR_MOVE = 2+        private const val TYPE_MASK = 3+        private const val A_SHIFT = 2+        private const val B_SHIFT = 8+        private const val FIELD_MASK = 63+        private const val TAPS_SHIFT = 14+        private const val TAPS_MASK = 127+        private const val WASTE_SLOT = 63+        private const val KING = 13+        private const val POS_BITS = 5+        private const val PYRAMID_CARDS = 28+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolitaireDeals.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolitaireDeals.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolitaireDeals.ktnew file mode 100644index 0000000000..18823ad378--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolitaireDeals.kt@@ -0,0 +1,132 @@+package com.vayunmathur.games.solitaire.domain++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.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.KLONDIKE_TABLEAU_COUNT+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.PYRAMID_ROWS+import com.vayunmathur.games.solitaire.data.PyramidState+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SPIDER_COLUMN_CARDS+import com.vayunmathur.games.solitaire.data.SPIDER_TABLEAU_COUNT+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.SpiderState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import com.vayunmathur.games.solitaire.data.createShuffledDeck+import com.vayunmathur.games.solitaire.data.createSpiderDeck+import com.vayunmathur.games.solitaire.data.redeals++/**+ * Pure deal construction: the one place a seed becomes a starting position.+ *+ * Layouts are exactly what the `new*GameImpl` functions dealt before seeds were+ * kept (same [createShuffledDeck] / [createSpiderDeck] shuffle, same dealing+ * order), so a seed always deals the same board on every device and version,+ * and the offline solver sees precisely the board the player gets.+ */+object SolitaireDeals {++    fun klondike(seed: Long, config: GameConfig): KlondikeState {+        val deck = createShuffledDeck(seed)+        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))+        }+        return KlondikeState(+            stock = deck.subList(index, deck.size),+            waste = emptyList(),+            tableauPiles = tableauPiles,+            foundations = List(FOUNDATION_COUNT) { emptyList() },+            drawMode = config.drawMode,+            difficulty = config.klondikeDifficulty,+            redealsRemaining = config.klondikeDifficulty.redeals(),+            variant = SolvableDeals.variant(GameMode.KLONDIKE, config),+            seed = seed,+        )+    }++    fun freeCell(seed: Long): FreeCellState {+        val deck = createShuffledDeck(seed)+        val piles = List(FREECELL_TABLEAU_COUNT) { mutableListOf<Card>() }+        for (i in deck.indices) piles[i % FREECELL_TABLEAU_COUNT].add(deck[i])+        return FreeCellState(+            tableauPiles = piles.map { it.toList() },+            freeCells = List(FREECELL_COUNT) { null },+            foundations = List(FOUNDATION_COUNT) { emptyList() },+            variant = SolvableDeals.variant(GameMode.FREECELL, GameConfig()),+            seed = seed,+        )+    }++    fun spider(seed: Long, config: GameConfig): SpiderState {+        val deck = createSpiderDeck(config.spiderSuits, seed)+        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))+        }+        return SpiderState(+            tableauPiles = tableauPiles,+            stockGroups = deck.subList(index, deck.size).chunked(SPIDER_TABLEAU_COUNT),+            suitCount = config.spiderSuits,+            variant = SolvableDeals.variant(GameMode.SPIDER, config),+            seed = seed,+        )+    }++    fun pyramid(seed: Long, config: GameConfig): PyramidState {+        val deck = createShuffledDeck(seed)+        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)+        }+        return PyramidState(+            pyramid = rows,+            stock = deck.subList(index, deck.size).toList(),+            waste = emptyList(),+            relaxed = config.relaxed,+            variant = SolvableDeals.variant(GameMode.PYRAMID, config),+            seed = seed,+        )+    }+}++/** Solver card code: `suit.ordinal * 13 + rank - 1`, so 0..51; suits 0-1 are red. */+internal fun Card.code(): Int = suit.ordinal * RANKS + rank.value - 1++internal fun codeToCard(code: Int): Card = Card(Suit.entries[code / RANKS], Rank.entries[code % RANKS])++internal fun codeSuit(code: Int): Int = code / RANKS++/** Rank 1 (Ace) .. 13 (King). */+internal fun codeRank(code: Int): Int = code % RANKS + 1++internal fun codeIsRed(code: Int): Boolean = code / RANKS < 2++internal fun DrawMode.cardsPerDraw(): Int = if (this == DrawMode.DRAW_THREE) 3 else 1++internal const val RANKS = 13
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolvableDeals.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolvableDeals.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolvableDeals.ktnew file mode 100644index 0000000000..efaa001a1e--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolvableDeals.kt@@ -0,0 +1,140 @@+package com.vayunmathur.games.solitaire.domain++import com.vayunmathur.games.solitaire.data.DrawMode+import com.vayunmathur.games.solitaire.data.GameConfig+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.KLONDIKE_DIFFICULTY_ORDER+import java.io.ByteArrayOutputStream+import kotlin.random.Random++/**+ * Which seeds may be dealt: one sorted table of solver-proven seeds per mode ×+ * option, generated offline (see games/solitaire/AGENTS.md) and shipped in+ * `assets/solvable_deals.bin`. Every seed in a table was solved to a full win by+ * the matching domain solver, so any deal picked here is winnable.+ *+ * Table keys reuse the stats variant names (`KLONDIKE__DRAW_THREE_HARD`,+ * `SPIDER__4SUIT`, ...), which are already frozen by the persisted stats keys.+ */+object SolvableDeals {++    const val ASSET_NAME = "solvable_deals.bin"++    private val SPIDER_SUIT_OPTIONS = listOf(1, 2, 4)++    /** The stats variant for a config: `<draw>_<difficulty>`, `<n>SUIT`, `STANDARD`, `RELAXED`/`ORIGINAL`. */+    fun variant(mode: GameMode, config: GameConfig): String = when (mode) {+        GameMode.KLONDIKE -> "${config.drawMode.name}_${config.klondikeDifficulty.name}"+        GameMode.SPIDER -> "${config.spiderSuits}SUIT"+        GameMode.FREECELL -> "STANDARD"+        GameMode.PYRAMID -> if (config.relaxed) "RELAXED" else "ORIGINAL"+    }++    fun tableKey(mode: GameMode, config: GameConfig): String = "${mode.name}__${variant(mode, config)}"++    /** Every config the New Game dialog can produce: 8 Klondike, 3 Spider, FreeCell, 2 Pyramid. */+    val allConfigs: List<Pair<GameMode, GameConfig>> = buildList {+        for (draw in DrawMode.entries) {+            for (difficulty in KLONDIKE_DIFFICULTY_ORDER) {+                add(GameMode.KLONDIKE to GameConfig(drawMode = draw, klondikeDifficulty = difficulty))+            }+        }+        for (suits in SPIDER_SUIT_OPTIONS) add(GameMode.SPIDER to GameConfig(spiderSuits = suits))+        add(GameMode.FREECELL to GameConfig())+        add(GameMode.PYRAMID to GameConfig(relaxed = true))+        add(GameMode.PYRAMID to GameConfig(relaxed = false))+    }++}++/** Decoded seed tables, keyed by [SolvableDeals.tableKey]. */+class SolvableDealTables(private val tables: Map<String, IntArray>) {++    fun seeds(mode: GameMode, config: GameConfig): IntArray? =+        tables[SolvableDeals.tableKey(mode, config)]?.takeIf { it.isNotEmpty() }++    /** A uniformly random proven seed for the config, or null if it has no table. */+    fun pick(mode: GameMode, config: GameConfig, random: Random): Long? =+        seeds(mode, config)?.let { it[random.nextInt(it.size)].toLong() }++    /**+     * The same proven seed on every device for a given [epochDay] (days since+     * 1970-01-01), for a daily or shared deal. Consecutive days are scattered+     * across the table by a fixed 64-bit mix, so they do not walk it in order.+     */+    fun seedForDay(mode: GameMode, config: GameConfig, epochDay: Long): Long? =+        seeds(mode, config)?.let { table ->+            table[Math.floorMod(mix64(epochDay xor DAILY_SALT), table.size.toLong()).toInt()].toLong()+        }++    companion object {+        /**+         * Format: `SOL1`, table count (u8), then per table its key (u8 length ++         * ASCII), seed count (varint) and ascending seeds as varint deltas.+         */+        fun decode(bytes: ByteArray): SolvableDealTables {+            val reader = Reader(bytes)+            require(MAGIC.all { reader.byte() == it.code }) { "not a solvable-deal table" }+            val count = reader.byte()+            val tables = LinkedHashMap<String, IntArray>()+            repeat(count) {+                val key = String(CharArray(reader.byte()) { reader.byte().toChar() })+                var seed = 0+                tables[key] = IntArray(reader.varint()) {+                    seed += reader.varint()+                    seed+                }+            }+            return SolvableDealTables(tables)+        }++        fun encode(tables: Map<String, IntArray>): ByteArray {+            val out = ByteArrayOutputStream()+            MAGIC.forEach { out.write(it.code) }+            out.write(tables.size)+            for ((key, seeds) in tables) {+                out.write(key.length)+                key.forEach { out.write(it.code) }+                writeVarint(out, seeds.size)+                var previous = 0+                for (seed in seeds.sorted()) {+                    writeVarint(out, seed - previous)+                    previous = seed+                }+            }+            return out.toByteArray()+        }++        private fun writeVarint(out: ByteArrayOutputStream, value: Int) {+            var v = value+            while (v >= VARINT_HIGH) {+                out.write((v and VARINT_LOW) or VARINT_HIGH)+                v = v ushr VARINT_SHIFT+            }+            out.write(v)+        }++        private const val MAGIC = "SOL1"+        private const val DAILY_SALT = 0x5EED_DA11L+        private const val VARINT_HIGH = 0x80+        private const val VARINT_LOW = 0x7F+        private const val VARINT_SHIFT = 7+    }++    private class Reader(private val bytes: ByteArray) {+        private var pos = 0++        fun byte(): Int = bytes[pos++].toInt() and 0xFF++        fun varint(): Int {+            var result = 0+            var shift = 0+            while (true) {+                val b = byte()+                result = result or ((b and VARINT_LOW) shl shift)+                if (b < VARINT_HIGH) return result+                shift += VARINT_SHIFT+            }+        }+    }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolverSearch.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolverSearch.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolverSearch.ktnew file mode 100644index 0000000000..e733acdaff--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SolverSearch.kt@@ -0,0 +1,308 @@+package com.vayunmathur.games.solitaire.domain++import java.util.PriorityQueue++/** How a budgeted solver run ended. */+enum class SolveStatus {+    /** A full winning line was found; the deal is proven solvable. */+    SOLVED,++    /** The (pruned) search space was exhausted without a win. */+    UNSOLVABLE,++    /** The node budget ran out first: nothing is proven either way. */+    UNKNOWN,+}++/**+ * Search limits for one solve: a depth-first pass of [dfsNodes] expanded+ * positions, then (if [beamNodes] > 0 and DFS proved nothing) a beam of+ * [beamWidth] for up to [beamNodes]. Tables are generated with each solver's+ * `DEFAULT_BUDGET`; re-verifying a table seed must use the same budget.+ */+data class SolverBudget(val dfsNodes: Int, val beamWidth: Int = 0, val beamNodes: Int = 0)++/**+ * A solver result. [moves] holds the winning line as packed per-mode move codes+ * (see each solver's `decode`); it is empty unless [status] is SOLVED.+ */+class SolveResult(val status: SolveStatus, val moves: IntArray, val nodes: Int)++/**+ * A solitaire position space for [orderedDepthFirstSearch]. States are flat byte arrays+ * whose layout each solver owns; children are fresh arrays, never aliases.+ */+interface SearchProblem {+    fun isWon(state: ByteArray): Boolean++    /** 64-bit key of the canonical position (symmetries folded). */+    fun key(state: ByteArray): Long++    /** Heuristic distance to a win; lower is explored first. */+    fun score(state: ByteArray): Int++    /** Emits every child worth exploring, each with its packed move code. */+    fun expand(state: ByteArray, sink: ChildSink)+}++/** Receives each child position a [SearchProblem] generates, with its packed move code. */+fun interface ChildSink {+    fun child(state: ByteArray, move: Int)+}++private class Level(val children: Array<ByteArray>, val moves: IntArray) {+    var next = 0+}++/**+ * Depth-first search over children ordered by [SearchProblem.score], with a+ * transposition set. Memory stays at the set plus one sorted child list per+ * level, which is what lets many solves run in parallel offline.+ * Deterministic: the same problem, start and [nodeBudget] always give the same+ * result, which is what lets offline-generated seed tables be re-verified by+ * tests. A key collision can only prune a branch (lose completeness), never+ * fake a win, because the returned line is a sequence of real moves from the+ * start position.+ */+internal fun orderedDepthFirstSearch(problem: SearchProblem, start: ByteArray, nodeBudget: Int): SolveResult {+    if (problem.isWon(start)) return SolveResult(SolveStatus.SOLVED, IntArray(0), 0)+    val seen = LongHashSet()+    seen.add(problem.key(start))+    val stack = ArrayList<Level>()+    stack.add(expandSorted(problem, start, seen))+    var expanded = 1+    while (stack.isNotEmpty()) {+        val level = stack[stack.size - 1]+        if (level.next >= level.children.size) {+            stack.removeAt(stack.size - 1)+            continue+        }+        val child = level.children[level.next++]+        if (problem.isWon(child)) return SolveResult(SolveStatus.SOLVED, pathOf(stack), expanded)+        if (expanded >= nodeBudget) return SolveResult(SolveStatus.UNKNOWN, IntArray(0), expanded)+        expanded+++        stack.add(expandSorted(problem, child, seen))+    }+    return SolveResult(SolveStatus.UNSOLVABLE, IntArray(0), expanded)+}++/** The move codes leading to the child each level last handed out. */+private fun pathOf(stack: List<Level>): IntArray = IntArray(stack.size) { stack[it].moves[stack[it].next - 1] }++private fun expandSorted(problem: SearchProblem, state: ByteArray, seen: LongHashSet): Level {+    val states = ArrayList<ByteArray>()+    val codes = ArrayList<Int>()+    val scores = ArrayList<Int>()+    problem.expand(state) { child, move ->+        if (!seen.add(problem.key(child))) return@expand+        states.add(child)+        codes.add(move)+        scores.add(problem.score(child))+    }+    // Stable sort by score keeps the problem's own generation order on ties.+    val order = states.indices.sortedBy { scores[it] }+    return Level(Array(order.size) { states[order[it]] }, IntArray(order.size) { codes[order[it]] })+}++private class Frontier(val priority: Int, val id: Int, val state: ByteArray)++private val FRONTIER_ORDER = Comparator<Frontier> { a, b ->+    // Lowest score first; among equals the newest node, so ties dive deeper.+    if (a.priority != b.priority) a.priority.compareTo(b.priority) else b.id.compareTo(a.id)+}++/**+ * Greedy best-first search with a transposition set: always expands the+ * best-scoring open position anywhere in the tree, so an early mistake is+ * abandoned as soon as a sibling line looks better. Costs memory for the open+ * set (bounded by [nodeBudget] times the branching factor), so it suits the+ * problems where depth-first recovers badly from early mistakes (Spider).+ * Deterministic for the same reasons as [orderedDepthFirstSearch].+ */+internal fun bestFirstSearch(problem: SearchProblem, start: ByteArray, nodeBudget: Int): SolveResult {+    if (problem.isWon(start)) return SolveResult(SolveStatus.SOLVED, IntArray(0), 0)+    val parents = GrowableIntArray()+    val moves = GrowableIntArray()+    val seen = LongHashSet()+    val open = PriorityQueue(FRONTIER_ORDER)+    seen.add(problem.key(start))+    parents.add(-1)+    moves.add(0)+    open.add(Frontier(problem.score(start), 0, start))+    var expanded = 0+    var wonId = -1+    while (open.isNotEmpty() && wonId < 0) {+        if (expanded >= nodeBudget) return SolveResult(SolveStatus.UNKNOWN, IntArray(0), expanded)+        val node = open.poll()+        expanded+++        problem.expand(node.state) { child, move ->+            if (wonId >= 0 || !seen.add(problem.key(child))) return@expand+            val id = parents.size+            parents.add(node.id)+            moves.add(move)+            if (problem.isWon(child)) wonId = id else open.add(Frontier(problem.score(child), id, child))+        }+    }+    if (wonId < 0) return SolveResult(SolveStatus.UNSOLVABLE, IntArray(0), expanded)+    val path = ArrayList<Int>()+    var id = wonId+    while (id > 0) {+        path.add(moves[id])+        id = parents[id]+    }+    return SolveResult(SolveStatus.SOLVED, path.asReversed().toIntArray(), expanded)+}++internal class GrowableIntArray {+    private var data = IntArray(INITIAL_CAPACITY)+    var size = 0+        private set++    fun add(value: Int) {+        if (size == data.size) data = data.copyOf(size * 2)+        data[size++] = value+    }++    operator fun get(index: Int): Int = data[index]++    private companion object {+        const val INITIAL_CAPACITY = 1024+    }+}++/**+ * Beam search: keeps the [width] best-scoring new positions of each depth and+ * expands only those. It cannot prove a deal unsolvable (an empty beam is+ * UNKNOWN), but on Spider it recovers from early mistakes far better than a+ * depth-first search, because every surviving line competes at each depth.+ * Deterministic: ties keep generation order.+ */+internal fun beamSearch(problem: SearchProblem, start: ByteArray, width: Int, nodeBudget: Int): SolveResult {+    if (problem.isWon(start)) return SolveResult(SolveStatus.SOLVED, IntArray(0), 0)+    val seen = LongHashSet()+    seen.add(problem.key(start))+    // Per depth: each kept node's parent index in the previous depth and its move.+    val parents = ArrayList<IntArray>()+    val moves = ArrayList<IntArray>()+    var beam = listOf(start)+    var expanded = 0+    while (beam.isNotEmpty() && expanded < nodeBudget) {+        val next = ArrayList<BeamChild>()+        val layer = LongHashSet()+        for ((index, state) in beam.withIndex()) {+            expanded+++            var won: BeamChild? = null+            problem.expand(state) { child, move ->+                val key = problem.key(child)+                if (won != null || seen.contains(key) || !layer.add(key)) return@expand+                val entry = BeamChild(child, key, problem.score(child), index, move)+                if (problem.isWon(child)) won = entry else next.add(entry)+            }+            won?.let { return SolveResult(SolveStatus.SOLVED, beamPath(parents, moves, it), expanded) }+        }+        // Only kept positions are marked seen: a trimmed one may still be reached later.+        val kept = next.sortedBy { it.score }.take(width)+        kept.forEach { seen.add(it.key) }+        parents.add(IntArray(kept.size) { kept[it].parent })+        moves.add(IntArray(kept.size) { kept[it].move })+        beam = kept.map { it.state }+    }+    return SolveResult(SolveStatus.UNKNOWN, IntArray(0), expanded)+}++private class BeamChild(val state: ByteArray, val key: Long, val score: Int, val parent: Int, val move: Int)++private fun beamPath(parents: List<IntArray>, moves: List<IntArray>, won: BeamChild): IntArray {+    val path = ArrayList<Int>()+    path.add(won.move)+    var index = won.parent+    for (depth in parents.indices.reversed()) {+        path.add(moves[depth][index])+        index = parents[depth][index]+    }+    return path.asReversed().toIntArray()+}++/**+ * A fixed portfolio: [orderedDepthFirstSearch], then, if that proved nothing,+ * [beamSearch], with the limits in [budget]. DFS+ * wins quickly on easy deals and can prove a deal unsolvable; beam rescues the+ * deals where DFS sinks into a hopeless subtree. Deterministic.+ */+internal fun portfolioSearch(problem: SearchProblem, start: ByteArray, budget: SolverBudget): SolveResult {+    val dfs = orderedDepthFirstSearch(problem, start, budget.dfsNodes)+    if (dfs.status != SolveStatus.UNKNOWN || budget.beamNodes <= 0) return dfs+    val beam = beamSearch(problem, start, budget.beamWidth, budget.beamNodes)+    return SolveResult(beam.status, beam.moves, dfs.nodes + beam.nodes)+}++/** Open-addressing set of non-zero-mixed longs; far lighter than HashSet<Long>. */+internal class LongHashSet {+    private var table = LongArray(INITIAL_CAPACITY)+    private var hasZero = false+    private var count = 0++    /** Adds [value]; returns false when it was already present. */+    fun add(value: Long): Boolean {+        if (value == 0L) {+            if (hasZero) return false+            hasZero = true+            return true+        }+        if ((count + 1) * 2 > table.size) grow()+        return insert(table, value)+    }++    fun contains(value: Long): Boolean {+        if (value == 0L) return hasZero+        val mask = table.size - 1+        var i = (mix64(value) and mask.toLong()).toInt()+        while (true) {+            val existing = table[i]+            if (existing == 0L) return false+            if (existing == value) return true+            i = (i + 1) and mask+        }+    }++    private fun insert(into: LongArray, value: Long): Boolean {+        val mask = into.size - 1+        var i = (mix64(value) and mask.toLong()).toInt()+        while (true) {+            val existing = into[i]+            if (existing == 0L) {+                into[i] = value+                if (into === table) count+++                return true+            }+            if (existing == value) return false+            i = (i + 1) and mask+        }+    }++    private fun grow() {+        val old = table+        val next = LongArray(old.size * 2)+        for (v in old) if (v != 0L) insert(next, v)+        table = next+    }++    private companion object {+        const val INITIAL_CAPACITY = 1 shl 12+    }+}++/** SplitMix64 finaliser: a strong 64-bit mixer for keys and hashing. */+internal fun mix64(value: Long): Long {+    var z = value + -0x61c8864680b583ebL+    z = (z xor (z ushr 30)) * -0x40a7b892e31b1a47L+    z = (z xor (z ushr 27)) * -0x6b2fb644ecceee15L+    return z xor (z ushr 31)+}++/** Order-dependent hash of `state[from until from + length]`. */+internal fun hashBytes(state: ByteArray, from: Int, length: Int, seed: Long): Long {+    var h = seed+    for (i in from until from + length) h = mix64(h xor (state[i].toLong() and 0xFF))+    return h+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SpiderSolver.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SpiderSolver.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SpiderSolver.ktnew file mode 100644index 0000000000..7d06b39a17--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/domain/SpiderSolver.kt@@ -0,0 +1,252 @@+package com.vayunmathur.games.solitaire.domain++import com.vayunmathur.games.solitaire.data.FULL_SUIT_SIZE+import com.vayunmathur.games.solitaire.data.SPIDER_TABLEAU_COUNT+import com.vayunmathur.games.solitaire.data.SpiderState+import com.vayunmathur.games.solitaire.data.TOTAL_SPIDER_SUITS++/** One player action in a Spider winning line, in the ViewModel's own vocabulary. */+sealed interface SpiderMove {+    /** Deal one stock row (needs every column non-empty). */+    data object Deal : SpiderMove++    /** Moves the same-suit run starting at [faceUpIndex] of column [from] onto [to]. */+    data class Move(val from: Int, val faceUpIndex: Int, val to: Int) : SpiderMove+}++/**+ * Spider solver for 1, 2 and 4 suits with the game's rules: any card may go on+ * one rank higher, only same-suit runs move, the stock deals a row only when no+ * column is empty, and a K-to-A same-suit run at a column's top clears itself.+ *+ * Pruned for speed (so a budget miss proves nothing): a run moves whole unless+ * it lands on its own suit, a run never slides sideways from one off-suit+ * parent to another, and only the first empty column is tried. Columns are+ * interchangeable once the stock is gone, so only then does the key fold+ * their order.+ */+class SpiderSolver private constructor(private val stock: Array<IntArray>) : SearchProblem {++    override fun isWon(state: ByteArray): Boolean = state[COMPLETED].toInt() >= TOTAL_SPIDER_SUITS++    override fun key(state: ByteArray): Long {+        val ordered = state[STOCK_LEFT].toInt() > 0+        var columns = 0L+        for (c in 0 until SPIDER_TABLEAU_COUNT) {+            val base = colBase(c)+            val h = mix64(hashBytes(state, base, state[base + 1] + 2, COLUMN_SEED))+            columns = if (ordered) mix64(columns xor h) else columns + h+        }+        return mix64(columns + state[STOCK_LEFT] * STOCK_MULT + state[COMPLETED])+    }++    override fun score(state: ByteArray): Int {+        var down = 0+        var breaks = 0+        var empty = 0+        for (c in 0 until SPIDER_TABLEAU_COUNT) {+            val base = colBase(c)+            val d = state[base].toInt()+            val len = state[base + 1].toInt()+            down += d+            if (len == 0) empty+++            for (i in d + 1 until len) breaks += linkCost(state[base + 1 + i].toInt(), state[base + 2 + i].toInt())+        }+        return 6 * down + 2 * breaks - 3 * empty - 2 * FULL_SUIT_SIZE * state[COMPLETED] + 2 * state[STOCK_LEFT]+    }++    override fun expand(state: ByteArray, sink: ChildSink) {+        val firstEmpty = (0 until SPIDER_TABLEAU_COUNT).firstOrNull { state[colBase(it) + 1].toInt() == 0 }+        val runLengths = IntArray(SPIDER_TABLEAU_COUNT) {+            if (state[colBase(it) + 1] > 0) naturalRunLength(state, it) else 0+        }+        // Deal deadlock: rows left, a hole, and every column is a single run, so+        // only splitting a run can fill the holes the deal needs filled.+        val mustSplit = firstEmpty != null && state[STOCK_LEFT] > 0 &&+            (0 until SPIDER_TABLEAU_COUNT).all { state[colBase(it) + 1].toInt() == runLengths[it] }+        for (from in 0 until SPIDER_TABLEAU_COUNT) {+            if (runLengths[from] == 0) continue+            for (to in 0 until SPIDER_TABLEAU_COUNT) {+                if (to != from && to != firstEmpty) emitRunOnto(state, from, runLengths[from], to, sink)+            }+            if (firstEmpty != null) emitRunToEmpty(state, from, runLengths[from], firstEmpty, mustSplit, sink)+        }+        if (firstEmpty == null && state[STOCK_LEFT] > 0) sink.child(dealt(state), pack(DEAL, 0, 0, 0))+    }++    private fun emitRunOnto(state: ByteArray, from: Int, runLen: Int, to: Int, sink: ChildSink) {+        val target = topCard(state, to)+        if (target < 0) return+        val base = colBase(from)+        val len = state[base + 1].toInt()+        val count = codeRank(target) - codeRank(state[base + 1 + len].toInt())+        if (count < 1 || count > runLen) return+        val start = len - count+        val sameSuit = codeSuit(state[base + 2 + start].toInt()) == codeSuit(target)+        if (!sameSuit && count < runLen) return+        if (!sameSuit && start > state[base].toInt() && sitsOnRankParent(state, from, start)) return+        moved(state, from, start, to)?.let { sink.child(it, pack(MOVE, from, start - state[base].toInt(), to)) }+    }++    /**+     * The whole natural run to an empty column, unless it already is the whole+     * column; when [mustSplit], any tail of a whole-column run instead.+     */+    private fun emitRunToEmpty(state: ByteArray, from: Int, runLen: Int, to: Int, mustSplit: Boolean, sink: ChildSink) {+        val base = colBase(from)+        val len = state[base + 1].toInt()+        val start = len - runLen+        val starts = when {+            start > 0 -> start..start+            mustSplit -> 1 until len+            else -> IntRange.EMPTY+        }+        for (s in starts) {+            moved(state, from, s, to)?.let { sink.child(it, pack(MOVE, from, s - state[base].toInt(), to)) }+        }+    }++    private fun sitsOnRankParent(state: ByteArray, from: Int, start: Int): Boolean {+        val base = colBase(from)+        return codeRank(state[base + 1 + start].toInt()) == codeRank(state[base + 2 + start].toInt()) + 1+    }++    private fun dealt(state: ByteArray): ByteArray {+        val child = state.copyOf()+        val row = stock[stock.size - state[STOCK_LEFT]]+        for (c in 0 until SPIDER_TABLEAU_COUNT) {+            if (c < row.size) push(child, c, row[c])+        }+        child[STOCK_LEFT]--+        clearCompletedRuns(child)+        return child+    }++    /** The move with flip and clearing; null if a column would outgrow the layout. */+    private fun moved(state: ByteArray, from: Int, start: Int, to: Int): ByteArray? {+        val fromBase = colBase(from)+        val len = state[fromBase + 1].toInt()+        if (state[colBase(to) + 1] + len - start > MAX_COLUMN) return null+        val child = state.copyOf()+        for (k in start until len) push(child, to, state[fromBase + 2 + k].toInt())+        child[fromBase + 1] = start.toByte()+        flip(child, from)+        clearCompletedRuns(child)+        return child+    }++    companion object {+        /** The budget the shipped tables were generated with. */+        val DEFAULT_BUDGET = SolverBudget(dfsNodes = 100_000, beamWidth = 300, beamNodes = 500_000)++        fun solve(state: SpiderState, budget: SolverBudget = DEFAULT_BUDGET): SolveResult {+            val stock = state.stockGroups.map { group -> group.map { it.code() }.toIntArray() }.toTypedArray()+            val s = ByteArray(SIZE)+            s[COMPLETED] = state.completedSuits.toByte()+            s[STOCK_LEFT] = stock.size.toByte()+            state.tableauPiles.forEachIndexed { c, pile ->+                val base = colBase(c)+                val cards = pile.faceDown + pile.faceUp+                s[base] = pile.faceDown.size.toByte()+                s[base + 1] = cards.size.toByte()+                cards.forEachIndexed { i, card -> s[base + 2 + i] = card.code().toByte() }+            }+            return portfolioSearch(SpiderSolver(stock), s, budget)+        }++        fun decode(moves: IntArray): List<SpiderMove> = moves.map { m ->+            if (m and TYPE_MASK == DEAL) {+                SpiderMove.Deal+            } else {+                SpiderMove.Move(+                    from = (m ushr A_SHIFT) and COLUMN_MASK,+                    faceUpIndex = (m ushr B_SHIFT) and INDEX_MASK,+                    to = (m ushr C_SHIFT) and COLUMN_MASK,+                )+            }+        }++        private fun colBase(c: Int) = COLUMNS + c * COLUMN_SPAN++        private fun topCard(s: ByteArray, c: Int): Int {+            val base = colBase(c)+            val len = s[base + 1].toInt()+            return if (len == 0) -1 else s[base + 1 + len].toInt()+        }++        /** 0 for a same-suit link, 1 for an off-suit rank link, 2 for a dead break. */+        private fun linkCost(parent: Int, child: Int): Int = when {+            codeRank(parent) != codeRank(child) + 1 -> 2+            codeSuit(parent) != codeSuit(child) -> 1+            else -> 0+        }++        private fun naturalRunLength(s: ByteArray, c: Int): Int {+            val base = colBase(c)+            val down = s[base].toInt()+            val len = s[base + 1].toInt()+            var run = 1+            while (len - run > down && isSameSuitLink(s, base, len - run)) {+                run+++            }+            return run+        }++        /** Whether the card at absolute index [i] (cards start at base + 2) sits on its same-suit parent. */+        private fun isSameSuitLink(s: ByteArray, base: Int, i: Int) =+            linkCost(s[base + 1 + i].toInt(), s[base + 2 + i].toInt()) == 0++        private fun push(s: ByteArray, c: Int, card: Int) {+            val base = colBase(c)+            val len = s[base + 1].toInt()+            s[base + 2 + len] = card.toByte()+            s[base + 1] = (len + 1).toByte()+        }++        private fun flip(s: ByteArray, c: Int) {+            val base = colBase(c)+            val len = s[base + 1].toInt()+            if (len > 0 && s[base].toInt() == len) s[base] = (len - 1).toByte()+        }++        /** The game's check: each column's top 13 face-up cards, once, then flip. */+        private fun clearCompletedRuns(s: ByteArray) {+            for (c in 0 until SPIDER_TABLEAU_COUNT) {+                val base = colBase(c)+                val down = s[base].toInt()+                val len = s[base + 1].toInt()+                if (len - down < FULL_SUIT_SIZE) continue+                val start = len - FULL_SUIT_SIZE+                val complete = codeRank(s[base + 2 + start].toInt()) == RANKS &&+                    (start + 1 until len).all { linkCost(s[base + 1 + it].toInt(), s[base + 2 + it].toInt()) == 0 }+                if (!complete) continue+                s[base + 1] = start.toByte()+                flip(s, c)+                s[COMPLETED]+++            }+        }++        private fun pack(type: Int, a: Int, b: Int, c: Int) =+            type or (a shl A_SHIFT) or (b shl B_SHIFT) or (c shl C_SHIFT)++        private const val MOVE = 0+        private const val DEAL = 1+        private const val TYPE_MASK = 1+        private const val A_SHIFT = 1+        private const val B_SHIFT = 5+        private const val C_SHIFT = 12+        private const val COLUMN_MASK = 15+        private const val INDEX_MASK = 127++        private const val COMPLETED = 0+        private const val STOCK_LEFT = 1+        private const val COLUMNS = 2+        private const val MAX_COLUMN = 64+        private const val COLUMN_SPAN = MAX_COLUMN + 2+        private const val SIZE = COLUMNS + SPIDER_TABLEAU_COUNT * COLUMN_SPAN++        private const val COLUMN_SEED = 0x6789_ABCDL+        private const val STOCK_MULT = 0x9E37_79B9L+    }+}+
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SeedTableGeneration.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SeedTableGeneration.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SeedTableGeneration.ktnew file mode 100644index 0000000000..848b5acc1b--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SeedTableGeneration.kt@@ -0,0 +1,155 @@+package com.vayunmathur.games.solitaire.domain++import com.vayunmathur.games.solitaire.data.GameConfig+import com.vayunmathur.games.solitaire.data.GameMode+import java.util.concurrent.Callable+import java.util.concurrent.Executors++/**+ * Offline generator for `assets/solvable_deals.bin` (see AGENTS.md, "Solvable+ * deals"). Scans seeds 1, 2, 3, ... per group of configs that share a deal+ * (Klondike draw-1, Klondike draw-3, Pyramid, FreeCell, each Spider suit count)+ * and keeps, per config, the first [target] seeds that [DealProofs] proves.+ *+ * Deterministic regardless of [threads]: seeds are evaluated in fixed rounds,+ * a config stops being evaluated only between rounds, and each table is the+ * ascending prefix of proven seeds, every seed below its last one decided.+ */+class SeedTableGeneration(+    private val target: Int,+    private val threads: Int,+    private val log: (String) -> Unit,+) {++    /** Per-config outcome counts over the seeds scanned for it. */+    class ConfigReport(val key: String) {+        var scanned = 0+        var solved = 0+        var unsolvable = 0+        var unknown = 0+        var lastSeed = 0+        var solveMillis = 0L++        fun line(): String =+            "%-28s table=%5d scanned=%7d solved=%6.2f%% proven-unsolvable=%6.2f%% unknown=%6.2f%% cpu=%ds".format(+                key, solved, scanned, pct(solved), pct(unsolvable), pct(unknown), solveMillis / 1000,+            )++        private fun pct(n: Int) = if (scanned == 0) 0.0 else 100.0 * n / scanned+    }++    private class Group(val name: String, val mode: GameMode, val configs: List<GameConfig>)++    /** Outcome of one seed for one group: per config, solved / unsolvable / unknown / not evaluated. */+    private class SeedOutcome(val seed: Int, val status: Array<SolveStatus?>, val millis: Long)++    fun generate(groups: List<String> = GROUP_NAMES): Pair<Map<String, IntArray>, List<ConfigReport>> {+        val tables = LinkedHashMap<String, IntArray>()+        val reports = ArrayList<ConfigReport>()+        val pool = Executors.newFixedThreadPool(threads)+        try {+            for (group in allGroups().filter { it.name in groups }) {+                val (groupTables, groupReports) = generateGroup(group, pool)+                tables.putAll(groupTables)+                reports.addAll(groupReports)+            }+        } finally {+            pool.shutdownNow()+        }+        return tables to reports+    }++    private fun generateGroup(+        group: Group,+        pool: java.util.concurrent.ExecutorService,+    ): Pair<Map<String, IntArray>, List<ConfigReport>> {+        val keys = group.configs.map { SolvableDeals.tableKey(group.mode, it) }+        val found = keys.map { ArrayList<Int>() }+        val reports = keys.map { ConfigReport(it) }+        var nextSeed = 1+        val started = System.currentTimeMillis()+        while (found.any { it.size < target }) {+            val needed = BooleanArray(keys.size) { found[it].size < target }+            val round = (nextSeed until nextSeed + ROUND_SIZE).map { seed ->+                Callable { evaluate(group, seed, needed) }+            }+            nextSeed += ROUND_SIZE+            for (outcome in pool.invokeAll(round).map { it.get() }) {+                record(outcome, needed, found, reports)+            }+            log(+                "${group.name}: seeds<${nextSeed} " + keys.indices.joinToString(" ") { "${keys[it]}=${found[it].size}" } ++                    " elapsed=${(System.currentTimeMillis() - started) / 1000}s",+            )+        }+        val tables = keys.indices.associate { keys[it] to found[it].take(target).toIntArray() }+        return tables to reports+    }++    private fun record(+        outcome: SeedOutcome,+        needed: BooleanArray,+        found: List<MutableList<Int>>,+        reports: List<ConfigReport>,+    ) {+        for (c in needed.indices) {+            if (!needed[c] || found[c].size >= target) continue+            val report = reports[c]+            report.scanned+++            report.lastSeed = outcome.seed+            report.solveMillis += outcome.millis+            when (outcome.status[c]) {+                SolveStatus.SOLVED -> {+                    report.solved+++                    found[c].add(outcome.seed)+                }+                SolveStatus.UNSOLVABLE -> report.unsolvable+++                else -> report.unknown+++            }+        }+    }++    /**+     * Climbs the group's ladder (configs are ordered strictest first, each a+     * rung of the next): the first rung that solves the seed solves it for+     * every later config. A rung is skipped once no config at or above it+     * still needs seeds; that changes no table, because those tables are full.+     */+    private fun evaluate(group: Group, seed: Int, needed: BooleanArray): SeedOutcome {+        val status = arrayOfNulls<SolveStatus>(group.configs.size)+        val t = System.currentTimeMillis()+        for (rung in group.configs.indices) {+            if ((rung until group.configs.size).none { needed[it] }) break+            val result = DealProofs.solve(group.mode, group.configs[rung], seed.toLong())+            status[rung] = result.status+            if (result.status == SolveStatus.SOLVED) {+                for (c in rung until group.configs.size) status[c] = SolveStatus.SOLVED+                break+            }+        }+        return SeedOutcome(seed, status, System.currentTimeMillis() - t)+    }++    private fun allGroups(): List<Group> {+        val klondike = SolvableDeals.allConfigs.filter { it.first == GameMode.KLONDIKE }.map { it.second }+        fun klondikeGroup(name: String, draw: com.vayunmathur.games.solitaire.data.DrawMode): Group {+            val top = klondike.first { it.drawMode == draw && it.klondikeDifficulty == RELAXED }+            return Group(name, GameMode.KLONDIKE, DealProofs.ladder(GameMode.KLONDIKE, top))+        }+        return listOf(+            klondikeGroup("klondike-draw1", com.vayunmathur.games.solitaire.data.DrawMode.DRAW_ONE),+            klondikeGroup("klondike-draw3", com.vayunmathur.games.solitaire.data.DrawMode.DRAW_THREE),+            Group("pyramid", GameMode.PYRAMID, DealProofs.ladder(GameMode.PYRAMID, GameConfig(relaxed = true))),+            Group("freecell", GameMode.FREECELL, listOf(GameConfig())),+            Group("spider1", GameMode.SPIDER, listOf(GameConfig(spiderSuits = 1))),+            Group("spider2", GameMode.SPIDER, listOf(GameConfig(spiderSuits = 2))),+            Group("spider4", GameMode.SPIDER, listOf(GameConfig(spiderSuits = 4))),+        )+    }++    companion object {+        val GROUP_NAMES = listOf("klondike-draw1", "klondike-draw3", "pyramid", "freecell", "spider1", "spider2", "spider4")+        private const val ROUND_SIZE = 2048+        private val RELAXED = com.vayunmathur.games.solitaire.data.KlondikeDifficulty.RELAXED+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SolitaireSolversTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SolitaireSolversTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SolitaireSolversTest.ktnew file mode 100644index 0000000000..e7da1a64ea--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SolitaireSolversTest.kt@@ -0,0 +1,236 @@+package com.vayunmathur.games.solitaire.domain++import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.DrawMode+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.KlondikeDifficulty+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.PyramidState+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SpiderState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import com.vayunmathur.games.solitaire.data.createShuffledDeck+import com.vayunmathur.games.solitaire.data.createSpiderDeck+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Solvers on small positions with known answers, plus deal and table-format invariants. */+class SolitaireSolversTest {++    private fun suit(s: Suit, ranks: IntRange) = ranks.map { Card(s, Rank.entries[it - 1]) }+    private fun full(s: Suit) = suit(s, 1..13)+    private val budget = SolverBudget(dfsNodes = 50_000)++    private fun klondike(+        tableau: List<TableauPile>,+        stock: List<Card> = emptyList(),+        waste: List<Card> = emptyList(),+        draw: DrawMode = DrawMode.DRAW_ONE,+        redeals: Int = 0,+    ) = KlondikeState(+        stock = stock,+        waste = waste,+        tableauPiles = tableau + List(7 - tableau.size) { TableauPile() },+        // Foundations are suit-indexed (Suit.entries order): only hearts are left in play.+        foundations = listOf(emptyList(), full(Suit.DIAMONDS), full(Suit.SPADES), full(Suit.CLUBS)),+        drawMode = draw,+        redealsRemaining = redeals,+    )++    @Test fun klondikeDrawOneSolvesAndLineIsLegalShape() {+        // A♥ over 2♥ in a column, 3♥..K♥ in the stock with 3♥ on top.+        val state = klondike(+            tableau = listOf(TableauPile(faceDown = suit(Suit.HEARTS, 2..2), faceUp = suit(Suit.HEARTS, 1..1))),+            stock = suit(Suit.HEARTS, 3..13).reversed(),+        )+        val result = KlondikeSolver.solve(state, budget)+        assertEquals(SolveStatus.SOLVED, result.status)+        val moves = KlondikeSolver.decode(result.moves)+        assertEquals(11, moves.count { it == KlondikeMove.Draw })+        assertEquals(13, moves.count { it !is KlondikeMove.Draw })+    }++    @Test fun klondikeDrawThreeSameStockIsUnsolvableEvenWithUnlimitedPasses() {+        // Drawing three at a time only ever exposes 5♥, 8♥, J♥, K♥: 3♥ is never reachable.+        val tableau = listOf(TableauPile(faceDown = suit(Suit.HEARTS, 2..2), faceUp = suit(Suit.HEARTS, 1..1)))+        val stock = suit(Suit.HEARTS, 3..13).reversed()+        for (redeals in listOf(0, 2, Int.MAX_VALUE)) {+            val result = KlondikeSolver.solve(klondike(tableau, stock, draw = DrawMode.DRAW_THREE, redeals = redeals), budget)+            assertEquals(SolveStatus.UNSOLVABLE, result.status, "redeals=$redeals")+        }+    }++    @Test fun klondikeBuriedAceIsUnsolvable() {+        // 2♥ sits on the face-down A♥ and only a black 3 could take it: none exists.+        val state = klondike(+            tableau = listOf(TableauPile(faceDown = suit(Suit.HEARTS, 1..1), faceUp = suit(Suit.HEARTS, 2..2))),+            waste = suit(Suit.HEARTS, 3..13).reversed(),+            redeals = Int.MAX_VALUE,+        )+        assertEquals(SolveStatus.UNSOLVABLE, KlondikeSolver.solve(state, budget).status)+    }++    @Test fun klondikePassLimitDecidesWin() {+        // 3♥ is the waste bottom: reachable only after a recycle.+        val state = klondike(+            tableau = listOf(TableauPile(faceUp = suit(Suit.HEARTS, 1..1)), TableauPile(faceUp = suit(Suit.HEARTS, 2..2))),+            waste = suit(Suit.HEARTS, 3..13),+        )+        assertEquals(SolveStatus.UNSOLVABLE, KlondikeSolver.solve(state, budget).status)+        assertEquals(SolveStatus.SOLVED, KlondikeSolver.solve(state.copy(redealsRemaining = 1), budget).status)+    }++    private fun freeCell(columns: List<List<Card>>, cells: List<Card?>) = FreeCellState(+        tableauPiles = columns + List(8 - columns.size) { emptyList() },+        freeCells = cells,+        foundations = listOf(emptyList(), full(Suit.DIAMONDS), full(Suit.SPADES), full(Suit.CLUBS)),+    )++    @Test fun freeCellDigsOutBuriedAcesWithSupermoves() {+        // Hearts and spades in play, each Ace under a 12-card alternating run (K down to 2):+        // only a supermove into an empty column frees them.+        fun run(ace: Suit, kingSuit: Suit, other: Suit) =+            listOf(Card(ace, Rank.ACE)) + (13 downTo 2).map { r -> Card(if ((13 - r) % 2 == 0) kingSuit else other, Rank.entries[r - 1]) }+        val state = FreeCellState(+            tableauPiles = listOf(run(Suit.HEARTS, Suit.SPADES, Suit.HEARTS), run(Suit.SPADES, Suit.HEARTS, Suit.SPADES)) ++                List(6) { emptyList() },+            foundations = listOf(emptyList(), full(Suit.DIAMONDS), emptyList(), full(Suit.CLUBS)),+        )+        val result = FreeCellSolver.solve(state, budget)+        assertEquals(SolveStatus.SOLVED, result.status)+        assertTrue(FreeCellSolver.decode(result.moves).any { it is FreeCellMove.TableauToTableau })+    }++    @Test fun freeCellTwelveSameColourCardsOverTheAceIsUnsolvable() {+        // All hearts in one column, Ace at the bottom: twelve cards that cannot stack on each+        // other need twelve free spots, and there are only eleven (4 cells + 7 columns).+        val state = freeCell(listOf(suit(Suit.HEARTS, 1..13)), List(4) { null })+        assertEquals(SolveStatus.UNSOLVABLE, FreeCellSolver.solve(state, budget).status)+    }++    @Test fun freeCellFullyBlockedIsUnsolvable() {+        // Cells hold 10-K, every column is occupied, and 9♥ covers the A♥ with nowhere to go.+        val columns = listOf(suit(Suit.HEARTS, 1..1) + suit(Suit.HEARTS, 9..9)) + (2..8).map { suit(Suit.HEARTS, it..it) }+        val state = freeCell(columns, suit(Suit.HEARTS, 10..13))+        assertEquals(SolveStatus.UNSOLVABLE, FreeCellSolver.solve(state, budget).status)+    }++    private fun pyramidWith(bottom: Card, stock: List<Card>, relaxed: Boolean) = PyramidState(+        pyramid = List(7) { r -> List<Card?>(r + 1) { c -> if (r == 6 && c == 0) bottom else null } },+        stock = stock,+        relaxed = relaxed,+    )++    @Test fun pyramidPairsWithWaste() {+        val queen = Card(Suit.SPADES, Rank.QUEEN)+        val ace = Card(Suit.HEARTS, Rank.ACE)+        val two = Card(Suit.HEARTS, Rank.TWO)+        val result = PyramidSolver.solve(pyramidWith(queen, listOf(ace, two), relaxed = false), budget)+        assertEquals(SolveStatus.SOLVED, result.status)+        assertEquals(+            listOf(PyramidMove.Deal, PyramidMove.Deal, PyramidMove.RemovePair("pyr_6_0", "waste")),+            PyramidSolver.decode(result.moves),+        )+        // Without a match in the stock it is a proof of failure, relaxed or not.+        for (relaxed in listOf(false, true)) {+            assertEquals(SolveStatus.UNSOLVABLE, PyramidSolver.solve(pyramidWith(queen, listOf(two), relaxed), budget).status)+        }+    }++    @Test fun pyramidRecycleNeededOnlyWhenRelaxed() {+        // Fresh, the Ace is dealt first and pairs. Once both are dealt the 2 covers the Ace and+        // cannot be removed: only a recycle (relaxed) brings the Ace back.+        val queen = Card(Suit.SPADES, Rank.QUEEN)+        val stock = listOf(Card(Suit.HEARTS, Rank.TWO), Card(Suit.HEARTS, Rank.ACE))+        // Both dealt already: the waste is [A, 2] with the 2 on top.+        val dealtPast = pyramidWith(queen, emptyList(), relaxed = false).copy(waste = stock.reversed())+        assertEquals(SolveStatus.SOLVED, PyramidSolver.solve(pyramidWith(queen, stock, relaxed = false), budget).status)+        assertEquals(SolveStatus.UNSOLVABLE, PyramidSolver.solve(dealtPast, budget).status)+        assertEquals(SolveStatus.SOLVED, PyramidSolver.solve(dealtPast.copy(relaxed = true), budget).status)+    }++    @Test fun spiderCompletesLastRunAcrossColumns() {+        // Seven suits done; K-2 of spades in one column (King face-down), the Ace alone in another.+        val spades = suit(Suit.SPADES, 1..13)+        val piles = listOf(+            TableauPile(faceDown = listOf(spades[12]), faceUp = spades.subList(1, 12).reversed()),+            TableauPile(faceUp = listOf(spades[0])),+        ) + List(8) { TableauPile() }+        val state = SpiderState(tableauPiles = piles, completedSuits = 7, suitCount = 1)+        val result = SpiderSolver.solve(state, SolverBudget(dfsNodes = 50_000, beamWidth = 50, beamNodes = 50_000))+        assertEquals(SolveStatus.SOLVED, result.status)+        assertTrue(SpiderSolver.decode(result.moves).all { it is SpiderMove.Move })+    }++    @Test fun dealsMatchTheLegacyShuffleExactly() {+        // The deal function must reproduce the pre-table deal for any seed, card for card.+        for (seed in listOf(1L, 42L, 1_794_515_229_000L)) {+            val deck = createShuffledDeck(seed)+            val k = SolitaireDeals.klondike(seed, GameConfig())+            assertEquals(deck, k.tableauPiles.flatMap { it.faceDown + it.faceUp } + k.stock)+            assertEquals(deck.take(28), SolitaireDeals.pyramid(seed, GameConfig()).pyramid.flatten())+            assertEquals(deck.drop(28), SolitaireDeals.pyramid(seed, GameConfig()).stock)+            val fc = SolitaireDeals.freeCell(seed)+            assertEquals(deck, (0 until 52).map { fc.tableauPiles[it % 8][it / 8] })+            val spiderDeck = createSpiderDeck(2, seed)+            val sp = SolitaireDeals.spider(seed, GameConfig(spiderSuits = 2))+            assertEquals(spiderDeck, sp.tableauPiles.flatMap { it.faceDown + it.faceUp } + sp.stockGroups.flatten())+            assertEquals(seed, k.seed)+        }+    }++    @Test fun klondikeTableauIsTheDeckPrefixColumnByColumn() {+        val deck = createShuffledDeck(7)+        val k = SolitaireDeals.klondike(7, GameConfig())+        assertEquals(deck.take(28), k.tableauPiles.flatMap { it.faceDown + it.faceUp })+        assertEquals((0 until 7).map { it }, k.tableauPiles.map { it.faceDown.size })+    }++    @Test fun tableFormatRoundTripsAndPicksOnlyTableSeeds() {+        val tables = mapOf("KLONDIKE__DRAW_ONE_HARD" to intArrayOf(3, 1, 900_000, 77), "SPIDER__4SUIT" to intArrayOf(5))+        val decoded = SolvableDealTables.decode(SolvableDealTables.encode(tables))+        val config = GameConfig(drawMode = DrawMode.DRAW_ONE, klondikeDifficulty = KlondikeDifficulty.HARD)+        assertEquals(listOf(1, 3, 77, 900_000), decoded.seeds(GameMode.KLONDIKE, config)!!.toList())+        val random = Random(1)+        repeat(200) { assertTrue(decoded.pick(GameMode.KLONDIKE, config, random)!!.toInt() in tables.getValue("KLONDIKE__DRAW_ONE_HARD")) }+        assertEquals(5L, decoded.pick(GameMode.SPIDER, GameConfig(spiderSuits = 4), random))+        assertNull(decoded.pick(GameMode.FREECELL, GameConfig(), random))+    }++    @Test fun dailySeedIsDeterministicAndFromTheTable() {+        val seeds = IntArray(1000) { it * 7 + 1 }+        val tables = SolvableDealTables(mapOf("FREECELL__STANDARD" to seeds))+        val again = SolvableDealTables.decode(SolvableDealTables.encode(mapOf("FREECELL__STANDARD" to seeds)))+        val days = (20_000L until 20_400L).map { tables.seedForDay(GameMode.FREECELL, GameConfig(), it)!! }+        assertEquals(days, (20_000L until 20_400L).map { again.seedForDay(GameMode.FREECELL, GameConfig(), it)!! })+        assertTrue(days.all { it.toInt() in seeds })+        // Scattered, not walking the table: 400 days hit many distinct entries.+        assertTrue(days.toSet().size > 300)+    }++    @Test fun tableKeysAreTheStatsVariantsForEveryDialogConfig() {+        assertEquals(14, SolvableDeals.allConfigs.size)+        assertEquals(14, SolvableDeals.allConfigs.map { (m, c) -> SolvableDeals.tableKey(m, c) }.toSet().size)+        assertEquals("KLONDIKE__DRAW_THREE_TWO_PASSES", SolvableDeals.tableKey(GameMode.KLONDIKE, GameConfig(DrawMode.DRAW_THREE, KlondikeDifficulty.TWO_PASSES)))+        assertEquals("SPIDER__4SUIT", SolvableDeals.tableKey(GameMode.SPIDER, GameConfig(spiderSuits = 4)))+        assertEquals("PYRAMID__ORIGINAL", SolvableDeals.tableKey(GameMode.PYRAMID, GameConfig(relaxed = false)))+        assertEquals("FREECELL__STANDARD", SolvableDeals.tableKey(GameMode.FREECELL, GameConfig()))+    }++    @Test fun ladderNestsPassLimits() {+        val hardest = DealProofs.ladder(GameMode.KLONDIKE, GameConfig(DrawMode.DRAW_THREE, KlondikeDifficulty.RELAXED))+        assertEquals(+            listOf(KlondikeDifficulty.HARD, KlondikeDifficulty.TWO_PASSES, KlondikeDifficulty.REGULAR, KlondikeDifficulty.RELAXED),+            hardest.map { it.klondikeDifficulty },+        )+        assertTrue(hardest.all { it.drawMode == DrawMode.DRAW_THREE })+        assertEquals(listOf(false, true), DealProofs.ladder(GameMode.PYRAMID, GameConfig(relaxed = true)).map { it.relaxed })+        assertEquals(1, DealProofs.ladder(GameMode.SPIDER, GameConfig(spiderSuits = 2)).size)+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SolvableSeedTableGenerator.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SolvableSeedTableGenerator.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SolvableSeedTableGenerator.ktnew file mode 100644index 0000000000..aa5a5077b9--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/domain/SolvableSeedTableGenerator.kt@@ -0,0 +1,41 @@+package com.vayunmathur.games.solitaire.domain++import java.io.File+import org.junit.Assume.assumeTrue+import org.junit.Test++/**+ * Regenerates `src/main/assets/solvable_deals.bin`. Skipped in normal test runs;+ * runs only when Gradle is given `-PsolitaireSeedGen=<output dir>` (see the+ * module build file and AGENTS.md, "Solvable deals"). Writes the table plus a+ * `solvable_deals_report.txt` with per-config solvable rates.+ */+class SolvableSeedTableGenerator {++    @Test+    fun generate() {+        val out = System.getProperty("solitaire.seedgen.out")+        assumeTrue("offline generator: pass -PsolitaireSeedGen=<dir>", !out.isNullOrBlank())+        val dir = File(out!!).apply { mkdirs() }+        val target = System.getProperty("solitaire.seedgen.target")?.toIntOrNull() ?: DEFAULT_TARGET+        val threads = System.getProperty("solitaire.seedgen.threads")?.toIntOrNull()?.takeIf { it > 0 }+            ?: Runtime.getRuntime().availableProcessors()+        val groups = System.getProperty("solitaire.seedgen.groups")?.takeIf { it.isNotBlank() }?.split(",")+            ?: SeedTableGeneration.GROUP_NAMES+        val reportFile = File(dir, "solvable_deals_report.txt")+        val log: (String) -> Unit = { line ->+            println(line)+            reportFile.appendText(line + "\n")+        }+        log("target=$target threads=$threads groups=$groups")+        val (tables, reports) = SeedTableGeneration(target, threads, log).generate(groups)+        reports.forEach { log(it.line()) }+        val bytes = SolvableDealTables.encode(tables)+        File(dir, SolvableDeals.ASSET_NAME).writeBytes(bytes)+        log("wrote ${SolvableDeals.ASSET_NAME}: ${bytes.size} bytes, ${tables.size} tables")+    }++    private companion object {+        const val DEFAULT_TARGET = 10_000+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolutionReplay.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolutionReplay.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolutionReplay.ktnew file mode 100644index 0000000000..5f2d16d82c--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolutionReplay.kt@@ -0,0 +1,113 @@+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.SolitaireUiState+import com.vayunmathur.games.solitaire.domain.DealProofs+import com.vayunmathur.games.solitaire.domain.FreeCellMove+import com.vayunmathur.games.solitaire.domain.FreeCellSolver+import com.vayunmathur.games.solitaire.domain.KlondikeMove+import com.vayunmathur.games.solitaire.domain.KlondikeSolver+import com.vayunmathur.games.solitaire.domain.PyramidMove+import com.vayunmathur.games.solitaire.domain.PyramidSolver+import com.vayunmathur.games.solitaire.domain.SolitaireDeals+import com.vayunmathur.games.solitaire.domain.SolvableDeals+import com.vayunmathur.games.solitaire.domain.SolveResult+import com.vayunmathur.games.solitaire.domain.SpiderMove+import com.vayunmathur.games.solitaire.domain.SpiderSolver+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Plays a solver's winning line through the real ViewModel rules, one player+ * action at a time, and checks that every action is accepted and the game+ * ends won. This is the guard against solver/rules drift: if a rule in the+ * `*Ops` files changes, lines stop replaying here and the seed tables must be+ * regenerated (AGENTS.md, "Solvable deals").+ */+internal object SolutionReplay {++    fun vm(): SolitaireViewModel = SolitaireViewModel(ApplicationProvider.getApplicationContext<Application>())++    /** Proves [seed] for [config] along its ladder and replays the line; returns the number of actions. */+    fun proveAndReplay(mode: GameMode, config: GameConfig, seed: Long): Int {+        val (_, result) = requireNotNull(DealProofs.prove(mode, config, seed)) { "$mode $config seed $seed: not proven" }+        return replay(mode, config, seed, result)+    }++    fun replay(mode: GameMode, config: GameConfig, seed: Long, result: SolveResult): Int {+        val vm = vm()+        // The deal exactly as a new game would start it (the line was found on this board).+        vm.uiStateInternal.value = 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))+        }+        val label = "$mode ${SolvableDeals.variant(mode, config)} seed=$seed"+        val actions = when (mode) {+            GameMode.KLONDIKE -> KlondikeSolver.decode(result.moves).onEachIndexed { i, m ->+                stepAccepted(vm, "$label step $i $m") { klondikeStep(vm, m) }+            }.size+            GameMode.FREECELL -> FreeCellSolver.decode(result.moves).onEachIndexed { i, m ->+                stepAccepted(vm, "$label step $i $m") { freeCellStep(vm, m) }+            }.size+            GameMode.SPIDER -> SpiderSolver.decode(result.moves).onEachIndexed { i, m ->+                stepAccepted(vm, "$label step $i $m") { spiderStep(vm, m) }+            }.size+            GameMode.PYRAMID -> PyramidSolver.decode(result.moves).onEachIndexed { i, m ->+                stepAccepted(vm, "$label step $i $m") { pyramidStep(vm, m) }+            }.size+        }+        assertTrue(won(vm), "$label: line replayed but the game is not won")+        return actions+    }++    private fun moveCount(vm: SolitaireViewModel): Int = with(vm.uiState.value) {+        klondike?.moveCount ?: spider?.moveCount ?: freeCell?.moveCount ?: pyramid?.moveCount ?: -1+    }++    private fun won(vm: SolitaireViewModel): Boolean = with(vm.uiState.value) {+        klondike?.isWon ?: spider?.isWon ?: freeCell?.isWon ?: pyramid?.isWon ?: false+    }++    /** Every player action counts exactly one move; a rejected action counts none. */+    private inline fun stepAccepted(vm: SolitaireViewModel, label: String, step: () -> Unit) {+        val before = moveCount(vm)+        step()+        assertEquals(before + 1, moveCount(vm), "$label was rejected by the game")+    }++    private fun klondikeStep(vm: SolitaireViewModel, m: KlondikeMove) = when (m) {+        KlondikeMove.Draw -> vm.drawFromStock()+        is KlondikeMove.WasteToFoundation -> vm.klondikeMoveWasteToFoundation(m.foundation)+        is KlondikeMove.WasteToTableau -> vm.klondikeMoveWasteToTableau(m.column)+        is KlondikeMove.TableauToFoundation -> vm.klondikeMoveTableauToFoundation(m.column, m.foundation)+        is KlondikeMove.TableauToTableau -> vm.klondikeMoveTableauToTableau(m.from, m.faceUpIndex, m.to)+    }++    private fun freeCellStep(vm: SolitaireViewModel, m: FreeCellMove) = when (m) {+        is FreeCellMove.TableauToFoundation -> vm.freeCellMoveTableauToFoundation(m.column, m.foundation)+        is FreeCellMove.FreeCellToFoundation -> vm.freeCellMoveFreeCellToFoundation(m.cell, m.foundation)+        is FreeCellMove.TableauToTableau -> vm.freeCellMoveTableauToTableau(m.from, m.cardIndex, m.to)+        is FreeCellMove.FreeCellToTableau -> vm.freeCellMoveFromFreeCell(m.cell, m.column)+        is FreeCellMove.TableauToFreeCell -> vm.freeCellMoveToFreeCell(m.column, m.cell)+    }++    private fun spiderStep(vm: SolitaireViewModel, m: SpiderMove) = when (m) {+        SpiderMove.Deal -> vm.dealSpiderStock()+        is SpiderMove.Move -> vm.spiderMoveCards(m.from, m.faceUpIndex, m.to)+    }++    /** A pair is two taps (select, then match); a King is one tap. */+    private fun pyramidStep(vm: SolitaireViewModel, m: PyramidMove) = when (m) {+        PyramidMove.Deal -> vm.pyramidDealStock()+        is PyramidMove.RemoveKing -> vm.pyramidTapCard(m.id)+        is PyramidMove.RemovePair -> {+            vm.pyramidTapCard(m.first)+            vm.pyramidTapCard(m.second)+        }+    }+}
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.ktnew file mode 100644index 0000000000..7cb0138f28--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SolverReplayTest.kt@@ -0,0 +1,35 @@+package com.vayunmathur.games.solitaire.platform++import com.vayunmathur.games.solitaire.domain.DealProofs+import com.vayunmathur.games.solitaire.domain.SolvableDeals+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]).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SolverReplayTest {++    @Test+    fun solverLinesWinUnderTheGameRulesForEveryConfig() {+        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) }+        }+    }++    private companion object {+        const val SAMPLES = 2+        const val MAX_SCAN = 400L+    }+}