Modern Apps git

← Modern-Apps.git

wordmaker: various fixes

Commit
54912631b8d02140c37483d1a7274d3c7bec561c
Author
Vayun Mathur <[email protected]>
When
2026-06-11 18:16 UTC (5 months ago)
Parents
e66a9d7

Diff

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 a285c7775f..3b861a70d2 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@@ -49,6 +49,7 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope@@ -76,6 +77,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.vayunmathur.games.wordmaker.data.CrosswordData import com.vayunmathur.games.wordmaker.data.LevelDataStore+import com.vayunmathur.games.wordmaker.ui.SettingsPage import com.vayunmathur.games.wordmaker.util.AppBackupAgent import com.vayunmathur.games.wordmaker.util.WordMakerViewModel import com.vayunmathur.library.ui.AchievementNotification@@ -104,6 +106,8 @@ sealed interface Route : NavKey {     data object Game : Route     @Serializable     data object GameCenter : Route+    @Serializable+    data object Settings : Route }  data class ChooserLetter(val id: Int, val char: Char)@@ -131,6 +135,9 @@ class MainActivity : ComponentActivity() {                             )                         }                     }+                    entry<Route.Settings> {+                        SettingsPage(viewModel = viewModel, onBack = { backStack.pop() })+                    }                 }             }         }@@ -182,7 +189,8 @@ fun WordMakerGameLoader(backStack: NavBackStack<Route>, viewModel: WordMakerView                     currentLevel = currentLevel,                     viewModel = viewModel,                     achievementsManager = achievementsManager,-                    onOpenGameCenter = { backStack.add(Route.GameCenter) }+                    onOpenGameCenter = { backStack.add(Route.GameCenter) },+                    onOpenSettings = { backStack.add(Route.Settings) }                 )             } @@ -215,11 +223,17 @@ fun WordGameScreen(     currentLevel: Int,     viewModel: WordMakerViewModel,     achievementsManager: AchievementsManager,-    onOpenGameCenter: () -> Unit+    onOpenGameCenter: () -> Unit,+    onOpenSettings: () -> Unit ) {     val foundWords by viewModel.foundWords.collectAsState()     val bonusWords by viewModel.bonusWords.collectAsState()+    val tapToSpell by viewModel.tapToSpell.collectAsState()+    val revealedHints by viewModel.revealedHints.collectAsState()+    val hintCooldownEnd by viewModel.hintCooldownEnd.collectAsState()     var showBonusWordsDialog by remember(currentLevel) { mutableStateOf(false) }+    var showHintDialog by remember(currentLevel) { mutableStateOf(false) }+    var remainingCooldown by remember { mutableLongStateOf(0L) }     val density = LocalDensity.current     var rootOffset by remember { mutableStateOf(Offset.Zero) }     var wordWithDefinition by remember { mutableStateOf<Pair<String, List<String>>?>(null) }@@ -303,6 +317,14 @@ fun WordGameScreen(         }     } +    LaunchedEffect(hintCooldownEnd) {+        while (true) {+            remainingCooldown = (hintCooldownEnd - System.currentTimeMillis()).coerceAtLeast(0)+            if (remainingCooldown <= 0) break+            delay(100)+        }+    }+     Scaffold(         Modifier.fillMaxSize(),         topBar = {@@ -312,9 +334,9 @@ fun WordGameScreen(                     IconButton(onClick = onOpenGameCenter) {                         Icon(painterResource(id = android.R.drawable.btn_star_big_on), "Achievements")                     }-                    com.vayunmathur.library.ui.BackupButtons(-                        datastoreNames = listOf("settings")-                    )+                    IconButton(onClick = onOpenSettings) {+                        Icon(painterResource(id = android.R.drawable.ic_menu_preferences), "Settings")+                    }                 }             )         }@@ -337,6 +359,7 @@ fun WordGameScreen(                 ) {                     CrosswordBoard(                         foundWords = foundWords,+                        revealedHints = revealedHints,                         crosswordData = crosswordData,                         wordToAnimate = wordToAnimate?.word,                         onCellPositioned = { position, offset ->@@ -373,6 +396,7 @@ fun WordGameScreen(                     } else {                         LetterChooser(                             letters = shuffledLetters,+                            tapToSpell = tapToSpell,                             onShuffle = {                                 var nextLetters = shuffledLetters.shuffled()                                 while (nextLetters == shuffledLetters && shuffledLetters.size > 1) {@@ -458,6 +482,54 @@ fun WordGameScreen(                 Icon(painterResource(R.drawable.outline_book_2_24), null)             } +            if (!isWon) {+                val hintEnabled = remainingCooldown <= 0L+                Box(+                    modifier = Modifier+                        .align(Alignment.BottomEnd)+                        .padding(16.dp)+                        .padding(bottom = 32.dp)+                ) {+                    FilledIconButton(+                        onClick = { showHintDialog = true },+                        enabled = hintEnabled+                    ) {+                        Icon(+                            painterResource(android.R.drawable.ic_menu_help),+                            contentDescription = "Hint",+                            modifier = Modifier.graphicsLayer { alpha = if (hintEnabled) 1f else 0.5f }+                        )+                    }+                    if (!hintEnabled) {+                        CircularProgressIndicator(+                            progress = { 1f - (remainingCooldown / 30_000f) },+                            modifier = Modifier.size(48.dp).align(Alignment.Center),+                            strokeWidth = 3.dp+                        )+                    }+                }+            }++            if (showHintDialog) {+                AlertDialog(+                    onDismissRequest = { showHintDialog = false },+                    title = { Text(stringResource(R.string.hint_confirmation)) },+                    confirmButton = {+                        Button(onClick = {+                            viewModel.revealHint(crosswordData, foundWords, revealedHints)+                            showHintDialog = false+                        }) {+                            Text(stringResource(R.string.yes))+                        }+                    },+                    dismissButton = {+                        Button(onClick = { showHintDialog = false }) {+                            Text(stringResource(R.string.no))+                        }+                    }+                )+            }+             if (showBonusWordsDialog) {                 BonusWordsDialog(bonusWords = bonusWords, getDefinition = viewModel::getDefinition) {                     showBonusWordsDialog = false@@ -496,8 +568,9 @@ fun WordGameScreen(                  SurfaceText(Modifier.offset { IntOffset(offset.x.toInt(), offset.y.toInt()) },                     RoundedCornerShape(4.dp * scale),-                    colorScheme.primaryContainer, letter.char.toString(),-                    Modifier, FontWeight.Bold, fontSize, size)+                    colorScheme.primary, letter.char.toString(),+                    Modifier, FontWeight.Bold, fontSize, size,+                    textColor = colorScheme.onPrimary)             }         }     }@@ -557,11 +630,11 @@ fun BonusWordsDialog( }  @Composable-fun SurfaceText(modifier: Modifier, surfaceShape: Shape, surfaceColor: Color, text: String, textModifier: Modifier, fontWeight: FontWeight? = null, fontSize: TextUnit = TextUnit.Unspecified, surfaceSize: Dp?) {+fun SurfaceText(modifier: Modifier, surfaceShape: Shape, surfaceColor: Color, text: String, textModifier: Modifier, fontWeight: FontWeight? = null, fontSize: TextUnit = TextUnit.Unspecified, surfaceSize: Dp?, textColor: Color = Color.Unspecified) {     val modifier2 = if(surfaceSize != null) modifier.size(surfaceSize) else modifier     Surface(modifier2, surfaceShape, surfaceColor) {         Box(if(surfaceSize == null) Modifier else Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {-            Text(text, textModifier, fontWeight = fontWeight, fontSize = fontSize)+            Text(text, textModifier, color = textColor, fontWeight = fontWeight, fontSize = fontSize)         }     } }@@ -569,6 +642,7 @@ fun SurfaceText(modifier: Modifier, surfaceShape: Shape, surfaceColor: Color, te @Composable fun CrosswordBoard(     foundWords: Set<String>,+    revealedHints: Set<Pair<Int, Int>>,     crosswordData: CrosswordData,     wordToAnimate: String?,     onCellPositioned: (position: Pair<Int, Int>, offset: Offset) -> Unit,@@ -583,6 +657,15 @@ fun CrosswordBoard(             }         }     }+    // Also reveal hint cells+    crosswordData.letterPositions.forEach { (word, positions) ->+        word.forEachIndexed { index, char ->+            val pos = positions[index]+            if (pos in revealedHints && pos !in allCharPositions) {+                allCharPositions[pos] = char+            }+        }+    }     val (size, fontSize) = Pair(35.dp, 18.sp)      BoxWithConstraints(@@ -644,8 +727,11 @@ fun CrosswordBoard(                                             onCellClicked(y, x)                                         },                                     RoundedCornerShape(4.dp),-                                    if (letter != null) colorScheme.primaryContainer else colorScheme.secondaryContainer,-                                    letter?.toString() ?: " ", Modifier, FontWeight.Bold, fontSize, size+                                    if (letter != null) colorScheme.primary else colorScheme.surfaceVariant,+                                    letter?.toString() ?: " ",+                                    Modifier,+                                    FontWeight.Bold, fontSize, size,+                                    textColor = if (letter != null) colorScheme.onPrimary else Color.Unspecified                                 )                             } else {                                 Box(Modifier.padding(1.dp).size(size))@@ -661,6 +747,7 @@ fun CrosswordBoard( @Composable fun LetterChooser(     letters: List<ChooserLetter>,+    tapToSpell: Boolean,     onShuffle: () -> Unit,     onWordSubmitted: suspend CoroutineScope.(String, List<Int>) -> Unit,     onWordBoxPositioned: (Offset) -> Unit,@@ -819,9 +906,16 @@ fun LetterChooser(                             .offset(x, y)                             .onGloballyPositioned { coordinates ->                                 onLetterPositioned(chooserLetter.id, coordinates.localToRoot(Offset.Zero))-                            },+                            }+                            .then(if (tapToSpell) Modifier.clickable {+                                if (selectedLettersIndices.lastOrNull() == index) {+                                    selectedLettersIndices = selectedLettersIndices.dropLast(1)+                                } else if (index !in selectedLettersIndices) {+                                    selectedLettersIndices = selectedLettersIndices + index+                                }+                            } else Modifier),                             CircleShape,-                            if (index in selectedLettersIndices) colorScheme.primary else colorScheme.secondary,+                            if (index in selectedLettersIndices) colorScheme.primary else colorScheme.surfaceVariant,                             chooserLetter.char.toString(),                             Modifier.padding(1.dp),                             FontWeight.Bold,@@ -835,6 +929,28 @@ fun LetterChooser(                 Icon(painterResource(R.drawable.ic_shuffle), contentDescription = "Shuffle")             }         }+        if (tapToSpell && selectedLettersIndices.isNotEmpty()) {+            Row(modifier = Modifier.padding(top = 8.dp)) {+                FilledIconButton(onClick = {+                    selectedLettersIndices = selectedLettersIndices.dropLast(1)+                }) {+                    Icon(painterResource(android.R.drawable.ic_input_delete), contentDescription = "Backspace")+                }+                Spacer(modifier = Modifier.width(16.dp))+                FilledIconButton(onClick = {+                    if (selectedLettersIndices.isNotEmpty()) {+                        val word = selectedLettersIndices.map { letters[it].char }.joinToString("")+                        val ids = selectedLettersIndices.map { letters[it].id }+                        coroutineScope.launch {+                            onWordSubmitted(word, ids)+                            selectedLettersIndices = emptyList()+                        }+                    }+                }) {+                    Icon(painterResource(android.R.drawable.ic_menu_send), contentDescription = "Submit")+                }+            }+        }     } } 
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 46f7556593..d642def35a 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@@ -3,6 +3,7 @@ package com.vayunmathur.games.wordmaker.data import android.content.Context import androidx.datastore.core.DataStore 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.stringSetPreferencesKey@@ -20,6 +21,8 @@ class LevelDataStore(context: Context) {         private val FOUND_WORDS_KEY = stringSetPreferencesKey("found_words")         private val BONUS_WORDS_KEY = stringSetPreferencesKey("bonus_words")         private val TOTAL_BONUS_WORDS_KEY = intPreferencesKey("total_bonus_words")+        private val TAP_TO_SPELL_KEY = booleanPreferencesKey("tap_to_spell")+        private val REVEALED_HINTS_KEY = stringSetPreferencesKey("revealed_hints")     }      val currentLevel: Flow<Int> = appContext.dataStore.data@@ -31,6 +34,27 @@ class LevelDataStore(context: Context) {     val bonusWords: Flow<Set<String>> = appContext.dataStore.data.map { it[BONUS_WORDS_KEY] ?: emptySet() }     val totalBonusWords: Flow<Int> = appContext.dataStore.data.map { it[TOTAL_BONUS_WORDS_KEY] ?: 0 } +    val tapToSpell: Flow<Boolean> = appContext.dataStore.data.map { it[TAP_TO_SPELL_KEY] ?: false }++    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()+    }++    suspend fun setTapToSpell(enabled: Boolean) {+        appContext.dataStore.edit { it[TAP_TO_SPELL_KEY] = enabled }+    }++    suspend fun addRevealedHint(row: Int, col: Int) {+        appContext.dataStore.edit { settings ->+            val current = settings[REVEALED_HINTS_KEY] ?: emptySet()+            settings[REVEALED_HINTS_KEY] = current + "$row,$col"+        }+    }+     suspend fun addBonusWord(word: String): Int {         var newTotal = 0         appContext.dataStore.edit { settings ->@@ -59,6 +83,7 @@ class LevelDataStore(context: Context) {             settings[LEVEL_KEY] = level             settings[FOUND_WORDS_KEY] = emptySet()             settings[BONUS_WORDS_KEY] = emptySet()+            settings[REVEALED_HINTS_KEY] = emptySet()         }     } }
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.ktnew file mode 100644index 0000000000..58510c5fcf--- /dev/null+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.kt@@ -0,0 +1,70 @@+package com.vayunmathur.games.wordmaker.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme.colorScheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Switch+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.wordmaker.R+import com.vayunmathur.games.wordmaker.util.WordMakerViewModel++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SettingsPage(viewModel: WordMakerViewModel, onBack: () -> Unit) {+    val tapToSpell by viewModel.tapToSpell.collectAsState()++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text(stringResource(R.string.settings)) },+                navigationIcon = {+                    IconButton(onClick = onBack) {+                        Icon(painterResource(android.R.drawable.ic_menu_revert), contentDescription = "Back")+                    }+                },+                actions = {+                    com.vayunmathur.library.ui.BackupButtons(+                        datastoreNames = listOf("settings")+                    )+                }+            )+        }+    ) { innerPadding ->+        Column(+            modifier = Modifier+                .padding(innerPadding)+                .fillMaxSize()+                .padding(16.dp)+        ) {+            Row(+                modifier = Modifier.fillMaxWidth(),+                verticalAlignment = Alignment.CenterVertically+            ) {+                Column(modifier = Modifier.weight(1f)) {+                    Text(stringResource(R.string.tap_to_spell), style = androidx.compose.material3.MaterialTheme.typography.titleMedium)+                    Text(stringResource(R.string.tap_to_spell_description), style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = colorScheme.onSurfaceVariant)+                }+                Switch(+                    checked = tapToSpell,+                    onCheckedChange = { viewModel.setTapToSpell(it) }+                )+            }+        }+    }+}
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 5a72d89cd9..e024147d17 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@@ -44,6 +44,15 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio     val bonusWords: StateFlow<Set<String>> = levelDataStore.bonusWords         .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()+     private val _crosswordData = MutableStateFlow<CrosswordData?>(null)     val crosswordData: StateFlow<CrosswordData?> = _crosswordData.asStateFlow() @@ -92,4 +101,28 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio      /** Suspending so callers (e.g. compose animation coroutines) can sequence achievement updates. */     suspend fun addBonusWord(word: String): Int = levelDataStore.addBonusWord(word)++    fun setTapToSpell(enabled: Boolean) {+        viewModelScope.launch { levelDataStore.setTapToSpell(enabled) }+    }++    fun revealHint(crosswordData: CrosswordData, foundWords: Set<String>, revealedHints: Set<Pair<Int, Int>>) {+        val revealedPositions = mutableSetOf<Pair<Int, Int>>()+        crosswordData.letterPositions.forEach { (word, positions) ->+            if (word in foundWords) {+                revealedPositions.addAll(positions)+            }+        }+        revealedPositions.addAll(revealedHints)++        val allCellPositions = mutableSetOf<Pair<Int, Int>>()+        crosswordData.letterPositions.values.forEach { allCellPositions.addAll(it) }++        val unrevealed = allCellPositions - revealedPositions+        if (unrevealed.isEmpty()) return++        val target = unrevealed.random()+        _hintCooldownEnd.value = System.currentTimeMillis() + 30_000L+        viewModelScope.launch { levelDataStore.addRevealedHint(target.first, target.second) }+    } }
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 11dd693a36..13c2078568 100644--- a/games/wordmaker/src/main/res/values/strings.xml+++ b/games/wordmaker/src/main/res/values/strings.xml@@ -8,4 +8,10 @@     <string name="next_level">Next Level</string>     <string name="close">Close</string>     <string name="bonus_words">Bonus Words</string>+    <string name="settings">Settings</string>+    <string name="tap_to_spell">Tap to Spell</string>+    <string name="tap_to_spell_description">Tap letters to build words instead of dragging</string>+    <string name="hint_confirmation">Are you sure you want to use a hint?</string>+    <string name="yes">Yes</string>+    <string name="no">No</string> </resources>\ No newline at end of file