Modern Apps git

← Modern-Apps.git

unblockjam: add a daily challenge pack of five date-seeded puzzles

Commit
36419fabd5691d65b3f811089e4c5758d2c2ae55
Author
Vayun Mathur <[email protected]>
When
2026-08-05 21:16 UTC (4 months ago)
Parents
4129d73

Diff

games/unblockjam/src/main/assets/achievements.json
diff --git a/games/unblockjam/src/main/assets/achievements.json b/games/unblockjam/src/main/assets/achievements.jsonindex de829e0da2..b32e06e1e1 100644--- a/games/unblockjam/src/main/assets/achievements.json+++ b/games/unblockjam/src/main/assets/achievements.json@@ -32,5 +32,22 @@     "name": "Unblock Pro",     "description": "Complete 50 unique levels.",     "targetProgress": 50+  },+  {+    "id": "first_daily",+    "name": "Daily Habit",+    "description": "Complete a daily challenge puzzle."+  },+  {+    "id": "daily_streak_7",+    "name": "Week Streak",+    "description": "Clear the daily pack 7 days in a row.",+    "targetProgress": 7+  },+  {+    "id": "daily_streak_30",+    "name": "Month Streak",+    "description": "Clear the daily pack 30 days in a row.",+    "targetProgress": 30   } ]
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 bf7791d206..2bd4f54c9a 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@@ -31,6 +31,7 @@ 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@@ -58,10 +59,12 @@ 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.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@@ -78,6 +81,9 @@ 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() { @@ -103,6 +109,10 @@ sealed interface Route: NavKey {     @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 } @@ -116,7 +126,7 @@ fun Navigation(viewModel: UnblockJamViewModel) {     Box(Modifier.fillMaxSize()) {         MainNavigation(backStack) {             entry<Route.PackSelector> {-                PackScreen(backStack, onOpenGameCenter = { backStack.add(Route.GameCenter) })+                PackPage(backStack, viewModel, onOpenGameCenter = { backStack.add(Route.GameCenter) })             }             entry<Route.LevelSelector> {                 val pack = LevelPack.PACKS[it.packIndex]@@ -130,6 +140,12 @@ fun Navigation(viewModel: UnblockJamViewModel) {                     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(),@@ -147,9 +163,36 @@ fun Navigation(viewModel: UnblockJamViewModel) {     } } +/** 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(backStack: NavBackStack<Route>, onOpenGameCenter: () -> Unit) {+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)) },@@ -165,12 +208,13 @@ fun PackScreen(backStack: NavBackStack<Route>, onOpenGameCenter: () -> Unit) {             contentPadding = paddingValues + PaddingValues(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 0.dp),             verticalArrangement = Arrangement.spacedBy(12.dp),         ) {-            itemsIndexed(LevelPack.PACKS) { index, pack ->+            daily?.let { item { DailyCard(it, onOpenDaily) } }+            itemsIndexed(packNames) { index, name ->                 Card(Modifier.clickable{-                    backStack.add(Route.LevelSelector(index))+                    onOpenPack(index)                 }, colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface)) {                     Box(Modifier.fillMaxWidth().padding(8.dp)) {-                        Text(pack.name, Modifier.align(Alignment.Center), style = MaterialTheme.typography.displayMedium)+                        Text(name, Modifier.align(Alignment.Center), style = MaterialTheme.typography.displayMedium)                     }                 }             }@@ -178,6 +222,61 @@ fun PackScreen(backStack: NavBackStack<Route>, onOpenGameCenter: () -> Unit) {     } } +@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) {@@ -199,10 +298,11 @@ fun LevelPage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel, pa fun LevelScreen(     pack: LevelPack,     levelStats: Map<String, LevelStats>,-    onOpenLevel: (Int) -> Unit+    onOpenLevel: (Int) -> Unit,+    title: String = stringResource(R.string.level_selector) ) {     Scaffold(topBar = {-        TopAppBar({Text(stringResource(R.string.level_selector))})+        TopAppBar({Text(title)})     }) { paddingValues ->         LazyVerticalGrid(             GridCells.Adaptive(88.dp),@@ -239,25 +339,42 @@ fun LevelScreen( /** Binds [UnblockJamViewModel] to the stateless [GameScreen]. */ @Composable fun GamePage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel, packIndex: Int, levelIndex: Int) {-    val pack = LevelPack.PACKS[packIndex]     val uiState by viewModel.uiState.collectAsState()-    val levelStats by viewModel.levelStats.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 -    LaunchedEffect(packIndex, levelIndex) {+    // 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 pack.levels[levelIndex]-    val currentLevelStats = pack.levels.getOrNull(levelIndex)?.id?.let { levelStats[it] }+    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, pack, packIndex) {+    val actions = remember(viewModel, backStack, packIndex, levels.lastIndex) {         object : GameActions by viewModel {             override fun onLevelChange(newIndex: Int) {-                backStack.setLast(Route.Game(packIndex, newIndex.coerceIn(0, pack.levels.lastIndex)))+                val clamped = newIndex.coerceIn(0, levels.lastIndex)+                backStack.setLast(+                    if (isDaily) Route.DailyGame(clamped) else Route.Game(packIndex, clamped)+                )             }         }     }@@ -266,7 +383,7 @@ fun GamePage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel, pac         state = GameUiState(             levelData = currentLevelData,             levelIndex = levelIndex,-            maxLevelIndex = pack.levels.lastIndex,+            maxLevelIndex = levels.lastIndex,             moves = if (isReady) viewModel.getCurrentMoves() else 0,             bestScore = currentLevelStats?.bestScore,             isCompleted = currentLevelStats != null,
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.ktnew file mode 100644index 0000000000..8fca419952--- /dev/null+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/data/DailyLevelGenerator.kt@@ -0,0 +1,154 @@+package com.vayunmathur.games.unblockjam.data++import com.vayunmathur.games.unblockjam.util.RushHourSolver+import kotlin.random.Random++/**+ * The five levels of a given day, generated from a seed derived purely from the epoch day, so+ * every player on that date gets exactly the same pack.+ *+ * Placing blocks at random gives an almost always trivial board, so the layout is only the+ * starting point: the whole state space for that set of pieces is explored, and the puzzle+ * actually shipped is the hardest configuration reachable within the day-index's difficulty band.+ * That also yields the exact `optimalMoves` the star threshold needs.+ *+ * Exploring a state space per candidate is not cheap — run this off the main thread.+ */+object DailyLevelGenerator {++    const val LEVELS_PER_DAY = 5++    private const val BOARD_SIZE = 6+    private const val MAIN_LENGTH = 2++    /** Preferred optimal-move band per level in the day, giving a difficulty ramp. */+    private val DIFFICULTY_BANDS = listOf(+        3..5,+        6..8,+        9..11,+        12..13,+        14..60,+    )++    /** How many blocks besides the main one to place, per level in the day. */+    private val BLOCK_COUNTS = listOf(7, 9, 11, 11, 11)++    fun levelId(day: Long, index: Int) = "daily_${day}_$index"++    /** Null only if every layout for a level was unsolvable, which should not happen in practice. */+    fun packFor(day: Long): LevelPack? {+        val levels = mutableListOf<LevelData>()+        for (index in 0 until LEVELS_PER_DAY) {+            val band = DIFFICULTY_BANDS[index]+            // Keep the ramp rising even when the previous level overshot its band.+            val floor = maxOf(band.first, (levels.lastOrNull()?.optimalMoves ?: 0) + 1)+            val level = levelFor(+                baseSeed = SEED_OFFSET + day * 100 + index,+                blockCount = BLOCK_COUNTS[index],+                band = floor..maxOf(band.last, floor),+                id = levelId(day, index)+            ) ?: return null+            levels.add(level)+        }+        return LevelPack(name = "daily_$day", levels = levels)+    }++    /**+     * Tries random piece sets until one can produce a puzzle inside [band]. Falls back to the+     * hardest puzzle seen across all attempts, so a day always gets its pack even when the band+     * turns out to be unreachable for the sets that came up.+     */+    private fun levelFor(baseSeed: Long, blockCount: Int, band: IntRange, id: String): LevelData? {+        var fallback: LevelData? = null+        for (attempt in 0 until MAX_ATTEMPTS) {+            val best = hardestUpTo(+                random = Random(baseSeed + attempt * SEED_BUMP),+                blockCount = blockCount,+                cap = band.last,+                id = id+            ) ?: continue+            if (best.optimalMoves in band) return best+            if (best.optimalMoves > (fallback?.optimalMoves ?: 1)) fallback = best+        }+        return fallback+    }++    /**+     * Lays out one random set of pieces and returns the hardest arrangement of them needing at+     * most [cap] moves, or null if the set cannot be solved at all.+     */+    private fun hardestUpTo(random: Random, blockCount: Int, cap: Int, id: String): LevelData? {+        val layout = randomLayout(random, blockCount, id) ?: return null+        val exploration = RushHourSolver.explore(layout, MAX_STATES) ?: return null++        var bestIndex = -1+        var bestMoves = 1+        exploration.distanceToGoal.forEachIndexed { index, distance ->+            if (distance < 0) return@forEachIndexed+            val moves = exploration.movesToWin(index)+            // A board solved before the player touches it is not a puzzle.+            if (moves > bestMoves && moves <= cap) {+                bestIndex = index+                bestMoves = moves+            }+        }+        if (bestIndex < 0) return null+        return exploration.levelAt(bestIndex, layout).copy(optimalMoves = bestMoves)+    }++    /** A random legal placement of the main block plus [blockCount] others. */+    private fun randomLayout(random: Random, blockCount: Int, id: String): LevelData? {+        val exitRow = random.nextInt(BOARD_SIZE)+        val blocks = mutableListOf(+            Block(+                position = Coord(random.nextInt(BOARD_SIZE - MAIN_LENGTH), exitRow),+                dimension = Dimension(MAIN_LENGTH, 1),+                fixed = false+            )+        )++        var placed = 0+        var tries = 0+        while (placed < blockCount && tries < PLACEMENT_TRIES) {+            tries+++            val horizontal = random.nextBoolean()+            val size = if (random.nextInt(3) == 0) 3 else 2+            val dim = if (horizontal) Dimension(size, 1) else Dimension(1, size)+            val position = Coord(+                random.nextInt(BOARD_SIZE - dim.width + 1),+                random.nextInt(BOARD_SIZE - dim.height + 1)+            )+            val block = Block(position, dim, fixed = false)+            if (overlapsAny(block, blocks)) continue+            // A horizontal block on the exit row can never be got out of the way, so the board+            // would be unsolvable for reasons that have nothing to do with the puzzle.+            if (horizontal && position.y == exitRow) continue+            blocks.add(block)+            placed+++        }+        if (placed < blockCount) return null++        return LevelData(+            id = id,+            dimension = Dimension(BOARD_SIZE, BOARD_SIZE),+            exit = Coord(BOARD_SIZE, exitRow),+            blocks = blocks,+            optimalMoves = 0+        )+    }++    private fun overlapsAny(block: Block, others: List<Block>): Boolean = others.any { other ->+        block.position.x < other.position.x + other.dimension.width &&+            block.position.x + block.dimension.width > other.position.x &&+            block.position.y < other.position.y + other.dimension.height &&+            block.position.y + block.dimension.height > other.position.y+    }++    private const val SEED_OFFSET = 900_000_000L+    private const val SEED_BUMP = 1_000_000L+    private const val MAX_ATTEMPTS = 40+    private const val PLACEMENT_TRIES = 200++    /** Comfortably above the ~25k states a 6x6 layout explores, so a runaway board is cut off. */+    private const val MAX_STATES = 80_000+}
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.ktindex 2ab24e9c48..6ef7bb7dc7 100644--- 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.kt@@ -4,5 +4,5 @@ import com.vayunmathur.library.util.BaseBackupAgent  class AppBackupAgent : BaseBackupAgent() {     override val prefNames: List<String>-        get() = listOf("level_stats")+        get() = listOf("level_stats", "daily_stats") }
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.ktindex e960d435d1..8eb1c137a0 100644--- 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.kt@@ -26,6 +26,15 @@ data class GameUiState(     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.
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.ktindex 8f788c5cad..d79d4e561f 100644--- 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.kt@@ -3,12 +3,19 @@ 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")@@ -16,5 +23,13 @@ class UnblockJamAchievementsManager(         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.ktindex 1b4a315752..2cb0b002af 100644--- 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.kt@@ -4,14 +4,20 @@ 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@@ -60,12 +66,72 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati         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@@ -77,11 +143,11 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati             current.levelIndex == levelIndex &&             current.currentLevelData != null         ) return-        val pack = LevelPack.PACKS[packIndex]+        val levelData = levelsFor(packIndex)?.getOrNull(levelIndex) ?: return         _uiState.value = UnblockJamUiState(             packIndex = packIndex,             levelIndex = levelIndex,-            currentLevelData = pack.levels[levelIndex],+            currentLevelData = levelData,         )     } @@ -128,13 +194,18 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati      override fun onLevelWon() {         val s = _uiState.value-        if (s.isLevelWon || s.packIndex < 0) return+        if (s.isLevelWon || s.packIndex == NO_PACK_INDEX) return         _uiState.update { it.copy(isLevelWon = true) } -        val pack = LevelPack.PACKS[s.packIndex]-        val level = pack.levels[s.levelIndex]+        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)@@ -153,6 +224,31 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati         }     } +    /** 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@@ -172,11 +268,11 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati      override fun onRestart() {         val s = _uiState.value-        if (s.history.isEmpty() || s.isLevelWon || s.packIndex < 0) return-        val pack = LevelPack.PACKS[s.packIndex]+        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 = pack.levels[it.levelIndex],+                currentLevelData = pristine,                 history = emptyList(),                 isLevelWon = false,             )@@ -186,4 +282,12 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati     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/main/res/values/strings.xml
diff --git a/games/unblockjam/src/main/res/values/strings.xml b/games/unblockjam/src/main/res/values/strings.xmlindex ea89da9bfb..9f62f79341 100644--- a/games/unblockjam/src/main/res/values/strings.xml+++ b/games/unblockjam/src/main/res/values/strings.xml@@ -17,4 +17,8 @@     <string name="completed">Completed</string>     <!-- Moves info: Title for move counter. Noun -->     <string name="moves">Moves</string>+    <!-- PackScreen / DailyLevelPage: Pinned card and screen title for the date-generated daily pack. Noun phrase -->+    <string name="daily_challenge">Daily Challenge</string>+    <!-- PackScreen daily card: Consecutive days the player has cleared the daily pack. %1$d = streak length e.g. 5. Noun phrase with number -->+    <string name="daily_streak"><xliff:g id="days" example="5">%1$d</xliff:g> day streak</string> </resources>
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.ktnew file mode 100644index 0000000000..ea35ade9a8--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/data/DailyLevelGeneratorTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.games.unblockjam.data++import com.vayunmathur.games.unblockjam.util.RushHourSolver+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class DailyLevelGeneratorTest {++    private val day = 20_300L++    @Test+    fun sameDayGeneratesIdenticalPack() {+        val first = assertNotNull(DailyLevelGenerator.packFor(day))+        val second = assertNotNull(DailyLevelGenerator.packFor(day))+        assertEquals(first, second)+    }++    @Test+    fun consecutiveDaysDiffer() {+        val today = assertNotNull(DailyLevelGenerator.packFor(day))+        val tomorrow = assertNotNull(DailyLevelGenerator.packFor(day + 1))+        assertTrue(today.levels.map { it.blocks } != tomorrow.levels.map { it.blocks })+    }++    @Test+    fun storedOptimalMovesMatchesTheSolver() {+        val pack = assertNotNull(DailyLevelGenerator.packFor(day))+        assertEquals(DailyLevelGenerator.LEVELS_PER_DAY, pack.levels.size)+        pack.levels.forEachIndexed { index, level ->+            assertEquals(DailyLevelGenerator.levelId(day, index), level.id)+            // The stored optimal is what the star badge compares against, so it has to be the+            // solver's answer for the board as shipped, not a placeholder.+            assertEquals(level.optimalMoves, RushHourSolver.optimalMoves(level), "level $index")+            assertTrue(level.optimalMoves > 1, "level $index is solved before the first move")+        }+    }++    @Test+    fun difficultyRises() {+        // Levels are picked from difficulty bands with a rising floor. The last level falls back+        // to the hardest layout found when its band is unreachable, so compare ends rather than+        // demanding every step is strictly harder.+        val pack = assertNotNull(DailyLevelGenerator.packFor(day))+        val moves = pack.levels.map { it.optimalMoves }+        assertTrue(moves.last() > moves.first(), "no ramp across $moves")+        assertTrue(moves[1] > moves[0] && moves[2] > moves[1], "no ramp across $moves")+    }++    @Test+    fun mainBlockSitsOnTheExitRow() {+        val pack = assertNotNull(DailyLevelGenerator.packFor(day))+        for (level in pack.levels) {+            assertEquals(level.exit.y, level.blocks[0].position.y)+            assertEquals(level.dimension.width, level.exit.x)+        }+    }+}