solitaire: add pyamid mode
- Commit
ca8c15756ae1d7a27d9d180c9dbc1997fef3dd4a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-11 14:50 UTC (4 months ago)
- Parents
466c27d
Diff
games/solitaire/src/main/assets/achievements.json
diff --git a/games/solitaire/src/main/assets/achievements.json b/games/solitaire/src/main/assets/achievements.jsonindex 3a9fd80169..c67d09ebf3 100644--- a/games/solitaire/src/main/assets/achievements.json+++ b/games/solitaire/src/main/assets/achievements.json@@ -19,6 +19,11 @@ "name": "Free at Last", "description": "Win a FreeCell game." },+ {+ "id": "pyramid_first",+ "name": "Pharaoh's Favor",+ "description": "Win a Pyramid game."+ }, { "id": "wins_10", "name": "Getting Started",
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.ktindex ed4e370696..e23ec71bbc 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.kt@@ -45,6 +45,7 @@ import com.vayunmathur.games.solitaire.data.GameMode import com.vayunmathur.games.solitaire.ui.FreeCellBoard import com.vayunmathur.games.solitaire.ui.GameActionBar import com.vayunmathur.games.solitaire.ui.KlondikeBoard+import com.vayunmathur.games.solitaire.ui.PyramidBoard import com.vayunmathur.games.solitaire.ui.SpiderBoard import com.vayunmathur.games.solitaire.ui.WinOverlay import com.vayunmathur.games.solitaire.util.AppBackupAgent@@ -91,6 +92,7 @@ fun GameMode.displayName(): String = when (this) { GameMode.KLONDIKE -> stringResource(R.string.klondike) GameMode.SPIDER -> stringResource(R.string.spider) GameMode.FREECELL -> stringResource(R.string.freecell)+ GameMode.PYRAMID -> stringResource(R.string.pyramid) } @Composable@@ -238,6 +240,9 @@ fun HomeScreen(backStack: NavBackStack<Route>, viewModel: SolitaireViewModel) { Button(onClick = { startGame(GameMode.FREECELL, DrawMode.DRAW_ONE) }, Modifier.fillMaxWidth()) { Text(stringResource(R.string.freecell)) }+ Button(onClick = { startGame(GameMode.PYRAMID, DrawMode.DRAW_ONE) }, Modifier.fillMaxWidth()) {+ Text(stringResource(R.string.pyramid))+ } } }, confirmButton = {},@@ -272,6 +277,7 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: SolitaireViewModel, mo GameMode.KLONDIKE -> uiState.klondike?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) } GameMode.SPIDER -> uiState.spider?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) } GameMode.FREECELL -> uiState.freeCell?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }+ GameMode.PYRAMID -> uiState.pyramid?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) } } val isWon = activeGame?.first == true val moveCount = activeGame?.second ?: 0@@ -353,6 +359,16 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: SolitaireViewModel, mo .fillMaxWidth() ) }+ GameMode.PYRAMID -> uiState.pyramid?.let {+ PyramidBoard(+ it,+ viewModel,+ Modifier+ .align(Alignment.CenterHorizontally)+ .widthIn(max = SolitaireBoardMaxWidth)+ .fillMaxWidth()+ )+ } } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.ktindex 7e82a73987..3c99e9d5f9 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/data/GameState.kt@@ -5,7 +5,7 @@ data class TableauPile( val faceUp: List<Card> = emptyList() ) -enum class GameMode { KLONDIKE, SPIDER, FREECELL }+enum class GameMode { KLONDIKE, SPIDER, FREECELL, PYRAMID } enum class DrawMode { DRAW_ONE, DRAW_THREE } @@ -41,10 +41,31 @@ data class FreeCellState( val isWon: Boolean = false ) +/**+ * Pyramid solitaire. [pyramid] is 7 rows (row r has r+1 slots); a removed card+ * becomes null so positions stay stable for the triangular layout. Cards are+ * removed in pairs whose ranks sum to 13 (Ace=1 … King=13); a King (13) is+ * removed on its own. [selectedId] is the currently picked card ("pyr_r_c" or+ * "waste"). [passesRemaining] is how many more times the waste may be recycled+ * back into the stock. Winning = the whole pyramid is cleared.+ */+data class PyramidState(+ val pyramid: List<List<Card?>> = emptyList(),+ val stock: List<Card> = emptyList(),+ val waste: List<Card> = emptyList(),+ val passesRemaining: Int = 2,+ val selectedId: String? = null,+ val moveCount: Int = 0,+ val elapsedSeconds: Int = 0,+ val usedUndo: Boolean = false,+ val isWon: Boolean = false+)+ data class SolitaireUiState( val gameMode: GameMode? = null, val klondike: KlondikeState? = null, val spider: SpiderState? = null, val freeCell: FreeCellState? = null,+ val pyramid: PyramidState? = null, val history: List<Any> = emptyList() )
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/PyramidBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/PyramidBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/PyramidBoard.ktnew file mode 100644index 0000000000..5a0c0ad673--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/PyramidBoard.kt@@ -0,0 +1,147 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.solitaire.data.PyramidState+import com.vayunmathur.games.solitaire.util.SolitaireViewModel++private val SelectionColor = Color(0xFFFFC107)++@Composable+fun PyramidBoard(state: PyramidState, viewModel: SolitaireViewModel, modifier: Modifier = Modifier) {+ BoxWithConstraints(modifier) {+ val cardWidth = (maxWidth - 8.dp) / 7+ val cardHeight = cardWidth * 1.4f+ val verticalStep = cardHeight * 0.5f++ Column {+ // Triangular pyramid. Rows are drawn top-to-bottom so the cards that+ // rest on top (lower rows) overlap the ones behind them.+ Box(+ Modifier+ .fillMaxWidth()+ .height(cardHeight + verticalStep * (state.pyramid.size - 1))+ ) {+ state.pyramid.forEachIndexed { r, row ->+ row.forEachIndexed { c, card ->+ if (card != null) {+ val id = "pyr_${r}_$c"+ val exposed = isExposed(state, r, c)+ val xOffset = cardWidth * (c + 3f - r / 2f)+ val yOffset = verticalStep * r+ Box(+ Modifier.offset(x = xOffset, y = yOffset)+ ) {+ SelectableCard(+ selected = state.selectedId == id,+ enabled = exposed,+ onClick = { viewModel.pyramidTapCard(id) },+ cardWidth = cardWidth,+ cardHeight = cardHeight+ ) {+ CardFace(card, cardWidth = cardWidth, cardHeight = cardHeight)+ }+ }+ }+ }+ }+ }++ Spacer(Modifier.height(12.dp))++ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ // Stock: deal one card to the waste, or recycle when empty.+ val canRecycle = state.passesRemaining > 0 && state.waste.isNotEmpty()+ if (state.stock.isNotEmpty()) {+ CardBack(+ modifier = Modifier.clickable { viewModel.pyramidDealStock() },+ cardWidth = cardWidth,+ cardHeight = cardHeight+ )+ } else {+ EmptySlot(+ modifier = Modifier.clickable(enabled = canRecycle) { viewModel.pyramidDealStock() },+ label = if (canRecycle) "↻" else "",+ cardWidth = cardWidth,+ cardHeight = cardHeight+ )+ }++ // Waste: the top card is playable.+ val wasteTop = state.waste.lastOrNull()+ if (wasteTop != null) {+ SelectableCard(+ selected = state.selectedId == "waste",+ enabled = true,+ onClick = { viewModel.pyramidTapCard("waste") },+ cardWidth = cardWidth,+ cardHeight = cardHeight+ ) {+ CardFace(wasteTop, cardWidth = cardWidth, cardHeight = cardHeight)+ }+ } else {+ EmptySlot(cardWidth = cardWidth, cardHeight = cardHeight)+ }++ Spacer(Modifier.width(8.dp))++ Text(+ "Recycles left: ${state.passesRemaining}",+ style = MaterialTheme.typography.bodyMedium+ )+ }+ }+ }+}++/** A card that can be tapped; shows a highlight border when [selected] and is+ * dimmed via a disabled click when not [enabled]. */+@Composable+private fun SelectableCard(+ selected: Boolean,+ enabled: Boolean,+ onClick: () -> Unit,+ cardWidth: androidx.compose.ui.unit.Dp,+ cardHeight: androidx.compose.ui.unit.Dp,+ content: @Composable () -> Unit+) {+ val scale = cardWidth.value / CARD_WIDTH.value+ val corner = (8 * scale).dp+ var m = Modifier+ .width(cardWidth)+ .height(cardHeight)+ .clickable(enabled = enabled, onClick = onClick)+ if (selected) {+ m = m.border(3.dp, SelectionColor, RoundedCornerShape(corner))+ }+ Box(m) { content() }+}++private fun isExposed(state: PyramidState, row: Int, col: Int): Boolean {+ if (state.pyramid[row][col] == null) return false+ if (row == state.pyramid.lastIndex) return true+ val below = state.pyramid[row + 1]+ return below[col] == null && below[col + 1] == null+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireAchievementsManager.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireAchievementsManager.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireAchievementsManager.ktindex 7feefa8ab7..b2b6e43d0f 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireAchievementsManager.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireAchievementsManager.kt@@ -20,6 +20,7 @@ class SolitaireAchievementsManager( GameMode.KLONDIKE -> onAchievementUnlocked("klondike_first") GameMode.SPIDER -> onAchievementUnlocked("spider_first") GameMode.FREECELL -> onAchievementUnlocked("freecell_first")+ GameMode.PYRAMID -> onAchievementUnlocked("pyramid_first") } } }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.ktindex ad5365da18..e688315245 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt@@ -45,6 +45,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio GameMode.KLONDIKE -> klondike?.isWon == false GameMode.SPIDER -> spider?.isWon == false GameMode.FREECELL -> freeCell?.isWon == false+ GameMode.PYRAMID -> pyramid?.isWon == false null -> false } }@@ -54,6 +55,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio GameMode.KLONDIKE -> newKlondikeGame(drawMode) GameMode.SPIDER -> newSpiderGame() GameMode.FREECELL -> newFreeCellGame()+ GameMode.PYRAMID -> newPyramidGame() } } @@ -541,6 +543,161 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio } } + // --- Pyramid ---++ fun newPyramidGame() {+ val deck = createShuffledDeck()+ var index = 0+ val rows = mutableListOf<List<Card?>>()+ for (r in 0 until 7) {+ val row = mutableListOf<Card?>()+ for (c in 0..r) {+ row.add(deck[index]); index+++ }+ rows.add(row)+ }+ val stock = deck.subList(index, deck.size).toList()+ _uiState.value = SolitaireUiState(+ gameMode = GameMode.PYRAMID,+ pyramid = PyramidState(+ pyramid = rows,+ stock = stock,+ waste = emptyList(),+ passesRemaining = 2+ ),+ history = emptyList()+ )+ statsRepository.recordGamePlayed(GameMode.PYRAMID)+ }++ /** A pyramid card is exposed when both cards resting on it have been removed. */+ private fun isPyramidCardExposed(state: PyramidState, row: Int, col: Int): Boolean {+ if (state.pyramid[row][col] == null) return false+ if (row == state.pyramid.lastIndex) return true+ val below = state.pyramid[row + 1]+ return below[col] == null && below[col + 1] == null+ }++ /** Whether the card identified by [id] can currently be selected/matched. */+ private fun isPyramidPlayable(state: PyramidState, id: String): Boolean = when {+ id == "waste" -> state.waste.isNotEmpty()+ id.startsWith("pyr_") -> {+ val (r, c) = parsePyramidId(id)+ isPyramidCardExposed(state, r, c)+ }+ else -> false+ }++ private fun parsePyramidId(id: String): Pair<Int, Int> {+ val parts = id.removePrefix("pyr_").split("_")+ return parts[0].toInt() to parts[1].toInt()+ }++ private fun pyramidCardAt(state: PyramidState, id: String): Card? = when {+ id == "waste" -> state.waste.lastOrNull()+ id.startsWith("pyr_") -> {+ val (r, c) = parsePyramidId(id)+ state.pyramid.getOrNull(r)?.getOrNull(c)+ }+ else -> null+ }++ /** Remove the card identified by [id] from the pyramid or the waste. */+ private fun pyramidRemove(state: PyramidState, id: String): PyramidState = when {+ id == "waste" -> state.copy(waste = state.waste.dropLast(1))+ id.startsWith("pyr_") -> {+ val (r, c) = parsePyramidId(id)+ val newPyramid = state.pyramid.map { it.toMutableList() }+ newPyramid[r][c] = null+ state.copy(pyramid = newPyramid.map { it.toList() })+ }+ else -> state+ }++ /**+ * Tap a card in the pyramid or on the waste. Kings (value 13) are removed on+ * their own; otherwise the tap either selects a card, deselects it, or — if a+ * second playable card is tapped and the two ranks sum to 13 — removes both.+ */+ fun pyramidTapCard(id: String) {+ val state = _uiState.value.pyramid ?: return+ if (state.isWon) return+ if (!isPyramidPlayable(state, id)) return+ val card = pyramidCardAt(state, id) ?: return++ // King removes immediately.+ if (card.rank.value == 13) {+ saveHistory()+ val removed = pyramidRemove(state, id).copy(+ selectedId = null,+ moveCount = state.moveCount + 1+ )+ _uiState.update { it.copy(pyramid = removed) }+ checkPyramidWin()+ return+ }++ val selected = state.selectedId+ when {+ selected == null -> _uiState.update { it.copy(pyramid = state.copy(selectedId = id)) }+ selected == id -> _uiState.update { it.copy(pyramid = state.copy(selectedId = null)) }+ else -> {+ val selectedCard = pyramidCardAt(state, selected)+ if (selectedCard != null && isPyramidPlayable(state, selected) &&+ selectedCard.rank.value + card.rank.value == 13+ ) {+ saveHistory()+ val afterFirst = pyramidRemove(state, id)+ val afterSecond = pyramidRemove(afterFirst, selected).copy(+ selectedId = null,+ moveCount = state.moveCount + 1+ )+ _uiState.update { it.copy(pyramid = afterSecond) }+ checkPyramidWin()+ } else {+ // Not a valid pair — treat the tap as a fresh selection.+ _uiState.update { it.copy(pyramid = state.copy(selectedId = id)) }+ }+ }+ }+ }++ fun pyramidDealStock() {+ val state = _uiState.value.pyramid ?: return+ if (state.isWon) return+ if (state.stock.isEmpty()) {+ // Recycle the waste back into the stock if any passes remain.+ if (state.passesRemaining <= 0 || state.waste.isEmpty()) return+ saveHistory()+ _uiState.update {+ it.copy(pyramid = state.copy(+ stock = state.waste.reversed(),+ waste = emptyList(),+ passesRemaining = state.passesRemaining - 1,+ selectedId = null,+ moveCount = state.moveCount + 1+ ))+ }+ return+ }+ saveHistory()+ _uiState.update {+ it.copy(pyramid = state.copy(+ stock = state.stock.dropLast(1),+ waste = state.waste + state.stock.last(),+ moveCount = state.moveCount + 1+ ))+ }+ }++ private fun checkPyramidWin() {+ val state = _uiState.value.pyramid ?: return+ if (state.pyramid.all { row -> row.all { it == null } }) {+ _uiState.update { it.copy(pyramid = state.copy(isWon = true)) }+ onGameWon(GameMode.PYRAMID, state.elapsedSeconds, state.moveCount, state.usedUndo)+ }+ }+ // --- Shared --- fun tryMoveByDrag(cards: List<Card>, sourceId: String, dropOffset: Offset) {@@ -552,6 +709,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio GameMode.KLONDIKE -> handleKlondikeDrop(cards, sourceId, targetId) GameMode.SPIDER -> handleSpiderDrop(cards, sourceId, targetId) GameMode.FREECELL -> handleFreeCellDrop(cards, sourceId, targetId)+ GameMode.PYRAMID -> {} // Pyramid is tap-based, not drag-based. null -> {} } }@@ -669,6 +827,9 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio is FreeCellState -> _uiState.update { it.copy(freeCell = prev.copy(usedUndo = true), history = newHistory) }+ is PyramidState -> _uiState.update {+ it.copy(pyramid = prev.copy(usedUndo = true), history = newHistory)+ } } } @@ -677,6 +838,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio GameMode.KLONDIKE -> newKlondikeGame(_uiState.value.klondike?.drawMode ?: DrawMode.DRAW_ONE) GameMode.SPIDER -> newSpiderGame() GameMode.FREECELL -> newFreeCellGame()+ GameMode.PYRAMID -> newPyramidGame() null -> {} } }@@ -693,6 +855,9 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio GameMode.FREECELL -> state.copy( freeCell = state.freeCell?.let { if (!it.isWon) it.copy(elapsedSeconds = it.elapsedSeconds + 1) else it } )+ GameMode.PYRAMID -> state.copy(+ pyramid = state.pyramid?.let { if (!it.isWon) it.copy(elapsedSeconds = it.elapsedSeconds + 1) else it }+ ) null -> state } }@@ -708,6 +873,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio GameMode.KLONDIKE -> state.klondike ?: return GameMode.SPIDER -> state.spider ?: return GameMode.FREECELL -> state.freeCell ?: return+ GameMode.PYRAMID -> state.pyramid ?: return null -> return } _uiState.update { it.copy(history = it.history + current) }@@ -723,6 +889,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio } GameMode.SPIDER -> achievementsManager.onAchievementUnlocked("spider_first") GameMode.FREECELL -> achievementsManager.onAchievementUnlocked("freecell_first")+ GameMode.PYRAMID -> achievementsManager.onAchievementUnlocked("pyramid_first") } if (!usedUndo) achievementsManager.onAchievementUnlocked("no_undo") val totalWins = statsRepository.getTotalGamesWon()
games/solitaire/src/main/res/values/strings.xml
diff --git a/games/solitaire/src/main/res/values/strings.xml b/games/solitaire/src/main/res/values/strings.xmlindex 73e2fec60a..0e08a2ed0a 100644--- a/games/solitaire/src/main/res/values/strings.xml+++ b/games/solitaire/src/main/res/values/strings.xml@@ -3,6 +3,7 @@ <string name="klondike">Klondike</string> <string name="spider">Spider</string> <string name="freecell">FreeCell</string>+ <string name="pyramid">Pyramid</string> <string name="new_game">New Game</string> <string name="continue_game">Continue</string> <string name="give_up">Give Up</string>