Modern Apps git

← Modern-Apps.git

wordmaker: add a daily challenge mode with one date-seeded puzzle

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

Diff

games/wordmaker/src/main/assets/achievements.json
diff --git a/games/wordmaker/src/main/assets/achievements.json b/games/wordmaker/src/main/assets/achievements.jsonindex 6ccadd1b83..57a53095c4 100644--- a/games/wordmaker/src/main/assets/achievements.json+++ b/games/wordmaker/src/main/assets/achievements.json@@ -38,5 +38,22 @@     "id": "long_word",     "name": "Lexicographer",     "description": "Find a word with 7 or more letters."+  },+  {+    "id": "first_daily",+    "name": "Daily Habit",+    "description": "Complete a daily challenge."+  },+  {+    "id": "daily_streak_7",+    "name": "Week Streak",+    "description": "Complete the daily challenge 7 days in a row.",+    "targetProgress": 7+  },+  {+    "id": "daily_streak_30",+    "name": "Month Streak",+    "description": "Complete the daily challenge 30 days in a row.",+    "targetProgress": 30   } ]\ No newline at end of file
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.ktindex d9b724113f..2a1988708e 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.kt@@ -260,8 +260,12 @@ fun WordGamePage(     val competitiveScore by viewModel.competitiveScore.collectAsState()     val competitiveLevelNumber by viewModel.competitiveLevelNumber.collectAsState()     val competitiveDeadline by viewModel.competitiveDeadline.collectAsState()+    val dailyDay by viewModel.dailyDay.collectAsState()+    val dailyStreak by viewModel.dailyStreak.collectAsState()+    val dailyBestStreak by viewModel.dailyBestStreak.collectAsState()      val isCompetitive = gameMode == GameMode.COMPETITIVE+    val isDaily = gameMode == GameMode.DAILY     val isWon = crosswordData.winsWith(foundWords)      LaunchedEffect(isWon) {@@ -270,6 +274,11 @@ fun WordGamePage(             viewModel.onCompetitiveWin()             return@LaunchedEffect         }+        if (isDaily) {+            viewModel.onDailyWin()+            achievementsManager.onAchievementUnlocked("first_daily")+            return@LaunchedEffect+        }         if (currentLevel == 1) achievementsManager.onAchievementUnlocked("level_1_done")         if (currentLevel == 861) achievementsManager.onAchievementUnlocked("manual_levels_done") @@ -279,6 +288,12 @@ fun WordGamePage(         achievementsManager.onProgressUpdated("level_500", currentLevel)     } +    LaunchedEffect(dailyBestStreak) {+        if (dailyBestStreak <= 0L) return@LaunchedEffect+        achievementsManager.onProgressUpdated("daily_streak_7", dailyBestStreak.toInt())+        achievementsManager.onProgressUpdated("daily_streak_30", dailyBestStreak.toInt())+    }+     // The achievements manager belongs to the activity, not the ViewModel, so the two     // achievement-reporting callbacks are stitched on here rather than pushed into the screen.     val actions = remember(viewModel, achievementsManager) {@@ -307,7 +322,9 @@ fun WordGamePage(             gameMode = gameMode,             competitiveScore = competitiveScore,             competitiveLevelNumber = competitiveLevelNumber,-            competitiveDeadline = competitiveDeadline+            competitiveDeadline = competitiveDeadline,+            dailyDay = dailyDay,+            dailyStreak = dailyStreak         ),         actions = actions,         onOpenGameCenter = onOpenGameCenter,@@ -340,7 +357,12 @@ fun WordGameScreen(     val competitiveLevelNumber = state.competitiveLevelNumber     val competitiveDeadline = state.competitiveDeadline     val isCompetitive = gameMode == GameMode.COMPETITIVE-    val levelKey = if (isCompetitive) "c$competitiveLevelNumber" else "n$currentLevel"+    val isDaily = gameMode == GameMode.DAILY+    val levelKey = when (gameMode) {+        GameMode.COMPETITIVE -> "c$competitiveLevelNumber"+        GameMode.DAILY -> "d${state.dailyDay}"+        GameMode.CASUAL -> "n$currentLevel"+    }     var showBonusWordsDialog by remember(levelKey) { mutableStateOf(false) }     var showHintDialog by remember(levelKey) { mutableStateOf(false) }     var remainingCooldown by remember { mutableLongStateOf(0L) }@@ -500,13 +522,20 @@ fun WordGameScreen(                         score = competitiveScore,                         remainingTimeMs = remainingTime                     )+                } else if (isDaily) {+                    DailyStatusBar(streak = state.dailyStreak)                 }                 Spacer(modifier = Modifier.weight(1f))                 Box(                     modifier = Modifier.height(320.dp),                     contentAlignment = Alignment.Center                 ) {-                    if (isWon && !isCompetitive) {+                    if (isWon && isDaily) {+                        Text(+                            stringResource(R.string.daily_come_back_tomorrow),+                            fontWeight = FontWeight.Bold+                        )+                    } else if (isWon && !isCompetitive) {                         Button(onClick = { actions.saveLevel(currentLevel + 1) }) {                             Text(stringResource(R.string.next_level))                         }@@ -682,33 +711,44 @@ fun GameModeDropdown(selected: GameMode, onSelected: (GameMode) -> Unit) {     var expanded by remember { mutableStateOf(false) }     Box {         TextButton(onClick = { expanded = true }) {-            Text(-                stringResource(-                    if (selected == GameMode.COMPETITIVE) R.string.mode_competitive else R.string.mode_casual-                ),-                fontWeight = FontWeight.Bold-            )+            Text(stringResource(gameModeLabel(selected)), fontWeight = FontWeight.Bold)             Text("  ▾", fontWeight = FontWeight.Bold)         }         DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {-            DropdownMenuItem(-                text = { Text(stringResource(R.string.mode_casual)) },-                onClick = {-                    expanded = false-                    onSelected(GameMode.CASUAL)-                }-            )-            DropdownMenuItem(-                text = { Text(stringResource(R.string.mode_competitive)) },-                onClick = {-                    expanded = false-                    onSelected(GameMode.COMPETITIVE)-                }-            )+            GameMode.entries.forEach { mode ->+                DropdownMenuItem(+                    text = { Text(stringResource(gameModeLabel(mode))) },+                    onClick = {+                        expanded = false+                        onSelected(mode)+                    }+                )+            }         }     } } +private fun gameModeLabel(mode: GameMode) = when (mode) {+    GameMode.CASUAL -> R.string.mode_casual+    GameMode.COMPETITIVE -> R.string.mode_competitive+    GameMode.DAILY -> R.string.mode_daily+}++/** Streak readout shown above the board in daily mode, in place of the competitive timer. */+@Composable+fun DailyStatusBar(streak: Long) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .padding(horizontal = 16.dp, vertical = 4.dp),+        verticalAlignment = Alignment.CenterVertically+    ) {+        Text(stringResource(R.string.daily_challenge), fontWeight = FontWeight.Bold)+        Spacer(Modifier.weight(1f))+        Text(stringResource(R.string.daily_streak, streak.toInt()))+    }+}+ @Composable fun DifficultyDropdown(selected: Difficulty, onSelected: (Difficulty) -> Unit) {     var expanded by remember { mutableStateOf(false) }
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/CompetitiveMode.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/CompetitiveMode.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/CompetitiveMode.ktindex e06727bd0a..a91cbea185 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/CompetitiveMode.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/CompetitiveMode.kt@@ -1,9 +1,13 @@ package com.vayunmathur.games.wordmaker.data -/** Whether the player is on the endless casual progression or the timed competitive ladder. */+/**+ * Whether the player is on the endless casual progression, the timed competitive ladder, or the+ * single date-seeded daily puzzle.+ */ enum class GameMode {     CASUAL,     COMPETITIVE,+    DAILY, }  /**
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/LevelDataStore.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/LevelDataStore.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/LevelDataStore.ktindex 38beb96aa4..acef1d6466 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/LevelDataStore.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/data/LevelDataStore.kt@@ -6,6 +6,7 @@ import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey+import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.preferencesDataStore@@ -27,6 +28,20 @@ class LevelDataStore(context: Context) {         private val GAME_MODE_KEY = stringPreferencesKey("game_mode")         private val DIFFICULTY_KEY = stringPreferencesKey("competitive_difficulty")         private val COMPETITIVE_SCORE_KEY = intPreferencesKey("competitive_score")+        private val DAILY_DAY_KEY = longPreferencesKey("daily_day")+        private val DAILY_FOUND_WORDS_KEY = stringSetPreferencesKey("daily_found_words")+        private val DAILY_BONUS_WORDS_KEY = stringSetPreferencesKey("daily_bonus_words")+        private val DAILY_REVEALED_HINTS_KEY = stringSetPreferencesKey("daily_revealed_hints")++        /** Sentinel for "no daily has ever been opened", distinct from epoch day 0 (1970-01-01). */+        const val NO_DAY = Long.MIN_VALUE++        private fun Set<String>?.toCells(): Set<Pair<Int, Int>> = this?.mapNotNull { s ->+            val parts = s.split(",")+            if (parts.size == 2) {+                parts[0].toIntOrNull()?.let { r -> parts[1].toIntOrNull()?.let { c -> r to c } }+            } else null+        }?.toSet() ?: emptySet()     }      val currentLevel: Flow<Int> = appContext.dataStore.data.map { it[LEVEL_KEY] ?: 1 }@@ -47,12 +62,55 @@ class LevelDataStore(context: Context) {      val competitiveScore: Flow<Int> = appContext.dataStore.data.map { it[COMPETITIVE_SCORE_KEY] ?: 0 } -    val revealedHints: Flow<Set<Pair<Int, Int>>> = appContext.dataStore.data.map { prefs ->-        prefs[REVEALED_HINTS_KEY]?.mapNotNull { s ->-            val parts = s.split(",")-            if (parts.size == 2) parts[0].toIntOrNull()?.let { r -> parts[1].toIntOrNull()?.let { c -> r to c } }-            else null-        }?.toSet() ?: emptySet()+    val revealedHints: Flow<Set<Pair<Int, Int>>> =+        appContext.dataStore.data.map { it[REVEALED_HINTS_KEY].toCells() }++    /** Epoch day the saved daily progress belongs to; [NO_DAY] before the first daily is opened. */+    val dailyDay: Flow<Long> = appContext.dataStore.data.map { it[DAILY_DAY_KEY] ?: NO_DAY }+    val dailyFoundWords: Flow<Set<String>> =+        appContext.dataStore.data.map { it[DAILY_FOUND_WORDS_KEY] ?: emptySet() }+    val dailyBonusWords: Flow<Set<String>> =+        appContext.dataStore.data.map { it[DAILY_BONUS_WORDS_KEY] ?: emptySet() }+    val dailyRevealedHints: Flow<Set<Pair<Int, Int>>> =+        appContext.dataStore.data.map { it[DAILY_REVEALED_HINTS_KEY].toCells() }++    /** Rolls the saved daily progress over to [day], discarding the previous day's state. */+    suspend fun ensureDailyDay(day: Long) {+        appContext.dataStore.edit { settings ->+            if (settings[DAILY_DAY_KEY] == day) return@edit+            settings[DAILY_DAY_KEY] = day+            settings[DAILY_FOUND_WORDS_KEY] = emptySet()+            settings[DAILY_BONUS_WORDS_KEY] = emptySet()+            settings[DAILY_REVEALED_HINTS_KEY] = emptySet()+        }+    }++    suspend fun addDailyFoundWord(word: String) {+        appContext.dataStore.edit { settings ->+            settings[DAILY_FOUND_WORDS_KEY] = (settings[DAILY_FOUND_WORDS_KEY] ?: emptySet()) + word+        }+    }++    suspend fun addDailyRevealedHint(row: Int, col: Int) {+        appContext.dataStore.edit { settings ->+            settings[DAILY_REVEALED_HINTS_KEY] =+                (settings[DAILY_REVEALED_HINTS_KEY] ?: emptySet()) + "$row,$col"+        }+    }++    /** Adds a daily bonus word, still folding it into the lifetime total the achievement tracks. */+    suspend fun addDailyBonusWord(word: String): Int {+        var newTotal = 0+        appContext.dataStore.edit { settings ->+            val current = settings[DAILY_BONUS_WORDS_KEY] ?: emptySet()+            newTotal = settings[TOTAL_BONUS_WORDS_KEY] ?: 0+            if (word !in current) {+                settings[DAILY_BONUS_WORDS_KEY] = current + word+                newTotal += 1+                settings[TOTAL_BONUS_WORDS_KEY] = newTotal+            }+        }+        return newTotal     }      suspend fun setTapToSpell(enabled: Boolean) {
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerAchievementsManager.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerAchievementsManager.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerAchievementsManager.ktindex f0d7044462..0b68584cab 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerAchievementsManager.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerAchievementsManager.kt@@ -3,6 +3,7 @@ package com.vayunmathur.games.wordmaker.util import android.content.Context import com.vayunmathur.games.wordmaker.data.LevelDataStore import com.vayunmathur.library.util.AchievementsManager+import com.vayunmathur.library.util.DailyChallengeStore import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first@@ -13,6 +14,9 @@ class WordMakerAchievementsManager(     json: String,     private val levelDataStore: LevelDataStore ) : AchievementsManager(context, json) {++    private val dailyStore = DailyChallengeStore(context, "wordmaker_daily")+     override fun checkExistingAchievements() {         CoroutineScope(Dispatchers.IO).launch {             val currentLevel = levelDataStore.currentLevel.first()@@ -25,6 +29,13 @@ class WordMakerAchievementsManager(                          val totalBonus = levelDataStore.totalBonusWords.first()             onProgressUpdated("bonus_hunter", totalBonus)++            val bestStreak = dailyStore.bestStreak()+            if (bestStreak > 0) {+                onAchievementUnlocked("first_daily")+                onProgressUpdated("daily_streak_7", bestStreak.toInt())+                onProgressUpdated("daily_streak_30", bestStreak.toInt())+            }         }     } }
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerUiContract.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerUiContract.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerUiContract.ktindex d4b61ef84d..8368f16420 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerUiContract.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerUiContract.kt@@ -28,6 +28,9 @@ data class WordGameUiState(     val competitiveLevelNumber: Int = 0,     /** Epoch millis at which the competitive timer expires; 0 outside competitive play. */     val competitiveDeadline: Long = 0L,+    /** Local epoch day the daily board belongs to. */+    val dailyDay: Long = 0L,+    val dailyStreak: Long = 0L, )  /** Everything the between-levels competitive lobby draws. */
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerViewModel.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerViewModel.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerViewModel.ktindex 3f2ec78dc6..3061f72930 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerViewModel.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/WordMakerViewModel.kt@@ -9,7 +9,9 @@ import com.vayunmathur.games.wordmaker.data.CrosswordData import com.vayunmathur.games.wordmaker.data.Difficulty import com.vayunmathur.games.wordmaker.data.GameMode import com.vayunmathur.games.wordmaker.data.LevelDataStore+import com.vayunmathur.library.util.DailyChallengeStore import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow@@ -37,15 +39,15 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio     private val casualFoundWords: StateFlow<Set<String>> = levelDataStore.foundWords         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet()) -    val bonusWords: StateFlow<Set<String>> = levelDataStore.bonusWords+    private val casualBonusWords: StateFlow<Set<String>> = levelDataStore.bonusWords+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())++    private val casualRevealedHints: StateFlow<Set<Pair<Int, Int>>> = levelDataStore.revealedHints         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())      val tapToSpell: StateFlow<Boolean> = levelDataStore.tapToSpell         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) -    val revealedHints: StateFlow<Set<Pair<Int, Int>>> = levelDataStore.revealedHints-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())-     private val _hintCooldownEnd = MutableStateFlow(System.currentTimeMillis() + 30_000L)     val hintCooldownEnd: StateFlow<Long> = _hintCooldownEnd.asStateFlow() @@ -83,14 +85,65 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio      private val _casualCrossword = MutableStateFlow<CrosswordData?>(null) +    // ---- Daily challenge state ----++    private val dailyStore = DailyChallengeStore(application, "wordmaker_daily")++    private val _dailyDay = MutableStateFlow(dailyStore.todayEpochDay())+    val dailyDay: StateFlow<Long> = _dailyDay.asStateFlow()++    private val _dailyCrossword = MutableStateFlow<CrosswordData?>(null)++    val dailyStreak: StateFlow<Long> = dailyStore.currentStreak+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0L)++    val dailyBestStreak: StateFlow<Long> = dailyStore.bestStreakFlow+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0L)++    /** Saved daily sets, blanked whenever the stored day is not the day currently being played. */+    private fun <T> dailyScoped(saved: Flow<T>, empty: T): Flow<T> =+        combine(_dailyDay, levelDataStore.dailyDay, saved) { today, stored, value ->+            if (stored == today) value else empty+        }++    private val dailyFoundWords: StateFlow<Set<String>> =+        dailyScoped(levelDataStore.dailyFoundWords, emptySet<String>())+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())++    private val dailyBonusWords: StateFlow<Set<String>> =+        dailyScoped(levelDataStore.dailyBonusWords, emptySet<String>())+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())++    private val dailyRevealedHints: StateFlow<Set<Pair<Int, Int>>> =+        dailyScoped(levelDataStore.dailyRevealedHints, emptySet<Pair<Int, Int>>())+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())+     val crosswordData: StateFlow<CrosswordData?> =-        combine(gameMode, _casualCrossword, _competitiveCrossword) { mode, casual, competitive ->-            if (mode == GameMode.COMPETITIVE) competitive else casual+        combine(gameMode, _casualCrossword, _competitiveCrossword, _dailyCrossword) { mode, casual, competitive, daily ->+            when (mode) {+                GameMode.COMPETITIVE -> competitive+                GameMode.DAILY -> daily+                GameMode.CASUAL -> casual+            }         }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)      val foundWords: StateFlow<Set<String>> =-        combine(gameMode, casualFoundWords, _competitiveFoundWords) { mode, casual, competitive ->-            if (mode == GameMode.COMPETITIVE) competitive else casual+        combine(gameMode, casualFoundWords, _competitiveFoundWords, dailyFoundWords) { mode, casual, competitive, daily ->+            when (mode) {+                GameMode.COMPETITIVE -> competitive+                GameMode.DAILY -> daily+                GameMode.CASUAL -> casual+            }+        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())++    val bonusWords: StateFlow<Set<String>> =+        combine(gameMode, casualBonusWords, dailyBonusWords) { mode, casual, daily ->+            if (mode == GameMode.DAILY) daily else casual+        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())++    val revealedHints: StateFlow<Set<Pair<Int, Int>>> =+        combine(gameMode, casualRevealedHints, dailyRevealedHints) { mode, casual, daily ->+            if (mode == GameMode.DAILY) daily else casual         }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())      private val _error = MutableStateFlow<String?>(null)@@ -106,6 +159,9 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio         viewModelScope.launch {             currentLevel.collectLatest { level -> loadCasualLevel(level) }         }+        viewModelScope.launch {+            gameMode.collectLatest { mode -> if (mode == GameMode.DAILY) refreshDaily() }+        }         // Auto-count words that become fully filled in by their crossing words, so the player         // never has to retrace a word that is already complete on the board.         viewModelScope.launch {@@ -114,16 +170,57 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio                     if (data == null) return@collect                     val incidental = data.incidentalWords(found)                     if (incidental.isEmpty()) return@collect-                    if (gameMode.value == GameMode.COMPETITIVE) {-                        _competitiveFoundWords.value = _competitiveFoundWords.value + incidental-                    } else {-                        incidental.forEach { levelDataStore.addFoundWord(it) }+                    when (gameMode.value) {+                        GameMode.COMPETITIVE ->+                            _competitiveFoundWords.value = _competitiveFoundWords.value + incidental+                        GameMode.DAILY -> incidental.forEach { levelDataStore.addDailyFoundWord(it) }+                        GameMode.CASUAL -> incidental.forEach { levelDataStore.addFoundWord(it) }                     }                 }         }         // Competitive mode always opens on the lobby; the player starts each level manually.     } +    /**+     * Rolls the daily over to today (discarding a previous day's progress) and generates the+     * board. Cheap to call repeatedly: the board is only regenerated when the day changes.+     */+    private suspend fun refreshDaily() {+        val today = dailyStore.todayEpochDay()+        if (_dailyDay.value == today && _dailyCrossword.value != null) return+        _dailyDay.value = today+        _dailyCrossword.value = null+        levelDataStore.ensureDailyDay(today)+        val ctx = getApplication<Application>()+        val data = withContext(Dispatchers.Default) { generateDailyLevel(ctx, today) }+        _dailyCrossword.value = data+        if (gameMode.value == GameMode.DAILY) {+            _error.value = if (data == null) ctx.getString(R.string.error_parse_level) else null+        }+    }++    /**+     * The day's board. The offset keeps daily seeds clear of the small level-number seeds casual+     * mode uses, so the two never generate the same puzzle.+     */+    private fun generateDailyLevel(ctx: Context, day: Long): CrosswordData? {+        val generator = levelGenerator+            ?: CompetitiveLevelGenerator.fromAssets(ctx).also { levelGenerator = it }+        val seed = DAILY_SEED_OFFSET + day * 100+        var data = generator.generate(Random(seed))+        var attempt = 1+        while (data == null && attempt < 5) {+            data = generator.generate(Random(seed + attempt * 1_000_000L))+            attempt+++        }+        return data+    }++    /** Records today's daily as solved, extending the streak. Idempotent within a day. */+    fun onDailyWin() {+        viewModelScope.launch { dailyStore.recordDayCompleted(_dailyDay.value) }+    }+     private suspend fun loadCasualLevel(level: Int) {         val ctx = getApplication<Application>()         val data = withContext(Dispatchers.Default) {@@ -136,7 +233,7 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio             asset ?: generateSeededLevel(ctx, level)         }         _casualCrossword.value = data-        if (gameMode.value != GameMode.COMPETITIVE) {+        if (gameMode.value == GameMode.CASUAL) {             _error.value = if (data == null) ctx.getString(R.string.error_parse_level) else null         }     }@@ -185,6 +282,8 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio             _competitiveActive.value = false             _competitiveResult.value = null             _competitiveDeadline.value = 0L+            // The error belongs to the mode that produced it, not to the one being entered.+            _error.value = null         }     } @@ -222,14 +321,16 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio     }      override fun addFoundWord(word: String) {-        if (gameMode.value == GameMode.COMPETITIVE) {-            _competitiveFoundWords.value = _competitiveFoundWords.value + word-        } else {-            viewModelScope.launch { levelDataStore.addFoundWord(word) }+        when (gameMode.value) {+            GameMode.COMPETITIVE -> _competitiveFoundWords.value = _competitiveFoundWords.value + word+            GameMode.DAILY -> viewModelScope.launch { levelDataStore.addDailyFoundWord(word) }+            GameMode.CASUAL -> viewModelScope.launch { levelDataStore.addFoundWord(word) }         }     } -    override suspend fun addBonusWord(word: String): Int = levelDataStore.addBonusWord(word)+    override suspend fun addBonusWord(word: String): Int =+        if (gameMode.value == GameMode.DAILY) levelDataStore.addDailyBonusWord(word)+        else levelDataStore.addBonusWord(word)      fun setTapToSpell(enabled: Boolean) {         viewModelScope.launch { levelDataStore.setTapToSpell(enabled) }@@ -246,12 +347,18 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio          val target = unrevealed.random()         _hintCooldownEnd.value = System.currentTimeMillis() + 30_000L+        val daily = gameMode.value == GameMode.DAILY         viewModelScope.launch {-            levelDataStore.addRevealedHint(target.first, target.second)+            if (daily) {+                levelDataStore.addDailyRevealedHint(target.first, target.second)+            } else {+                levelDataStore.addRevealedHint(target.first, target.second)+            }             val nowRevealed = revealed + target             crosswordData.letterPositions.forEach { (word, occurrences) ->                 if (word !in foundWords && occurrences.any { nowRevealed.containsAll(it) }) {-                    levelDataStore.addFoundWord(word)+                    if (daily) levelDataStore.addDailyFoundWord(word)+                    else levelDataStore.addFoundWord(word)                 }             }         }@@ -260,5 +367,8 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio     companion object {         /** Highest level shipped as a designed asset; higher levels are generated at runtime. */         const val MAX_DESIGNED_LEVEL = 8000++        /** Keeps date-derived daily seeds far away from the level-number seeds casual mode uses. */+        private const val DAILY_SEED_OFFSET = 700_000_000L     } }
games/wordmaker/src/main/res/values/strings.xml
diff --git a/games/wordmaker/src/main/res/values/strings.xml b/games/wordmaker/src/main/res/values/strings.xmlindex 7f9d4dabfc..9741b592b6 100644--- a/games/wordmaker/src/main/res/values/strings.xml+++ b/games/wordmaker/src/main/res/values/strings.xml@@ -42,6 +42,15 @@     <!-- CompetitiveLobbyScreen: Result when timer expired. %1$d = points delta negative e.g. -15 or penalized, but displays as positive in string with context. Sentence -->     <string name="competitive_timed_out">Time\'s up! <xliff:g id="points" example="-15">%1$d</xliff:g> points</string> +    <!-- GameModeDropdown: Daily challenge mode label. One date-seeded puzzle per day. Adjective -->+    <string name="mode_daily">Daily</string>+    <!-- DailyStatusBar: Title shown above the board in daily mode. Noun phrase -->+    <string name="daily_challenge">Daily Challenge</string>+    <!-- DailyStatusBar: Consecutive days solved. %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>+    <!-- WordGameScreen: Shown after solving the daily, in place of the Next Level button. Sentence -->+    <string name="daily_come_back_tomorrow">Solved! Come back tomorrow.</string>+     <!-- LetterChooser: Accessibility content description for shuffle button that randomizes letter order. Verb -->     <string name="cd_shuffle">Shuffle</string>     <!-- WordGameScreen: Accessibility description for hint button (help icon) that reveals a letter with 30s cooldown indicator. Noun -->