Modern Apps git

← Modern-Apps.git

pipes: add a daily challenge pack of five date-seeded levels

Commit
e848d8477dab93cbd6a7b7b22dbbb94254896417
Author
Vayun Mathur <[email protected]>
When
2026-08-05 21:16 UTC (4 months ago)
Parents
143ade4

Diff

games/pipes/src/main/assets/achievements.json
diff --git a/games/pipes/src/main/assets/achievements.json b/games/pipes/src/main/assets/achievements.jsonindex 4c3cee6fd9..606a800bbf 100644--- a/games/pipes/src/main/assets/achievements.json+++ b/games/pipes/src/main/assets/achievements.json@@ -31,5 +31,22 @@     "name": "5×5 Champion",     "description": "Complete all levels in the 5×5 pack.",     "targetProgress": 30+  },+  {+    "id": "first_daily",+    "name": "Daily Habit",+    "description": "Complete a daily challenge level."+  },+  {+    "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/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.ktindex 4f9a48370c..4125ace55b 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.kt@@ -29,6 +29,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@@ -50,10 +51,12 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.games.pipes.data.DailyLevels import com.vayunmathur.games.pipes.data.LevelPack import com.vayunmathur.games.pipes.ui.GameBoard import com.vayunmathur.games.pipes.ui.PipesTheme import com.vayunmathur.games.pipes.util.AppBackupAgent+import com.vayunmathur.games.pipes.util.DailyProgress import com.vayunmathur.games.pipes.util.GameBoardUiState import com.vayunmathur.games.pipes.util.PackProgress import com.vayunmathur.games.pipes.util.PipesActions@@ -72,6 +75,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() { @@ -99,6 +105,12 @@ 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 @@ -126,6 +138,12 @@ fun Navigation(viewModel: PipesViewModel) {             entry<Route.Game> {                 GameScreen(backStack, viewModel, it.packIndex, it.levelIndex)             }+            entry<Route.DailySelector> {+                DailyLevelScreen(backStack, viewModel)+            }+            entry<Route.DailyGame> {+                GameScreen(backStack, viewModel, PipesViewModel.DAILY_PACK_INDEX, it.levelIndex)+            }             entry<Route.GameCenter> {                 GameCenterScreen(                     backupAgent = AppBackupAgent(),@@ -150,7 +168,17 @@ fun Navigation(viewModel: PipesViewModel) { @Composable fun PackScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, onOpenGameCenter: () -> Unit) {     val levelStats by viewModel.levelStats.collectAsState()+    val dailyCompleted by viewModel.dailyCompleted.collectAsState()+    val dailyDay by viewModel.dailyDay.collectAsState()+    val dailyStreak by viewModel.dailyStreak.collectAsState()+     PackListScreen(+        daily = DailyProgress(+            day = dailyDay,+            completed = dailyCompleted,+            total = DailyLevels.LEVELS_PER_DAY,+            streak = dailyStreak,+        ),         packs = LevelPack.PACKS.map { pack ->             PackProgress(                 name = pack.name,@@ -159,6 +187,7 @@ fun PackScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, onOpen                 total = pack.levels.size,             )         },+        onOpenDaily = { backStack.add(Route.DailySelector) },         onOpenPack = { backStack.add(Route.LevelSelector(it)) },         onOpenSettings = { backStack.add(Route.Settings) },         onOpenGameCenter = onOpenGameCenter,@@ -177,6 +206,8 @@ fun PackListScreen(     onOpenPack: (Int) -> Unit,     onOpenSettings: () -> Unit,     onOpenGameCenter: () -> Unit,+    daily: DailyProgress? = null,+    onOpenDaily: () -> Unit = {}, ) {     Scaffold(topBar = {         TopAppBar(@@ -196,6 +227,7 @@ fun PackListScreen(             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(packs) { index, pack ->                 Card(                     Modifier.clickable { onOpenPack(index) },@@ -230,6 +262,105 @@ fun PackListScreen(     } } +@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(+                    formatEpochDay(daily.day),+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f)+                )+            }+            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+                )+            }+        }+    }+}++private fun formatEpochDay(day: Long): String = LocalDate.ofEpochDay(day)+    .format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))++/** The 5 levels of today's daily pack, reusing the badge logic of the pack level grid. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DailyLevelScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel) {+    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() }+    Scaffold(topBar = {+        TopAppBar(+            { Text(stringResource(R.string.daily_challenge)) },+            navigationIcon = { IconNavigation(backStack) }+        )+    }) { paddingValues ->+        val levels = dailyPack?.levels+        if (levels == null) {+            Box(Modifier.fillMaxSize().padding(paddingValues), Alignment.Center) {+                CircularProgressIndicator()+            }+            return@Scaffold+        }+        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(levels) { index, levelData ->+                Card(+                    Modifier+                        .fillMaxWidth()+                        .clickable { backStack.add(Route.DailyGame(index)) },+                    colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface)+                ) {+                    Box(Modifier.fillMaxSize().padding(8.dp)) {+                        Text("${index + 1}", Modifier.align(Alignment.Center))+                        val levelStat = dailyStats[levelData.id]+                        Box(+                            Modifier+                                .size(20.dp)+                                .align(Alignment.CenterEnd),+                            Alignment.Center+                        ) {+                            when {+                                levelStat == null -> return@Box+                                levelStat.bestScore <= levelData.optimalMoves -> IconStar()+                                else -> IconCheck()+                            }+                        }+                    }+                }+            }+        }+    }+}+ @OptIn(ExperimentalMaterial3Api::class) @Composable fun LevelScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, packIndex: Int) {@@ -288,25 +419,39 @@ fun LevelScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, packI /** Binds [PipesViewModel] to the stateless [GameBoardScreen] and loads the level. */ @Composable fun GameScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, 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 colorblind by viewModel.colorblind.collectAsState() -    LaunchedEffect(packIndex, levelIndex) {+    val isDaily = packIndex == PipesViewModel.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 levelData = levels?.getOrNull(levelIndex)+    if (levels == null || levelData == null) {+        Box(Modifier.fillMaxSize(), Alignment.Center) { CircularProgressIndicator() }+        return+    }+     val isReady = uiState.packIndex == packIndex &&             uiState.levelIndex == levelIndex &&             uiState.levelData != null-    val currentLevelStats = pack.levels.getOrNull(levelIndex)?.id?.let { levelStats[it] }+    val currentLevelStats = levelStats[levelData.id]      GameBoardScreen(         state = GameBoardUiState(-            levelData = if (isReady) uiState.levelData!! else pack.levels[levelIndex],+            levelData = if (isReady) uiState.levelData!! else levelData,             levelIndex = levelIndex,-            maxLevelIndex = pack.levels.lastIndex,+            maxLevelIndex = levels.lastIndex,             gameState = if (isReady) uiState.gameState else PipesGameState(),             activeColor = if (isReady) uiState.activeColor else null,             activePath = if (isReady) uiState.activePath else emptyList(),@@ -320,7 +465,10 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, packIn         actions = viewModel,         onBack = { backStack.pop() },         onLevelChange = { newIndex ->-            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)+            )         },     ) }
games/pipes/src/main/java/com/vayunmathur/games/pipes/data/DailyLevels.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/DailyLevels.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/DailyLevels.ktnew file mode 100644index 0000000000..e44bba4c69--- /dev/null+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/DailyLevels.kt@@ -0,0 +1,55 @@+package com.vayunmathur.games.pipes.data++/**+ * 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 without any server or shipped asset.+ *+ * Unlike the shipped packs these are not verified to have a unique solution — the ZDD solver the+ * asset pipeline uses has no Kotlin equivalent — so some dailies admit more than one layout.+ */+object DailyLevels {++    const val LEVELS_PER_DAY = 5++    /**+     * Board size and early-stop probability per level. A lower early stop yields fewer, longer+     * flows, which is the harder puzzle — so difficulty ramps on board size and flow length+     * together. The flow count itself falls out of the carve.+     */+    private val RAMP = listOf(+        6 to 0.10f,+        7 to 0.05f,+        8 to 0.0f,+        9 to 0.0f,+        10 to 0.0f,+    )++    fun levelId(day: Long, index: Int) = "daily_${day}_$index"++    /** Null only if generation somehow fails for a level, in which case the day has no daily. */+    fun packFor(day: Long): LevelPack? {+        val levels = RAMP.mapIndexedNotNull { index, (size, earlyStop) ->+            val cells = LevelGenerator.rectangularCells(size, size)+            val adjacency = computeAdjacency(cells)+            val baseSeed = SEED_OFFSET + day * 100 + index+            // generateLevel can fail outright for a given seed; bump it until a board comes back.+            (0 until MAX_SEED_BUMPS).firstNotNullOfOrNull { bump ->+                LevelGenerator.generateLevel(+                    cells = cells,+                    adjacency = adjacency,+                    maxFlows = LevelGenerator.flowCeiling(cells),+                    seed = baseSeed + bump * SEED_BUMP,+                    id = levelId(day, index),+                    earlyStopProb = earlyStop+                )+            }+        }+        return if (levels.size == RAMP.size) {+            LevelPack(name = "daily_$day", shape = "square", levels = levels)+        } else null+    }++    private const val SEED_OFFSET = 500_000_000L+    private const val SEED_BUMP = 1_000_000L+    private const val MAX_SEED_BUMPS = 40+}
games/pipes/src/main/java/com/vayunmathur/games/pipes/util/AppBackupAgent.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/AppBackupAgent.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/AppBackupAgent.ktindex 9cffcd1124..47351bf493 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/AppBackupAgent.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/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/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesAchievementsManager.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesAchievementsManager.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesAchievementsManager.ktindex 19622cfda0..47421e01cd 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesAchievementsManager.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesAchievementsManager.kt@@ -3,12 +3,19 @@ package com.vayunmathur.games.pipes.util import android.content.Context import com.vayunmathur.games.pipes.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 PipesAchievementsManager(     context: Context,     json: String,     private val repository: CompletedLevelsRepository ) : AchievementsManager(context, json) {++    private val dailyStore = DailyChallengeStore(context, "pipes_daily")+     override fun checkExistingAchievements() {         val stats = repository.getLevelStats()         if (stats.isNotEmpty()) {@@ -17,5 +24,13 @@ class PipesAchievementsManager(         }         onProgressUpdated("level_50", stats.size)         onProgressUpdated("pipes_1000", repository.getTotalPipesPlaced())++        CoroutineScope(Dispatchers.IO).launch {+            val bestStreak = dailyStore.bestStreak()+            if (bestStreak > 0) {+                onProgressUpdated("daily_streak_7", bestStreak.toInt())+                onProgressUpdated("daily_streak_30", bestStreak.toInt())+            }+        }     } }
games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesUiContract.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesUiContract.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesUiContract.ktindex 76142d4170..6836acd823 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesUiContract.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesUiContract.kt@@ -12,8 +12,7 @@ import com.vayunmathur.games.pipes.data.LevelData  * runs one way: the screens depend on `util`, and the ViewModel implements [PipesActions].  */ -/**- * One row of the pack selector. Flattened to plain counts so the screen needs neither the+/** One row of the pack selector. Flattened to plain counts so the screen needs neither the  * asset-loaded packs nor the stats repository.  */ data class PackProgress(@@ -23,6 +22,15 @@ data class PackProgress(     val total: Int, ) +/** 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,+)+ /** Everything the game screen draws for one level. */ data class GameBoardUiState(     val levelData: LevelData,
games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.ktindex dc8013ea1e..b542ad35d9 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.kt@@ -5,16 +5,20 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.games.pipes.data.CellPos import com.vayunmathur.games.pipes.data.CompletedLevelsRepository+import com.vayunmathur.games.pipes.data.DailyLevels import com.vayunmathur.games.pipes.data.LevelData import com.vayunmathur.games.pipes.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.DataStoreUtils+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@@ -56,6 +60,36 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),      private val ds = DataStoreUtils.getInstance(application) +    // ---- 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` achievement and the pack-completion+     * checks — five new level IDs a day would inflate both.+     */+    private val dailyRepository = LevelStatsRepository(application, "daily_stats")++    private val dailyStore = DailyChallengeStore(application, "pipes_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 DailyLevels.LEVELS_PER_DAY)+                .count { stats.containsKey(DailyLevels.levelId(day, it)) }+        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)+     val colorblind: StateFlow<Boolean> = ds.booleanFlow(KEY_COLORBLIND)         .stateIn(viewModelScope, SharingStarted.Eagerly, ds.getBoolean(KEY_COLORBLIND, false)) @@ -69,14 +103,43 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),         }     } +    /**+     * Generates the day's pack off the main thread — deliberately not in `LevelPack.init()`, which+     * runs synchronously in `onCreate`. Only runs when the player 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 = DailyLevels.packFor(today)+        }+    }++    private fun todayLevelIds(day: Long): Set<String> =+        (0 until DailyLevels.LEVELS_PER_DAY)+            .mapTo(mutableSetOf()) { DailyLevels.levelId(day, it) }++    /** Resolves a pack index to its levels, covering both 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+    }+     fun loadLevel(packIndex: Int, levelIndex: Int) {         val current = _uiState.value         if (current.packIndex == packIndex &&             current.levelIndex == levelIndex &&             current.levelData != null         ) return-        val pack = LevelPack.PACKS[packIndex]-        val levelData = pack.levels[levelIndex]+        val levelData = levelsFor(packIndex)?.getOrNull(levelIndex) ?: return         _uiState.value = PipesUiState(             packIndex = packIndex,             levelIndex = levelIndex,@@ -246,13 +309,17 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),      private 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.levelData ?: return         val moves = getCurrentMoves() +        if (s.packIndex == DAILY_PACK_INDEX) {+            onDailyLevelWon(level.id, moves, level.optimalMoves)+            return+        }+         viewModelScope.launch {             val refreshed = withContext(Dispatchers.IO) {                 repository.updateBestScore(level.id, moves)@@ -274,6 +341,32 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),         }     } +    /** Daily wins record into the separate store, and extend the streak once the day is cleared. */+    private fun onDailyLevelWon(levelId: String, moves: Int, optimalMoves: Int) {+        val day = _dailyDay.value+        viewModelScope.launch {+            val refreshed = withContext(Dispatchers.IO) {+                dailyRepository.updateBestScore(levelId, moves)+                dailyRepository.getLevelStats()+            }+            _dailyStats.value = refreshed++            achievementsManager.onAchievementUnlocked("first_flow")+            achievementsManager.onAchievementUnlocked("first_daily")+            if (moves <= optimalMoves) {+                achievementsManager.onAchievementUnlocked("optimal_win")+            }++            val dayComplete = (0 until DailyLevels.LEVELS_PER_DAY)+                .all { refreshed.containsKey(DailyLevels.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())+            }+        }+    }+     fun getCurrentMoves(): Int = _uiState.value.history.size      override fun onUndo() {@@ -291,7 +384,7 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),      override fun onRestart() {         val s = _uiState.value-        if (s.history.isEmpty() || s.isLevelWon || s.packIndex < 0) return+        if (s.history.isEmpty() || s.isLevelWon || s.packIndex == NO_PACK_INDEX) return         _uiState.update {             it.copy(                 gameState = PipesGameState(),@@ -309,5 +402,11 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),      companion object {         const val KEY_COLORBLIND = "pipes_colorblind"++        /** Sentinel [PipesUiState.packIndex] for the date-generated daily pack. */+        const val DAILY_PACK_INDEX = -2++        /** Sentinel [PipesUiState.packIndex] for "no level loaded". */+        private const val NO_PACK_INDEX = -1     } }
games/pipes/src/main/res/values/strings.xml
diff --git a/games/pipes/src/main/res/values/strings.xml b/games/pipes/src/main/res/values/strings.xmlindex 0498cd3973..ce744b1ddc 100644--- a/games/pipes/src/main/res/values/strings.xml+++ b/games/pipes/src/main/res/values/strings.xml@@ -21,4 +21,8 @@     <string name="colorblind_mode">Colorblind mode</string>     <!-- SettingsScreen: Subtitle explaining colorblind mode labels each flow with letter A-Z. Sentence -->     <string name="colorblind_mode_desc">Label each flow with a letter (A–Z)</string>+    <!-- PackScreen / DailyLevelScreen: 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/pipes/src/test/java/com/vayunmathur/games/pipes/data/DailyLevelsTest.kt
diff --git a/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/DailyLevelsTest.kt b/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/DailyLevelsTest.ktnew file mode 100644index 0000000000..4811b74415--- /dev/null+++ b/games/pipes/src/test/java/com/vayunmathur/games/pipes/data/DailyLevelsTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.games.pipes.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class DailyLevelsTest {++    private val day = 20_300L++    @Test+    fun sameDayGeneratesIdenticalPack() {+        val first = assertNotNull(DailyLevels.packFor(day))+        val second = assertNotNull(DailyLevels.packFor(day))+        assertEquals(first, second)+    }++    @Test+    fun consecutiveDaysDiffer() {+        val today = assertNotNull(DailyLevels.packFor(day))+        val tomorrow = assertNotNull(DailyLevels.packFor(day + 1))+        assertTrue(today.levels.map { it.endpoints } != tomorrow.levels.map { it.endpoints })+    }++    @Test+    fun packHasFiveLevelsOfRisingSize() {+        val pack = assertNotNull(DailyLevels.packFor(day))+        assertEquals(DailyLevels.LEVELS_PER_DAY, pack.levels.size)+        var previousCells = 0+        pack.levels.forEachIndexed { index, level ->+            assertEquals(DailyLevels.levelId(day, index), level.id)+            assertTrue(level.cells.size > previousCells, "level $index is not bigger than the last")+            previousCells = level.cells.size+        }+    }++    @Test+    fun optimalMovesIsTheEndpointCount() {+        val pack = assertNotNull(DailyLevels.packFor(day))+        // cells.size here would make `bestScore <= optimalMoves` trivially true and hand out a+        // star plus the optimal_win achievement for every daily win.+        for (level in pack.levels) {+            assertEquals(level.endpoints.size, level.optimalMoves, level.id)+        }+    }++    @Test+    fun endpointsAreDistinctCellsOnTheBoard() {+        val pack = assertNotNull(DailyLevels.packFor(day))+        for (level in pack.levels) {+            val endpointCells = level.endpoints.flatMap { it.cells }+            assertEquals(endpointCells.size, endpointCells.toSet().size, "${level.id} reuses a cell")+            assertTrue(endpointCells.all { it in level.cells }, "${level.id} has an off-board endpoint")+            assertTrue(level.endpoints.all { it.cells.size == 2 }, "${level.id} has a malformed pair")+        }+    }++    @Test+    fun flowsAreLongEnoughToBeInteresting() {+        // The short-pair filter and the flow ceiling both exist to stop a board becoming a swarm+        // of tiny pairs. Note endpoints can still land next to each other on a U-shaped flow —+        // the shipped packs contain a handful of those too.+        val pack = assertNotNull(DailyLevels.packFor(day))+        for (level in pack.levels) {+            assertTrue(+                level.endpoints.size <= LevelGenerator.flowCeiling(level.cells),+                "${level.id} has ${level.endpoints.size} flows, over the ceiling"+            )+            val averageFlowLength = level.cells.size.toFloat() / level.endpoints.size+            assertTrue(averageFlowLength >= 4f, "${level.id} averages $averageFlowLength cells per flow")+        }+    }+}