Modern Apps git

← Modern-Apps.git

wordmaker: generate levels past 8000 at runtime and rework competitive mode into a between-levels lobby

Commit
95abff87ec250bdb57d60194026dd6fa30270107
Author
Vayun Mathur <[email protected]>
When
2026-06-24 03:26 UTC (5 months ago)
Parents
d2eeba3

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 3a48d40b77..f7d83e2b47 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@@ -14,6 +14,7 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.rememberTransformableState import androidx.compose.foundation.gestures.transformable+import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column@@ -165,6 +166,8 @@ fun WordMakerGameLoader(backStack: NavBackStack<Route>, viewModel: WordMakerView     val currentLevel by viewModel.currentLevel.collectAsState()     val crosswordData by viewModel.crosswordData.collectAsState()     val error by viewModel.error.collectAsState()+    val gameMode by viewModel.gameMode.collectAsState()+    val competitiveActive by viewModel.competitiveActive.collectAsState()      val achievementsManager = rememberAchievementsManager(viewModel.levelDataStore)     if (achievementsManager == null) {@@ -181,6 +184,14 @@ fun WordMakerGameLoader(backStack: NavBackStack<Route>, viewModel: WordMakerView      Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {         when {+            gameMode == GameMode.COMPETITIVE && !competitiveActive -> {+                CompetitiveLobbyScreen(+                    viewModel = viewModel,+                    onOpenGameCenter = { backStack.add(Route.GameCenter) },+                    onOpenSettings = { backStack.add(Route.Settings) }+                )+            }+             error != null -> {                 Text(text = error!!, color = colorScheme.error)             }@@ -234,7 +245,6 @@ fun WordGameScreen(     val revealedHints by viewModel.revealedHints.collectAsState()     val hintCooldownEnd by viewModel.hintCooldownEnd.collectAsState()     val gameMode by viewModel.gameMode.collectAsState()-    val difficulty by viewModel.difficulty.collectAsState()     val competitiveScore by viewModel.competitiveScore.collectAsState()     val competitiveLevelNumber by viewModel.competitiveLevelNumber.collectAsState()     val competitiveDeadline by viewModel.competitiveDeadline.collectAsState()@@ -358,21 +368,11 @@ fun WordGameScreen(     Scaffold(         Modifier.fillMaxSize(),         topBar = {-            TopAppBar(-                title = {-                    GameModeDropdown(-                        selected = gameMode,-                        onSelected = { viewModel.setGameMode(it) }-                    )-                },-                actions = {-                    IconButton(onClick = onOpenGameCenter) {-                        Icon(painterResource(id = android.R.drawable.btn_star_big_on), "Achievements")-                    }-                    IconButton(onClick = onOpenSettings) {-                        IconSettings()-                    }-                }+            WordMakerTopBar(+                gameMode = gameMode,+                onModeSelected = { viewModel.setGameMode(it) },+                onOpenGameCenter = onOpenGameCenter,+                onOpenSettings = onOpenSettings             )         }     ) { innerPadding ->@@ -390,10 +390,7 @@ fun WordGameScreen(             ) {                 if (isCompetitive) {                     CompetitiveStatusBar(-                        difficulty = difficulty,-                        onDifficultySelected = { viewModel.setDifficulty(it) },                         score = competitiveScore,-                        roundNumber = competitiveLevelNumber,                         remainingTimeMs = remainingTime                     )                 }@@ -429,28 +426,12 @@ fun WordGameScreen(                     modifier = Modifier.height(320.dp),                     contentAlignment = Alignment.Center                 ) {-                    if (isWon) {-                        Button(-                            onClick = {-                                if (isCompetitive) viewModel.loadNextCompetitiveLevel()-                                else viewModel.saveLevel(currentLevel + 1)-                            }-                        ) {-                            Text(stringResource(if (isCompetitive) R.string.next_round else R.string.next_level))-                        }-                    } else if (isCompetitive && timedOut) {-                        Column(horizontalAlignment = Alignment.CenterHorizontally) {-                            Text(-                                stringResource(R.string.time_up),-                                color = colorScheme.error,-                                fontWeight = FontWeight.Bold,-                                fontSize = 24.sp-                            )-                            Spacer(Modifier.height(16.dp))-                            Button(onClick = { viewModel.loadNextCompetitiveLevel() }) {-                                Text(stringResource(R.string.next_round))-                            }+                    if (isWon && !isCompetitive) {+                        Button(onClick = { viewModel.saveLevel(currentLevel + 1) }) {+                            Text(stringResource(R.string.next_level))                         }+                    } else if (isCompetitive && (isWon || timedOut)) {+                        // Level finished — the between-levels lobby (WordMakerGameLoader) takes over.                     } else {                         LetterChooser(                             letters = shuffledLetters,@@ -676,12 +657,101 @@ fun DifficultyDropdown(selected: Difficulty, onSelected: (Difficulty) -> Unit) {     } } +@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun WordMakerTopBar(+    gameMode: GameMode,+    onModeSelected: (GameMode) -> Unit,+    onOpenGameCenter: () -> Unit,+    onOpenSettings: () -> Unit+) {+    TopAppBar(+        title = { GameModeDropdown(selected = gameMode, onSelected = onModeSelected) },+        actions = {+            IconButton(onClick = onOpenGameCenter) {+                Icon(painterResource(id = android.R.drawable.btn_star_big_on), "Achievements")+            }+            IconButton(onClick = onOpenSettings) {+                IconSettings()+            }+        }+    )+}++/**+ * The between-levels screen for competitive mode: shows the score and last result, lets the player+ * pick the difficulty (which only applies from the next level), and starts the next level on demand.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun CompetitiveLobbyScreen(+    viewModel: WordMakerViewModel,+    onOpenGameCenter: () -> Unit,+    onOpenSettings: () -> Unit+) {+    val gameMode by viewModel.gameMode.collectAsState()+    val difficulty by viewModel.difficulty.collectAsState()+    val score by viewModel.competitiveScore.collectAsState()+    val result by viewModel.competitiveResult.collectAsState()++    Scaffold(+        topBar = {+            WordMakerTopBar(+                gameMode = gameMode,+                onModeSelected = { viewModel.setGameMode(it) },+                onOpenGameCenter = onOpenGameCenter,+                onOpenSettings = onOpenSettings+            )+        }+    ) { innerPadding ->+        Column(+            modifier = Modifier+                .padding(innerPadding)+                .fillMaxSize()+                .padding(24.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.Center+        ) {+            Text(+                stringResource(R.string.competitive_score, score),+                fontWeight = FontWeight.Bold,+                fontSize = 20.sp+            )++            result?.let {+                Spacer(Modifier.height(24.dp))+                Text(+                    text = if (it.won) {+                        stringResource(R.string.competitive_solved, it.delta)+                    } else {+                        stringResource(R.string.competitive_timed_out, it.delta)+                    },+                    color = if (it.won) colorScheme.primary else colorScheme.error,+                    fontWeight = FontWeight.Bold,+                    fontSize = 22.sp+                )+            }++            Spacer(Modifier.height(32.dp))+            Text(stringResource(R.string.competitive_difficulty), fontWeight = FontWeight.Bold)+            DifficultyDropdown(selected = difficulty, onSelected = { viewModel.setDifficulty(it) })+            Text(stringResource(R.string.competitive_time_limit, difficulty.timeLimitSeconds))++            Spacer(Modifier.height(32.dp))+            Button(onClick = { viewModel.loadNextCompetitiveLevel() }) {+                Text(+                    stringResource(+                        if (result == null) R.string.competitive_start else R.string.next_level+                    )+                )+            }+        }+    }+}+ @Composable fun CompetitiveStatusBar(-    difficulty: Difficulty,-    onDifficultySelected: (Difficulty) -> Unit,     score: Int,-    roundNumber: Int,     remainingTimeMs: Long ) {     val totalSeconds = (remainingTimeMs / 1000L).toInt()@@ -694,12 +764,8 @@ fun CompetitiveStatusBar(             .padding(horizontal = 16.dp, vertical = 4.dp),         verticalAlignment = Alignment.CenterVertically     ) {-        DifficultyDropdown(selected = difficulty, onSelected = onDifficultySelected)-        Spacer(Modifier.width(8.dp))-        Text(stringResource(R.string.competitive_level, roundNumber))-        Spacer(Modifier.weight(1f))         Text(stringResource(R.string.competitive_score, score))-        Spacer(Modifier.width(16.dp))+        Spacer(Modifier.weight(1f))         Text(             text = "%d:%02d".format(minutes, seconds),             fontWeight = FontWeight.Bold,
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/CompetitiveLevelGenerator.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/CompetitiveLevelGenerator.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/CompetitiveLevelGenerator.ktindex 0d2ea99771..d32d54cd17 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/CompetitiveLevelGenerator.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/util/CompetitiveLevelGenerator.kt@@ -2,6 +2,7 @@ package com.vayunmathur.games.wordmaker.util  import android.content.Context import com.vayunmathur.games.wordmaker.data.CrosswordData+import kotlin.random.Random  /**  * Runtime crossword generator. This is a Kotlin port of scripts/wordmaker/generate_levels.py@@ -20,11 +21,17 @@ class CompetitiveLevelGenerator(private val words: List<String>) {     private val pool: List<String> = words.take(COMMON_LIMIT).filter { it.length in 3..8 }     private val wheelCandidates: List<String> = pool.filter { it.length in 7..8 } -    /** Generates a fresh crossword, or null if generation failed after the attempt budget. */-    fun generate(): CrosswordData? {+    /** Generates a fresh random crossword, or null if generation failed after the attempt budget. */+    fun generate(): CrosswordData? = generate(Random.Default)++    /**+     * Generates a crossword using the supplied [rng]. Passing a seeded [Random] makes generation+     * deterministic, so a given seed (e.g. a casual level number) always yields the same board.+     */+    fun generate(rng: Random): CrosswordData? {         if (wheelCandidates.isEmpty()) return null         repeat(WHEEL_ATTEMPTS) {-            val wheelWord = wheelCandidates.random()+            val wheelWord = wheelCandidates.random(rng)             val wheelCounts = counts(wheelWord)              val candidates = pool.filter { w ->@@ -39,18 +46,18 @@ class CompetitiveLevelGenerator(private val words: List<String>) {                 val grid = Array(rows) { CharArray(cols) { ' ' } }                  val mandatory = mutableListOf(wheelWord)-                if (Math.random() < 0.5) {+                if (rng.nextDouble() < 0.5) {                     val longCandidates = candidates.filter { it.length in 6..8 && it != wheelWord }                     if (longCandidates.isNotEmpty()) {-                        mandatory.add(longCandidates.take(10).random())+                        mandatory.add(longCandidates.take(10).random(rng))                     }                 } -                val others = candidates.filter { it !in mandatory }.shuffled()+                val others = candidates.filter { it !in mandatory }.shuffled(rng)                 val wordsToTry = (mandatory + others).take(15)                  val placed = mutableListOf<String>()-                if (placeWords(grid, wordsToTry, placed, rows, cols) &&+                if (placeWords(grid, wordsToTry, placed, rows, cols, rng) &&                     placed.size >= 6 && mandatory.all { it in placed }                 ) {                     val wheel = wheelLetters(placed)@@ -85,24 +92,25 @@ class CompetitiveLevelGenerator(private val words: List<String>) {         words: List<String>,         placed: MutableList<String>,         rows: Int,-        cols: Int+        cols: Int,+        rng: Random     ): Boolean {         if (words.isEmpty()) return true         val sorted = words.sortedByDescending { it.length }         val first = sorted[0]-        if (!placeFirstWord(grid, first, rows, cols)) return false+        if (!placeFirstWord(grid, first, rows, cols, rng)) return false         placed.add(first)         for (i in 1 until sorted.size) {-            if (tryPlaceIntersecting(grid, sorted[i], rows, cols)) placed.add(sorted[i])+            if (tryPlaceIntersecting(grid, sorted[i], rows, cols, rng)) placed.add(sorted[i])             if (placed.size >= 12) break         }         return placed.size >= 4     } -    private fun placeFirstWord(grid: Array<CharArray>, word: String, rows: Int, cols: Int): Boolean {-        val horizontal = Math.random() < 0.5-        val r = (rows / 4) + (0..(rows / 4)).random()-        val c = (cols / 4) + (0..(cols / 4)).random()+    private fun placeFirstWord(grid: Array<CharArray>, word: String, rows: Int, cols: Int, rng: Random): Boolean {+        val horizontal = rng.nextDouble() < 0.5+        val r = (rows / 4) + (0..(rows / 4)).random(rng)+        val c = (cols / 4) + (0..(cols / 4)).random(rng)         if (canPlace(grid, word, r, c, horizontal, rows, cols)) {             doPlace(grid, word, r, c, horizontal)             return true@@ -110,7 +118,7 @@ class CompetitiveLevelGenerator(private val words: List<String>) {         return false     } -    private fun tryPlaceIntersecting(grid: Array<CharArray>, word: String, rows: Int, cols: Int): Boolean {+    private fun tryPlaceIntersecting(grid: Array<CharArray>, word: String, rows: Int, cols: Int, rng: Random): Boolean {         val placements = mutableListOf<Triple<Int, Int, Boolean>>()         for (r in 0 until rows) {             for (c in 0 until cols) {@@ -123,7 +131,7 @@ class CompetitiveLevelGenerator(private val words: List<String>) {             }         }         if (placements.isEmpty()) return false-        val (r, c, horizontal) = placements.random()+        val (r, c, horizontal) = placements.random(rng)         doPlace(grid, word, r, c, horizontal)         return true     }
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 24d18a5576..822541bdee 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@@ -1,6 +1,7 @@ package com.vayunmathur.games.wordmaker.util  import android.app.Application+import android.content.Context import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.games.wordmaker.R@@ -15,10 +16,13 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine-import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import kotlin.random.Random++/** Outcome of a finished competitive level, shown on the between-levels lobby. */+data class CompetitiveResult(val won: Boolean, val delta: Int)  class WordMakerViewModel(application: Application) : AndroidViewModel(application) { @@ -61,6 +65,14 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio     private val _competitiveLevelNumber = MutableStateFlow(0)     val competitiveLevelNumber: StateFlow<Int> = _competitiveLevelNumber.asStateFlow() +    /** True while a competitive level is being played; false on the between-levels lobby. */+    private val _competitiveActive = MutableStateFlow(false)+    val competitiveActive: StateFlow<Boolean> = _competitiveActive.asStateFlow()++    /** Result of the last finished competitive level (null before the first level of the session). */+    private val _competitiveResult = MutableStateFlow<CompetitiveResult?>(null)+    val competitiveResult: StateFlow<CompetitiveResult?> = _competitiveResult.asStateFlow()+     private val _competitiveCrossword = MutableStateFlow<CrosswordData?>(null)     private val _competitiveFoundWords = MutableStateFlow<Set<String>>(emptySet()) @@ -93,19 +105,19 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio         viewModelScope.launch {             currentLevel.collectLatest { level -> loadCasualLevel(level) }         }-        // Restore a competitive board on launch if the player left the app in competitive mode.-        viewModelScope.launch {-            if (levelDataStore.gameMode.first() == GameMode.COMPETITIVE) {-                _competitiveLevelNumber.value = 0-                loadNextCompetitiveLevel()-            }-        }+        // Competitive mode always opens on the lobby; the player starts each level manually.     }      private suspend fun loadCasualLevel(level: Int) {         val ctx = getApplication<Application>()-        val data = withContext(Dispatchers.IO) {-            CrosswordData.fromAsset(ctx, "levels/$level.txt")+        val data = withContext(Dispatchers.Default) {+            // Designed levels (1..MAX_DESIGNED_LEVEL) ship as assets; beyond that (and for any+            // missing asset) generate a board deterministically seeded by the level number, so the+            // same level always yields the same layout and saved progress stays valid.+            val asset = if (level <= MAX_DESIGNED_LEVEL) {+                CrosswordData.fromAsset(ctx, "levels/$level.txt")+            } else null+            asset ?: generateSeededLevel(ctx, level)         }         _casualCrossword.value = data         if (gameMode.value != GameMode.COMPETITIVE) {@@ -113,10 +125,25 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio         }     } +    /** Deterministically generates the board for a level beyond the designed set (seeded by level). */+    private fun generateSeededLevel(ctx: Context, level: Int): CrosswordData? {+        val generator = levelGenerator+            ?: CompetitiveLevelGenerator.fromAssets(ctx).also { levelGenerator = it }+        var data = generator.generate(Random(level.toLong()))+        var attempt = 1+        while (data == null && attempt < 5) {+            data = generator.generate(Random(level.toLong() + attempt * 1_000_000L))+            attempt+++        }+        return data+    }+     /** Generates a fresh competitive layout on the fly, resets its found words and restarts the timer. */     fun loadNextCompetitiveLevel() {         viewModelScope.launch {             val ctx = getApplication<Application>()+            _competitiveActive.value = true+            _competitiveResult.value = null             // Show the loading spinner while the next board is generated.             _competitiveCrossword.value = null             _competitiveFoundWords.value = emptySet()@@ -138,39 +165,35 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio     fun setGameMode(mode: GameMode) {         viewModelScope.launch {             levelDataStore.setGameMode(mode)-            if (mode == GameMode.COMPETITIVE) {-                _competitiveLevelNumber.value = 0-                loadNextCompetitiveLevel()-            } else {-                _competitiveDeadline.value = 0L-            }+            // Both modes return to a neutral state: competitive opens its lobby, casual resumes play.+            _competitiveActive.value = false+            _competitiveResult.value = null+            _competitiveDeadline.value = 0L         }     }      fun setDifficulty(difficulty: Difficulty) {-        viewModelScope.launch {-            levelDataStore.setDifficulty(difficulty)-            // Restart with a fresh level so the new time limit applies cleanly.-            if (gameMode.value == GameMode.COMPETITIVE) {-                _competitiveLevelNumber.value = 0-                loadNextCompetitiveLevel()-            }-        }+        // Difficulty is chosen on the lobby between levels, so it only needs to be persisted.+        viewModelScope.launch { levelDataStore.setDifficulty(difficulty) }     } -    /** Player solved the competitive level in time: award points and stop the timer. */+    /** Player solved the competitive level in time: award points and return to the lobby. */     fun onCompetitiveWin() {         viewModelScope.launch {             levelDataStore.addToCompetitiveScore(difficulty.value.winDelta)+            _competitiveResult.value = CompetitiveResult(won = true, delta = difficulty.value.winDelta)             _competitiveDeadline.value = 0L+            _competitiveActive.value = false         }     } -    /** Timer ran out: deduct points and stop the timer. */+    /** Timer ran out: deduct points and return to the lobby. */     fun onCompetitiveTimeout() {         viewModelScope.launch {             levelDataStore.addToCompetitiveScore(-difficulty.value.lossDelta)+            _competitiveResult.value = CompetitiveResult(won = false, delta = -difficulty.value.lossDelta)             _competitiveDeadline.value = 0L+            _competitiveActive.value = false         }     } @@ -217,4 +240,9 @@ 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+    } }
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 7b3802f456..159d302344 100644--- a/games/wordmaker/src/main/res/values/strings.xml+++ b/games/wordmaker/src/main/res/values/strings.xml@@ -20,7 +20,9 @@     <string name="difficulty_medium">Medium</string>     <string name="difficulty_hard">Hard</string>     <string name="competitive_score">Score: %1$d</string>-    <string name="competitive_level">Round %1$d</string>-    <string name="time_up">Time\'s up!</string>-    <string name="next_round">Next Round</string>+    <string name="competitive_start">Start</string>+    <string name="competitive_difficulty">Difficulty</string>+    <string name="competitive_time_limit">%1$d seconds per level</string>+    <string name="competitive_solved">Solved! +%1$d points</string>+    <string name="competitive_timed_out">Time\'s up! %1$d points</string> </resources>\ No newline at end of file