solitaire: migrate to canonical structure
- Commit
449440b30aac518402d344867705e10a7631f882- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 19:36 UTC (3 months ago)
- Parents
9da1101
- App root: MainActivity class-only; new Route.kt (Route:NavKey) + Navigation.kt
- util/ -> platform/ via git mv (history preserved): AppBackupAgent, SolitaireAchievementsManager, SolitaireUiContract, SolitaireViewModel
- ui/ one-public-composable-per-file: HomeScreen, GameScreen, GameBoardScreen, GameModeDisplayName + ui/dialogs/GameConfigDialog; no empty components placeholder
- Manifest backupAgent util->platform; all ui + screenshotTest imports updated
- Roots {data,platform,ui} subset of allow-listDiff
games/solitaire/src/main/AndroidManifest.xml
diff --git a/games/solitaire/src/main/AndroidManifest.xml b/games/solitaire/src/main/AndroidManifest.xmlindex 2e7095f918..8ecf7f4106 100644--- a/games/solitaire/src/main/AndroidManifest.xml+++ b/games/solitaire/src/main/AndroidManifest.xml@@ -6,7 +6,7 @@ <application android:allowBackup="true"- android:backupAgent=".util.AppBackupAgent"+ android:backupAgent=".platform.AppBackupAgent" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"@@ -27,3 +27,4 @@ </application> </manifest>+
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 983dc7e3f2..db0ee7e583 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@@ -4,74 +4,9 @@ import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.widthIn-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll-import com.vayunmathur.library.ui.AlertDialog-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CardDefaults-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.SegmentedButton-import com.vayunmathur.library.ui.SegmentedButtonDefaults-import com.vayunmathur.library.ui.SingleChoiceSegmentedButtonRow-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton-import com.vayunmathur.library.ui.TopAppBar-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.painterResource-import androidx.compose.ui.res.stringResource-import com.vayunmathur.games.solitaire.R-import androidx.compose.ui.text.style.TextAlign-import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel-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.SolitaireUiState-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-import com.vayunmathur.games.solitaire.util.SolitaireActions-import com.vayunmathur.games.solitaire.util.SolitaireViewModel-import com.vayunmathur.library.ui.AchievementNotification+import com.vayunmathur.games.solitaire.platform.SolitaireViewModel import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.ui.GameCenterScreen-import com.vayunmathur.library.util.GameHubComposeHook-import com.vayunmathur.library.util.MainNavigation-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.util.NavKey-import com.vayunmathur.library.util.rememberNavBackStack-import kotlinx.coroutines.delay-import kotlinx.serialization.Serializable--private val SolitaireBoardMaxWidth = 640.dp class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) {@@ -84,435 +19,4 @@ class MainActivity : ComponentActivity() { } } }-}--@Serializable-sealed interface Route : NavKey {- @Serializable- data object Home : Route-- @Serializable- data class Game(val mode: GameMode) : Route-- @Serializable- data object GameCenter : Route-}--@Composable-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-fun Navigation(viewModel: SolitaireViewModel) {- val backStack = rememberNavBackStack<Route>(Route.Home)- val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()-- GameHubComposeHook("solitaire", viewModel.achievementsManager)-- Box(Modifier.fillMaxSize()) {- MainNavigation(backStack) {- entry<Route.Home> {- HomeScreen(backStack, viewModel)- }- entry<Route.Game> {- GameScreen(backStack, viewModel, it.mode)- }- entry<Route.GameCenter> {- GameCenterScreen(- backupAgent = AppBackupAgent(),- manager = viewModel.achievementsManager,- onBack = { backStack.pop() }- )- }- }-- newAchievement?.let {- AchievementNotification(it) {- viewModel.dismissAchievementNotification()- }- }- }-}--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun HomeScreen(backStack: NavBackStack<Route>, viewModel: SolitaireViewModel) {- var showGamePicker by remember { mutableStateOf(false) }- var configMode by remember { mutableStateOf<GameMode?>(null) }-- val startGame = { mode: GameMode, config: GameConfig ->- showGamePicker = false- configMode = null- if (viewModel.hasActiveGame()) viewModel.giveUp()- viewModel.selectMode(mode, config)- backStack.add(Route.Game(mode))- }-- Scaffold(topBar = {- TopAppBar(- title = { Text(stringResource(R.string.app_name)) },- actions = {- IconButton(onClick = { backStack.add(Route.GameCenter) }) {- Icon(painterResource(id = android.R.drawable.btn_star_big_on), "Achievements")- }- }- )- }) { paddingValues ->- Column(- Modifier- .fillMaxSize()- .padding(paddingValues)- .padding(16.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- val uiState by viewModel.uiState.collectAsState()- val hasGame = viewModel.hasActiveGame()-- if (hasGame) {- Button(- onClick = { backStack.add(Route.Game(uiState.gameMode!!)) },- Modifier.fillMaxWidth()- ) {- Text(stringResource(R.string.continue_game))- }- }-- Button(- onClick = {- showGamePicker = true- },- Modifier.fillMaxWidth()- ) {- Text(stringResource(R.string.new_game))- }-- Row(- Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(8.dp)- ) {- GameMode.entries.forEach { mode ->- val stats = viewModel.getStats(mode)- val modeName = mode.displayName()- Card(- Modifier.weight(1f),- colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface)- ) {- Column(- Modifier.padding(12.dp).fillMaxWidth(),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- modeName,- style = MaterialTheme.typography.titleSmall,- textAlign = TextAlign.Center- )- Text(- "${stats.gamesWon}/${stats.gamesPlayed}",- style = MaterialTheme.typography.bodyLarge,- textAlign = TextAlign.Center- )- Text(- stringResource(R.string.won),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),- textAlign = TextAlign.Center- )- if (stats.bestTimeSeconds < Int.MAX_VALUE) {- Text(- "%02d:%02d".format(stats.bestTimeSeconds / 60, stats.bestTimeSeconds % 60),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),- textAlign = TextAlign.Center- )- }- }- }- }- }- }- }-- if (showGamePicker) {- AlertDialog(- onDismissRequest = { showGamePicker = false },- title = { Text(stringResource(R.string.select_mode)) },- text = {- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- GameMode.entries.forEach { mode ->- Button(- onClick = {- // FreeCell has no options — start immediately.- if (mode == GameMode.FREECELL) startGame(mode, GameConfig())- else { showGamePicker = false; configMode = mode }- },- Modifier.fillMaxWidth()- ) {- Text(mode.displayName())- }- }- }- },- confirmButton = {},- dismissButton = {- TextButton(onClick = { showGamePicker = false }) {- Text(stringResource(R.string.back))- }- }- )- }-- configMode?.let { mode ->- GameConfigDialog(- mode = mode,- onStart = { config -> startGame(mode, config) },- onDismiss = { configMode = null }- )- }-}--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun GameConfigDialog(mode: GameMode, onStart: (GameConfig) -> Unit, onDismiss: () -> Unit) {- var drawMode by remember { mutableStateOf(DrawMode.DRAW_ONE) }- var klondikeDifficulty by remember { mutableStateOf(KlondikeDifficulty.REGULAR) }- var relaxed by remember { mutableStateOf(false) }- var spiderSuits by remember { mutableStateOf(4) }-- AlertDialog(- onDismissRequest = onDismiss,- title = { Text(mode.displayName()) },- text = {- Column(- Modifier.fillMaxWidth(),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- when (mode) {- GameMode.KLONDIKE -> {- SingleChoiceSegmentedButtonRow {- listOf(- DrawMode.DRAW_ONE to R.string.draw_one,- DrawMode.DRAW_THREE to R.string.draw_three- ).forEachIndexed { idx, (value, label) ->- SegmentedButton(- shape = SegmentedButtonDefaults.itemShape(idx, 2),- onClick = { drawMode = value },- selected = drawMode == value- ) { Text(stringResource(label)) }- }- }- SingleChoiceSegmentedButtonRow {- listOf(- KlondikeDifficulty.RELAXED to R.string.mode_relaxed,- KlondikeDifficulty.REGULAR to R.string.difficulty_regular,- KlondikeDifficulty.HARD to R.string.difficulty_hard- ).forEachIndexed { idx, (value, label) ->- SegmentedButton(- shape = SegmentedButtonDefaults.itemShape(idx, 3),- onClick = { klondikeDifficulty = value },- selected = klondikeDifficulty == value- ) { Text(stringResource(label)) }- }- }- }- GameMode.SPIDER -> {- SingleChoiceSegmentedButtonRow {- listOf(- 1 to R.string.difficulty_easy,- 2 to R.string.difficulty_medium,- 4 to R.string.difficulty_hard- ).forEachIndexed { idx, (value, label) ->- SegmentedButton(- shape = SegmentedButtonDefaults.itemShape(idx, 3),- onClick = { spiderSuits = value },- selected = spiderSuits == value- ) { Text(stringResource(label)) }- }- }- }- GameMode.PYRAMID -> DifficultyRow(relaxed) { relaxed = it }- GameMode.FREECELL -> {}- }- Button(- onClick = { onStart(GameConfig(drawMode = drawMode, klondikeDifficulty = klondikeDifficulty, relaxed = relaxed, spiderSuits = spiderSuits)) },- Modifier.fillMaxWidth()- ) {- Text(stringResource(R.string.new_game))- }- }- },- confirmButton = {},- dismissButton = {- TextButton(onClick = onDismiss) { Text(stringResource(R.string.back)) }- }- )-}--@OptIn(ExperimentalMaterial3Api::class)-@Composable-private fun DifficultyRow(relaxed: Boolean, onChange: (Boolean) -> Unit) {- SingleChoiceSegmentedButtonRow {- listOf(- false to R.string.mode_original,- true to R.string.mode_relaxed- ).forEachIndexed { idx, (value, label) ->- SegmentedButton(- shape = SegmentedButtonDefaults.itemShape(idx, 2),- onClick = { onChange(value) },- selected = relaxed == value- ) { Text(stringResource(label)) }- }- }-}--/** Binds [SolitaireViewModel] to the stateless [GameBoardScreen] and runs the game clock. */-@Composable-fun GameScreen(backStack: NavBackStack<Route>, viewModel: SolitaireViewModel, mode: GameMode) {- val uiState by viewModel.uiState.collectAsState()-- LaunchedEffect(mode) {- if (uiState.gameMode != mode) {- viewModel.selectMode(mode)- }- }-- LaunchedEffect(uiState.gameMode) {- while (true) {- delay(1000)- viewModel.incrementTimer()- }- }-- GameBoardScreen(state = uiState, mode = mode, actions = viewModel, onExit = { backStack.pop() })-}--/**- * A dealt board, with no dependency on the ViewModel so it can be rendered from a- * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.- * The clock lives in the binder above, since a preview must not start one.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun GameBoardScreen(- state: SolitaireUiState,- mode: GameMode,- actions: SolitaireActions,- onExit: () -> Unit,-) {- val activeGame = when (mode) {- GameMode.KLONDIKE -> state.klondike?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }- GameMode.SPIDER -> state.spider?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }- GameMode.FREECELL -> state.freeCell?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }- GameMode.PYRAMID -> state.pyramid?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }- }- val isWon = activeGame?.first == true- val moveCount = activeGame?.second ?: 0- val elapsed = activeGame?.third ?: 0- val modeName = mode.displayName()- val timeText = "%02d:%02d".format(elapsed / 60, elapsed % 60)-- Scaffold(topBar = {- TopAppBar(- title = { Text(modeName) },- actions = {- Text(- timeText,- style = MaterialTheme.typography.titleMedium,- modifier = Modifier.padding(end = 16.dp)- )- Text(- "${stringResource(R.string.moves)}: $moveCount",- style = MaterialTheme.typography.titleMedium,- modifier = Modifier.padding(end = 16.dp)- )- }- )- }) { innerPadding ->- Box(Modifier.fillMaxSize()) {- Column(- Modifier- .fillMaxSize()- .padding(innerPadding)- .padding(horizontal = 8.dp)- .verticalScroll(rememberScrollState()),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- GameActionBar(- onUndo = { actions.undo() },- onGiveUp = {- actions.giveUp()- onExit()- },- undoEnabled = state.history.isNotEmpty() && !isWon- )-- when (mode) {- GameMode.KLONDIKE -> state.klondike?.let {- KlondikeBoard(- it,- actions,- Modifier- .align(Alignment.CenterHorizontally)- .widthIn(max = SolitaireBoardMaxWidth)- .fillMaxWidth()- )- if (!it.isWon && it.tableauPiles.none { p -> p.faceDown.isNotEmpty() }) {- Button(- onClick = { actions.klondikeAutoComplete() },- Modifier.align(Alignment.CenterHorizontally)- ) {- Text(stringResource(R.string.auto_complete))- }- }- }- GameMode.SPIDER -> state.spider?.let {- SpiderBoard(- it,- actions,- Modifier- .align(Alignment.CenterHorizontally)- .widthIn(max = SolitaireBoardMaxWidth)- .fillMaxWidth()- )- }- GameMode.FREECELL -> state.freeCell?.let {- FreeCellBoard(- it,- actions,- Modifier- .align(Alignment.CenterHorizontally)- .widthIn(max = SolitaireBoardMaxWidth)- .fillMaxWidth()- )- }- GameMode.PYRAMID -> state.pyramid?.let {- PyramidBoard(- it,- actions,- Modifier- .align(Alignment.CenterHorizontally)- .widthIn(max = SolitaireBoardMaxWidth)- .fillMaxWidth()- )- }- }- }-- if (isWon) {- WinOverlay(- elapsedSeconds = elapsed,- moveCount = moveCount,- // Same thing selectMode(mode, currentConfig()) did: redeal this variant.- onNewGame = { actions.restart() },- onBack = onExit- )- }- }- }-}+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/Navigation.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/Navigation.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/Navigation.ktnew file mode 100644index 0000000000..7d0ef142e8--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/Navigation.kt@@ -0,0 +1,34 @@+package com.vayunmathur.games.solitaire++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import com.vayunmathur.games.solitaire.platform.AppBackupAgent+import com.vayunmathur.games.solitaire.platform.SolitaireViewModel+import com.vayunmathur.games.solitaire.ui.GameScreen+import com.vayunmathur.games.solitaire.ui.HomeScreen+import com.vayunmathur.library.ui.AchievementNotification+import com.vayunmathur.library.ui.GameCenterScreen+import com.vayunmathur.library.util.GameHubComposeHook+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack++@Composable+fun Navigation(viewModel: SolitaireViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.Home)+ val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()+ GameHubComposeHook("solitaire", viewModel.achievementsManager)+ Box(Modifier.fillMaxSize()) {+ MainNavigation(backStack) {+ entry<Route.Home> { HomeScreen(backStack, viewModel) }+ entry<Route.Game> { GameScreen(backStack, viewModel, it.mode) }+ entry<Route.GameCenter> {+ GameCenterScreen(backupAgent = AppBackupAgent(), manager = viewModel.achievementsManager, onBack = { backStack.pop() })+ }+ }+ newAchievement?.let { AchievementNotification(it) { viewModel.dismissAchievementNotification() } }+ }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/Route.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/Route.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/Route.ktnew file mode 100644index 0000000000..20ba26e7cc--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/Route.kt@@ -0,0 +1,15 @@+package com.vayunmathur.games.solitaire++import com.vayunmathur.library.util.NavKey+import com.vayunmathur.games.solitaire.data.GameMode+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+ @Serializable+ data object Home : Route+ @Serializable+ data class Game(val mode: GameMode) : Route+ @Serializable+ data object GameCenter : Route+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/AppBackupAgent.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/AppBackupAgent.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/AppBackupAgent.ktsimilarity index 78%rename from games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/AppBackupAgent.ktrename to games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/AppBackupAgent.ktindex 975278e181..a5c0f5b97a 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/AppBackupAgent.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/AppBackupAgent.kt@@ -1,4 +1,4 @@-package com.vayunmathur.games.solitaire.util+package com.vayunmathur.games.solitaire.platform import com.vayunmathur.library.util.BaseBackupAgent @@ -6,3 +6,4 @@ class AppBackupAgent : BaseBackupAgent() { override val prefNames: List<String> get() = listOf("solitaire_stats") }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/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/platform/SolitaireAchievementsManager.ktsimilarity index 96%rename from games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireAchievementsManager.ktrename to games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireAchievementsManager.ktindex 93177abbd1..db2c9ae875 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireAchievementsManager.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireAchievementsManager.kt@@ -1,4 +1,4 @@-package com.vayunmathur.games.solitaire.util+package com.vayunmathur.games.solitaire.platform import android.content.Context import com.vayunmathur.games.solitaire.data.GameMode@@ -29,3 +29,4 @@ class SolitaireAchievementsManager( onProgressUpdated("win_streak_5", statsRepository.getBestWinStreak()) } }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireUiContract.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.ktsimilarity index 90%rename from games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireUiContract.ktrename to games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.ktindex 273c9089e8..463e9033c3 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireUiContract.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireUiContract.kt@@ -1,4 +1,4 @@-package com.vayunmathur.games.solitaire.util+package com.vayunmathur.games.solitaire.platform import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect@@ -11,8 +11,8 @@ import kotlinx.coroutines.flow.StateFlow * * The boards and the card widgets they share take this interface rather than the ViewModel * itself, so they can be rendered by a `@Preview` — which is what the store listing images- * are generated from. It lives in `util` rather than next to the boards so the dependency- * runs one way: `ui` depends on `util`, and the ViewModel implements this.+ * are generated from. It lives in `platform` rather than next to the boards so the dependency+ * runs one way: `ui` depends on `platform`, and the ViewModel implements this. * * Every member has a no-op default, so [Noop] is the whole implementation a preview needs. */@@ -56,3 +56,4 @@ private val NoDrag: StateFlow<DragInfo?> = MutableStateFlow(null) /** Somewhere for a [SolitaireActions.Noop] board to register its drop zones and forget them. */ private val DiscardedDropTargets: MutableMap<String, Rect> = mutableMapOf()+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/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/platform/SolitaireViewModel.ktsimilarity index 99%rename from games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.ktrename to games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.ktindex 9df9e0ae94..2250667851 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/platform/SolitaireViewModel.kt@@ -1,4 +1,4 @@-package com.vayunmathur.games.solitaire.util+package com.vayunmathur.games.solitaire.platform import android.app.Application import androidx.compose.ui.geometry.Offset@@ -1141,3 +1141,4 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio achievementsManager.onProgressUpdated("win_streak_5", statsRepository.getBestWinStreak()) } }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.ktindex 56420df1eb..802c7e0586 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt@@ -23,7 +23,7 @@ import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import com.vayunmathur.games.solitaire.data.Card-import com.vayunmathur.games.solitaire.util.SolitaireActions+import com.vayunmathur.games.solitaire.platform.SolitaireActions /** * A card the player can pick up. [sourceId] identifies the pile position it comes from;@@ -149,3 +149,4 @@ fun DropTarget( content() } }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.ktindex 59e71cf052..e1eca6a934 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt@@ -5,7 +5,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.data.Suit-import com.vayunmathur.games.solitaire.util.SolitaireActions+import com.vayunmathur.games.solitaire.platform.SolitaireActions @Composable fun FoundationSlot(@@ -51,3 +51,4 @@ fun FreeCellSlot( } } }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.ktindex a2abd71f07..481072309c 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FreeCellBoard.kt@@ -12,7 +12,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.vayunmathur.games.solitaire.data.FreeCellState-import com.vayunmathur.games.solitaire.util.SolitaireActions+import com.vayunmathur.games.solitaire.platform.SolitaireActions @Composable fun FreeCellBoard(state: FreeCellState, actions: SolitaireActions, modifier: Modifier = Modifier) {@@ -57,3 +57,4 @@ fun FreeCellBoard(state: FreeCellState, actions: SolitaireActions, modifier: Mod } } }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.ktnew file mode 100644index 0000000000..a5726bbc04--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameBoardScreen.kt@@ -0,0 +1,68 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.solitaire.R+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.data.SolitaireUiState+import com.vayunmathur.games.solitaire.platform.SolitaireActions+import com.vayunmathur.library.ui.Button++private val SolitaireBoardMaxWidth = 640.dp++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun GameBoardScreen(state: SolitaireUiState, mode: GameMode, actions: SolitaireActions, onExit: () -> Unit) {+ val activeGame = when (mode) {+ GameMode.KLONDIKE -> state.klondike?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }+ GameMode.SPIDER -> state.spider?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }+ GameMode.FREECELL -> state.freeCell?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }+ GameMode.PYRAMID -> state.pyramid?.let { Triple(it.isWon, it.moveCount, it.elapsedSeconds) }+ }+ val isWon = activeGame?.first == true+ val moveCount = activeGame?.second ?: 0+ val elapsed = activeGame?.third ?: 0+ val modeName = mode.displayName()+ val timeText = "%02d:%02d".format(elapsed / 60, elapsed % 60)+ Scaffold(topBar = {+ TopAppBar(title = { Text(modeName) }, actions = {+ Text(timeText, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(end = 16.dp))+ Text("{stringResource(R.string.moves)}: moveCount", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(end = 16.dp))+ })+ }) { innerPadding ->+ Box(Modifier.fillMaxSize()) {+ Column(Modifier.fillMaxSize().padding(innerPadding).padding(horizontal = 8.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ GameActionBar(onUndo = { actions.undo() }, onGiveUp = { actions.giveUp(); onExit() }, undoEnabled = state.history.isNotEmpty() && !isWon)+ when (mode) {+ GameMode.KLONDIKE -> state.klondike?.let {+ KlondikeBoard(it, actions, Modifier.align(Alignment.CenterHorizontally).widthIn(max = SolitaireBoardMaxWidth).fillMaxWidth())+ if (!it.isWon && it.tableauPiles.none { p -> p.faceDown.isNotEmpty() }) {+ Button(onClick = { actions.klondikeAutoComplete() }, Modifier.align(Alignment.CenterHorizontally)) { Text(stringResource(R.string.auto_complete)) }+ }+ }+ GameMode.SPIDER -> state.spider?.let { SpiderBoard(it, actions, Modifier.align(Alignment.CenterHorizontally).widthIn(max = SolitaireBoardMaxWidth).fillMaxWidth()) }+ GameMode.FREECELL -> state.freeCell?.let { FreeCellBoard(it, actions, Modifier.align(Alignment.CenterHorizontally).widthIn(max = SolitaireBoardMaxWidth).fillMaxWidth()) }+ GameMode.PYRAMID -> state.pyramid?.let { PyramidBoard(it, actions, Modifier.align(Alignment.CenterHorizontally).widthIn(max = SolitaireBoardMaxWidth).fillMaxWidth()) }+ }+ }+ if (isWon) { WinOverlay(elapsedSeconds = elapsed, moveCount = moveCount, onNewGame = { actions.restart() }, onBack = onExit) }+ }+ }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameModeDisplayName.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameModeDisplayName.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameModeDisplayName.ktnew file mode 100644index 0000000000..4d780baf54--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameModeDisplayName.kt@@ -0,0 +1,14 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.games.solitaire.R+import com.vayunmathur.games.solitaire.data.GameMode++@Composable+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)+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.ktnew file mode 100644index 0000000000..fa3ce7ab70--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/GameScreen.kt@@ -0,0 +1,19 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.games.solitaire.Route+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.platform.SolitaireViewModel+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.delay++@Composable+fun GameScreen(backStack: NavBackStack<Route>, viewModel: SolitaireViewModel, mode: GameMode) {+ val uiState by viewModel.uiState.collectAsState()+ LaunchedEffect(mode) { if (uiState.gameMode != mode) viewModel.selectMode(mode) }+ LaunchedEffect(uiState.gameMode) { while (true) { delay(1000); viewModel.incrementTimer() } }+ GameBoardScreen(state = uiState, mode = mode, actions = viewModel, onExit = { backStack.pop() })+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/HomeScreen.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/HomeScreen.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/HomeScreen.ktnew file mode 100644index 0000000000..d1932fd58c--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/HomeScreen.kt@@ -0,0 +1,110 @@+package com.vayunmathur.games.solitaire.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Card+import androidx.compose.material3.CardDefaults+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.solitaire.R+import com.vayunmathur.games.solitaire.Route+import com.vayunmathur.games.solitaire.data.GameConfig+import com.vayunmathur.games.solitaire.data.GameMode+import com.vayunmathur.games.solitaire.platform.SolitaireViewModel+import com.vayunmathur.games.solitaire.ui.dialogs.GameConfigDialog+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.NavBackStack++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun HomeScreen(backStack: NavBackStack<Route>, viewModel: SolitaireViewModel) {+ var showGamePicker by remember { mutableStateOf(false) }+ var configMode by remember { mutableStateOf<GameMode?>(null) }+ val startGame = { mode: GameMode, config: GameConfig ->+ showGamePicker = false+ configMode = null+ if (viewModel.hasActiveGame()) viewModel.giveUp()+ viewModel.selectMode(mode, config)+ backStack.add(Route.Game(mode))+ }+ Scaffold(topBar = {+ TopAppBar(+ title = { Text(stringResource(R.string.app_name)) },+ actions = {+ IconButton(onClick = { backStack.add(Route.GameCenter) }) {+ Icon(painterResource(id = android.R.drawable.btn_star_big_on), "Achievements")+ }+ }+ )+ }) { paddingValues ->+ Column(+ Modifier.fillMaxSize().padding(paddingValues).padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ val uiState by viewModel.uiState.collectAsState()+ val hasGame = viewModel.hasActiveGame()+ if (hasGame) {+ Button(onClick = { backStack.add(Route.Game(uiState.gameMode!!)) }, Modifier.fillMaxWidth()) { Text(stringResource(R.string.continue_game)) }+ }+ Button(onClick = { showGamePicker = true }, Modifier.fillMaxWidth()) { Text(stringResource(R.string.new_game)) }+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ GameMode.entries.forEach { mode ->+ val stats = viewModel.getStats(mode)+ val modeName = mode.displayName()+ Card(Modifier.weight(1f), colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface)) {+ Column(Modifier.padding(12.dp).fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(modeName, style = MaterialTheme.typography.titleSmall, textAlign = TextAlign.Center)+ Text("{stats.gamesWon}/{stats.gamesPlayed}", style = MaterialTheme.typography.bodyLarge, textAlign = TextAlign.Center)+ Text(stringResource(R.string.won), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f), textAlign = TextAlign.Center)+ if (stats.bestTimeSeconds < Int.MAX_VALUE) {+ Text("%02d:%02d".format(stats.bestTimeSeconds / 60, stats.bestTimeSeconds % 60), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f), textAlign = TextAlign.Center)+ }+ }+ }+ }+ }+ }+ }+ if (showGamePicker) {+ AlertDialog(+ onDismissRequest = { showGamePicker = false },+ title = { Text(stringResource(R.string.select_mode)) },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ GameMode.entries.forEach { mode ->+ Button(onClick = { if (mode == GameMode.FREECELL) startGame(mode, GameConfig()) else { showGamePicker = false; configMode = mode } }, Modifier.fillMaxWidth()) { Text(mode.displayName()) }+ }+ }+ },+ confirmButton = {},+ dismissButton = { TextButton(onClick = { showGamePicker = false }) { Text(stringResource(R.string.back)) } }+ )+ }+ configMode?.let { mode ->+ GameConfigDialog(mode = mode, onStart = { config -> startGame(mode, config) }, onDismiss = { configMode = null })+ }+}
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.ktindex 69559c7705..49ae09be7f 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt@@ -17,7 +17,7 @@ import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp import com.vayunmathur.games.solitaire.data.DrawMode import com.vayunmathur.games.solitaire.data.KlondikeState-import com.vayunmathur.games.solitaire.util.SolitaireActions+import com.vayunmathur.games.solitaire.platform.SolitaireActions @Composable fun KlondikeBoard(state: KlondikeState, actions: SolitaireActions, modifier: Modifier = Modifier) {@@ -110,3 +110,4 @@ fun KlondikeBoard(state: KlondikeState, actions: SolitaireActions, modifier: Mod } } }+
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.ktindex cc5c20fe96..6f3c430dcf 100644--- 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.kt@@ -19,7 +19,7 @@ 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.SolitaireActions+import com.vayunmathur.games.solitaire.platform.SolitaireActions private val SelectionColor = Color(0xFFFFC107) @@ -125,3 +125,4 @@ private fun SelectableCard( } Box(m) { content() } }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.ktindex 53cca7925e..ca8cbba4b3 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/SpiderBoard.kt@@ -16,7 +16,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.vayunmathur.games.solitaire.data.SpiderState-import com.vayunmathur.games.solitaire.util.SolitaireActions+import com.vayunmathur.games.solitaire.platform.SolitaireActions import androidx.compose.ui.res.stringResource import com.vayunmathur.games.solitaire.R @@ -74,3 +74,4 @@ fun SpiderBoard(state: SpiderState, actions: SolitaireActions, modifier: Modifie } } }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.ktindex 2b61ca352a..ebea3602b4 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt@@ -9,7 +9,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.data.TableauPile-import com.vayunmathur.games.solitaire.util.SolitaireActions+import com.vayunmathur.games.solitaire.platform.SolitaireActions private val FACE_DOWN_OVERLAP = 8.dp private val FACE_UP_OVERLAP = 22.dp@@ -103,3 +103,4 @@ fun FreeCellTableauColumn( } } }+
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/dialogs/GameConfigDialog.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/dialogs/GameConfigDialog.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/dialogs/GameConfigDialog.ktnew file mode 100644index 0000000000..ade457ea77--- /dev/null+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/dialogs/GameConfigDialog.kt@@ -0,0 +1,81 @@+package com.vayunmathur.games.solitaire.ui.dialogs++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+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.displayName+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.TextButton++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun GameConfigDialog(mode: GameMode, onStart: (GameConfig) -> Unit, onDismiss: () -> Unit) {+ var drawMode by remember { mutableStateOf(DrawMode.DRAW_ONE) }+ var klondikeDifficulty by remember { mutableStateOf(KlondikeDifficulty.REGULAR) }+ var relaxed by remember { mutableStateOf(false) }+ var spiderSuits by remember { mutableStateOf(4) }+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(mode.displayName()) },+ text = {+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {+ when (mode) {+ GameMode.KLONDIKE -> {+ SingleChoiceSegmentedButtonRow {+ listOf(DrawMode.DRAW_ONE to R.string.draw_one, DrawMode.DRAW_THREE to R.string.draw_three).forEachIndexed { idx, (value, label) ->+ SegmentedButton(shape = SegmentedButtonDefaults.itemShape(idx, 2), onClick = { drawMode = value }, selected = drawMode == value) { Text(stringResource(label)) }+ }+ }+ SingleChoiceSegmentedButtonRow {+ listOf(KlondikeDifficulty.RELAXED to R.string.mode_relaxed, KlondikeDifficulty.REGULAR to R.string.difficulty_regular, KlondikeDifficulty.HARD to R.string.difficulty_hard).forEachIndexed { idx, (value, label) ->+ SegmentedButton(shape = SegmentedButtonDefaults.itemShape(idx, 3), onClick = { klondikeDifficulty = value }, selected = klondikeDifficulty == value) { Text(stringResource(label)) }+ }+ }+ }+ GameMode.SPIDER -> {+ SingleChoiceSegmentedButtonRow {+ listOf(1 to R.string.difficulty_easy, 2 to R.string.difficulty_medium, 4 to R.string.difficulty_hard).forEachIndexed { idx, (value, label) ->+ SegmentedButton(shape = SegmentedButtonDefaults.itemShape(idx, 3), onClick = { spiderSuits = value }, selected = spiderSuits == value) { Text(stringResource(label)) }+ }+ }+ }+ GameMode.PYRAMID -> DifficultyRow(relaxed) { relaxed = it }+ GameMode.FREECELL -> {}+ }+ Button(onClick = { onStart(GameConfig(drawMode = drawMode, klondikeDifficulty = klondikeDifficulty, relaxed = relaxed, spiderSuits = spiderSuits)) }, Modifier.fillMaxWidth()) { Text(stringResource(R.string.new_game)) }+ }+ },+ confirmButton = {},+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.back)) } }+ )+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun DifficultyRow(relaxed: Boolean, onChange: (Boolean) -> Unit) {+ SingleChoiceSegmentedButtonRow {+ listOf(false to R.string.mode_original, true to R.string.mode_relaxed).forEachIndexed { idx, (value, label) ->+ SegmentedButton(shape = SegmentedButtonDefaults.itemShape(idx, 2), onClick = { onChange(value) }, selected = relaxed == value) { Text(stringResource(label)) }+ }+ }+}
games/solitaire/src/screenshotTest/kotlin/com/vayunmathur/games/solitaire/MetadataPreviews.kt
diff --git a/games/solitaire/src/screenshotTest/kotlin/com/vayunmathur/games/solitaire/MetadataPreviews.kt b/games/solitaire/src/screenshotTest/kotlin/com/vayunmathur/games/solitaire/MetadataPreviews.ktindex 0de9ccabf9..35cee95f65 100644--- a/games/solitaire/src/screenshotTest/kotlin/com/vayunmathur/games/solitaire/MetadataPreviews.kt+++ b/games/solitaire/src/screenshotTest/kotlin/com/vayunmathur/games/solitaire/MetadataPreviews.kt@@ -14,7 +14,7 @@ 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 com.vayunmathur.games.solitaire.util.SolitaireActions+import com.vayunmathur.games.solitaire.platform.SolitaireActions import com.vayunmathur.library.ui.DynamicTheme /** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */@@ -183,3 +183,4 @@ class MetadataPreviews { private fun faceDown(count: Int): List<Card> = List(count) { Card(Suit.SPADES, Rank.entries[it % Rank.entries.size]) } }+
games/unblockjam/src/main/AndroidManifest.xml
diff --git a/games/unblockjam/src/main/AndroidManifest.xml b/games/unblockjam/src/main/AndroidManifest.xmlindex 44cc715e65..3a07c31311 100644--- a/games/unblockjam/src/main/AndroidManifest.xml+++ b/games/unblockjam/src/main/AndroidManifest.xml@@ -6,7 +6,7 @@ <application android:allowBackup="true"- android:backupAgent=".util.AppBackupAgent"+ android:backupAgent=".platform.AppBackupAgent" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.ktindex a5d4833ad6..73eaee2d61 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.kt@@ -4,87 +4,10 @@ import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge-import androidx.compose.animation.core.animateDpAsState-import androidx.compose.animation.core.tween-import androidx.compose.foundation.background-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.PaddingValues-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxHeight-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.offset-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.plus-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.grid.GridCells-import androidx.compose.foundation.lazy.grid.LazyVerticalGrid-import androidx.compose.foundation.lazy.grid.itemsIndexed-import androidx.compose.foundation.lazy.itemsIndexed-import androidx.compose.foundation.shape.RoundedCornerShape-import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CardDefaults-import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Surface-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.graphics.Brush-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.res.painterResource-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.unit.IntOffset-import androidx.compose.ui.unit.dp-import androidx.compose.ui.unit.sp-import androidx.compose.ui.zIndex import androidx.lifecycle.viewmodel.compose.viewModel-import com.vayunmathur.games.unblockjam.data.DailyLevelGenerator-import com.vayunmathur.games.unblockjam.data.LevelData import com.vayunmathur.games.unblockjam.data.LevelPack+import com.vayunmathur.games.unblockjam.platform.UnblockJamViewModel import com.vayunmathur.games.unblockjam.ui.UnblockJamTheme-import com.vayunmathur.games.unblockjam.util.AppBackupAgent-import com.vayunmathur.games.unblockjam.util.DailyProgress-import com.vayunmathur.games.unblockjam.util.GameActions-import com.vayunmathur.games.unblockjam.util.GameUiState-import com.vayunmathur.games.unblockjam.util.UnblockJamViewModel-import com.vayunmathur.games.unblockjam.util.blockDragGestures-import com.vayunmathur.library.ui.AchievementNotification-import com.vayunmathur.library.ui.GameCenterScreen-import com.vayunmathur.library.ui.IconCheck-import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.ui.IconStar-import com.vayunmathur.library.util.GameHubComposeHook-import com.vayunmathur.library.util.LevelStats-import com.vayunmathur.library.util.MainNavigation-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.util.NavKey-import com.vayunmathur.library.util.rememberNavBackStack-import kotlinx.serialization.Serializable-import java.time.LocalDate-import java.time.format.DateTimeFormatter-import java.time.format.FormatStyle class MainActivity : ComponentActivity() { @@ -99,597 +22,4 @@ class MainActivity : ComponentActivity() { } } }-}--@Serializable-sealed interface Route: NavKey {- @Serializable- data object PackSelector: Route- @Serializable- data class LevelSelector(val packIndex: Int): Route- @Serializable- data class Game(val packIndex: Int, val levelIndex: Int): Route- @Serializable- data object DailySelector: Route- @Serializable- data class DailyGame(val levelIndex: Int): Route- @Serializable- data object GameCenter: Route-}--@Composable-fun Navigation(viewModel: UnblockJamViewModel) {- val backStack = rememberNavBackStack<Route>(Route.PackSelector)- val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()-- GameHubComposeHook("unblockjam", viewModel.achievementsManager)-- Box(Modifier.fillMaxSize()) {- MainNavigation(backStack) {- entry<Route.PackSelector> {- PackPage(backStack, viewModel, onOpenGameCenter = { backStack.add(Route.GameCenter) })- }- entry<Route.LevelSelector> {- val pack = LevelPack.PACKS[it.packIndex]- UnblockJamTheme(pack = pack) {- LevelPage(backStack, viewModel, it.packIndex)- }- }- entry<Route.Game> {- val pack = LevelPack.PACKS[it.packIndex]- UnblockJamTheme(pack = pack) {- GamePage(backStack, viewModel, it.packIndex, it.levelIndex)- }- }- entry<Route.DailySelector> {- DailyLevelPage(backStack, viewModel)- }- entry<Route.DailyGame> {- GamePage(backStack, viewModel, UnblockJamViewModel.DAILY_PACK_INDEX, it.levelIndex)- }- entry<Route.GameCenter> {- GameCenterScreen(- backupAgent = AppBackupAgent(),- manager = viewModel.achievementsManager,- onBack = { backStack.pop() }- )- }- }-- newAchievement?.let {- AchievementNotification(it) {- viewModel.dismissAchievementNotification()- }- }- }-}--/** Binds [UnblockJamViewModel] to the stateless [PackScreen]. */-@Composable-fun PackPage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel, onOpenGameCenter: () -> Unit) {- val dailyCompleted by viewModel.dailyCompleted.collectAsState()- val dailyDay by viewModel.dailyDay.collectAsState()- val dailyStreak by viewModel.dailyStreak.collectAsState()-- PackScreen(- packNames = LevelPack.PACKS.map { it.name },- daily = DailyProgress(- day = dailyDay,- completed = dailyCompleted,- total = DailyLevelGenerator.LEVELS_PER_DAY,- streak = dailyStreak,- ),- onOpenPack = { backStack.add(Route.LevelSelector(it)) },- onOpenDaily = { backStack.add(Route.DailySelector) },- onOpenGameCenter = onOpenGameCenter,- )-}--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun PackScreen(- packNames: List<String>,- onOpenPack: (Int) -> Unit,- onOpenGameCenter: () -> Unit,- daily: DailyProgress? = null,- onOpenDaily: () -> Unit = {},-) {- Scaffold(topBar = {- TopAppBar(- title = { Text(stringResource(R.string.pack_selector)) },- actions = {- IconButton(onClick = onOpenGameCenter) {- Icon(painterResource(id = android.R.drawable.btn_star_big_on), "Achievements")- }- }- )- }) { paddingValues ->- LazyColumn(- Modifier.fillMaxSize(),- contentPadding = paddingValues + PaddingValues(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 0.dp),- verticalArrangement = Arrangement.spacedBy(12.dp),- ) {- daily?.let { item { DailyCard(it, onOpenDaily) } }- itemsIndexed(packNames) { index, name ->- Card(Modifier.clickable{- onOpenPack(index)- }, colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface)) {- Box(Modifier.fillMaxWidth().padding(8.dp)) {- Text(name, Modifier.align(Alignment.Center), style = MaterialTheme.typography.displayMedium)- }- }- }- }- }-}--@Composable-private fun DailyCard(daily: DailyProgress, onOpen: () -> Unit) {- Card(- Modifier.clickable { onOpen() },- colors = CardDefaults.cardColors(MaterialTheme.colorScheme.primaryContainer)- ) {- Row(- Modifier.fillMaxWidth().padding(16.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column {- Text(- stringResource(R.string.daily_challenge),- style = MaterialTheme.typography.headlineMedium- )- Text(- LocalDate.ofEpochDay(daily.day)- .format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)),- style = MaterialTheme.typography.bodyMedium- )- }- Column(horizontalAlignment = Alignment.End) {- Text("${daily.completed}/${daily.total}", style = MaterialTheme.typography.titleMedium)- Text(- stringResource(R.string.daily_streak, daily.streak.toInt()),- style = MaterialTheme.typography.bodyMedium- )- }- }- }-}--/** Binds [UnblockJamViewModel] to today's daily pack, reusing the pack level grid. */-@Composable-fun DailyLevelPage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel) {- val dailyPack by viewModel.dailyPack.collectAsState()- val dailyStats by viewModel.dailyStats.collectAsState()-- // Generates on first open, and again if the day rolled over while the app was backgrounded.- LaunchedEffect(Unit) { viewModel.refreshDaily() }-- val pack = dailyPack- if (pack == null) {- Box(Modifier.fillMaxSize(), Alignment.Center) { CircularProgressIndicator() }- return- }- LevelScreen(- pack = pack,- levelStats = dailyStats,- title = stringResource(R.string.daily_challenge),- onOpenLevel = { backStack.add(Route.DailyGame(it)) }- )-}--/** Binds [UnblockJamViewModel] to the stateless [LevelScreen]. */-@Composable-fun LevelPage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel, packIndex: Int) {- val levelStats by viewModel.levelStats.collectAsState()- LevelScreen(- pack = LevelPack.PACKS[packIndex],- levelStats = levelStats,- onOpenLevel = { backStack.add(Route.Game(packIndex, it)) }- )-}--/**- * The puzzle grid for one pack, with no dependency on the ViewModel so it can be rendered- * from a `@Preview` — see `src/screenshotTest`, which is where the store listing images- * come from.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun LevelScreen(- pack: LevelPack,- levelStats: Map<String, LevelStats>,- onOpenLevel: (Int) -> Unit,- title: String = stringResource(R.string.level_selector)-) {- Scaffold(topBar = {- TopAppBar({Text(title)})- }) { paddingValues ->- LazyVerticalGrid(- GridCells.Adaptive(88.dp),- Modifier.fillMaxSize(),- contentPadding = paddingValues + PaddingValues(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 0.dp),- verticalArrangement = Arrangement.spacedBy(12.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- ) {- itemsIndexed(pack.levels) { index, levelData ->- Card(- Modifier.fillMaxWidth().clickable { onOpenLevel(index) },- colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface)- ) {- Box(Modifier.fillMaxSize().padding(8.dp)) {- Text("${index + 1}", Modifier.align(Alignment.Center))- val levelStat = levelStats[levelData.id]- Box(- Modifier.size(20.dp).align(Alignment.CenterEnd),- Alignment.Center- ) {- when {- levelStat == null -> return@Box- levelStat.bestScore <= levelData.optimalMoves -> IconStar()- else -> IconCheck()- }- }- }- }- }- }- }-}--/** Binds [UnblockJamViewModel] to the stateless [GameScreen]. */-@Composable-fun GamePage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel, packIndex: Int, levelIndex: Int) {- val uiState by viewModel.uiState.collectAsState()- val packStats by viewModel.levelStats.collectAsState()- val dailyStats by viewModel.dailyStats.collectAsState()- val dailyPack by viewModel.dailyPack.collectAsState()-- val isDaily = packIndex == UnblockJamViewModel.DAILY_PACK_INDEX- val levels = if (isDaily) dailyPack?.levels else LevelPack.PACKS[packIndex].levels- val levelStats = if (isDaily) dailyStats else packStats-- // Restoring straight onto a daily level can outrun pack generation.- LaunchedEffect(isDaily) { if (isDaily) viewModel.refreshDaily() }-- LaunchedEffect(packIndex, levelIndex, levels) {- viewModel.loadLevel(packIndex, levelIndex)- }-- val startingLevelData = levels?.getOrNull(levelIndex)- if (levels == null || startingLevelData == null) {- Box(Modifier.fillMaxSize(), Alignment.Center) { CircularProgressIndicator() }- return- }-- val isReady = uiState.packIndex == packIndex &&- uiState.levelIndex == levelIndex &&- uiState.currentLevelData != null- val currentLevelData = if (isReady) uiState.currentLevelData!! else startingLevelData- val currentLevelStats = levelStats[startingLevelData.id]-- // Everything except level navigation is the ViewModel's; that one is the back stack's.- val actions = remember(viewModel, backStack, packIndex, levels.lastIndex) {- object : GameActions by viewModel {- override fun onLevelChange(newIndex: Int) {- val clamped = newIndex.coerceIn(0, levels.lastIndex)- backStack.setLast(- if (isDaily) Route.DailyGame(clamped) else Route.Game(packIndex, clamped)- )- }- }- }-- GameScreen(- state = GameUiState(- levelData = currentLevelData,- levelIndex = levelIndex,- maxLevelIndex = levels.lastIndex,- moves = if (isReady) viewModel.getCurrentMoves() else 0,- bestScore = currentLevelStats?.bestScore,- isCompleted = currentLevelStats != null,- isLevelWon = isReady && uiState.isLevelWon,- canUndo = isReady && uiState.history.isNotEmpty()- ),- actions = actions,- onBack = { backStack.pop() }- )-}--/**- * The playable board, with no dependency on the ViewModel so it can be rendered from a- * `@Preview` — see `src/screenshotTest`.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun GameScreen(state: GameUiState, actions: GameActions, onBack: () -> Unit) {- val currentLevelData = state.levelData- val isLevelWon = state.isLevelWon-- Scaffold(- topBar = { TopAppBar({}, navigationIcon = { IconNavigation(onBack) }) },- ) { innerPadding ->- Surface(- modifier = Modifier.fillMaxSize(),- color = MaterialTheme.colorScheme.background- ) {- val infoBoxes = @Composable {- PuzzleInfoBox(- levelIndex = state.levelIndex,- onLevelChange = actions::onLevelChange,- isCompleted = state.isCompleted,- maxLevelIndex = state.maxLevelIndex- )- MovesInfoBox(- moves = state.moves,- bestScore = state.bestScore,- optimalMoves = currentLevelData.optimalMoves- )- }- val actionButtons = @Composable {- // While playing show Undo/Restart; once solved they're replaced by the- // "next level" button in the same row.- if (!isLevelWon) {- Button(- onClick = { actions.onUndo() },- enabled = state.canUndo- ) {- Text(stringResource(UiR.string.undo))- }- Button(- onClick = { actions.onRestart() },- enabled = state.canUndo- ) {- Text(stringResource(R.string.restart))- }- } else if (state.levelIndex < state.maxLevelIndex) {- Button(onClick = { actions.onLevelChange(state.levelIndex + 1) }) {- Text(stringResource(R.string.next_level))- }- }- }- val board = @Composable { boardModifier: Modifier ->- GameBoard(- levelData = currentLevelData,- onLevelChanged = actions::onBlockMoved,- onLevelWon = actions::onLevelWon,- isLevelWon = isLevelWon,- modifier = boardModifier- )- }-- BoxWithConstraints(- modifier = Modifier- .fillMaxSize()- .padding(innerPadding)- .padding(16.dp)- ) {- if (maxWidth > maxHeight) {- Row(- modifier = Modifier.fillMaxSize(),- horizontalArrangement = Arrangement.spacedBy(16.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Box(- modifier = Modifier.weight(1f).fillMaxHeight(),- contentAlignment = Alignment.Center- ) {- board(Modifier.fillMaxSize())- }- Column(- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(16.dp)- ) {- infoBoxes()- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- actionButtons()- }- }- }- } else {- Column(- modifier = Modifier.fillMaxSize(),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(16.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceAround,- verticalAlignment = Alignment.CenterVertically- ) {- infoBoxes()- }- Box(- modifier = Modifier.weight(1f).fillMaxWidth(),- contentAlignment = Alignment.Center- ) {- board(Modifier.fillMaxSize())- }- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceEvenly- ) {- actionButtons()- }- }- }- }- }- }-}--@Composable-fun PuzzleInfoBox(levelIndex: Int, onLevelChange: (Int) -> Unit, isCompleted: Boolean, maxLevelIndex: Int) {- InfoBox(title = stringResource(R.string.level)) {- Row(- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween,- modifier = Modifier.fillMaxWidth()- ) {- IconButton(- onClick = { onLevelChange(levelIndex - 1) },- enabled = levelIndex > 0- ) {- Icon(- painterResource(R.drawable.arrow_back_24px),- contentDescription = stringResource(R.string.previous_level),- )- }- Text(- text = "${levelIndex + 1}",- fontSize = 24.sp,- fontWeight = FontWeight.Bold- )- IconButton(- onClick = { onLevelChange(levelIndex + 1) },- enabled = levelIndex < maxLevelIndex- ) {- Icon(- painterResource(R.drawable.arrow_forward_24px),- contentDescription = stringResource(R.string.next_level),- )- }- }- if (isCompleted) {- Text(- text = stringResource(R.string.completed),- color = MaterialTheme.colorScheme.error,- fontSize = 12.sp,- fontWeight = FontWeight.Bold- )- }- }-}--@Composable-fun MovesInfoBox(moves: Int, bestScore: Int?, optimalMoves: Int) {- InfoBox(title = stringResource(R.string.moves)) {- Column(horizontalAlignment = Alignment.CenterHorizontally) {- Text(- text = "$moves",- fontSize = 24.sp,- fontWeight = FontWeight.Bold- )- Text(- text = "${bestScore ?: "-"} / $optimalMoves",- fontSize = 18.sp,- fontWeight = FontWeight.Bold- )- }- }-}--@Composable-fun InfoBox(title: String, content: @Composable () -> Unit) {- Surface(- modifier = Modifier.size(width = 150.dp, height = 120.dp),- shape = RoundedCornerShape(12.dp),- ) {- Column(- modifier = Modifier.padding(8.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.SpaceAround- ) {- Text(text = title, fontSize = 16.sp)- content()- }- }-}--@Composable-fun GameBoard(- levelData: LevelData,- onLevelChanged: (LevelData) -> Unit,- onLevelWon: () -> Unit,- isLevelWon: Boolean,- modifier: Modifier = Modifier-) {- BoxWithConstraints(modifier = modifier, contentAlignment = Alignment.Center) {- val boardSize = minOf(maxWidth, maxHeight)- val cellWidth = boardSize / levelData.dimension.width- val cellHeight = boardSize / levelData.dimension.height-- // scale values based on the level's dimensions for consistent visuals- val scaling = boardSize / minOf(levelData.dimension.width, levelData.dimension.height) / 100-- // make sure the exit can cover the whole main block- val exitWidthMult = 1 + levelData.blocks[0].dimension.width-- Box {- Box(- Modifier- .size(cellWidth * exitWidthMult + 1.dp, cellHeight)- .offset(boardSize - 1.dp, cellHeight * levelData.exit.y)- .background(MaterialTheme.colorScheme.primary)- )- Box(- Modifier- .size(cellWidth * exitWidthMult, cellHeight)- .offset(boardSize, cellHeight * levelData.exit.y)- .zIndex(1f)- .background(- brush = Brush.horizontalGradient(- colorStops = arrayOf(- 0f to Color.Transparent,- 1f / exitWidthMult to MaterialTheme.colorScheme.background- )- )- )- )-- Box(- Modifier- .size(boardSize)- .background(MaterialTheme.colorScheme.primary, RoundedCornerShape(scaling * 12))- ) {-- levelData.blocks.forEachIndexed { index, block ->- val isMainBlock = index == 0- val color = when {- isMainBlock -> MaterialTheme.colorScheme.tertiary- block.fixed -> MaterialTheme.colorScheme.secondaryContainer- else -> MaterialTheme.colorScheme.primaryContainer- }- val blockWidth = cellWidth * block.dimension.width- val blockHeight = cellHeight * block.dimension.height-- var offsetX by remember(block, levelData) { mutableStateOf(cellWidth * block.position.x) }- var offsetY by remember(block, levelData) { mutableStateOf(cellHeight * block.position.y) }-- val targetOffsetX = if (isMainBlock && isLevelWon) boardSize + cellWidth else offsetX- val currentOffsetX by animateDpAsState(- targetOffsetX,- tween(if (isMainBlock && isLevelWon) 600 else 0),- "blockOffset"- )-- var modifier = Modifier- .size(blockWidth, blockHeight)- .offset { IntOffset(currentOffsetX.roundToPx(), offsetY.roundToPx()) }- .padding(scaling * 4)- .background(color, shape = RoundedCornerShape(percent = 10))- - if (!block.fixed) {- modifier = modifier.blockDragGestures(- block = block,- levelData = levelData,- isLevelWon = isLevelWon,- cellWidth = cellWidth,- cellHeight = cellHeight,- isMainBlock = isMainBlock,- onLevelWon = onLevelWon,- onLevelChanged = onLevelChanged,- index = index,- offsetXProvider = { offsetX },- offsetYProvider = { offsetY },- offsetXUpdater = { offsetX = it },- offsetYUpdater = { offsetY = it }- )- }-- Box(modifier = modifier)- }- }- }- }-}+}\ No newline at end of file
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/data/DailyLevelGenerator.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/data/DailyLevelGenerator.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/data/DailyLevelGenerator.ktindex 8fca419952..8064b9fabb 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/data/DailyLevelGenerator.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/data/DailyLevelGenerator.kt@@ -1,6 +1,6 @@ package com.vayunmathur.games.unblockjam.data -import com.vayunmathur.games.unblockjam.util.RushHourSolver+import com.vayunmathur.games.unblockjam.domain.RushHourSolver import kotlin.random.Random /**
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/AppBackupAgent.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/AppBackupAgent.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/AppBackupAgent.ktdeleted file mode 100644index 6ef7bb7dc7..0000000000--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/AppBackupAgent.kt+++ /dev/null@@ -1,8 +0,0 @@-package com.vayunmathur.games.unblockjam.util--import com.vayunmathur.library.util.BaseBackupAgent--class AppBackupAgent : BaseBackupAgent() {- override val prefNames: List<String>- get() = listOf("level_stats", "daily_stats")-}
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/BlockDragGestures.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/BlockDragGestures.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/BlockDragGestures.ktdeleted file mode 100644index c1d0b58fea..0000000000--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/BlockDragGestures.kt+++ /dev/null@@ -1,133 +0,0 @@-package com.vayunmathur.games.unblockjam.util-import androidx.compose.foundation.gestures.detectDragGestures-import androidx.compose.ui.Modifier-import androidx.compose.ui.input.pointer.pointerInput-import androidx.compose.ui.unit.Dp-import androidx.compose.ui.unit.dp-import kotlin.math.roundToInt-import com.vayunmathur.games.unblockjam.data.Block-import com.vayunmathur.games.unblockjam.data.Coord-import com.vayunmathur.games.unblockjam.data.Dimension-import com.vayunmathur.games.unblockjam.data.LevelData--private fun findMovementRange(- block: Block,- otherBlocks: List<Block>,- levelData: LevelData,- isMainBlock: Boolean,- isHorizontal: Boolean-): IntRange {- fun isOccupied(x: Int, y: Int) = otherBlocks.any {- x in it.position.x until it.position.x + it.dimension.width &&- y in it.position.y until it.position.y + it.dimension.height- }-- val pos = if (isHorizontal) block.position.x else block.position.y- val size = if (isHorizontal) block.dimension.width else block.dimension.height- val boardLimit = if (isHorizontal) levelData.dimension.width else levelData.dimension.height- val perpPos = if (isHorizontal) block.position.y else block.position.x- val perpSize = if (isHorizontal) block.dimension.height else block.dimension.width-- fun isClearAt(primary: Int) = (perpPos until perpPos + perpSize).all { p ->- if (isHorizontal) !isOccupied(primary, p) else !isOccupied(p, primary)- }-- var min = pos- while (min > 0 && isClearAt(min - 1)) min---- var max = pos- while (max + size < boardLimit && isClearAt(max + size)) max++-- if (isHorizontal && isMainBlock && block.position.y == levelData.exit.y) {- val pathClear = (max + size until levelData.dimension.width).all { x ->- !isOccupied(x, block.position.y)- }- if (pathClear) max = levelData.exit.x- }-- return min..max-}--fun Modifier.blockDragGestures(- block: Block,- levelData: LevelData,- isLevelWon: Boolean,- cellWidth: Dp,- cellHeight: Dp,- isMainBlock: Boolean,- onLevelWon: () -> Unit,- onLevelChanged: (LevelData) -> Unit,- index: Int,- offsetXProvider: () -> Dp,- offsetYProvider: () -> Dp,- offsetXUpdater: (Dp) -> Unit,- offsetYUpdater: (Dp) -> Unit-): Modifier {- val isHorizontal = block.dimension.width > block.dimension.height- return pointerInput(block, levelData, isLevelWon) {- if (isLevelWon || block.fixed) return@pointerInput-- var minOffset = 0.dp- var maxOffset = 0.dp-- detectDragGestures(- onDragStart = {- val range = findMovementRange(block, levelData.blocks - block, levelData, isMainBlock, isHorizontal)- val cellSize = if (isHorizontal) cellWidth else cellHeight- minOffset = cellSize * range.first- maxOffset = cellSize * range.last- },- onDragEnd = {- val newX: Int- val newY: Int- if (isHorizontal) {- newX = (offsetXProvider() / cellWidth).roundToInt()- newY = block.position.y- } else {- newX = block.position.x- newY = (offsetYProvider() / cellHeight).roundToInt()- }-- val newBlock = block.copy(position = Coord(newX, newY))- when {- isMainBlock && block.position.y == levelData.exit.y && newX >= levelData.exit.x -> onLevelWon()- newBlock.position != block.position && isMoveValid(newBlock, levelData.blocks - block, levelData.dimension) -> {- val newBlocks = levelData.blocks.toMutableList()- newBlocks[index] = newBlock- onLevelChanged(levelData.copy(blocks = newBlocks, lastMovedBlockIndex = index))- }- else -> {- offsetXUpdater(cellWidth * block.position.x)- offsetYUpdater(cellHeight * block.position.y)- }- }- },- onDrag = { change, dragAmount ->- change.consume()- if (isHorizontal) {- val newOffsetX = (offsetXProvider() + dragAmount.x.toDp()).coerceIn(minOffset, maxOffset)- offsetXUpdater(newOffsetX)- if (isMainBlock && block.position.y == levelData.exit.y &&- (newOffsetX / cellWidth).roundToInt() + block.dimension.width - 1 >= levelData.exit.x) {- onLevelWon()- }- } else {- offsetYUpdater((offsetYProvider() + dragAmount.y.toDp()).coerceIn(minOffset, maxOffset))- }- }- )- }-}--fun isMoveValid(movedBlock: Block, otherBlocks: List<Block>, dimension: Dimension): Boolean {- if (movedBlock.position.x < 0 || movedBlock.position.y < 0) return false- if (movedBlock.position.x + movedBlock.dimension.width > dimension.width) return false- if (movedBlock.position.y + movedBlock.dimension.height > dimension.height) return false-- return otherBlocks.none { other ->- movedBlock.position.x < other.position.x + other.dimension.width &&- movedBlock.position.x + movedBlock.dimension.width > other.position.x &&- movedBlock.position.y < other.position.y + other.dimension.height &&- movedBlock.position.y + movedBlock.dimension.height > other.position.y- }-}
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/GameUiContract.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/GameUiContract.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/GameUiContract.ktdeleted file mode 100644index 8eb1c137a0..0000000000--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/GameUiContract.kt+++ /dev/null@@ -1,57 +0,0 @@-package com.vayunmathur.games.unblockjam.util--import com.vayunmathur.games.unblockjam.data.LevelData--/**- * The UI contract between [UnblockJamViewModel] and the game screen.- *- * The screen takes a state value plus an actions interface rather than the ViewModel itself,- * so it can be rendered by a `@Preview` — which is what the store listing images are- * generated from. It lives in `util` alongside the ViewModel so the dependency runs one way:- * the screen depends on this contract, and the ViewModel implements it.- */--/**- * Everything the game screen draws. [levelData] is the board as it currently stands, which- * is the loaded level's starting layout until the player moves something.- */-data class GameUiState(- val levelData: LevelData,- val levelIndex: Int = 0,- val maxLevelIndex: Int = 0,- val moves: Int = 0,- val bestScore: Int? = null,- val isCompleted: Boolean = false,- val isLevelWon: Boolean = false,- val canUndo: Boolean = false,-)--/** The pinned daily-challenge card above the pack list. Null while the day's pack is generating. */-data class DailyProgress(- /** Local epoch day the pack was generated for. */- val day: Long,- val completed: Int,- val total: Int,- val streak: Long,-)--/**- * Game screen callbacks. Every method has a no-op default so a preview can render a board- * without supplying behaviour — [Noop] is the whole implementation a preview needs.- */-interface GameActions {- fun onBlockMoved(newLevelData: LevelData) {}- fun onLevelWon() {}- fun onUndo() {}- fun onRestart() {}-- /**- * Jump to another puzzle in the same pack. Navigation, not game logic, so the ViewModel- * leaves this at its default and the binder supplies it.- */- fun onLevelChange(newIndex: Int) {}-- companion object {- val Noop: GameActions = object : GameActions {}- }-}
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/RushHourSolver.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/RushHourSolver.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/RushHourSolver.ktdeleted file mode 100644index 58fa8c1825..0000000000--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/RushHourSolver.kt+++ /dev/null@@ -1,236 +0,0 @@-package com.vayunmathur.games.unblockjam.util--import com.vayunmathur.games.unblockjam.data.Block-import com.vayunmathur.games.unblockjam.data.Coord-import com.vayunmathur.games.unblockjam.data.LevelData--/**- * Breadth-first search over board configurations.- *- * A move here is "slide one block any distance along its axis", which is exactly what the game- * counts: [UnblockJamViewModel.onBlockMoved] only extends the history when the dragged block- * changes, so a run of drags on one block collapses into a single move.- */-object RushHourSolver {-- /**- * Every configuration reachable from a level's starting layout, with each one's distance from- * a position the main block can drive out of.- *- * Sliding is reversible, so the graph is undirected and one sweep outwards from the winning- * positions gives the distance for every state at once.- */- class Exploration internal constructor(- private val board: Board,- private val states: LongArray,- val distanceToGoal: IntArray,- val startIndex: Int,- ) {- val stateCount: Int get() = states.size-- /** Moves needed to win from [stateIndex], counting the final drive-out. */- fun movesToWin(stateIndex: Int): Int = distanceToGoal[stateIndex] + 1-- /** Rebuilds a playable level whose starting layout is [stateIndex]. */- fun levelAt(stateIndex: Int, level: LevelData): LevelData =- level.copy(blocks = board.blocksFor(states[stateIndex], level.blocks))- }-- /** Null when the board is malformed, or when the search hits [maxStates]. */- fun explore(level: LevelData, maxStates: Int = 200_000): Exploration? {- val board = Board.of(level) ?: return null- val start = board.startState(level)-- val indexByState = HashMap<Long, Int>()- var states = LongArray(64)- var count = 0- fun add(state: Long): Boolean {- if (indexByState.putIfAbsent(state, count) != null) return false- if (count == states.size) states = states.copyOf(count * 2)- states[count++] = state- return true- }- add(start)-- // Enumerate the component the starting layout belongs to.- var cursor = 0- val successors = LongArray(MAX_SUCCESSORS)- while (cursor < count) {- if (count > maxStates) return null- val found = board.successors(states[cursor], successors)- for (i in 0 until found) add(successors[i])- cursor++- }-- states = states.copyOf(count)- val distance = IntArray(count) { UNREACHABLE }- val queue = ArrayDeque<Int>()- for (index in 0 until count) {- if (board.isGoal(states[index])) {- distance[index] = 0- queue.add(index)- }- }- while (queue.isNotEmpty()) {- val index = queue.removeFirst()- val found = board.successors(states[index], successors)- for (i in 0 until found) {- val neighbour = indexByState.getValue(successors[i])- if (distance[neighbour] == UNREACHABLE) {- distance[neighbour] = distance[index] + 1- queue.add(neighbour)- }- }- }- return Exploration(board, states, distance, startIndex = 0)- }-- /** Fewest moves that free the main block, or null if the board cannot be solved. */- fun optimalMoves(level: LevelData, maxStates: Int = 200_000): Int? {- val exploration = explore(level, maxStates) ?: return null- if (exploration.distanceToGoal[exploration.startIndex] == UNREACHABLE) return null- return exploration.movesToWin(exploration.startIndex)- }-- /**- * A board as bit-packed state plus per-block geometry. Only the coordinate along a block's own- * axis ever changes, so a state is [BITS_PER_BLOCK] bits per block packed into a Long.- */- internal class Board private constructor(- private val n: Int,- private val width: Int,- height: Int,- private val horizontal: BooleanArray,- private val fixed: BooleanArray,- private val length: IntArray,- private val cross: IntArray,- private val crossLength: IntArray,- private val limit: IntArray,- ) {- private val occupied = BooleanArray(width * height)-- private fun index(x: Int, y: Int) = y * width + x-- private fun positionOf(state: Long, i: Int) =- ((state ushr (i * BITS_PER_BLOCK)) and POSITION_MASK).toInt()-- private fun withPosition(state: Long, i: Int, position: Int): Long {- val shift = i * BITS_PER_BLOCK- return (state and (POSITION_MASK shl shift).inv()) or (position.toLong() shl shift)- }-- private fun fill(state: Long, value: Boolean) {- for (i in 0 until n) {- val primary = positionOf(state, i)- for (step in 0 until length[i]) {- for (c in 0 until crossLength[i]) {- if (horizontal[i]) occupied[index(primary + step, cross[i] + c)] = value- else occupied[index(cross[i] + c, primary + step)] = value- }- }- }- }-- /** The main block can drive out when nothing sits between it and the right edge. */- fun isGoal(state: Long): Boolean {- fill(state, true)- val clear = (positionOf(state, 0) + length[0] until width)- .none { occupied[index(it, cross[0])] }- fill(state, false)- return clear- }-- /** Writes every one-move successor into [out], returning how many there are. */- fun successors(state: Long, out: LongArray): Int {- fill(state, true)- var found = 0- for (i in 0 until n) {- if (fixed[i]) continue- for (direction in intArrayOf(-1, 1)) {- var pos = positionOf(state, i)- while (true) {- val entering = if (direction < 0) pos - 1 else pos + length[i]- if (entering < 0 || entering >= limit[i]) break- var blocked = false- for (c in 0 until crossLength[i]) {- blocked = if (horizontal[i]) occupied[index(entering, cross[i] + c)]- else occupied[index(cross[i] + c, entering)]- if (blocked) break- }- if (blocked) break- pos += direction- out[found++] = withPosition(state, i, pos)- }- }- }- fill(state, false)- return found- }-- fun startState(level: LevelData): Long {- var state = 0L- for (i in 0 until n) {- val block = level.blocks[i]- state = withPosition(- state, i, if (horizontal[i]) block.position.x else block.position.y- )- }- return state- }-- fun blocksFor(state: Long, template: List<Block>): List<Block> = template.mapIndexed { i, block ->- val primary = positionOf(state, i)- val position =- if (horizontal[i]) Coord(primary, cross[i]) else Coord(cross[i], primary)- block.copy(position = position)- }-- companion object {- fun of(level: LevelData): Board? {- val blocks = level.blocks- if (blocks.isEmpty()) return null- val main = blocks[0]- // The main block always slides out along the exit row; anything else is not a- // Rush Hour board.- if (main.dimension.width <= main.dimension.height) return null- if (main.position.y != level.exit.y) return null- // Bit-packing bound. The shipped pack tops out at 14 blocks on a 6x6.- if (blocks.size > MAX_BLOCKS) return null- if (level.dimension.width > MAX_EXTENT || level.dimension.height > MAX_EXTENT) return null-- val n = blocks.size- val horizontal = BooleanArray(n) {- blocks[it].dimension.width > blocks[it].dimension.height- }- return Board(- n = n,- width = level.dimension.width,- height = level.dimension.height,- horizontal = horizontal,- fixed = BooleanArray(n) { blocks[it].fixed },- length = IntArray(n) {- if (horizontal[it]) blocks[it].dimension.width else blocks[it].dimension.height- },- cross = IntArray(n) {- if (horizontal[it]) blocks[it].position.y else blocks[it].position.x- },- crossLength = IntArray(n) {- if (horizontal[it]) blocks[it].dimension.height else blocks[it].dimension.width- },- limit = IntArray(n) {- if (horizontal[it]) level.dimension.width else level.dimension.height- },- )- }- }- }-- private const val UNREACHABLE = -1- private const val BITS_PER_BLOCK = 4- private const val POSITION_MASK = 0xFL- private const val MAX_BLOCKS = 16- private const val MAX_EXTENT = 16-- /** Worst case: every block slides the full width of the board in both directions. */- private const val MAX_SUCCESSORS = MAX_BLOCKS * MAX_EXTENT-}
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/UnblockJamAchievementsManager.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/UnblockJamAchievementsManager.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/UnblockJamAchievementsManager.ktdeleted file mode 100644index d79d4e561f..0000000000--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/UnblockJamAchievementsManager.kt+++ /dev/null@@ -1,35 +0,0 @@-package com.vayunmathur.games.unblockjam.util--import android.content.Context-import com.vayunmathur.games.unblockjam.data.CompletedLevelsRepository-import com.vayunmathur.library.util.AchievementsManager-import com.vayunmathur.library.util.DailyChallengeStore-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.launch--class UnblockJamAchievementsManager(- context: Context,- json: String,- private val repository: CompletedLevelsRepository-) : AchievementsManager(context, json) {-- private val dailyStore = DailyChallengeStore(context, "unblockjam_daily")-- override fun checkExistingAchievements() {- val stats = repository.getLevelStats()- if (stats.isNotEmpty()) onAchievementUnlocked("first_level")- onProgressUpdated("level_50", stats.size)- onProgressUpdated("moves_1000", repository.getTotalMoves())- onProgressUpdated("undo_master", repository.getUndoCount())- onProgressUpdated("all_levels_pack_0", stats.size)-- CoroutineScope(Dispatchers.IO).launch {- val bestStreak = dailyStore.bestStreak()- if (bestStreak > 0) {- onProgressUpdated("daily_streak_7", bestStreak.toInt())- onProgressUpdated("daily_streak_30", bestStreak.toInt())- }- }- }-}
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/UnblockJamViewModel.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/UnblockJamViewModel.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/UnblockJamViewModel.ktdeleted file mode 100644index 2cb0b002af..0000000000--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/util/UnblockJamViewModel.kt+++ /dev/null@@ -1,293 +0,0 @@-package com.vayunmathur.games.unblockjam.util--import android.app.Application-import androidx.lifecycle.AndroidViewModel-import androidx.lifecycle.viewModelScope-import com.vayunmathur.games.unblockjam.data.CompletedLevelsRepository-import com.vayunmathur.games.unblockjam.data.DailyLevelGenerator-import com.vayunmathur.games.unblockjam.data.LevelData-import com.vayunmathur.games.unblockjam.data.LevelPack-import com.vayunmathur.library.util.LevelStats-import com.vayunmathur.library.util.AchievementsManager-import com.vayunmathur.library.util.DailyChallengeStore-import com.vayunmathur.library.util.LevelStatsRepository-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.SharingStarted-import kotlinx.coroutines.flow.StateFlow-import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.flow.combine-import kotlinx.coroutines.flow.stateIn-import kotlinx.coroutines.flow.update-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext--/**- * UI state for the active game screen.- *- * [currentLevelData] is null until [UnblockJamViewModel.loadLevel] has been- * called for the current ([packIndex], [levelIndex]).- */-data class UnblockJamUiState(- val packIndex: Int = -1,- val levelIndex: Int = -1,- val currentLevelData: LevelData? = null,- val history: List<LevelData> = emptyList(),- val isLevelWon: Boolean = false,-)--/**- * ViewModel for the UnblockJam game.- *- * Owns:- * - Current level data + move history + win state- * - Persistent level stats (best scores, total moves, undo count) via- * [CompletedLevelsRepository]- * - The [AchievementsManager] instance and existing-achievement check- *- * Composables keep only purely-visual state: the in-flight drag offsets,- * dialog visibility, and the slide-out animation for the main block when- * a level is won.- */-class UnblockJamViewModel(application: Application) : AndroidViewModel(application), GameActions {-- val repository: CompletedLevelsRepository = CompletedLevelsRepository(application)-- val achievementsManager: AchievementsManager = run {- val json = application.assets.open("achievements.json")- .bufferedReader().use { it.readText() }- UnblockJamAchievementsManager(application, json, repository)- }-- private val _uiState = MutableStateFlow(UnblockJamUiState())- val uiState: StateFlow<UnblockJamUiState> = _uiState.asStateFlow()-- private val _levelStats =- MutableStateFlow<Map<String, LevelStats>>(repository.getLevelStats())- val levelStats: StateFlow<Map<String, LevelStats>> = _levelStats.asStateFlow()-- // ---- Daily challenge ------ /**- * Daily scores live in their own prefs file, pruned to the current day. They must not land in- * [repository], whose map size feeds the `level_50` and `all_levels_pack_0` achievements —- * five new level IDs a day would inflate both.- */- private val dailyRepository = LevelStatsRepository(application, "daily_stats")-- private val dailyStore = DailyChallengeStore(application, "unblockjam_daily")-- private val _dailyDay = MutableStateFlow(dailyStore.todayEpochDay())- val dailyDay: StateFlow<Long> = _dailyDay.asStateFlow()-- private val _dailyPack = MutableStateFlow<LevelPack?>(null)- val dailyPack: StateFlow<LevelPack?> = _dailyPack.asStateFlow()-- private val _dailyStats = MutableStateFlow(dailyRepository.getLevelStats())- val dailyStats: StateFlow<Map<String, LevelStats>> = _dailyStats.asStateFlow()-- val dailyStreak: StateFlow<Long> = dailyStore.currentStreak- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0L)-- /** How many of today's daily levels are solved. Derived from the IDs, so it needs no pack. */- val dailyCompleted: StateFlow<Int> =- combine(_dailyDay, _dailyStats) { day, stats ->- (0 until DailyLevelGenerator.LEVELS_PER_DAY)- .count { stats.containsKey(DailyLevelGenerator.levelId(day, it)) }- }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)-- init {- viewModelScope.launch {- achievementsManager.checkExistingAchievements()- }- }-- /**- * Generates the day's pack off the main thread. Solving every candidate is expensive, so this- * runs only when the player actually opens the daily — the pack-list card derives its progress- * from the level IDs alone.- */- fun refreshDaily() {- viewModelScope.launch(Dispatchers.Default) {- val today = dailyStore.todayEpochDay()- if (_dailyDay.value == today && _dailyPack.value != null) return@launch- _dailyDay.value = today- withContext(Dispatchers.IO) {- // Only today's pack is ever playable, so yesterday's scores are dead weight.- dailyRepository.retainOnly(todayLevelIds(today))- _dailyStats.value = dailyRepository.getLevelStats()- }- _dailyPack.value = DailyLevelGenerator.packFor(today)- }- }-- private fun todayLevelIds(day: Long): Set<String> =- (0 until DailyLevelGenerator.LEVELS_PER_DAY)- .mapTo(mutableSetOf()) { DailyLevelGenerator.levelId(day, it) }-- /** Resolves a pack index to its levels, covering both the shipped packs and the daily pack. */- private fun levelsFor(packIndex: Int): List<LevelData>? = when (packIndex) {- DAILY_PACK_INDEX -> _dailyPack.value?.levels- in LevelPack.PACKS.indices -> LevelPack.PACKS[packIndex].levels- else -> null- }-- /**- * Loads the requested level if it differs from the currently-loaded one.- * Safe to call from a [androidx.compose.runtime.LaunchedEffect] keyed on- * ([packIndex], [levelIndex]).- */- fun loadLevel(packIndex: Int, levelIndex: Int) {- val current = _uiState.value- if (current.packIndex == packIndex &&- current.levelIndex == levelIndex &&- current.currentLevelData != null- ) return- val levelData = levelsFor(packIndex)?.getOrNull(levelIndex) ?: return- _uiState.value = UnblockJamUiState(- packIndex = packIndex,- levelIndex = levelIndex,- currentLevelData = levelData,- )- }-- /** Move count for the active attempt, including the winning move if applicable. */- fun getCurrentMoves(): Int {- val s = _uiState.value- val winningMoveIncrement =- if (s.isLevelWon && s.currentLevelData?.lastMovedBlockIndex != 0) 1 else 0- return s.history.size + winningMoveIncrement- }-- override fun onBlockMoved(newLevelData: LevelData) {- val s = _uiState.value- val current = s.currentLevelData ?: return- // Block moved back to its previous position — collapse with last history entry.- if (s.history.isNotEmpty() && s.history.last().blocks == newLevelData.blocks) {- _uiState.update {- it.copy(- currentLevelData = it.history.last(),- history = it.history.dropLast(1),- )- }- return- }- if (s.isLevelWon) return-- if (newLevelData.lastMovedBlockIndex != current.lastMovedBlockIndex) {- _uiState.update {- it.copy(- currentLevelData = newLevelData,- history = it.history + current,- )- }- viewModelScope.launch(Dispatchers.IO) {- repository.incrementTotalMoves()- achievementsManager.onProgressUpdated(- "moves_1000", repository.getTotalMoves(),- )- }- } else {- _uiState.update { it.copy(currentLevelData = newLevelData) }- }- }-- override fun onLevelWon() {- val s = _uiState.value- if (s.isLevelWon || s.packIndex == NO_PACK_INDEX) return- _uiState.update { it.copy(isLevelWon = true) }-- val level = s.currentLevelData ?: return- val moves = getCurrentMoves()-- if (s.packIndex == DAILY_PACK_INDEX) {- onDailyLevelWon(level, moves)- return- }-- val pack = LevelPack.PACKS[s.packIndex]- viewModelScope.launch {- withContext(Dispatchers.IO) {- repository.updateBestScore(level.id, moves)- }- val refreshed = withContext(Dispatchers.IO) { repository.getLevelStats() }- _levelStats.value = refreshed-- achievementsManager.onAchievementUnlocked("first_level")- achievementsManager.onProgressUpdated("level_50", refreshed.size)- if (moves <= level.optimalMoves) {- achievementsManager.onAchievementUnlocked("optimal_win")- }- if (s.packIndex == 0 && refreshed.size >= pack.levels.size) {- achievementsManager.onAchievementUnlocked("all_levels_pack_0")- }- }- }-- /** Daily wins record into the separate store, and extend the streak once the day is cleared. */- private fun onDailyLevelWon(level: LevelData, moves: Int) {- val day = _dailyDay.value- viewModelScope.launch {- val refreshed = withContext(Dispatchers.IO) {- dailyRepository.updateBestScore(level.id, moves)- dailyRepository.getLevelStats()- }- _dailyStats.value = refreshed-- achievementsManager.onAchievementUnlocked("first_daily")- if (moves <= level.optimalMoves) {- achievementsManager.onAchievementUnlocked("optimal_win")- }-- val dayComplete = (0 until DailyLevelGenerator.LEVELS_PER_DAY)- .all { refreshed.containsKey(DailyLevelGenerator.levelId(day, it)) }- if (dayComplete) {- val streak = dailyStore.recordDayCompleted(day)- achievementsManager.onProgressUpdated("daily_streak_7", streak.best.toInt())- achievementsManager.onProgressUpdated("daily_streak_30", streak.best.toInt())- }- }- }-- override fun onUndo() {- val s = _uiState.value- if (s.history.isEmpty() || s.isLevelWon) return- _uiState.update {- it.copy(- currentLevelData = it.history.last(),- history = it.history.dropLast(1),- )- }- viewModelScope.launch(Dispatchers.IO) {- repository.incrementUndoCount()- achievementsManager.onProgressUpdated(- "undo_master", repository.getUndoCount(),- )- }- }-- override fun onRestart() {- val s = _uiState.value- if (s.history.isEmpty() || s.isLevelWon || s.packIndex == NO_PACK_INDEX) return- val pristine = levelsFor(s.packIndex)?.getOrNull(s.levelIndex) ?: return- _uiState.update {- it.copy(- currentLevelData = pristine,- history = emptyList(),- isLevelWon = false,- )- }- }-- fun dismissAchievementNotification() {- achievementsManager.dismissNotification()- }-- companion object {- /** Sentinel [UnblockJamUiState.packIndex] for the date-generated daily pack. */- const val DAILY_PACK_INDEX = -2-- /** Sentinel [UnblockJamUiState.packIndex] for "no level loaded". */- private const val NO_PACK_INDEX = -1- }-}
games/unblockjam/src/screenshotTest/kotlin/com/vayunmathur/games/unblockjam/MetadataPreviews.kt
diff --git a/games/unblockjam/src/screenshotTest/kotlin/com/vayunmathur/games/unblockjam/MetadataPreviews.kt b/games/unblockjam/src/screenshotTest/kotlin/com/vayunmathur/games/unblockjam/MetadataPreviews.ktindex 75e202fd0b..37bdedfcdd 100644--- a/games/unblockjam/src/screenshotTest/kotlin/com/vayunmathur/games/unblockjam/MetadataPreviews.kt+++ b/games/unblockjam/src/screenshotTest/kotlin/com/vayunmathur/games/unblockjam/MetadataPreviews.kt@@ -10,8 +10,8 @@ import com.vayunmathur.games.unblockjam.data.LevelData import com.vayunmathur.games.unblockjam.data.LevelPack import com.vayunmathur.games.unblockjam.data.PackColorScheme import com.vayunmathur.games.unblockjam.ui.UnblockJamTheme-import com.vayunmathur.games.unblockjam.util.GameActions-import com.vayunmathur.games.unblockjam.util.GameUiState+import com.vayunmathur.games.unblockjam.platform.GameActions+import com.vayunmathur.games.unblockjam.platform.GameUiState import com.vayunmathur.library.util.LevelStats /** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/DailyLevelGeneratorTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/DailyLevelGeneratorTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/DailyLevelGeneratorTest.ktindex ea35ade9a8..881779f899 100644--- a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/DailyLevelGeneratorTest.kt+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/DailyLevelGeneratorTest.kt@@ -1,6 +1,6 @@ package com.vayunmathur.games.unblockjam.data -import com.vayunmathur.games.unblockjam.util.RushHourSolver+import com.vayunmathur.games.unblockjam.domain.RushHourSolver import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/util/RushHourSolverTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/util/RushHourSolverTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/util/RushHourSolverTest.ktdeleted file mode 100644index dfbfa7b036..0000000000--- a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/util/RushHourSolverTest.kt+++ /dev/null@@ -1,48 +0,0 @@-package com.vayunmathur.games.unblockjam.util--import com.vayunmathur.games.unblockjam.data.LevelData-import com.vayunmathur.games.unblockjam.data.packFromJson-import java.io.File-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertNotNull-import kotlin.test.assertTrue--/**- * The solver decides the star threshold for every generated daily, so it is checked against the- * shipped pack, whose optimal move counts were computed independently by the original authoring- * pipeline.- */-class RushHourSolverTest {-- private val levels: List<LevelData> by lazy {- val candidates = listOf(- "src/main/assets/original_pack.json",- "games/unblockjam/src/main/assets/original_pack.json",- )- val file = candidates.map(::File).firstOrNull { it.exists() }- assertNotNull(file, "original_pack.json not found from ${File(".").absolutePath}")- packFromJson(file.readText()).levels- }-- @Test- fun matchesShippedOptimalMoves() {- // Every 7th level, so the test covers the whole difficulty range without solving all 250.- val sample = levels.filterIndexed { index, _ -> index % 7 == 0 }- assertTrue(sample.size > 20, "expected a meaningful sample, got ${sample.size}")- for (level in sample) {- assertEquals(- level.optimalMoves,- RushHourSolver.optimalMoves(level),- "level ${level.id}"- )- }- }-- @Test- fun everySampledLevelIsSolvable() {- for (level in levels.take(25)) {- assertNotNull(RushHourSolver.optimalMoves(level), "level ${level.id} unsolvable")- }- }-}
translate/src/main/java/com/vayunmathur/translate/data/TranslateSettings.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/TranslateSettings.kt b/translate/src/main/java/com/vayunmathur/translate/data/TranslateSettings.ktsimilarity index 100%rename from translate/src/main/java/com/vayunmathur/translate/util/TranslateSettings.ktrename to translate/src/main/java/com/vayunmathur/translate/data/TranslateSettings.kt
translate/src/main/java/com/vayunmathur/translate/domain/Languages.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/Languages.kt b/translate/src/main/java/com/vayunmathur/translate/domain/Languages.ktsimilarity index 100%rename from translate/src/main/java/com/vayunmathur/translate/util/Languages.ktrename to translate/src/main/java/com/vayunmathur/translate/domain/Languages.kt
translate/src/main/java/com/vayunmathur/translate/domain/TranslationEngine.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/TranslationEngine.kt b/translate/src/main/java/com/vayunmathur/translate/domain/TranslationEngine.ktsimilarity index 100%rename from translate/src/main/java/com/vayunmathur/translate/util/TranslationEngine.ktrename to translate/src/main/java/com/vayunmathur/translate/domain/TranslationEngine.kt
translate/src/main/java/com/vayunmathur/translate/platform/Small100Model.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/Small100Model.kt b/translate/src/main/java/com/vayunmathur/translate/platform/Small100Model.ktsimilarity index 100%rename from translate/src/main/java/com/vayunmathur/translate/util/Small100Model.ktrename to translate/src/main/java/com/vayunmathur/translate/platform/Small100Model.kt
translate/src/main/java/com/vayunmathur/translate/platform/Small100Translator.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/Small100Translator.kt b/translate/src/main/java/com/vayunmathur/translate/platform/Small100Translator.ktsimilarity index 100%rename from translate/src/main/java/com/vayunmathur/translate/util/Small100Translator.ktrename to translate/src/main/java/com/vayunmathur/translate/platform/Small100Translator.kt