Modern Apps git

← Modern-Apps.git

games-solitaire: add tests for variant ops, drag, boards and screens

Commit
75f11909ef7fba67291dded4c4b4d3cd387d06f7
Author
Vayun Mathur <[email protected]>
When
2026-11-07 10:57 UTC (29 days ago)
Parents
9119fa0
Pass 3 for :games:solitaire (was 26.6% merged). New tests:

- Klondike/FreeCell/Spider/Pyramid operations through the
  ViewModel with crafted states: draw modes and redeal limits,
  waste/tableau/foundation moves, auto-complete draining to a
  win, FreeCell supermove capacity (free cells x empty columns),
  Spider run completion and the eighth-suit win, Pyramid
  exposure/sole-cover pairs, Kings, selection toggling and
  relaxed-vs-original recycling.
- Drag and drop: drag lifecycle, drop-target ranking by overlap
  with point fallback, fall-through to the first accepting
  target, per-mode drop dispatch by source/target ids, and
  draggedCards read from live state per mode.
- Stats/settings repositories (per-variant aggregation, legacy
  key folding, corrupt-record behaviour), card colour schemes,
  achievements manager and backup agent lists.
- Compose under Robolectric: all four boards, tableau columns,
  drag overlay, tap-to-autoMove, GameBoardScreen (auto-complete
  button, give-up confirm/dismiss, win overlay), HomeScreen
  picker and config-dialog flows plus Continue, GameConfigDialog
  for every mode, SettingsScreen, WinOverlay, GameScreen and
  Navigation/MainActivity.

111 unit tests pass. Merged INSTRUCTION coverage:
26.6% -> 91.7% (15508/16914 instructions).
Untestable remainder: DraggableCard drag-gesture internals
(pointer-input drags need a real input pipeline; tap is covered),
Route serializer companion, and MainActivity beyond onCreate.
No production code changes.

(cherry picked from commit 8bd4263d17c8e757e85a59c98525bdd9d7f7bd33)

Diff

games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/RepositoriesTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/RepositoriesTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/RepositoriesTest.ktnew file mode 100644index 0000000000..e5c11f9df3--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/data/RepositoriesTest.kt@@ -0,0 +1,149 @@+package com.vayunmathur.games.solitaire.data++import android.content.Context+import androidx.compose.ui.graphics.Color+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.platform.AppBackupAgent+import com.vayunmathur.games.solitaire.platform.SolitaireAchievementsManager+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Stats persistence/aggregation, settings, colour schemes, backup lists. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class RepositoriesTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    @BeforeTest fun clearPrefs() {+        ctx.getSharedPreferences("solitaire_stats", Context.MODE_PRIVATE).edit().clear().commit()+        ctx.getSharedPreferences("solitaire_settings", Context.MODE_PRIVATE).edit().clear().commit()+    }++    @Test fun statsRecordPlayedWonLostAndAggregatePerMode() {+        val repo = SolitaireStatsRepository(ctx)+        assertEquals(GameStats(), repo.getStats(GameMode.KLONDIKE, "DRAW_ONE_REGULAR"))+        assertEquals(GameStats(), repo.getModeStats(GameMode.KLONDIKE))+        assertEquals(0, repo.getTotalGamesWon())+        assertEquals(0, repo.getBestWinStreak())++        repo.recordGamePlayed(GameMode.KLONDIKE, "DRAW_ONE_REGULAR")+        repo.recordGamePlayed(GameMode.KLONDIKE, "DRAW_ONE_REGULAR")+        repo.recordGamePlayed(GameMode.KLONDIKE, "DRAW_THREE_HARD")+        repo.recordGameWon(GameMode.KLONDIKE, "DRAW_ONE_REGULAR", 300)+        repo.recordGameWon(GameMode.KLONDIKE, "DRAW_ONE_REGULAR", 120)+        repo.recordGameWon(GameMode.KLONDIKE, "DRAW_THREE_HARD", 600)++        val variant = repo.getStats(GameMode.KLONDIKE, "DRAW_ONE_REGULAR")+        assertEquals(2, variant.gamesPlayed)+        assertEquals(2, variant.gamesWon)+        assertEquals(2, variant.currentWinStreak)+        assertEquals(2, variant.bestWinStreak)+        assertEquals(120, variant.bestTimeSeconds)++        val mode = repo.getModeStats(GameMode.KLONDIKE)+        assertEquals(3, mode.gamesPlayed)+        assertEquals(3, mode.gamesWon)+        assertEquals(2, mode.currentWinStreak) // max across variants+        assertEquals(120, mode.bestTimeSeconds) // min across variants+        assertEquals(3, repo.getTotalGamesWon())+        assertEquals(2, repo.getBestWinStreak())+        assertEquals(GameStats(), repo.getModeStats(GameMode.SPIDER))++        // A loss resets only that variant's current streak.+        repo.recordGameLost(GameMode.KLONDIKE, "DRAW_ONE_REGULAR")+        val after = repo.getStats(GameMode.KLONDIKE, "DRAW_ONE_REGULAR")+        assertEquals(0, after.currentWinStreak)+        assertEquals(2, after.bestWinStreak)+        assertEquals(2, after.gamesWon)+    }++    @Test fun statsSurviveNewRepositoryInstanceAndLegacyKeyFoldsIn() {+        val repo = SolitaireStatsRepository(ctx)+        repo.recordGameWon(GameMode.FREECELL, "STANDARD", 90)+        // Legacy pre-variant key written directly.+        ctx.getSharedPreferences("solitaire_stats", Context.MODE_PRIVATE)+            .edit()+            .putString("stats_FREECELL", """{"gamesPlayed":5,"gamesWon":1,"currentWinStreak":0,"bestWinStreak":4,"bestTimeSeconds":45}""")+            .commit()+        val fresh = SolitaireStatsRepository(ctx)+        val mode = fresh.getModeStats(GameMode.FREECELL)+        assertEquals(5 + 0, mode.gamesPlayed) // variant record played 0 games+        assertEquals(2, mode.gamesWon)+        assertEquals(4, mode.bestWinStreak)+        assertEquals(45, mode.bestTimeSeconds)+        assertEquals(2, fresh.getTotalGamesWon())+    }++    @Test fun corruptedStatsJsonIsToleratedAsMissing() {+        ctx.getSharedPreferences("solitaire_stats", Context.MODE_PRIVATE)+            .edit().putString("stats_SPIDER__1SUIT", "not json").commit()+        val repo = SolitaireStatsRepository(ctx)+        // Current behaviour: a corrupt record surfaces as a decode failure+        // rather than silently resetting the player's stats.+        kotlin.test.assertFailsWith<kotlinx.serialization.SerializationException> {+            repo.getStats(GameMode.SPIDER, "1SUIT")+        }+    }++    @Test fun settingsDefaultPersistAndInvalidValue() {+        val repo = SolitaireSettingsRepository(ctx)+        assertEquals(CardColorScheme.TWO_COLOUR, repo.getCardColorScheme())+        repo.setCardColorScheme(CardColorScheme.FOUR_COLOUR)+        assertEquals(CardColorScheme.FOUR_COLOUR, SolitaireSettingsRepository(ctx).getCardColorScheme())+        ctx.getSharedPreferences("solitaire_settings", Context.MODE_PRIVATE)+            .edit().putString("card_color_scheme", "RAINBOW").commit()+        assertEquals(CardColorScheme.TWO_COLOUR, repo.getCardColorScheme())+        repo.setCardColorScheme(CardColorScheme.TWO_COLOUR)+        assertEquals(CardColorScheme.TWO_COLOUR, repo.getCardColorScheme())+    }++    @Test fun cardColorSchemes() {+        val two = CardColorScheme.TWO_COLOUR+        assertEquals(Color(0xFFCC0000), two.colorFor(Suit.HEARTS))+        assertEquals(Color(0xFFCC0000), two.colorFor(Suit.DIAMONDS))+        assertEquals(Color(0xFF000000), two.colorFor(Suit.SPADES))+        assertEquals(Color(0xFF000000), two.colorFor(Suit.CLUBS))+        val four = CardColorScheme.FOUR_COLOUR+        assertEquals(Color(0xFFCC0000), four.colorFor(Suit.HEARTS))+        assertEquals(Color(0xFF0B57D0), four.colorFor(Suit.DIAMONDS))+        assertEquals(Color(0xFF1B7F3B), four.colorFor(Suit.CLUBS))+        assertEquals(Color(0xFF000000), four.colorFor(Suit.SPADES))+    }++    @Test fun gameStatsDefaultsAndCopy() {+        val s = GameStats()+        assertEquals(Int.MAX_VALUE, s.bestTimeSeconds)+        assertEquals(0, s.gamesPlayed)+        assertEquals(s.copy(gamesWon = 3), GameStats(gamesWon = 3))+    }++    @Test fun backupAgentLists() {+        val agent = AppBackupAgent()+        assertEquals(listOf("solitaire_stats"), agent.prefNames)+        assertEquals(listOf("datastore_default"), agent.datastoreNames)+    }++    @Test fun achievementsManagerChecksExistingFromStats() {+        val stats = SolitaireStatsRepository(ctx)+        stats.recordGameWon(GameMode.KLONDIKE, "DRAW_ONE_REGULAR", 100)+        stats.recordGameWon(GameMode.SPIDER, "1SUIT", 100)+        val json = ctx.assets.open("achievements.json").bufferedReader().readText()+        val manager = SolitaireAchievementsManager(ctx, json, stats)+        // Construction does not auto-check; the explicit check must run+        // without error against recorded wins and report progress calls.+        manager.checkExistingAchievements()+        manager.dismissNotification()+    }++    @Test fun achievementsManagerWithNoWinsChecksCleanly() {+        val stats = SolitaireStatsRepository(ctx)+        val json = ctx.assets.open("achievements.json").bufferedReader().readText()+        val manager = SolitaireAchievementsManager(ctx, json, stats)+        manager.checkExistingAchievements()+        manager.dismissNotification()+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.ktnew file mode 100644index 0000000000..ca878ccd5f--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/DragAndViewModelTest.kt@@ -0,0 +1,346 @@+package com.vayunmathur.games.solitaire.platform++import android.app.Application+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.unit.IntSize+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.FreeCellState+import com.vayunmathur.games.solitaire.data.GameMode+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.SolitaireUiState+import com.vayunmathur.games.solitaire.data.SpiderState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Drag lifecycle, drop-target ranking, drop dispatch and ViewModel shell. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class DragAndViewModelTest {+    private val app = ApplicationProvider.getApplicationContext<Application>()+    private fun vm() = SolitaireViewModel(app)+    private fun c(suit: Suit, rank: Rank) = Card(suit, rank)++    private fun setK(vm: SolitaireViewModel, state: KlondikeState) {+        vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.KLONDIKE, klondike = state)+    }++    @Test fun dragLifecycleStartsUpdatesEndsAndCancels() {+        val vm = vm()+        val queen = c(Suit.HEARTS, Rank.QUEEN)+        val king = c(Suit.SPADES, Rank.KING)+        setK(+            vm,+            KlondikeState(+                waste = listOf(queen),+                tableauPiles = listOf(TableauPile(faceUp = listOf(king))) + List(6) { TableauPile() },+            ),+        )+        assertFalse(vm.startDrag("tableau_3_0", Offset.Zero)) // empty source+        assertNull(vm.dragInfo.value)+        assertTrue(vm.startDrag("waste", Offset(10f, 20f), IntSize(60, 84)))+        var info = vm.dragInfo.value!!+        assertEquals(listOf(queen), info.cards)+        assertEquals("waste", info.sourceId)+        vm.updateDrag(Offset(50f, 60f))+        info = vm.dragInfo.value!!+        assertEquals(Offset(50f, 60f), info.offset)+        // Drop over the king's column (large overlap) moves the queen.+        vm.dropTargets["tableau_0"] = Rect(0f, 0f, 100f, 100f)+        vm.endDrag(Offset(50f, 50f), IntSize(60, 84))+        assertNull(vm.dragInfo.value)+        val k = vm.uiState.value.klondike!!+        assertTrue(k.waste.isEmpty())+        assertEquals(queen, k.tableauPiles[0].faceUp.last())+        // Cancel clears without moving.+        assertTrue(vm.startDrag("tableau_0_1", Offset.Zero, IntSize(60, 84)))+        vm.cancelDrag()+        assertNull(vm.dragInfo.value)+        assertEquals(1, vm.uiState.value.klondike!!.moveCount)+        // EndDrag with nothing in flight is a no-op.+        vm.endDrag(Offset.Zero, IntSize.Zero)+        vm.updateDrag(Offset(1f, 1f))+        assertNull(vm.dragInfo.value)+    }++    @Test fun endDragFallsBackToDragStartCardSize() {+        val vm = vm()+        val queen = c(Suit.HEARTS, Rank.QUEEN)+        setK(+            vm,+            KlondikeState(+                waste = listOf(queen),+                tableauPiles = listOf(TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.KING)))) + List(6) { TableauPile() },+            ),+        )+        vm.dropTargets["tableau_0"] = Rect(0f, 0f, 100f, 100f)+        assertTrue(vm.startDrag("waste", Offset.Zero, IntSize(60, 84)))+        // Zero size at drop: the size recorded at drag start is used.+        vm.endDrag(Offset(50f, 50f), IntSize.Zero)+        assertTrue(vm.uiState.value.klondike!!.waste.isEmpty())+    }++    @Test fun dropTargetRankingByOverlapThenPointFallback() {+        val vm = vm()+        vm.dropTargets["tableau_0"] = Rect(0f, 0f, 100f, 100f)+        vm.dropTargets["tableau_1"] = Rect(50f, 0f, 150f, 100f)+        vm.dropTargets["foundation_0"] = Rect(500f, 500f, 560f, 584f)+        // Card centred at (75,50) size 100x100 overlaps both columns equally-ish:+        // tableau_0 overlap 75 wide, tableau_1 overlap 75 wide — order is by area.+        val ranked = vm.candidateDropTargets(Offset(75f, 50f), IntSize(100, 100))+        assertEquals(setOf("tableau_0", "tableau_1"), ranked.toSet())+        assertEquals(2, ranked.size)+        // Zero-size card falls back to point containment.+        assertEquals(listOf("foundation_0"), vm.candidateDropTargets(Offset(530f, 540f), IntSize.Zero))+        assertEquals(emptyList(), vm.candidateDropTargets(Offset(999f, 999f), IntSize.Zero))+        // Overlap area helper directly.+        assertEquals(2500f, overlapArea(Rect(0f, 0f, 100f, 100f), Rect(50f, 50f, 150f, 150f)))+        assertEquals(0f, overlapArea(Rect(0f, 0f, 10f, 10f), Rect(20f, 20f, 30f, 30f)))+        assertEquals(0f, overlapArea(Rect(0f, 0f, 10f, 10f), Rect(10f, 0f, 20f, 10f)))+    }++    @Test fun tryMoveByDragFallsThroughToAcceptingTarget() {+        val vm = vm()+        val queen = c(Suit.HEARTS, Rank.QUEEN)+        // tableau_0 (red king) cannot take the red queen; tableau_1 (black king) can.+        // Give the illegal target the larger overlap so ranking tries it first.+        setK(+            vm,+            KlondikeState(+                waste = listOf(queen),+                tableauPiles = listOf(+                    TableauPile(faceUp = listOf(c(Suit.DIAMONDS, Rank.KING))),+                    TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.KING))),+                ) + List(5) { TableauPile() },+            ),+        )+        vm.dropTargets["tableau_0"] = Rect(0f, 0f, 200f, 200f)+        vm.dropTargets["tableau_1"] = Rect(0f, 0f, 100f, 100f)+        vm.tryMoveByDrag("waste", Offset(50f, 50f), IntSize(50, 50))+        val k = vm.uiState.value.klondike!!+        assertTrue(k.waste.isEmpty())+        assertEquals(queen, k.tableauPiles[1].faceUp.last())+    }++    @Test fun tryMoveByDragFoundationAndSpiderAndPyramidModes() {+        val vm = vm()+        val ace = c(Suit.HEARTS, Rank.ACE)+        setK(vm, KlondikeState(waste = listOf(ace)))+        vm.dropTargets["foundation_0"] = Rect(0f, 0f, 100f, 100f)+        vm.tryMoveByDrag("waste", Offset(50f, 50f), IntSize(50, 50))+        assertEquals(listOf(ace), vm.uiState.value.klondike!!.foundations[0])+        // Spider: tableau to tableau by drag.+        vm.uiStateInternal.value = SolitaireUiState(+            gameMode = GameMode.SPIDER,+            spider = SpiderState(+                tableauPiles = listOf(+                    TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.EIGHT))),+                    TableauPile(faceUp = listOf(c(Suit.HEARTS, Rank.NINE))),+                ) + List(8) { TableauPile() },+            ),+        )+        vm.dropTargets.clear()+        vm.dropTargets["tableau_1"] = Rect(0f, 0f, 100f, 100f)+        vm.tryMoveByDrag("tableau_0_0", Offset(50f, 50f), IntSize(50, 50))+        assertEquals(2, vm.uiState.value.spider!!.tableauPiles[1].faceUp.size)+        // Pyramid ignores drags entirely.+        val pyr = PyramidState(pyramid = listOf(listOf(ace)))+        vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.PYRAMID, pyramid = pyr)+        vm.tryMoveByDrag("pyr_0_0", Offset(50f, 50f), IntSize(50, 50))+        assertEquals(pyr, vm.uiState.value.pyramid)+        // No mode: no-op.+        vm.uiStateInternal.value = SolitaireUiState()+        vm.tryMoveByDrag("waste", Offset.Zero, IntSize.Zero)+    }++    @Test fun freeCellDropDispatchByIds() {+        val vm = vm()+        val seven = c(Suit.SPADES, Rank.SEVEN)+        val six = c(Suit.HEARTS, Rank.SIX)+        vm.uiStateInternal.value = SolitaireUiState(+            gameMode = GameMode.FREECELL,+            freeCell = FreeCellState(+                tableauPiles = listOf(listOf(seven), listOf(c(Suit.CLUBS, Rank.EIGHT))) + List(6) { emptyList() },+            ),+        )+        vm.dropTargets["freecell_1"] = Rect(0f, 0f, 100f, 100f)+        vm.tryMoveByDrag("tableau_0_0", Offset(50f, 50f), IntSize(50, 50))+        assertEquals(seven, vm.uiState.value.freeCell!!.freeCells[1])+        // Cell -> tableau via drag.+        vm.dropTargets.clear()+        vm.dropTargets["tableau_1"] = Rect(0f, 0f, 100f, 100f)+        // Put a red seven into the cell first via state, then drag it onto+        // the black eight.+        vm.uiStateInternal.value = vm.uiStateInternal.value.copy(+            freeCell = vm.uiStateInternal.value.freeCell!!.copy(+                freeCells = listOf(c(Suit.HEARTS, Rank.SEVEN), null, null, null),+            ),+        )+        vm.tryMoveByDrag("freecell_0", Offset(50f, 50f), IntSize(50, 50))+        var f = vm.uiState.value.freeCell!!+        assertEquals(c(Suit.HEARTS, Rank.SEVEN), f.tableauPiles[1].last())+        // Tableau ace -> foundation via drag.+        vm.uiStateInternal.value = vm.uiStateInternal.value.copy(+            freeCell = f.copy(tableauPiles = listOf(listOf(c(Suit.HEARTS, Rank.ACE))) + List(7) { emptyList() }),+        )+        vm.dropTargets.clear()+        vm.dropTargets["foundation_0"] = Rect(0f, 0f, 100f, 100f)+        vm.tryMoveByDrag("tableau_0_0", Offset(50f, 50f), IntSize(50, 50))+        f = vm.uiState.value.freeCell!!+        assertEquals(1, f.foundations[0].size)+    }++    @Test fun klondikeDropFromTableauToFoundationAndTableau() {+        val vm = vm()+        val ace = c(Suit.DIAMONDS, Rank.ACE) // foundation index 1+        setK(+            vm,+            KlondikeState(+                tableauPiles = listOf(+                    TableauPile(faceUp = listOf(ace)),+                    TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.KING))),+                ) + List(5) { TableauPile() },+            ),+        )+        vm.dropTargets["foundation_1"] = Rect(0f, 0f, 100f, 100f)+        vm.tryMoveByDrag("tableau_0_0", Offset(50f, 50f), IntSize(50, 50))+        assertEquals(listOf(ace), vm.uiState.value.klondike!!.foundations[1])+        // A multi-card drag onto a foundation is ignored (single-card only),+        // but the same drag onto a tableau works at the run level below.+        val runTop = c(Suit.HEARTS, Rank.QUEEN)+        setK(+            vm,+            KlondikeState(+                tableauPiles = listOf(+                    TableauPile(faceUp = listOf(c(Suit.CLUBS, Rank.KING), runTop)),+                    TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.KING))),+                ) + List(5) { TableauPile() },+            ),+        )+        vm.dropTargets.clear()+        vm.dropTargets["foundation_0"] = Rect(0f, 0f, 100f, 100f)+        vm.tryMoveByDrag("tableau_0_0", Offset(50f, 50f), IntSize(50, 50))+        assertTrue(vm.uiState.value.klondike!!.foundations[0].isEmpty())+        assertEquals(2, vm.uiState.value.klondike!!.tableauPiles[0].faceUp.size)+    }++    @Test fun draggedCardsReadsLiveStatePerMode() {+        val vm = vm()+        setK(+            vm,+            KlondikeState(+                waste = listOf(c(Suit.HEARTS, Rank.QUEEN)),+                tableauPiles = listOf(TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.SEVEN), c(Suit.HEARTS, Rank.SIX)))) + List(6) { TableauPile() },+            ),+        )+        assertEquals(listOf(c(Suit.HEARTS, Rank.QUEEN)), vm.draggedCards("waste"))+        assertEquals(2, vm.draggedCards("tableau_0_0").size)+        assertEquals(listOf(c(Suit.HEARTS, Rank.SIX)), vm.draggedCards("tableau_0_1"))+        assertEquals(emptyList(), vm.draggedCards("tableau_0_9"))+        assertEquals(emptyList(), vm.draggedCards("tableau_z_0"))+        assertEquals(emptyList(), vm.draggedCards("freecell_x"))+        assertEquals(emptyList(), vm.draggedCards("pyr_0_0"))+        assertTrue(vm.isSingleCardDrag("waste"))+        assertFalse(vm.isSingleCardDrag("tableau_0_0"))+        // FreeCell tableau drags come from the flat pile lists.+        vm.uiStateInternal.value = SolitaireUiState(+            gameMode = GameMode.FREECELL,+            freeCell = FreeCellState(+                tableauPiles = listOf(listOf(c(Suit.SPADES, Rank.SEVEN), c(Suit.HEARTS, Rank.SIX))) + List(7) { emptyList() },+                freeCells = listOf(c(Suit.CLUBS, Rank.ACE), null, null, null),+            ),+        )+        assertEquals(listOf(c(Suit.CLUBS, Rank.ACE)), vm.draggedCards("freecell_0"))+        assertEquals(2, vm.draggedCards("tableau_0_0").size)+        // Spider tableau drags too.+        vm.uiStateInternal.value = SolitaireUiState(+            gameMode = GameMode.SPIDER,+            spider = SpiderState(tableauPiles = listOf(TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.NINE)))) + List(9) { TableauPile() }),+        )+        assertEquals(1, vm.draggedCards("tableau_0_0").size)+    }++    @Test fun viewModelShellTimerRestartGiveUpAndUndoPerMode() {+        val vm = vm()+        // Timer with no game is a no-op; each mode ticks.+        vm.incrementTimer()+        assertEquals(SolitaireUiState(), vm.uiState.value)+        vm.selectMode(GameMode.FREECELL)+        assertEquals(GameMode.FREECELL, vm.uiState.value.gameMode)+        vm.incrementTimer()+        assertEquals(1, vm.uiState.value.freeCell!!.elapsedSeconds)+        assertTrue(vm.hasActiveGame())+        // Undo with empty history no-ops; restart redeals same mode.+        vm.undo()+        vm.restart()+        assertEquals(GameMode.FREECELL, vm.uiState.value.gameMode)+        assertEquals(0, vm.uiState.value.freeCell!!.elapsedSeconds)+        // Give up clears the board and records the loss.+        vm.giveUp()+        assertEquals(SolitaireUiState(), vm.uiState.value)+        assertFalse(vm.hasActiveGame())+        vm.giveUp() // no mode: returns quietly+        // Undo restores each variant type.+        vm.selectMode(GameMode.SPIDER, com.vayunmathur.games.solitaire.data.GameConfig(spiderSuits = 2))+        vm.incrementTimer()+        vm.undo() // history empty (deal doesn't save)+        val before = vm.uiState.value.spider!!+        vm.dealSpiderStock()+        vm.undo()+        assertEquals(before.stockGroups, vm.uiState.value.spider!!.stockGroups)+        assertTrue(vm.uiState.value.spider!!.usedUndo)+        assertEquals(2, vm.currentConfig().spiderSuits)+    }++    @Test fun undoRestoresPyramidAndFreeCellStates() {+        val vm = vm()+        vm.selectMode(GameMode.PYRAMID, com.vayunmathur.games.solitaire.data.GameConfig(relaxed = true))+        val p0 = vm.uiState.value.pyramid!!+        vm.pyramidDealStock()+        assertEquals(1, vm.uiState.value.pyramid!!.waste.size)+        vm.undo()+        assertEquals(p0.stock, vm.uiState.value.pyramid!!.stock)+        assertTrue(vm.uiState.value.pyramid!!.usedUndo)+        vm.selectMode(GameMode.FREECELL)+        val f0 = vm.uiState.value.freeCell!!+        // Move any tableau top card into a free cell, then undo.+        val col = f0.tableauPiles.indexOfFirst { it.isNotEmpty() }+        vm.freeCellMoveToFreeCell(col, 0)+        assertEquals(1, vm.uiState.value.history.size)+        vm.undo()+        assertEquals(f0.tableauPiles, vm.uiState.value.freeCell!!.tableauPiles)+        assertTrue(vm.uiState.value.freeCell!!.usedUndo)+    }++    @Test fun actionsInterfaceDefaultsAndNoop() {+        val noop = SolitaireActions.Noop+        assertNull(noop.dragInfo.value)+        assertFalse(noop.startDrag("waste", Offset.Zero))+        // Defaults swallow every call.+        noop.updateDrag(Offset.Zero); noop.endDrag(Offset.Zero); noop.cancelDrag()+        noop.drawFromStock(); noop.klondikeAutoComplete(); noop.dealSpiderStock()+        noop.pyramidTapCard("x"); noop.pyramidDealStock(); noop.autoMove("x")+        noop.undo(); noop.restart(); noop.giveUp()+        noop.dropTargets["probe"] = Rect(0f, 0f, 1f, 1f)+        assertTrue(noop.dropTargets.containsKey("probe"))+        noop.dropTargets.remove("probe")+    }++    @Test fun dragInfoDataClass() {+        val info = DragInfo(listOf(c(Suit.HEARTS, Rank.ACE)), "waste")+        assertEquals(Offset.Zero, info.offset)+        assertEquals(IntSize.Zero, info.cardSize)+        assertEquals(info, info.copy(offset = Offset(1f, 2f)).copy(offset = Offset.Zero))+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/FreeCellOpsTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/FreeCellOpsTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/FreeCellOpsTest.ktnew file mode 100644index 0000000000..da7066c2a4--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/FreeCellOpsTest.kt@@ -0,0 +1,187 @@+package com.vayunmathur.games.solitaire.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.FreeCellState+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.data.Suit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** FreeCell moves, capacity rule, drops and auto-move. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class FreeCellOpsTest {+    private val app = ApplicationProvider.getApplicationContext<Application>()+    private fun vm() = SolitaireViewModel(app)+    private fun c(suit: Suit, rank: Rank) = Card(suit, rank)++    private fun setF(vm: SolitaireViewModel, state: FreeCellState) {+        vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.FREECELL, freeCell = state)+    }++    private fun state(+        piles: List<List<Card>>,+        cells: List<Card?> = List(4) { null },+        foundations: List<List<Card>> = List(4) { emptyList() },+    ): FreeCellState = FreeCellState(+        tableauPiles = piles + List(8 - piles.size) { emptyList() },+        freeCells = cells,+        foundations = foundations,+    )++    @Test fun moveToAndFromFreeCell() {+        val vm = vm()+        val seven = c(Suit.SPADES, Rank.SEVEN)+        setF(vm, state(listOf(listOf(seven))))+        vm.freeCellMoveToFreeCell(0, 2)+        var f = vm.uiState.value.freeCell!!+        assertEquals(seven, f.freeCells[2])+        assertTrue(f.tableauPiles[0].isEmpty())+        // Occupied cell and empty source reject.+        setF(vm, state(listOf(listOf(c(Suit.HEARTS, Rank.SIX))), cells = listOf(seven, null, null, null)))+        vm.freeCellMoveToFreeCell(0, 0)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+        vm.freeCellMoveToFreeCell(5, 1)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+        // Back out onto a black seven.+        setF(vm, state(listOf(listOf(c(Suit.SPADES, Rank.SEVEN))), cells = listOf(c(Suit.HEARTS, Rank.SIX), null, null, null)))+        vm.freeCellMoveFromFreeCell(0, 0)+        f = vm.uiState.value.freeCell!!+        assertEquals(listOf(c(Suit.SPADES, Rank.SEVEN), c(Suit.HEARTS, Rank.SIX)), f.tableauPiles[0])+        assertEquals(null, f.freeCells[0])+        // Illegal placement (same colour sequence break) rejects; empty cell source rejects.+        setF(vm, state(listOf(listOf(c(Suit.CLUBS, Rank.SEVEN))), cells = listOf(c(Suit.SPADES, Rank.SIX), null, null, null)))+        vm.freeCellMoveFromFreeCell(0, 0)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+        vm.freeCellMoveFromFreeCell(3, 0)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+    }++    @Test fun freeCellAndTableauToFoundationAndWin() {+        val vm = vm()+        val ace = c(Suit.HEARTS, Rank.ACE)+        setF(vm, state(listOf(emptyList()), cells = listOf(ace, null, null, null)))+        vm.freeCellMoveFreeCellToFoundation(0, 0)+        var f = vm.uiState.value.freeCell!!+        assertEquals(listOf(ace), f.foundations[0])+        assertEquals(null, f.freeCells[0])+        // Wrong foundation rejects.+        setF(vm, state(listOf(listOf(c(Suit.HEARTS, Rank.TWO)))))+        vm.freeCellMoveTableauToFoundation(0, 1)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+        vm.freeCellMoveTableauToFoundation(0, 0)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount) // needs ace first+        setF(vm, state(listOf(listOf(ace))))+        vm.freeCellMoveTableauToFoundation(0, 0)+        assertEquals(listOf(ace), vm.uiState.value.freeCell!!.foundations[0])+        // Empty pile rejects.+        vm.freeCellMoveTableauToFoundation(4, 0)+        // Win: foundations all but one king complete, last king in a cell.+        val foundations = Suit.entries.map { suit ->+            if (suit == Suit.CLUBS) Rank.entries.filter { it != Rank.KING }.map { Card(suit, it) }+            else Rank.entries.map { Card(suit, it) }+        }+        setF(+            vm,+            state(listOf(emptyList()), cells = listOf(c(Suit.CLUBS, Rank.KING), null, null, null), foundations = foundations),+        )+        vm.freeCellMoveFreeCellToFoundation(0, 3)+        assertTrue(vm.uiState.value.freeCell!!.isWon)+    }++    @Test fun tableauToTableauSequenceAndCapacity() {+        val vm = vm()+        val run = listOf(c(Suit.SPADES, Rank.SEVEN), c(Suit.HEARTS, Rank.SIX), c(Suit.CLUBS, Rank.FIVE))+        val target = listOf(c(Suit.HEARTS, Rank.EIGHT))+        // With all 4 cells free, a 3-run can move.+        setF(vm, state(listOf(run, target)))+        vm.freeCellMoveTableauToTableau(0, 0, 1)+        var f = vm.uiState.value.freeCell!!+        assertEquals(target + run, f.tableauPiles[1])+        // Fill every free cell and every other column: capacity is 1, so the+        // same 3-run cannot move, but a single card still can.+        val full = listOf(c(Suit.CLUBS, Rank.ACE), c(Suit.CLUBS, Rank.TWO), c(Suit.CLUBS, Rank.THREE), c(Suit.CLUBS, Rank.FOUR))+        val fillers = List(6) { listOf(c(Suit.CLUBS, Rank.SEVEN)) }+        setF(vm, state(listOf(run, target) + fillers, cells = full.map { it as Card? }))+        vm.freeCellMoveTableauToTableau(0, 0, 1)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+        // A single card (the filler seven onto the red eight) still can.+        vm.freeCellMoveTableauToTableau(2, 0, 1)+        assertEquals(1, vm.uiState.value.freeCell!!.moveCount)+        // Broken sequence rejects even the sub-run start.+        val broken = listOf(c(Suit.SPADES, Rank.SEVEN), c(Suit.SPADES, Rank.SIX))+        setF(vm, state(listOf(broken, target)))+        vm.freeCellMoveTableauToTableau(0, 0, 1)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+        // Out-of-range indices reject.+        vm.freeCellMoveTableauToTableau(0, -1, 1)+        vm.freeCellMoveTableauToTableau(0, 9, 1)+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+    }++    @Test fun capacityGrowsWithEmptyColumns() {+        val vm = vm()+        val run = listOf(c(Suit.SPADES, Rank.SEVEN), c(Suit.HEARTS, Rank.SIX))+        val target = listOf(c(Suit.HEARTS, Rank.EIGHT))+        // No free cells but one other empty column: maxMove = 1 * 2 = 2.+        val cells = List<Card?>(4) { c(Suit.CLUBS, Rank.ACE) }+        // Exactly one other column empty: maxMove = (1 + 0) * 2^1 = 2.+        val fillers = List(5) { listOf(c(Suit.CLUBS, Rank.KING)) }+        setF(vm, state(listOf(run, target) + fillers + listOf(emptyList()), cells = cells))+        vm.freeCellMoveTableauToTableau(0, 0, 1)+        assertEquals(1, vm.uiState.value.freeCell!!.moveCount)+    }++    @Test fun autoMoveFoundationTableauAndEmptyCellFallback() {+        val vm = vm()+        // Tableau ace prefers foundation.+        setF(vm, state(listOf(listOf(c(Suit.HEARTS, Rank.ACE)))))+        vm.autoMove("tableau_0_0")+        assertEquals(1, vm.uiState.value.freeCell!!.foundations[0].size)+        // Cell card to tableau.+        setF(vm, state(listOf(listOf(c(Suit.SPADES, Rank.SEVEN))), cells = listOf(c(Suit.HEARTS, Rank.SIX), null, null, null)))+        vm.autoMove("freecell_0")+        var f = vm.uiState.value.freeCell!!+        assertEquals(2, f.tableauPiles[0].size)+        assertEquals(null, f.freeCells[0])+        // Tableau run to another tableau.+        val run = listOf(c(Suit.SPADES, Rank.SEVEN), c(Suit.HEARTS, Rank.SIX))+        setF(vm, state(listOf(run, listOf(c(Suit.HEARTS, Rank.EIGHT)))))+        vm.autoMove("tableau_0_0")+        f = vm.uiState.value.freeCell!!+        assertTrue(f.tableauPiles[0].isEmpty())+        assertEquals(3, f.tableauPiles[1].size)+        // No foundation/tableau spot (every other column topped by a queen,+        // the rest empty is not the case here): the top card parks in a cell.+        val pile = listOf(c(Suit.SPADES, Rank.KING), c(Suit.HEARTS, Rank.QUEEN))+        val blockers = List(7) { listOf(c(Suit.CLUBS, Rank.QUEEN)) }+        setF(vm, state(listOf(pile) + blockers))+        vm.autoMove("tableau_0_1")+        f = vm.uiState.value.freeCell!!+        assertEquals(c(Suit.HEARTS, Rank.QUEEN), f.freeCells[0])+        // Bad sources no-op.+        vm.autoMove("waste")+        vm.autoMove("tableau_x")+        vm.autoMove("freecell_9")+        assertEquals(1, vm.uiState.value.freeCell!!.moveCount)+    }++    @Test fun wonGameIgnoresMoves() {+        val vm = vm()+        val won = state(listOf(listOf(c(Suit.HEARTS, Rank.ACE)))).copy(isWon = true)+        setF(vm, won)+        vm.freeCellMoveToFreeCell(0, 0)+        vm.autoMove("tableau_0_0")+        assertEquals(0, vm.uiState.value.freeCell!!.moveCount)+        assertEquals(null, vm.uiState.value.freeCell!!.freeCells[0])+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/KlondikeOpsTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/KlondikeOpsTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/KlondikeOpsTest.ktnew file mode 100644index 0000000000..b33e70e6f9--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/KlondikeOpsTest.kt@@ -0,0 +1,273 @@+package com.vayunmathur.games.solitaire.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.Card+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.KlondikeDifficulty+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Klondike operations beyond the basic waste/tableau moves covered elsewhere. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class KlondikeOpsTest {+    private val app = ApplicationProvider.getApplicationContext<Application>()+    private fun vm() = SolitaireViewModel(app)+    private fun c(suit: Suit, rank: Rank) = Card(suit, rank)++    private fun setK(vm: SolitaireViewModel, state: KlondikeState) {+        vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.KLONDIKE, klondike = state)+    }++    private fun sevenPiles(vararg piles: TableauPile): List<TableauPile> =+        piles.toList() + List(7 - piles.size) { TableauPile() }++    @Test fun drawThreeDrawsUpToThreeAndRecycleHonoursRedeals() {+        val vm = vm()+        val stock = listOf(c(Suit.HEARTS, Rank.ACE), c(Suit.HEARTS, Rank.TWO), c(Suit.HEARTS, Rank.THREE), c(Suit.HEARTS, Rank.FOUR))+        setK(vm, KlondikeState(stock = stock, drawMode = DrawMode.DRAW_THREE, redealsRemaining = 1))+        vm.drawFromStock()+        var k = vm.uiState.value.klondike!!+        assertEquals(3, k.waste.size)+        assertEquals(1, k.stock.size)+        // Waste top is the stock's original top card.+        assertEquals(c(Suit.HEARTS, Rank.TWO), k.waste.last())+        vm.drawFromStock()+        k = vm.uiState.value.klondike!!+        assertEquals(4, k.waste.size)+        assertEquals(0, k.stock.size)+        // Recycle consumes the one redeal; second recycle is refused.+        vm.drawFromStock()+        k = vm.uiState.value.klondike!!+        assertEquals(4, k.stock.size)+        assertEquals(0, k.redealsRemaining)+        val movesBefore = k.moveCount+        vm.drawFromStock()+        vm.drawFromStock()+        // After drawing all out again, no redeals remain: stock empties and stays.+        k = vm.uiState.value.klondike!!+        assertTrue(k.stock.isEmpty() || k.redealsRemaining == 0)+        assertTrue(k.moveCount >= movesBefore)+    }++    @Test fun drawFromStockNoOpsWhenEmptyOrWon() {+        val vm = vm()+        setK(vm, KlondikeState(stock = emptyList(), waste = emptyList()))+        vm.drawFromStock()+        assertEquals(0, vm.uiState.value.klondike!!.moveCount)+        val won = KlondikeState(stock = listOf(c(Suit.HEARTS, Rank.ACE)), isWon = true)+        setK(vm, won)+        vm.drawFromStock()+        assertEquals(won, vm.uiState.value.klondike)+        // No game at all.+        vm.uiStateInternal.value = SolitaireUiState()+        vm.drawFromStock()+        assertEquals(null, vm.uiState.value.klondike)+    }++    @Test fun relaxedRecycleStaysUnlimited() {+        val vm = vm()+        setK(vm, KlondikeState(stock = emptyList(), waste = listOf(c(Suit.CLUBS, Rank.FIVE)), redealsRemaining = Int.MAX_VALUE))+        vm.drawFromStock()+        val k = vm.uiState.value.klondike!!+        assertEquals(listOf(c(Suit.CLUBS, Rank.FIVE)), k.stock)+        assertEquals(Int.MAX_VALUE, k.redealsRemaining)+    }++    @Test fun tableauToFoundationMovesAndFlipsAndRejects() {+        val vm = vm()+        val down = c(Suit.CLUBS, Rank.NINE)+        val ace = c(Suit.HEARTS, Rank.ACE)+        setK(+            vm,+            KlondikeState(+                tableauPiles = sevenPiles(TableauPile(faceDown = listOf(down), faceUp = listOf(ace))),+            ),+        )+        vm.klondikeMoveTableauToFoundation(0, 0)+        var k = vm.uiState.value.klondike!!+        assertEquals(listOf(ace), k.foundations[0])+        assertEquals(listOf(down), k.tableauPiles[0].faceUp)+        assertTrue(k.tableauPiles[0].faceDown.isEmpty())+        // Wrong suit index (foundation 1 is Diamonds) rejects a Hearts two on empty.+        setK(vm, KlondikeState(tableauPiles = sevenPiles(TableauPile(faceUp = listOf(c(Suit.HEARTS, Rank.TWO))))))+        vm.klondikeMoveTableauToFoundation(0, 1)+        assertTrue(vm.uiState.value.klondike!!.foundations[1].isEmpty())+        // Empty pile rejects.+        vm.klondikeMoveTableauToFoundation(3, 0)+        assertEquals(0, vm.uiState.value.klondike!!.moveCount)+    }++    @Test fun tableauToTableauRangeChecksAndSequenceMove() {+        val vm = vm()+        val pile0 = TableauPile(faceUp = listOf(c(Suit.HEARTS, Rank.SEVEN), c(Suit.SPADES, Rank.SIX)))+        val pile1 = TableauPile(faceUp = listOf(c(Suit.CLUBS, Rank.EIGHT)))+        setK(vm, KlondikeState(tableauPiles = sevenPiles(pile0, pile1)))+        vm.klondikeMoveTableauToTableau(0, -1, 1)+        vm.klondikeMoveTableauToTableau(0, 5, 1)+        assertEquals(0, vm.uiState.value.klondike!!.moveCount)+        // Move the two-card run onto the black eight.+        vm.klondikeMoveTableauToTableau(0, 0, 1)+        val k = vm.uiState.value.klondike!!+        assertEquals(listOf(c(Suit.CLUBS, Rank.EIGHT), c(Suit.HEARTS, Rank.SEVEN), c(Suit.SPADES, Rank.SIX)), k.tableauPiles[1].faceUp)+        assertTrue(k.tableauPiles[0].faceUp.isEmpty())+    }++    @Test fun foundationPlacementRules() {+        val vm = vm()+        assertTrue(vm.canPlaceOnFoundation(c(Suit.HEARTS, Rank.ACE), emptyList(), 0))+        assertFalse(vm.canPlaceOnFoundation(c(Suit.DIAMONDS, Rank.ACE), emptyList(), 0))+        assertFalse(vm.canPlaceOnFoundation(c(Suit.HEARTS, Rank.TWO), emptyList(), 0))+        val f = listOf(c(Suit.HEARTS, Rank.ACE), c(Suit.HEARTS, Rank.TWO))+        assertTrue(vm.canPlaceOnFoundation(c(Suit.HEARTS, Rank.THREE), f, 0))+        assertFalse(vm.canPlaceOnFoundation(c(Suit.SPADES, Rank.THREE), f, 0))+        assertFalse(vm.canPlaceOnFoundation(c(Suit.HEARTS, Rank.FOUR), f, 0))+    }++    @Test fun autoCompleteDrainsStockWasteAndTableauToWin() {+        val vm = vm()+        // Foundations one card short per suit except Hearts needs its King from tableau.+        fun almost(suit: Suit) = Suit.entries.indexOf(suit).let { }+        val foundations = Suit.entries.map { suit ->+            Rank.entries.filter { it != Rank.KING }.map { Card(suit, it) }+        }+        val state = KlondikeState(+            stock = listOf(Card(Suit.SPADES, Rank.KING)),+            waste = listOf(Card(Suit.HEARTS, Rank.KING)),+            tableauPiles = sevenPiles(+                TableauPile(faceUp = listOf(Card(Suit.DIAMONDS, Rank.KING))),+                TableauPile(faceUp = listOf(Card(Suit.CLUBS, Rank.KING))),+            ),+            foundations = foundations,+            elapsedSeconds = 42,+        )+        setK(vm, state)+        assertTrue(canKlondikeAutoComplete(state))+        vm.klondikeAutoComplete()+        val k = vm.uiState.value.klondike!!+        assertTrue(k.isWon, "state=$k")+        assertTrue(k.foundations.all { it.size == 13 })+        assertTrue(k.stock.isEmpty() && k.waste.isEmpty())+    }++    @Test fun autoCompleteNoOpsWhenFaceDownPresent() {+        val vm = vm()+        val state = KlondikeState(+            tableauPiles = sevenPiles(TableauPile(faceDown = listOf(c(Suit.HEARTS, Rank.ACE)), faceUp = listOf(c(Suit.HEARTS, Rank.TWO)))),+        )+        setK(vm, state)+        vm.klondikeAutoComplete()+        assertEquals(0, vm.uiState.value.klondike!!.foundations[0].size)+    }++    @Test fun klondikeWinDetectedWhenLastFoundationCompletes() {+        val vm = vm()+        val foundations = Suit.entries.map { suit ->+            if (suit == Suit.HEARTS) Rank.entries.filter { it != Rank.KING }.map { Card(suit, it) }+            else Rank.entries.map { Card(suit, it) }+        }+        setK(+            vm,+            KlondikeState(+                waste = listOf(c(Suit.HEARTS, Rank.KING)),+                foundations = foundations,+                elapsedSeconds = 500,+            ),+        )+        vm.klondikeMoveWasteToFoundation(0)+        assertTrue(vm.uiState.value.klondike!!.isWon)+    }++    @Test fun autoMoveWasteToFoundationThenTableau() {+        val vm = vm()+        // Waste ace goes to its foundation first.+        setK(vm, KlondikeState(waste = listOf(c(Suit.HEARTS, Rank.ACE))))+        vm.autoMove("waste")+        assertEquals(listOf(c(Suit.HEARTS, Rank.ACE)), vm.uiState.value.klondike!!.foundations[0])+        // Waste red queen with no foundation spot goes onto a black king.+        setK(+            vm,+            KlondikeState(+                waste = listOf(c(Suit.HEARTS, Rank.QUEEN)),+                tableauPiles = sevenPiles(TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.KING)))),+            ),+        )+        vm.autoMove("waste")+        var k = vm.uiState.value.klondike!!+        assertTrue(k.waste.isEmpty())+        assertEquals(c(Suit.HEARTS, Rank.QUEEN), k.tableauPiles[0].faceUp.last())+        // Tableau top two of hearts follows its ace.+        setK(+            vm,+            KlondikeState(+                foundations = listOf(listOf(c(Suit.HEARTS, Rank.ACE))) + List(3) { emptyList() },+                tableauPiles = sevenPiles(TableauPile(faceUp = listOf(c(Suit.HEARTS, Rank.TWO)))),+            ),+        )+        vm.autoMove("tableau_0_0")+        k = vm.uiState.value.klondike!!+        assertEquals(2, k.foundations[0].size)+    }++    @Test fun autoMoveNoOpsForBadSourcesAndLoneKingShuffle() {+        val vm = vm()+        // Lone king in an empty-origin column does not shuffle to another empty column.+        setK(+            vm,+            KlondikeState(tableauPiles = sevenPiles(TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.KING))))),+        )+        vm.autoMove("tableau_0_0")+        assertEquals(listOf(c(Suit.SPADES, Rank.KING)), vm.uiState.value.klondike!!.tableauPiles[0].faceUp)+        vm.autoMove("nonsense")+        vm.autoMove("tableau_9_0")+        vm.autoMove("")+        assertEquals(0, vm.uiState.value.klondike!!.moveCount)+        // Won game ignores auto-move.+        setK(vm, KlondikeState(waste = listOf(c(Suit.HEARTS, Rank.ACE)), isWon = true))+        vm.autoMove("waste")+        assertTrue(vm.uiState.value.klondike!!.waste.isNotEmpty())+    }++    @Test fun canPlaceOnTableauEdgeCases() {+        val vm = vm()+        assertTrue(vm.canPlaceOnKlondikeTableau(c(Suit.SPADES, Rank.KING), TableauPile()))+        assertFalse(vm.canPlaceOnKlondikeTableau(c(Suit.SPADES, Rank.QUEEN), TableauPile()))+        // Pile with only face-down cards accepts nothing (not even a King).+        assertFalse(+            vm.canPlaceOnKlondikeTableau(+                c(Suit.SPADES, Rank.KING),+                TableauPile(faceDown = listOf(c(Suit.HEARTS, Rank.ACE))),+            ),+        )+        val topBlack = TableauPile(faceUp = listOf(c(Suit.CLUBS, Rank.SEVEN)))+        assertTrue(vm.canPlaceOnKlondikeTableau(c(Suit.HEARTS, Rank.SIX), topBlack))+        assertFalse(vm.canPlaceOnKlondikeTableau(c(Suit.SPADES, Rank.SIX), topBlack))+        assertFalse(vm.canPlaceOnKlondikeTableau(c(Suit.HEARTS, Rank.FIVE), topBlack))+    }++    @Test fun newGameVariantsAndDrawModesRecorded() {+        val vm = vm()+        vm.newKlondikeGame(GameConfig(drawMode = DrawMode.DRAW_ONE, klondikeDifficulty = KlondikeDifficulty.RELAXED))+        var k = vm.uiState.value.klondike!!+        assertEquals("DRAW_ONE_RELAXED", k.variant)+        assertEquals(Int.MAX_VALUE, k.redealsRemaining)+        assertEquals(DrawMode.DRAW_ONE, vm.currentConfig().drawMode)+        vm.newKlondikeGame(GameConfig(drawMode = DrawMode.DRAW_THREE, klondikeDifficulty = KlondikeDifficulty.REGULAR))+        k = vm.uiState.value.klondike!!+        assertEquals(2, k.redealsRemaining)+        assertEquals("DRAW_THREE_REGULAR", vm.currentVariant())+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SpiderPyramidOpsTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SpiderPyramidOpsTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SpiderPyramidOpsTest.ktnew file mode 100644index 0000000000..35b52c1a04--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/platform/SpiderPyramidOpsTest.kt@@ -0,0 +1,304 @@+package com.vayunmathur.games.solitaire.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.GameConfig+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.PyramidState+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.data.SpiderState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.data.TableauPile+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Spider moves/deal/completion and Pyramid tap/pair/deal rules. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SpiderPyramidOpsTest {+    private val app = ApplicationProvider.getApplicationContext<Application>()+    private fun vm() = SolitaireViewModel(app)+    private fun c(suit: Suit, rank: Rank) = Card(suit, rank)++    private fun setS(vm: SolitaireViewModel, state: SpiderState) {+        vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.SPIDER, spider = state)+    }++    private fun tenPiles(vararg piles: TableauPile): List<TableauPile> =+        piles.toList() + List(10 - piles.size) { TableauPile() }++    // ---- Spider ----++    @Test fun spiderMoveSequencesAndPlacement() {+        val vm = vm()+        val run = listOf(c(Suit.SPADES, Rank.NINE), c(Suit.SPADES, Rank.EIGHT))+        val down = c(Suit.CLUBS, Rank.TWO)+        setS(+            vm,+            SpiderState(+                tableauPiles = tenPiles(+                    TableauPile(faceDown = listOf(down), faceUp = run),+                    TableauPile(faceUp = listOf(c(Suit.HEARTS, Rank.TEN))),+                    TableauPile(faceUp = listOf(c(Suit.HEARTS, Rank.NINE))),+                ),+            ),+        )+        // Mixed-suit landing is fine in Spider (rank only).+        vm.spiderMoveCards(0, 0, 1)+        var s = vm.uiState.value.spider!!+        assertEquals(listOf(down), s.tableauPiles[0].faceUp) // auto-flipped+        assertEquals(3, s.tableauPiles[1].faceUp.size)+        // Same-rank landing rejects; out-of-range rejects; mixed run cannot move as a unit.+        setS(+            vm,+            SpiderState(+                tableauPiles = tenPiles(+                    TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.NINE), c(Suit.HEARTS, Rank.EIGHT))),+                    TableauPile(faceUp = listOf(c(Suit.HEARTS, Rank.NINE))),+                ),+            ),+        )+        vm.spiderMoveCards(0, 0, 1)+        assertEquals(0, vm.uiState.value.spider!!.moveCount)+        // But its top card alone can move.+        vm.spiderMoveCards(0, 1, 1)+        assertEquals(1, vm.uiState.value.spider!!.moveCount)+        vm.spiderMoveCards(0, -1, 1)+        vm.spiderMoveCards(0, 42, 1)+        assertEquals(1, vm.uiState.value.spider!!.moveCount)+        // Empty column accepts anything.+        vm.spiderMoveCards(1, 0, 5)+        assertEquals(2, vm.uiState.value.spider!!.moveCount)+    }++    @Test fun spiderDealStockGuardsAndDeals() {+        val vm = vm()+        val group = (0 until 10).map { c(Suit.SPADES, Rank.entries[it % 13]) }+        // Empty column blocks dealing.+        setS(vm, SpiderState(stockGroups = listOf(group)))+        vm.dealSpiderStock()+        assertEquals(1, vm.uiState.value.spider!!.stockGroups.size)+        // Every column occupied: one card each, group consumed.+        val piles = tenPiles(*Array(10) { TableauPile(faceUp = listOf(c(Suit.HEARTS, Rank.ACE))) })+        setS(vm, SpiderState(tableauPiles = piles, stockGroups = listOf(group, group)))+        vm.dealSpiderStock()+        var s = vm.uiState.value.spider!!+        assertEquals(1, s.stockGroups.size)+        assertTrue(s.tableauPiles.all { it.faceUp.size == 2 })+        assertEquals(group[3], s.tableauPiles[3].faceUp.last())+        // No stock left: no-op. Won: no-op.+        setS(vm, SpiderState(tableauPiles = piles, stockGroups = emptyList()))+        vm.dealSpiderStock()+        assertEquals(0, vm.uiState.value.spider!!.moveCount)+    }++    @Test fun spiderRunClearsOnMoveCompletion() {+        val vm = vm()+        val run = Rank.entries.reversed().map { c(Suit.SPADES, it) } // K..A, 13 cards+        val down = c(Suit.CLUBS, Rank.FOUR)+        // Move the intact K..A run onto an empty column: it lands whole and clears.+        setS(+            vm,+            SpiderState(+                tableauPiles = tenPiles(+                    TableauPile(faceDown = listOf(down), faceUp = run),+                    TableauPile(),+                ),+                completedSuits = 0,+            ),+        )+        vm.spiderMoveCards(0, 0, 1)+        val s = vm.uiState.value.spider!!+        assertEquals(1, s.completedSuits)+        assertTrue(s.tableauPiles[1].faceUp.isEmpty())+        assertEquals(listOf(down), s.tableauPiles[0].faceUp)+        assertFalse(s.isWon)+    }++    @Test fun spiderEighthSuitWins() {+        val vm = vm()+        val run = Rank.entries.reversed().map { c(Suit.HEARTS, it) }+        setS(+            vm,+            SpiderState(+                tableauPiles = tenPiles(TableauPile(faceUp = run), TableauPile()),+                completedSuits = 7,+                elapsedSeconds = 99,+            ),+        )+        vm.spiderMoveCards(0, 0, 1)+        val s = vm.uiState.value.spider!!+        assertEquals(8, s.completedSuits)+        assertTrue(s.isWon)+    }++    @Test fun spiderNewGameSuitVariants() {+        val vm = vm()+        vm.newSpiderGame(GameConfig(spiderSuits = 2))+        assertEquals("2SUIT", vm.uiState.value.spider!!.variant)+        assertEquals(2, vm.currentConfig().spiderSuits)+        vm.newSpiderGame(GameConfig(spiderSuits = 1))+        assertEquals("1SUIT", vm.uiState.value.spider!!.variant)+    }++    // ---- Pyramid ----++    private fun setP(vm: SolitaireViewModel, state: PyramidState) {+        vm.uiStateInternal.value = SolitaireUiState(gameMode = GameMode.PYRAMID, pyramid = state)+    }++    private fun pyramidState(+        rows: List<List<Card?>>,+        stock: List<Card> = emptyList(),+        waste: List<Card> = emptyList(),+        relaxed: Boolean = false,+        selectedId: String? = null,+    ) = PyramidState(pyramid = rows, stock = stock, waste = waste, relaxed = relaxed, selectedId = selectedId)++    @Test fun pyramidExposureAndSoleCover() {+        val vm = vm()+        val a = c(Suit.SPADES, Rank.ACE); val b = c(Suit.HEARTS, Rank.TWO); val cc = c(Suit.CLUBS, Rank.THREE)+        val state = pyramidState(listOf(listOf(a), listOf(b, cc)))+        assertFalse(vm.isPyramidCardExposed(state, 0, 0))+        assertTrue(vm.isPyramidCardExposed(state, 1, 0))+        assertTrue(vm.isPyramidPlayable(state, "pyr_1_1"))+        assertFalse(vm.isPyramidPlayable(state, "pyr_0_0"))+        assertFalse(vm.isPyramidPlayable(state, "waste"))+        assertFalse(vm.isPyramidPlayable(state, "bogus"))+        // b is sole cover of a once cc is gone.+        val cleared = pyramidState(listOf(listOf(a), listOf(b, null)))+        assertTrue(vm.isPyramidSoleCover(cleared, "pyr_1_0", "pyr_0_0"))+        assertFalse(vm.isPyramidSoleCover(state, "pyr_1_0", "pyr_0_0"))+        assertFalse(vm.isPyramidSoleCover(state, "pyr_0_0", "pyr_1_0"))+        assertFalse(vm.isPyramidSoleCover(state, "waste", "pyr_0_0"))+        // Removed card is not exposed.+        assertFalse(vm.isPyramidCardExposed(pyramidState(listOf(listOf(null))), 0, 0))+    }++    @Test fun pyramidTapSelectsPairsAndKings() {+        val vm = vm()+        val queen = c(Suit.HEARTS, Rank.QUEEN); val ace = c(Suit.CLUBS, Rank.ACE); val king = c(Suit.SPADES, Rank.KING)+        setP(vm, pyramidState(listOf(listOf(c(Suit.DIAMONDS, Rank.FIVE)), listOf(queen, ace))))+        // Tap queen (exposed bottom) selects it.+        vm.pyramidTapCard("pyr_1_0")+        assertEquals("pyr_1_0", vm.uiState.value.pyramid!!.selectedId)+        // Tapping it again deselects.+        vm.pyramidTapCard("pyr_1_0")+        assertNull(vm.uiState.value.pyramid!!.selectedId)+        // Select queen then tap ace: pair removes both.+        vm.pyramidTapCard("pyr_1_0")+        vm.pyramidTapCard("pyr_1_1")+        var p = vm.uiState.value.pyramid!!+        assertEquals(listOf(null, null), p.pyramid[1])+        assertEquals(1, p.moveCount)+        assertNull(p.selectedId)+        // King on the bottom row removes alone. The 5 above is covered, so use+        // a fresh single-row pyramid.+        setP(vm, pyramidState(listOf(listOf(king))))+        vm.pyramidTapCard("pyr_0_0")+        p = vm.uiState.value.pyramid!!+        assertEquals(listOf(null), p.pyramid[0])+        assertTrue(p.isWon)+    }++    @Test fun pyramidTapCoveredCardAndWastePair() {+        val vm = vm()+        val top = c(Suit.DIAMONDS, Rank.FIVE)+        val queen = c(Suit.HEARTS, Rank.QUEEN); val ace = c(Suit.CLUBS, Rank.ACE)+        // Covered card tap does nothing.+        setP(vm, pyramidState(listOf(listOf(top), listOf(queen, ace))))+        vm.pyramidTapCard("pyr_0_0")+        assertNull(vm.uiState.value.pyramid!!.selectedId)+        assertEquals(0, vm.uiState.value.pyramid!!.moveCount)+        // Waste queen pairs with pyramid ace.+        setP(vm, pyramidState(listOf(listOf(top), listOf(queen, ace)), waste = listOf(c(Suit.SPADES, Rank.QUEEN))))+        vm.pyramidTapCard("waste")+        assertEquals("waste", vm.uiState.value.pyramid!!.selectedId)+        vm.pyramidTapCard("pyr_1_1")+        val p = vm.uiState.value.pyramid!!+        assertTrue(p.waste.isEmpty())+        assertEquals(null, p.pyramid[1][1])+        assertEquals(queen, p.pyramid[1][0])+        // Unknown id and empty waste tap do nothing.+        vm.pyramidTapCard("bogus_id")+        vm.pyramidTapCard("waste")+        assertEquals(1, vm.uiState.value.pyramid!!.moveCount)+    }++    @Test fun pyramidSoleCoverPairRemoval() {+        val vm = vm()+        // Apex 5 covered solely by queen (ace slot cleared); Q + 8? Use ranks+        // summing to 13: apex is 8, cover is 5 — 8+5=13, cover exposed.+        val eight = c(Suit.DIAMONDS, Rank.EIGHT); val five = c(Suit.HEARTS, Rank.FIVE)+        setP(vm, pyramidState(listOf(listOf(eight), listOf(five, null))))+        // Five is exposed and is sole cover of the eight: pair is removable+        // even though the eight itself is not exposed.+        assertTrue(vm.canPyramidRemovePair(vm.uiState.value.pyramid!!, "pyr_1_0", "pyr_0_0"))+        vm.pyramidTapCard("pyr_1_0")+        vm.pyramidTapCard("pyr_0_0")+        val p = vm.uiState.value.pyramid!!+        assertEquals(listOf(null), p.pyramid[0])+        assertEquals(listOf(null, null), p.pyramid[1])+    }++    @Test fun pyramidDealAndRecycleModes() {+        val vm = vm()+        val a = c(Suit.SPADES, Rank.ACE); val b = c(Suit.HEARTS, Rank.TWO)+        setP(vm, pyramidState(listOf(listOf(a)), stock = listOf(a, b)))+        vm.pyramidDealStock()+        var p = vm.uiState.value.pyramid!!+        assertEquals(listOf(b), p.waste)+        assertEquals(1, p.stock.size)+        vm.pyramidDealStock()+        p = vm.uiState.value.pyramid!!+        assertEquals(2, p.waste.size)+        // Original: no recycle.+        vm.pyramidDealStock()+        assertEquals(2, vm.uiState.value.pyramid!!.waste.size)+        // Relaxed: recycle reverses waste back to stock.+        setP(vm, pyramidState(listOf(listOf(a)), stock = emptyList(), waste = listOf(a, b), relaxed = true))+        vm.pyramidDealStock()+        p = vm.uiState.value.pyramid!!+        assertEquals(listOf(b, a), p.stock)+        assertTrue(p.waste.isEmpty())+        // Relaxed with empty waste and stock: no-op.+        setP(vm, pyramidState(listOf(listOf(a)), relaxed = true))+        vm.pyramidDealStock()+        assertEquals(0, vm.uiState.value.pyramid!!.moveCount)+    }++    @Test fun pyramidCardAtAndRemoveAndParse() {+        val vm = vm()+        val a = c(Suit.SPADES, Rank.ACE); val b = c(Suit.HEARTS, Rank.TWO)+        val state = pyramidState(listOf(listOf(a), listOf(b, null)), waste = listOf(b))+        assertEquals(a, vm.pyramidCardAt(state, "pyr_0_0"))+        assertEquals(b, vm.pyramidCardAt(state, "waste"))+        assertNull(vm.pyramidCardAt(state, "pyr_5_5"))+        assertNull(vm.pyramidCardAt(state, "other"))+        assertNull(vm.pyramidCardAt(state, "pyr_1_1"))+        val removed = vm.pyramidRemove(state, "pyr_0_0")+        assertNull(removed.pyramid[0][0])+        assertEquals(state, vm.pyramidRemove(state, "other"))+        assertTrue(vm.pyramidRemove(state, "waste").waste.isEmpty())+        assertEquals(3 to 2, vm.parsePyramidId("pyr_3_2"))+        assertFalse(vm.canPyramidRemovePair(state, "pyr_0_0", "pyr_0_0"))+        assertFalse(vm.canPyramidRemovePair(state, "pyr_0_0", "missing"))+    }++    @Test fun pyramidNewGameModes() {+        val vm = vm()+        vm.newPyramidGame(GameConfig(relaxed = false))+        assertEquals("ORIGINAL", vm.uiState.value.pyramid!!.variant)+        assertFalse(vm.currentConfig().relaxed)+        vm.newPyramidGame(GameConfig(relaxed = true))+        assertTrue(vm.currentConfig().relaxed)+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/BoardsComposeTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/BoardsComposeTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/BoardsComposeTest.ktnew file mode 100644index 0000000000..d506399b94--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/BoardsComposeTest.kt@@ -0,0 +1,203 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.click+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.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.platform.DragInfo+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** The four boards and shared column/overlay components with scripted state. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class BoardsComposeTest {+    @get:Rule val rule = createComposeRule()+    private fun c(suit: Suit, rank: Rank) = Card(suit, rank)++    @Test fun klondikeBoardShowsStockWasteFoundationsAndDraws() {+        val actions = RecordingActions()+        val state = KlondikeState(+            stock = listOf(c(Suit.CLUBS, Rank.THREE)),+            waste = listOf(c(Suit.HEARTS, Rank.QUEEN), c(Suit.SPADES, Rank.SEVEN), c(Suit.HEARTS, Rank.SIX)),+            tableauPiles = listOf(+                TableauPile(faceDown = listOf(c(Suit.CLUBS, Rank.TWO)), faceUp = listOf(c(Suit.SPADES, Rank.KING))),+            ) + List(6) { TableauPile() },+            foundations = listOf(listOf(c(Suit.HEARTS, Rank.ACE))) + List(3) { emptyList() },+            drawMode = DrawMode.DRAW_THREE,+        )+        rule.setContent { KlondikeBoard(state, actions) }+        // Waste top and the fanned card behind it both render in DRAW_THREE.+        rule.onNodeWithText("6").assertIsDisplayed()+        rule.onNodeWithText("K").assertIsDisplayed()+        rule.onNodeWithText("A").assertIsDisplayed()+        // First clickable node is the stock pile.+        rule.onAllNodes(hasClickAction())[0].performClick()+        assertEquals(listOf("drawFromStock"), actions.calls)+        // Drop targets were registered by foundations/columns during layout.+        assertTrue(actions.dropTargets.keys.any { it.startsWith("foundation_") }, "${actions.dropTargets.keys}")+        assertTrue(actions.dropTargets.keys.any { it.startsWith("tableau_") }, "${actions.dropTargets.keys}")+    }++    @Test fun klondikeBoardEmptyStockAndWaste() {+        val actions = RecordingActions()+        rule.setContent { KlondikeBoard(KlondikeState(), actions) }+        // Empty stock slot is still the draw target.+        rule.onAllNodes(hasClickAction())[0].performClick()+        assertEquals(listOf("drawFromStock"), actions.calls)+    }++    @Test fun klondikeWasteDrawOneShowsOnlyTop() {+        val actions = RecordingActions()+        val state = KlondikeState(+            waste = listOf(c(Suit.HEARTS, Rank.QUEEN), c(Suit.SPADES, Rank.SEVEN)),+            drawMode = DrawMode.DRAW_ONE,+        )+        rule.setContent { KlondikeBoard(state, actions) }+        rule.onNodeWithText("7").assertIsDisplayed()+        assertTrue(rule.onAllNodesWithText("Q").fetchSemanticsNodes().isEmpty())+    }++    @Test fun spiderBoardShowsProgressStockAndDeals() {+        val actions = RecordingActions()+        val state = SpiderState(+            tableauPiles = listOf(TableauPile(faceUp = listOf(c(Suit.SPADES, Rank.NINE)))) + List(9) { TableauPile() },+            stockGroups = listOf(listOf(c(Suit.HEARTS, Rank.ACE)), listOf(c(Suit.HEARTS, Rank.TWO))),+            completedSuits = 3,+        )+        rule.setContent { SpiderBoard(state, actions) }+        rule.onNodeWithText("Completed: 3/8").assertIsDisplayed()+        rule.onNodeWithText("9").assertIsDisplayed()+        val clickables = rule.onAllNodes(hasClickAction())+        clickables[0].performClick()+        assertTrue(actions.calls.contains("dealSpiderStock"), "${actions.calls}")+    }++    @Test fun spiderBoardWithoutStock() {+        val actions = RecordingActions()+        rule.setContent { SpiderBoard(SpiderState(completedSuits = 8), actions) }+        rule.onNodeWithText("Completed: 8/8").assertIsDisplayed()+    }++    @Test fun freeCellBoardShowsCellsFoundationsAndColumns() {+        val actions = RecordingActions()+        val state = FreeCellState(+            tableauPiles = listOf(listOf(c(Suit.SPADES, Rank.SEVEN), c(Suit.HEARTS, Rank.SIX))) + List(7) { emptyList() },+            freeCells = listOf(c(Suit.CLUBS, Rank.KING), null, null, null),+            foundations = listOf(listOf(c(Suit.HEARTS, Rank.ACE))) + List(3) { emptyList() },+        )+        rule.setContent { FreeCellBoard(state, actions) }+        rule.onNodeWithText("K").assertIsDisplayed()+        rule.onNodeWithText("7").assertIsDisplayed()+        rule.onNodeWithText("6").assertIsDisplayed()+        assertTrue(actions.dropTargets.keys.any { it.startsWith("freecell_") })+    }++    @Test fun pyramidBoardTapsCardsStockAndWaste() {+        val actions = RecordingActions()+        val state = PyramidState(+            pyramid = listOf(+                listOf(c(Suit.DIAMONDS, Rank.FIVE)),+                listOf(c(Suit.HEARTS, Rank.QUEEN), c(Suit.CLUBS, Rank.ACE)),+            ),+            stock = listOf(c(Suit.SPADES, Rank.TWO)),+            waste = listOf(c(Suit.SPADES, Rank.KING)),+            selectedId = "pyr_1_0",+        )+        rule.setContent { PyramidBoard(state, actions) }+        rule.onNodeWithText("Q").performClick()+        assertTrue(actions.calls.contains("pyramidTapCard:pyr_1_0"), "${actions.calls}")+        rule.onNodeWithText("K").performClick()+        assertTrue(actions.calls.contains("pyramidTapCard:waste"), "${actions.calls}")+        // Clickables in composition order: pyramid cards, then stock, then waste.+        rule.onAllNodes(hasClickAction())[3].performClick()+        assertTrue(actions.calls.contains("pyramidDealStock"), "${actions.calls}")+    }++    @Test fun pyramidBoardEmptyStockRecycleLabelAndNoWaste() {+        val actions = RecordingActions()+        val state = PyramidState(+            pyramid = listOf(listOf(c(Suit.DIAMONDS, Rank.FIVE))),+            stock = emptyList(),+            waste = listOf(c(Suit.SPADES, Rank.KING)),+            relaxed = true,+        )+        rule.setContent { PyramidBoard(state, actions) }+        rule.onNodeWithText("↻").assertIsDisplayed()+        // Clickables: the pyramid card, then the stock slot, then the waste.+        rule.onAllNodes(hasClickAction())[1].performClick()+        assertTrue(actions.calls.contains("pyramidDealStock"), "${actions.calls}")+    }++    @Test fun tableauColumnsEmptyFaceDownAndFaceUp() {+        val actions = RecordingActions()+        rule.setContent {+            TableauColumn(+                pile = TableauPile(+                    faceDown = listOf(c(Suit.CLUBS, Rank.TWO), c(Suit.CLUBS, Rank.THREE)),+                    faceUp = listOf(c(Suit.SPADES, Rank.KING), c(Suit.HEARTS, Rank.QUEEN)),+                ),+                columnIndex = 2,+                actions = actions,+            )+        }+        rule.onNodeWithText("K").assertIsDisplayed()+        rule.onNodeWithText("Q").assertIsDisplayed()+        assertTrue(actions.dropTargets.containsKey("tableau_2"))+    }++    @Test fun freeCellTableauColumnEmpty() {+        val actions = RecordingActions()+        rule.setContent {+            FreeCellTableauColumn(pile = emptyList(), columnIndex = 4, actions = actions)+        }+        rule.waitForIdle()+        assertTrue(actions.dropTargets.containsKey("tableau_4"))+    }++    @Test fun dragOverlayShowsDraggedCardsAndHiddenWhenIdle() {+        val actions = RecordingActions()+        rule.setContent { DragOverlay(actions, CARD_WIDTH, CARD_HEIGHT) }+        rule.onNodeWithText("Q").assertDoesNotExist()+        actions.dragFlow.value = DragInfo(+            cards = listOf(c(Suit.HEARTS, Rank.QUEEN), c(Suit.SPADES, Rank.JACK)),+            sourceId = "tableau_0_0",+        )+        rule.waitForIdle()+        rule.onNodeWithText("Q").assertIsDisplayed()+        rule.onNodeWithText("J").assertIsDisplayed()+        actions.dragFlow.value = null+        rule.waitForIdle()+        rule.onNodeWithText("Q").assertDoesNotExist()+    }++    @Test fun draggableCardTapAutoMoves() {+        val actions = RecordingActions()+        rule.setContent {+            DraggableCard(card = c(Suit.HEARTS, Rank.QUEEN), sourceId = "waste", actions = actions) {+                CardFace(c(Suit.HEARTS, Rank.QUEEN))+            }+        }+        rule.onNodeWithText("Q").performTouchInput { click() }+        rule.waitForIdle()+        assertTrue(actions.calls.contains("autoMove:waste"), "${actions.calls}")+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/GameConfigDialogTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/GameConfigDialogTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/GameConfigDialogTest.ktnew file mode 100644index 0000000000..ac0b528821--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/GameConfigDialogTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.R+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.KlondikeDifficulty+import com.vayunmathur.games.solitaire.ui.dialogs.GameConfigDialog+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Per-mode configuration dialog selections. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class GameConfigDialogTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int) = ctx.getString(id)+    private fun uiStr(id: Int) = ctx.getString(id)++    @Test fun klondikeDialogSelectsDrawThreeAndHard() {+        var started: GameConfig? = null+        rule.setContent { GameConfigDialog(GameMode.KLONDIKE, onStart = { started = it }, onDismiss = {}) }+        rule.onNodeWithText("Klondike").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.draw_three)).performClick()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.hard)).performClick()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(GameConfig(drawMode = DrawMode.DRAW_THREE, klondikeDifficulty = KlondikeDifficulty.HARD), started)+    }++    @Test fun klondikeDialogDefaultsAndRelaxed() {+        var started: GameConfig? = null+        rule.setContent { GameConfigDialog(GameMode.KLONDIKE, onStart = { started = it }, onDismiss = {}) }+        rule.onNodeWithText(str(R.string.mode_relaxed)).performClick()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(DrawMode.DRAW_ONE, started!!.drawMode)+        assertEquals(KlondikeDifficulty.RELAXED, started!!.klondikeDifficulty)+    }++    @Test fun klondikeDialogBackDismisses() {+        var dismissals = 0+        var started: GameConfig? = null+        rule.setContent { GameConfigDialog(GameMode.KLONDIKE, onStart = { started = it }, onDismiss = { dismissals++ }) }+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.back)).performClick()+        assertEquals(1, dismissals)+        assertEquals(null, started)+    }++    @Test fun spiderDialogSelectsSuitCount() {+        var started: GameConfig? = null+        rule.setContent { GameConfigDialog(GameMode.SPIDER, onStart = { started = it }, onDismiss = {}) }+        rule.onNodeWithText("Spider").assertIsDisplayed()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.medium)).performClick()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(2, started!!.spiderSuits)+    }++    @Test fun spiderDialogEasyAndDefaultHard() {+        var started: GameConfig? = null+        rule.setContent { GameConfigDialog(GameMode.SPIDER, onStart = { started = it }, onDismiss = {}) }+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(4, started!!.spiderSuits)+        assertTrue(started!!.spiderSuits == 4)+    }++    @Test fun pyramidDialogSelectsRelaxed() {+        var started: GameConfig? = null+        rule.setContent { GameConfigDialog(GameMode.PYRAMID, onStart = { started = it }, onDismiss = {}) }+        rule.onNodeWithText("Pyramid").assertIsDisplayed()+        rule.onNodeWithText(str(R.string.mode_relaxed)).performClick()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(true, started!!.relaxed)+    }++    @Test fun pyramidDialogOriginalDefault() {+        var started: GameConfig? = null+        rule.setContent { GameConfigDialog(GameMode.PYRAMID, onStart = { started = it }, onDismiss = {}) }+        rule.onNodeWithText(str(R.string.mode_original)).assertIsDisplayed()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(false, started!!.relaxed)+    }++    @Test fun freeCellDialogStartsImmediatelyWithDefaults() {+        var started: GameConfig? = null+        rule.setContent { GameConfigDialog(GameMode.FREECELL, onStart = { started = it }, onDismiss = {}) }+        rule.onNodeWithText("FreeCell").assertIsDisplayed()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(GameConfig(), started)+    }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.ktnew file mode 100644index 0000000000..772590c9e7--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/RecordingActions.kt@@ -0,0 +1,35 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.unit.IntSize+import com.vayunmathur.games.solitaire.platform.DragInfo+import com.vayunmathur.games.solitaire.platform.SolitaireActions+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow++/** Records every board callback so Compose tests can assert routing. */+class RecordingActions : SolitaireActions {+    override val dragInfo: StateFlow<DragInfo?> = MutableStateFlow(null)+    val dragFlow = dragInfo as MutableStateFlow<DragInfo?>+    override val dropTargets: MutableMap<String, Rect> = mutableMapOf()+    val calls = mutableListOf<String>()++    override fun startDrag(sourceId: String, startPos: Offset, cardSize: IntSize): Boolean {+        calls += "startDrag:$sourceId"+        return true+    }++    override fun updateDrag(offset: Offset) { calls += "updateDrag" }+    override fun endDrag(dropOffset: Offset, cardSize: IntSize) { calls += "endDrag" }+    override fun cancelDrag() { calls += "cancelDrag" }+    override fun drawFromStock() { calls += "drawFromStock" }+    override fun klondikeAutoComplete() { calls += "klondikeAutoComplete" }+    override fun dealSpiderStock() { calls += "dealSpiderStock" }+    override fun pyramidTapCard(id: String) { calls += "pyramidTapCard:$id" }+    override fun pyramidDealStock() { calls += "pyramidDealStock" }+    override fun autoMove(sourceId: String) { calls += "autoMove:$sourceId" }+    override fun undo() { calls += "undo" }+    override fun restart() { calls += "restart" }+    override fun giveUp() { calls += "giveUp" }+}
games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/ScreensComposeTest.kt
diff --git a/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/ScreensComposeTest.kt b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/ScreensComposeTest.ktnew file mode 100644index 0000000000..325b13feca--- /dev/null+++ b/games/solitaire/src/test/java/com/vayunmathur/games/solitaire/ui/ScreensComposeTest.kt@@ -0,0 +1,260 @@+package com.vayunmathur.games.solitaire.ui++import android.app.Application+import androidx.compose.foundation.layout.Column+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.solitaire.R+import com.vayunmathur.games.solitaire.Route+import com.vayunmathur.games.solitaire.data.CardColorScheme+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.KlondikeState+import com.vayunmathur.games.solitaire.data.PyramidState+import com.vayunmathur.games.solitaire.data.Card+import com.vayunmathur.games.solitaire.data.Rank+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.data.Suit+import com.vayunmathur.games.solitaire.platform.SolitaireViewModel+import com.vayunmathur.games.solitaire.platform.newKlondikeGame+import com.vayunmathur.library.util.NavBackStack+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Board screen chrome, home, settings, win overlay and display names. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ScreensComposeTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int) = ctx.getString(id)+    private fun uiStr(id: Int) = ctx.getString(id)+    private fun vm() = SolitaireViewModel(ApplicationProvider.getApplicationContext<Application>())++    @Test fun displayNamesForAllModes() {+        rule.setContent {+            Column {+                androidx.compose.material3.Text(GameMode.KLONDIKE.displayName())+                androidx.compose.material3.Text(GameMode.SPIDER.displayName())+                androidx.compose.material3.Text(GameMode.FREECELL.displayName())+                androidx.compose.material3.Text(GameMode.PYRAMID.displayName())+            }+        }+        // library.ui Text is used inside displayName call sites elsewhere; the+        // names themselves come from string resources:+        assertEquals("Klondike", str(R.string.klondike))+        assertEquals("Spider", str(R.string.spider))+        assertEquals("FreeCell", str(R.string.freecell))+        assertEquals("Pyramid", str(R.string.pyramid))+        rule.onNodeWithText("Klondike").assertIsDisplayed()+        rule.onNodeWithText("Pyramid").assertIsDisplayed()+    }++    @Test fun gameActionBarButtons() {+        var undos = 0; var giveUps = 0+        rule.setContent {+            GameActionBar(onUndo = { undos++ }, onGiveUp = { giveUps++ }, undoEnabled = true)+        }+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.undo)).performClick()+        rule.onNodeWithText(str(R.string.give_up)).performClick()+        assertEquals(1, undos)+        assertEquals(1, giveUps)+    }++    @Test fun gameActionBarUndoDisabled() {+        var undos = 0+        rule.setContent {+            GameActionBar(onUndo = { undos++ }, onGiveUp = {}, undoEnabled = false)+        }+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.undo))+            .assertExists()+        // Disabled button does not fire.+        runCatching { rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.undo)).performClick() }+        assertEquals(0, undos)+    }++    @Test fun winOverlayShowsStatsAndActions() {+        var newGames = 0; var backs = 0+        rule.setContent {+            WinOverlay(elapsedSeconds = 125, moveCount = 87, onNewGame = { newGames++ }, onBack = { backs++ })+        }+        rule.onNodeWithText(str(R.string.congratulations)).assertIsDisplayed()+        rule.onNodeWithText("${uiStr(com.vayunmathur.library.ui.R.string.time)}: 02:05").assertExists()+        rule.onNodeWithText("${str(R.string.moves)}: 87").assertExists()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertEquals(1, newGames)+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.back)).performClick()+        assertEquals(1, backs)+    }++    @Test fun settingsScreenSelectsFourColour() {+        var selected: CardColorScheme? = null+        var backs = 0+        rule.setContent {+            SettingsScreen(+                cardColorScheme = CardColorScheme.TWO_COLOUR,+                onCardColorSchemeChange = { selected = it },+                onBack = { backs++ },+            )+        }+        rule.onNodeWithText(str(R.string.card_colors)).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.card_colors)).performClick()+        rule.onNodeWithText(str(R.string.card_colors_four)).performClick()+        assertEquals(CardColorScheme.FOUR_COLOUR, selected)+        assertEquals(0, backs)+    }++    @Test fun gameBoardScreenKlondikeAutoCompleteAndGiveUpDialog() {+        val actions = RecordingActions()+        var exits = 0+        val state = SolitaireUiState(+            gameMode = GameMode.KLONDIKE,+            klondike = KlondikeState(+                stock = listOf(Card(Suit.HEARTS, Rank.ACE)),+                moveCount = 12,+                elapsedSeconds = 65,+            ),+        )+        rule.setContent {+            GameBoardScreen(state = state, mode = GameMode.KLONDIKE, actions = actions, onExit = { exits++ })+        }+        rule.onNodeWithText("Klondike").assertExists()+        rule.onNodeWithText("${str(R.string.moves)}: 12").assertExists()+        rule.onNodeWithText(str(R.string.auto_complete)).performClick()+        assertTrue(actions.calls.contains("klondikeAutoComplete"), "${actions.calls}")+        // Give up asks first, dismiss keeps the game, confirm ends it.+        rule.onNodeWithText(str(R.string.give_up)).performClick()+        rule.onNodeWithText(str(R.string.confirm_give_up_title)).assertIsDisplayed()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel)).performClick()+        assertTrue(actions.calls.none { it == "giveUp" })+        assertEquals(0, exits)+        rule.onNodeWithText(str(R.string.give_up)).performClick()+        rule.onAllNodesWithText(str(R.string.give_up))[1].performClick()+        assertTrue(actions.calls.contains("giveUp"))+        assertEquals(1, exits)+        // Undo is wired too (disabled state is covered in the action bar test).+        assertTrue(actions.calls.none { it == "undo" })+    }++    @Test fun gameBoardScreenWonShowsOverlayAndGiveUpSkipsConfirm() {+        val actions = RecordingActions()+        var exits = 0+        val state = SolitaireUiState(+            gameMode = GameMode.KLONDIKE,+            klondike = KlondikeState(isWon = true, moveCount = 40, elapsedSeconds = 61),+        )+        rule.setContent {+            GameBoardScreen(state = state, mode = GameMode.KLONDIKE, actions = actions, onExit = { exits++ })+        }+        rule.onNodeWithText(str(R.string.congratulations)).assertIsDisplayed()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        assertTrue(actions.calls.contains("restart"))+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.back)).performClick()+        assertEquals(1, exits)+    }++    @Test fun gameBoardScreenOtherModesRender() {+        val actions = RecordingActions()+        // Pyramid with an empty pyramid (no state) renders chrome only.+        rule.setContent {+            GameBoardScreen(state = SolitaireUiState(gameMode = GameMode.PYRAMID), mode = GameMode.PYRAMID, actions = actions, onExit = {})+        }+        rule.onNodeWithText("Pyramid").assertExists()+        rule.onNodeWithText("${str(R.string.moves)}: 0").assertExists()+    }++    @Test fun gameBoardScreenPyramidStateRendersBoard() {+        val actions = RecordingActions()+        val state = SolitaireUiState(+            gameMode = GameMode.PYRAMID,+            pyramid = PyramidState(pyramid = listOf(listOf(Card(Suit.HEARTS, Rank.KING)))),+        )+        rule.setContent {+            GameBoardScreen(state = state, mode = GameMode.PYRAMID, actions = actions, onExit = {})+        }+        rule.onNodeWithText("K").assertIsDisplayed()+    }++    @Test fun homeScreenStartsFreeCellAndKlondikeViaDialogs() {+        val vm = vm()+        val backStack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent { HomeScreen(backStack, vm) }+        rule.onNodeWithText("Solitaire").assertExists()+        // Stats cards for all four modes.+        rule.onNodeWithText("Klondike").assertExists()+        rule.onNodeWithText("FreeCell").assertExists()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        rule.onNodeWithText(str(R.string.select_mode)).assertIsDisplayed()+        // "FreeCell" also labels the stats card behind the dialog; the dialog+        // button is the second match.+        rule.onAllNodesWithText("FreeCell")[1].performClick()+        assertEquals(Route.Game(GameMode.FREECELL), backStack.last())+        assertEquals(GameMode.FREECELL, vm.uiState.value.gameMode)+    }++    @Test fun homeScreenKlondikeConfigDialogFlow() {+        val vm = vm()+        val backStack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent { HomeScreen(backStack, vm) }+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        // As above, the dialog's Klondike button follows the stats card.+        rule.onAllNodesWithText("Klondike")[1].performClick()+        // Config dialog for Klondike shows draw options; start the game.+        rule.onNodeWithText(str(R.string.draw_three)).performClick()+        // The config dialog's New Game button follows the home screen's own.+        val newGameNodes = rule.onAllNodesWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game))+        newGameNodes[newGameNodes.fetchSemanticsNodes().size - 1].performClick()+        assertEquals(Route.Game(GameMode.KLONDIKE), backStack.last())+        assertEquals(com.vayunmathur.games.solitaire.data.DrawMode.DRAW_THREE, vm.uiState.value.klondike!!.drawMode)+    }++    @Test fun homeScreenContinueResumesActiveGame() {+        val vm = vm()+        vm.newKlondikeGame(com.vayunmathur.games.solitaire.data.GameConfig())+        val backStack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent { HomeScreen(backStack, vm) }+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.continue_label)).performClick()+        assertEquals(Route.Game(GameMode.KLONDIKE), backStack.last())+    }++    @Test fun homeScreenPickerDismissesWithBack() {+        val vm = vm()+        val backStack = NavBackStack<Route>(arrayOf(Route.Home))+        rule.setContent { HomeScreen(backStack, vm) }+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+        rule.onNodeWithText(str(R.string.select_mode)).assertIsDisplayed()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.back)).performClick()+        rule.onNodeWithText(str(R.string.select_mode)).assertDoesNotExist()+        assertEquals(Route.Home, backStack.last())+    }++    @Test fun navigationShowsHomeAndMainActivityCreates() {+        val vm = vm()+        rule.setContent { com.vayunmathur.games.solitaire.Navigation(vm) }+        rule.onNodeWithText("Solitaire").assertExists()+        rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).assertExists()++        val controller = Robolectric.buildActivity(com.vayunmathur.games.solitaire.MainActivity::class.java)+        controller.create()+        assertTrue(!controller.get().isFinishing)+        controller.destroy()+    }++    @Test fun gameScreenDealsRequestedMode() {+        val vm = vm()+        val backStack = NavBackStack<Route>(arrayOf(Route.Home, Route.Game(GameMode.FREECELL)))+        rule.setContent { GameScreen(backStack, vm, GameMode.FREECELL) }+        rule.waitForIdle()+        assertEquals(GameMode.FREECELL, vm.uiState.value.gameMode)+        rule.onNodeWithText(str(R.string.give_up)).assertExists()+    }+}