nonogram: new game with level progression and daily puzzle
- Commit
c84b045a220dd039150e3fcb62334d55c4514b81- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-24 03:38 UTC (3 months ago)
- Parents
a85f664
Diff
games/hub/src/main/AndroidManifest.xml
diff --git a/games/hub/src/main/AndroidManifest.xml b/games/hub/src/main/AndroidManifest.xmlindex de93a7f54d..02dca58ff7 100644--- a/games/hub/src/main/AndroidManifest.xml+++ b/games/hub/src/main/AndroidManifest.xml@@ -19,6 +19,7 @@ <package android:name="com.vayunmathur.games.voxels" /> <package android:name="com.vayunmathur.games.sudoku" /> <package android:name="com.vayunmathur.games.minesweeper" />+ <package android:name="com.vayunmathur.games.nonogram" /> <package android:name="com.vayunmathur.games" /> <intent> <action android:name="android.intent.action.MAIN" />
games/nonogram/build.gradle.kts
diff --git a/games/nonogram/build.gradle.kts b/games/nonogram/build.gradle.ktsnew file mode 100644index 0000000000..f7c7c22417--- /dev/null+++ b/games/nonogram/build.gradle.kts@@ -0,0 +1,22 @@+plugins {+ id("common-conventions-app")+ // Listing screenshots come from Compose previews (src/screenshotTest), not from an+ // instrumented test on a device. Same `:games:nonogram:metadata` task name either way.+ id("common-conventions-preview-metadata")+}++launcherIcon {+ symbol = "grid_view"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.games.nonogram"+ }+}++dependencies {+ implementation(project(":sdk:games"))+ implementation(project(":library:work"))+ implementation(libs.androidx.datastore.preferences)+}
games/nonogram/src/main/AndroidManifest.xml
diff --git a/games/nonogram/src/main/AndroidManifest.xml b/games/nonogram/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..1d28acf67f--- /dev/null+++ b/games/nonogram/src/main/AndroidManifest.xml@@ -0,0 +1,34 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-permission android:name="com.vayunmathur.games.hub.permission.READ_GAME_DATA" />+ <uses-permission android:name="com.vayunmathur.games.hub.permission.WRITE_GAME_DATA" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />++ <application+ android:allowBackup="true"+ android:backupAgent=".platform.AppBackupAgent"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">+ <activity+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:name=".MainActivity"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ <!-- Pairs with openSettingsIfRequested, so App Info's settings cog deep-links there. -->+ <intent-filter>+ <action android:name="android.intent.action.APPLICATION_PREFERENCES" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ </activity>+ </application>++</manifest>
games/nonogram/src/main/assets/achievements.json
diff --git a/games/nonogram/src/main/assets/achievements.json b/games/nonogram/src/main/assets/achievements.jsonnew file mode 100644index 0000000000..7d79d6f02b--- /dev/null+++ b/games/nonogram/src/main/assets/achievements.json@@ -0,0 +1,46 @@+[+ {+ "id": "first_puzzle",+ "name": "Picture Perfect",+ "description": "Complete your first puzzle!"+ },+ {+ "id": "big_picture",+ "name": "The Big Picture",+ "description": "Complete a 15x15 puzzle."+ },+ {+ "id": "no_mistakes",+ "name": "Careful Reader",+ "description": "Complete a puzzle without ever filling a wrong cell."+ },+ {+ "id": "first_daily",+ "name": "Daily Habit",+ "description": "Complete a daily puzzle."+ },+ {+ "id": "puzzles_10",+ "name": "Getting The Hang Of It",+ "description": "Complete 10 puzzles.",+ "targetProgress": 10+ },+ {+ "id": "puzzles_50",+ "name": "Gallery Owner",+ "description": "Complete 50 puzzles.",+ "targetProgress": 50+ },+ {+ "id": "daily_streak_7",+ "name": "Week Streak",+ "description": "Complete the daily puzzle 7 days in a row.",+ "targetProgress": 7+ },+ {+ "id": "daily_streak_30",+ "name": "Month Streak",+ "description": "Complete the daily puzzle 30 days in a row.",+ "targetProgress": 30+ }+]
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/MainActivity.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/MainActivity.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/MainActivity.ktnew file mode 100644index 0000000000..04bbc67b69--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/MainActivity.kt@@ -0,0 +1,22 @@+package com.vayunmathur.games.nonogram++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.games.nonogram.platform.NonogramViewModel+import com.vayunmathur.library.ui.DynamicTheme++class MainActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ DynamicTheme {+ val viewModel: NonogramViewModel = viewModel()+ Navigation(viewModel)+ }+ }+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/Navigation.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/Navigation.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/Navigation.ktnew file mode 100644index 0000000000..1d25b61744--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/Navigation.kt@@ -0,0 +1,45 @@+package com.vayunmathur.games.nonogram++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import com.vayunmathur.games.nonogram.platform.AppBackupAgent+import com.vayunmathur.games.nonogram.platform.NonogramViewModel+import com.vayunmathur.games.nonogram.ui.NonogramGamePage+import com.vayunmathur.games.nonogram.ui.SettingsPage+import com.vayunmathur.library.ui.AchievementNotification+import com.vayunmathur.library.ui.GameCenterScreen+import com.vayunmathur.library.util.GameHubComposeHook+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.openSettingsIfRequested+import com.vayunmathur.library.util.rememberNavBackStack++@Composable+fun Navigation(viewModel: NonogramViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.Game)+ // Launching from App Info's settings cog deep-links straight to Settings.+ backStack.openSettingsIfRequested(Route.Settings)+ val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()+ GameHubComposeHook("nonogram", viewModel.achievementsManager)+ Box(Modifier.fillMaxSize()) {+ MainNavigation(backStack) {+ entry<Route.Game> { NonogramGamePage(backStack, viewModel) }+ entry<Route.GameCenter> {+ GameCenterScreen(+ backupAgent = AppBackupAgent(),+ manager = viewModel.achievementsManager,+ onBack = { backStack.pop() },+ )+ }+ entry<Route.Settings> {+ SettingsPage(viewModel = viewModel, onBack = { backStack.pop() })+ }+ }+ newAchievement?.let {+ AchievementNotification(it) { viewModel.dismissAchievementNotification() }+ }+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/Route.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/Route.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/Route.ktnew file mode 100644index 0000000000..0cd337ae0d--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/Route.kt@@ -0,0 +1,17 @@+package com.vayunmathur.games.nonogram++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+ /** The only board there is: which puzzle it shows comes from the stored mode and level. */+ @Serializable+ data object Game : Route++ @Serializable+ data object GameCenter : Route++ @Serializable+ data object Settings : Route+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.ktnew file mode 100644index 0000000000..71003b9ef9--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramDataStore.kt@@ -0,0 +1,146 @@+package com.vayunmathur.games.nonogram.data++import android.content.Context+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+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++private val Context.dataStore by preferencesDataStore(name = "settings")++/**+ * Everything the game remembers.+ *+ * Casual progress is a single level number plus the marks on that one level; there is no per-level+ * record, because advancing clears the marks and there is no way back. Daily progress is kept+ * separately and stamped with the day it belongs to, so yesterday's work can never bleed into today's+ * puzzle — see [dailyDay] and `ensureDailyDay`.+ */+class NonogramDataStore(private val context: Context) {++ val currentLevel: Flow<Int> = context.dataStore.data.map { it[LEVEL_KEY] ?: 1 }++ val filledCells: Flow<Set<Int>> = context.dataStore.data.map { it[FILLED_KEY].toCells() }+ val crossedCells: Flow<Set<Int>> = context.dataStore.data.map { it[CROSSED_KEY].toCells() }++ val gameMode: Flow<GameMode> = context.dataStore.data.map { prefs ->+ prefs[GAME_MODE_KEY]?.let { runCatching { GameMode.valueOf(it) }.getOrNull() }+ ?: GameMode.CASUAL+ }++ val showMistakes: Flow<Boolean> = context.dataStore.data.map { it[SHOW_MISTAKES_KEY] ?: true }++ /** Lifetime count of completed puzzles, which survives [saveLevel] clearing the board. */+ val puzzlesCompleted: Flow<Int> = context.dataStore.data.map { it[COMPLETED_KEY] ?: 0 }++ // ---- Daily ----++ val dailyDay: Flow<Long> = context.dataStore.data.map { it[DAILY_DAY_KEY] ?: NO_DAY }+ val dailyFilledCells: Flow<Set<Int>> =+ context.dataStore.data.map { it[DAILY_FILLED_KEY].toCells() }+ val dailyCrossedCells: Flow<Set<Int>> =+ context.dataStore.data.map { it[DAILY_CROSSED_KEY].toCells() }++ suspend fun setGameMode(mode: GameMode) {+ context.dataStore.edit { it[GAME_MODE_KEY] = mode.name }+ }++ suspend fun setShowMistakes(enabled: Boolean) {+ context.dataStore.edit { it[SHOW_MISTAKES_KEY] = enabled }+ }++ /**+ * Moves to [level] and wipes the board in the same write.+ *+ * One edit rather than two, so a crash between them cannot leave the previous level's marks on the+ * new puzzle.+ */+ suspend fun saveLevel(level: Int) {+ context.dataStore.edit { prefs ->+ prefs[LEVEL_KEY] = level+ prefs[FILLED_KEY] = emptySet()+ prefs[CROSSED_KEY] = emptySet()+ }+ }++ /** Clears the current level's marks without advancing, for the restart button. */+ suspend fun clearMarks(daily: Boolean) {+ context.dataStore.edit { prefs ->+ prefs[if (daily) DAILY_FILLED_KEY else FILLED_KEY] = emptySet()+ prefs[if (daily) DAILY_CROSSED_KEY else CROSSED_KEY] = emptySet()+ }+ }++ /**+ * Records the mark on [index], keeping the two sets disjoint.+ *+ * A cell is either filled, crossed, or neither, so setting one mark always removes the other.+ */+ suspend fun setMark(index: Int, mark: CellMark, daily: Boolean) {+ val filledKey = if (daily) DAILY_FILLED_KEY else FILLED_KEY+ val crossedKey = if (daily) DAILY_CROSSED_KEY else CROSSED_KEY+ context.dataStore.edit { prefs ->+ val filled = prefs[filledKey].toCells().toMutableSet()+ val crossed = prefs[crossedKey].toCells().toMutableSet()+ filled.remove(index)+ crossed.remove(index)+ when (mark) {+ CellMark.FILLED -> filled.add(index)+ CellMark.CROSSED -> crossed.add(index)+ CellMark.BLANK -> Unit+ }+ prefs[filledKey] = filled.mapTo(mutableSetOf()) { it.toString() }+ prefs[crossedKey] = crossed.mapTo(mutableSetOf()) { it.toString() }+ }+ }++ /** Bumps and returns the lifetime completed count. */+ suspend fun recordCompleted(): Int {+ var total = 0+ context.dataStore.edit { prefs ->+ total = (prefs[COMPLETED_KEY] ?: 0) + 1+ prefs[COMPLETED_KEY] = total+ }+ return total+ }++ /**+ * Rolls the daily board over to [day] if it is not already there.+ *+ * Clearing on rollover is what stops yesterday's marks appearing on today's puzzle. The early+ * return keeps re-entering daily mode from wiping work in progress.+ */+ suspend fun ensureDailyDay(day: Long) {+ context.dataStore.edit { prefs ->+ if (prefs[DAILY_DAY_KEY] == day) return@edit+ prefs[DAILY_DAY_KEY] = day+ prefs[DAILY_FILLED_KEY] = emptySet()+ prefs[DAILY_CROSSED_KEY] = emptySet()+ }+ }++ private companion object {+ val LEVEL_KEY = intPreferencesKey("current_level")+ val FILLED_KEY = stringSetPreferencesKey("filled_cells")+ val CROSSED_KEY = stringSetPreferencesKey("crossed_cells")+ val GAME_MODE_KEY = stringPreferencesKey("game_mode")+ val SHOW_MISTAKES_KEY = booleanPreferencesKey("show_mistakes")+ val COMPLETED_KEY = intPreferencesKey("puzzles_completed")++ val DAILY_DAY_KEY = longPreferencesKey("daily_day")+ val DAILY_FILLED_KEY = stringSetPreferencesKey("daily_filled_cells")+ val DAILY_CROSSED_KEY = stringSetPreferencesKey("daily_crossed_cells")++ /** Sentinel for "no daily played yet"; distinct from epoch day 0, which is a real date. */+ const val NO_DAY = Long.MIN_VALUE+ }+}++/** Cell indices are stored as strings because DataStore has no int-set type. */+private fun Set<String>?.toCells(): Set<Int> =+ this?.mapNotNullTo(mutableSetOf()) { it.toIntOrNull() } ?: emptySet()
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.ktnew file mode 100644index 0000000000..7489939670--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramModels.kt@@ -0,0 +1,74 @@+package com.vayunmathur.games.nonogram.data++import kotlinx.serialization.Serializable++/**+ * Which puzzle the player is looking at.+ *+ * There is no level picker: [CASUAL] is a single "current level" counter that only ever moves+ * forward, and [DAILY] is one puzzle per calendar day shared by everyone on the same date.+ */+@Serializable+enum class GameMode { CASUAL, DAILY }++/**+ * What the player has put in a cell.+ *+ * [CROSSED] is the "definitely blank" mark. It is bookkeeping only — the win check looks at [FILLED]+ * alone — but it is how a nonogram is actually solved, so it has to persist alongside the fills.+ */+enum class CellMark { BLANK, FILLED, CROSSED }++/**+ * A puzzle plus the player's work on it.+ *+ * [filled] and [crossed] are disjoint sets of cell indices: marking a cell one way clears the other,+ * because a cell cannot be both. Storing them as sets rather than a per-cell list keeps the DataStore+ * write small — only the cells actually touched are persisted.+ */+data class NonogramGameState(+ val puzzle: NonogramPuzzle,+ val filled: Set<Int>,+ val crossed: Set<Int>,+ val mode: GameMode,+ val level: Int,+ val elapsedSeconds: Int = 0,+) {+ val size: Int get() = puzzle.size++ fun markAt(index: Int): CellMark = when (index) {+ in filled -> CellMark.FILLED+ in crossed -> CellMark.CROSSED+ else -> CellMark.BLANK+ }++ /**+ * Won when the filled cells are exactly the solution's.+ *+ * Crosses are ignored, and an over-filled grid does not count — the sets must match, not merely+ * cover.+ */+ val isWon: Boolean+ get() = filled.size == puzzle.filledCount &&+ filled.all { puzzle.solution[it] }++ /** Cells the player filled that should be blank, so the board can point out a wrong guess. */+ fun isMistake(index: Int): Boolean = index in filled && !puzzle.solution[index]++ val hasMistake: Boolean get() = filled.any { !puzzle.solution[it] }+}++/**+ * How big level [level] is.+ *+ * The ramp exists so the first few levels teach the mechanic on a grid small enough to hold in your+ * head, and so a new player is not handed a 15x15 as their introduction.+ */+fun sizeForLevel(level: Int): Int = when {+ level <= 8 -> 5+ level <= 20 -> 10+ else -> 15+}++/** Daily puzzles are a fixed size, so the challenge is comparable from one day to the next. */+const val DAILY_SIZE = 10
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramPuzzle.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramPuzzle.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramPuzzle.ktnew file mode 100644index 0000000000..84f671a557--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/data/NonogramPuzzle.kt@@ -0,0 +1,46 @@+package com.vayunmathur.games.nonogram.data++/**+ * A generated puzzle.+ *+ * [solution] is row-major and `size * size` long. The clues are derived from it, so they are always+ * consistent; an empty clue list means the line holds no filled cells and is drawn as a single 0.+ */+data class NonogramPuzzle(+ val size: Int,+ val solution: List<Boolean>,+ val rowClues: List<List<Int>>,+ val colClues: List<List<Int>>,+) {+ val filledCount: Int get() = solution.count { it }++ companion object {+ /** Run lengths of filled cells along [line], the clue a player reads. */+ fun cluesFor(line: List<Boolean>): List<Int> {+ val out = mutableListOf<Int>()+ var run = 0+ for (filled in line) {+ if (filled) {+ run+++ } else if (run > 0) {+ out.add(run)+ run = 0+ }+ }+ if (run > 0) out.add(run)+ return out+ }++ /** Clues for every row and column of [solution]. */+ fun from(size: Int, solution: List<Boolean>): NonogramPuzzle = NonogramPuzzle(+ size = size,+ solution = solution,+ rowClues = (0 until size).map { row ->+ cluesFor((0 until size).map { solution[row * size + it] })+ },+ colClues = (0 until size).map { col ->+ cluesFor((0 until size).map { solution[it * size + col] })+ },+ )+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.ktnew file mode 100644index 0000000000..f221edd2ca--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt@@ -0,0 +1,69 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.NonogramPuzzle+import kotlin.random.Random++/**+ * Paints a random pattern, derives its clues, and keeps it only if [NonogramSolver] can crack it+ * without guessing.+ *+ * Most random patterns fail that test, which is why this loops. Rejection sampling is cheap here+ * because the check is line propagation over a grid of at most 15 — a handful of milliseconds — so a+ * few dozen attempts still finish fast enough to run on a background dispatcher while a spinner+ * shows. This is the opposite trade to `games/pipes`, whose win condition needs a full-board+ * uniqueness proof too slow to attempt on device.+ */+object NonogramGenerator {++ /**+ * A puzzle of [size] that line logic alone can finish, or null if [attempts] candidates all+ * needed guesswork.+ *+ * Returning null rather than looping forever keeps the caller in control: it can widen the search+ * with a fresh seed instead of blocking the UI indefinitely on a bad starting point.+ */+ fun generate(+ size: Int,+ rng: Random,+ fillRatio: Double = DEFAULT_FILL_RATIO,+ attempts: Int = DEFAULT_ATTEMPTS,+ ): NonogramPuzzle? {+ repeat(attempts) {+ val candidate = paint(size, rng, fillRatio)+ // An all-blank grid is technically line-solvable and completely pointless to play.+ if (candidate.none { it }) return@repeat+ val puzzle = NonogramPuzzle.from(size, candidate)+ if (NonogramSolver.isLineSolvable(size, puzzle.rowClues, puzzle.colClues)) return puzzle+ }+ return null+ }++ /**+ * A puzzle for [size], retrying with derived seeds until one is found.+ *+ * Every seed is a pure function of [seed], so the same level number always yields the same+ * puzzle however many rounds it takes — that is what lets saved progress stay valid.+ */+ fun generateSeeded(size: Int, seed: Long, rounds: Int = DEFAULT_ROUNDS): NonogramPuzzle? {+ for (round in 0 until rounds) {+ generate(size, Random(seed + round * SEED_STRIDE))?.let { return it }+ }+ return null+ }++ /** Independent coin flips per cell. Simple, and the solver filters out the unfair results. */+ private fun paint(size: Int, rng: Random, fillRatio: Double): List<Boolean> =+ List(size * size) { rng.nextDouble() < fillRatio }++ /**+ * Roughly half filled. Much sparser and the picture is mostly blank; much denser and the clues+ * collapse into a few long runs that give the whole thing away.+ */+ const val DEFAULT_FILL_RATIO = 0.55++ private const val DEFAULT_ATTEMPTS = 60+ private const val DEFAULT_ROUNDS = 8++ /** Keeps the per-round seeds far apart so consecutive rounds do not repaint near-identical grids. */+ private const val SEED_STRIDE = 1_000_003L+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramSolver.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramSolver.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramSolver.ktnew file mode 100644index 0000000000..6239e29205--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramSolver.kt@@ -0,0 +1,123 @@+package com.vayunmathur.games.nonogram.domain++/** What is known about a cell part-way through solving. */+enum class CellState { UNKNOWN, FILLED, EMPTY }++/**+ * Line-by-line constraint propagation — the deduction a human actually does.+ *+ * For each row and column it enumerates every arrangement of that line's clues that is consistent+ * with what is already known, then keeps only the cells every arrangement agrees on. Repeating that+ * over all lines until nothing changes solves any puzzle that can be solved without guessing.+ *+ * This is a deliberately *weaker* test than "has exactly one solution". A puzzle can be unique and+ * still require a chain of hypothetical moves to crack, which is miserable on a phone. Requiring full+ * determination by line logic is what makes a generated puzzle fair, so it is the bar the generator+ * holds candidates to.+ */+object NonogramSolver {++ /**+ * Solves [rowClues] / [colClues] as far as line logic reaches.+ *+ * Returns the grid — which may still hold [CellState.UNKNOWN] cells if the puzzle needs guessing+ * — or null if the clues contradict each other and no arrangement exists.+ */+ fun solve(size: Int, rowClues: List<List<Int>>, colClues: List<List<Int>>): List<CellState>? {+ val grid = MutableList(size * size) { CellState.UNKNOWN }++ var changed = true+ while (changed) {+ changed = false+ for (row in 0 until size) {+ val indices = IntArray(size) { row * size + it }+ val progressed = refineLine(grid, indices, rowClues[row]) ?: return null+ if (progressed) changed = true+ }+ for (col in 0 until size) {+ val indices = IntArray(size) { it * size + col }+ val progressed = refineLine(grid, indices, colClues[col]) ?: return null+ if (progressed) changed = true+ }+ }+ return grid+ }++ /** True when line logic alone pins down every cell. */+ fun isLineSolvable(size: Int, rowClues: List<List<Int>>, colClues: List<List<Int>>): Boolean {+ val solved = solve(size, rowClues, colClues) ?: return false+ return solved.none { it == CellState.UNKNOWN }+ }++ /**+ * Narrows one line to the cells every legal arrangement agrees on.+ *+ * Returns whether anything new was learned, or null if the line has no legal arrangement at all.+ */+ private fun refineLine(+ grid: MutableList<CellState>,+ indices: IntArray,+ clues: List<Int>,+ ): Boolean? {+ val n = indices.size+ val known = Array(n) { grid[indices[it]] }++ // Space each clue suffix needs, including one gap between neighbours, so a placement loop+ // can stop early instead of recursing into arrangements that cannot fit.+ val minLengths = IntArray(clues.size + 1)+ for (i in clues.indices.reversed()) {+ minLengths[i] = clues[i] + if (i + 1 < clues.size) 1 + minLengths[i + 1] else 0+ }++ // Bits set in every arrangement must be filled; bits set in none must be empty.+ var andMask = -1+ var orMask = 0+ var found = false++ fun place(clueIndex: Int, from: Int, mask: Int) {+ if (clueIndex == clues.size) {+ // Everything left over has to be blank, so a known-filled cell rules this out.+ for (i in from until n) if (known[i] == CellState.FILLED) return+ found = true+ andMask = andMask and mask+ orMask = orMask or mask+ return+ }++ val len = clues[clueIndex]+ val lastStart = n - minLengths[clueIndex]+ var start = from+ while (start <= lastStart) {+ val fits = (start until start + len).none { known[it] == CellState.EMPTY }+ if (fits) {+ val after = start + len+ // The cell just past a block must be blank, or the block would be longer.+ if (after >= n || known[after] != CellState.FILLED) {+ place(clueIndex + 1, after + 1, mask or (((1 shl len) - 1) shl start))+ }+ }+ // Sliding further would leave this cell in a gap, which a filled cell cannot be.+ if (known[start] == CellState.FILLED) break+ start+++ }+ }+ place(0, 0, 0)++ if (!found) return null++ var changed = false+ for (i in 0 until n) {+ val bit = 1 shl i+ val deduced = when {+ andMask and bit != 0 -> CellState.FILLED+ orMask and bit == 0 -> CellState.EMPTY+ else -> null+ } ?: continue+ if (grid[indices[i]] == CellState.UNKNOWN) {+ grid[indices[i]] = deduced+ changed = true+ }+ }+ return changed+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/AppBackupAgent.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/AppBackupAgent.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..74f42540e3--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/AppBackupAgent.kt@@ -0,0 +1,12 @@+package com.vayunmathur.games.nonogram.platform++import com.vayunmathur.library.util.BaseBackupAgent++class AppBackupAgent : BaseBackupAgent() {+ /**+ * Both files, or a restore silently wipes half the player's history: "settings" holds the level+ * and the marks on it, while the shared DataStoreUtils file holds the daily streak and the+ * achievement unlocks.+ */+ override val datastoreNames: List<String> get() = listOf("settings", "datastore_default")+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramAchievementsManager.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramAchievementsManager.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramAchievementsManager.ktnew file mode 100644index 0000000000..b74e2ea39f--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramAchievementsManager.kt@@ -0,0 +1,42 @@+package com.vayunmathur.games.nonogram.platform++import android.content.Context+import com.vayunmathur.games.nonogram.data.NonogramDataStore+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+import kotlinx.coroutines.launch++class NonogramAchievementsManager(+ context: Context,+ json: String,+ private val dataStore: NonogramDataStore,+ private val dailyStore: DailyChallengeStore,+) : AchievementsManager(context, json) {++ /**+ * Back-fills from stored progress on launch, so an achievement added in a later release is awarded+ * for work the player has already done rather than only for the next puzzle they finish.+ *+ * The reads are suspending, so this hands off to a coroutine rather than blocking. Anything about+ * how a single puzzle was played — whether a wrong cell was ever filled — is gone once the level+ * advances, so those are unlocked from the win handler instead.+ */+ override fun checkExistingAchievements() {+ CoroutineScope(Dispatchers.IO).launch {+ val total = dataStore.puzzlesCompleted.first()+ if (total > 0) onAchievementUnlocked("first_puzzle")+ onProgressUpdated("puzzles_10", total)+ onProgressUpdated("puzzles_50", total)++ if (dailyStore.lastCompletedDay() != DailyChallengeStore.NO_DAY) {+ onAchievementUnlocked("first_daily")+ }+ val best = dailyStore.bestStreak().toInt()+ onProgressUpdated("daily_streak_7", best)+ onProgressUpdated("daily_streak_30", best)+ }+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.ktnew file mode 100644index 0000000000..9889045352--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt@@ -0,0 +1,57 @@+package com.vayunmathur.games.nonogram.platform++import com.vayunmathur.games.nonogram.data.GameMode+import com.vayunmathur.games.nonogram.data.NonogramGameState++/**+ * The UI contract between [NonogramViewModel] and the board.+ *+ * The board takes this interface rather than the ViewModel itself so it can be rendered by a+ * `@Preview` — which is what the store listing images are generated from. It lives in `platform`+ * rather than next to the board so the dependency runs one way: `ui` depends on `platform`, and the+ * ViewModel implements this.+ *+ * Every member has a no-op default, so `Noop` is the whole implementation a preview needs.+ */+interface NonogramGameActions {+ /** Tap: cycles blank to filled to crossed and back. */+ fun tapCell(index: Int) {}++ /** Long press: crosses a cell directly, skipping the fill step. */+ fun crossCell(index: Int) {}++ fun nextLevel() {}+ fun restartLevel() {}+ fun setGameMode(mode: GameMode) {}++ companion object { val Noop: NonogramGameActions = object : NonogramGameActions {} }+}++/** What the board needs to draw itself. [game] is null only while a puzzle is being generated. */+data class NonogramUiState(+ val game: NonogramGameState? = null,+ val mode: GameMode = GameMode.CASUAL,+ val level: Int = 1,+ val showMistakes: Boolean = true,+ val dailyStreak: Long = 0,+ /** True once today's daily has been completed, which swaps the next-level button for a note. */+ val dailyDone: Boolean = false,+ val generating: Boolean = false,+ /** Set when even a widened seed search found no fair puzzle, so the board can offer a retry. */+ val generationFailed: Boolean = false,+)++interface SettingsActions {+ fun setShowMistakes(enabled: Boolean) {}+ fun setReminderEnabled(enabled: Boolean) {}+ fun setReminderTime(hour: Int, minute: Int) {}++ companion object { val Noop: SettingsActions = object : SettingsActions {} }+}++data class SettingsUiState(+ val showMistakes: Boolean = true,+ val reminderEnabled: Boolean = false,+ val reminderHour: Int = 20,+ val reminderMinute: Int = 0,+)
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.ktnew file mode 100644index 0000000000..89545f6c9c--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt@@ -0,0 +1,285 @@+package com.vayunmathur.games.nonogram.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.games.nonogram.data.CellMark+import com.vayunmathur.games.nonogram.data.DAILY_SIZE+import com.vayunmathur.games.nonogram.data.GameMode+import com.vayunmathur.games.nonogram.data.NonogramDataStore+import com.vayunmathur.games.nonogram.data.NonogramGameState+import com.vayunmathur.games.nonogram.data.NonogramPuzzle+import com.vayunmathur.games.nonogram.data.sizeForLevel+import com.vayunmathur.games.nonogram.domain.NonogramGenerator+import com.vayunmathur.library.util.AchievementsManager+import com.vayunmathur.library.util.DailyChallengeStore+import com.vayunmathur.library.util.DailyStreakReporter+import com.vayunmathur.library.work.DailyPuzzleReminder+import com.vayunmathur.library.work.DailyReminderSettings+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.collectLatest+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Owns the puzzle on screen and the progress behind it.+ *+ * Casual mode is a single level counter: finishing writes `level + 1` and clears the board in one+ * DataStore edit, so there is no level list and no way back. Daily mode is one puzzle per calendar+ * day, generated from the date, with its own marks stamped with the day they belong to.+ *+ * Generation runs on [Dispatchers.Default]: the generator paints candidates and rejects any the line+ * solver cannot finish, which is fast but not free, and a 15x15 should not stutter the board.+ */+class NonogramViewModel(application: Application) : AndroidViewModel(application),+ NonogramGameActions, SettingsActions {++ val dataStore = NonogramDataStore(application)+ private val dailyStore = DailyChallengeStore(application, DAILY_KEY_PREFIX)+ private val reminderSettings = DailyReminderSettings(application, DAILY_KEY_PREFIX)++ private val _uiState = MutableStateFlow(NonogramUiState())+ val uiState: StateFlow<NonogramUiState> = _uiState.asStateFlow()++ /** Cached per (size, seed) so flipping modes back and forth does not regenerate. */+ private var casualPuzzle: Pair<Int, NonogramPuzzle>? = null+ private var dailyPuzzle: Pair<Long, NonogramPuzzle>? = null++ val reminderEnabled: StateFlow<Boolean> = reminderSettings.enabled+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)++ val reminderMinutesOfDay: StateFlow<Long> = reminderSettings.minutesOfDay+ .stateIn(+ viewModelScope,+ SharingStarted.WhileSubscribed(5_000),+ DailyPuzzleReminder.DEFAULT_MINUTES_OF_DAY,+ )++ val achievementsManager: AchievementsManager = run {+ val json = application.assets.open("achievements.json").bufferedReader().readText()+ NonogramAchievementsManager(application, json, dataStore, dailyStore)+ }++ init {+ achievementsManager.checkExistingAchievements()++ // One collector drives the whole screen: whichever of mode, level or marks changes, the+ // board is rebuilt from the stored state rather than mutated in place.+ viewModelScope.launch {+ combine(+ dataStore.gameMode,+ dataStore.currentLevel,+ dataStore.showMistakes,+ dailyStore.currentStreak,+ ) { mode, level, showMistakes, streak -> Session(mode, level, showMistakes, streak) }+ .collectLatest { session -> load(session) }+ }+ }++ /** The stored inputs that decide which puzzle is on screen. */+ private data class Session(+ val mode: GameMode,+ val level: Int,+ val showMistakes: Boolean,+ val streak: Long,+ )++ private suspend fun load(session: Session) {+ val daily = session.mode == GameMode.DAILY+ val day = dailyStore.todayEpochDay()+ if (daily) dataStore.ensureDailyDay(day)++ _uiState.value = _uiState.value.copy(+ mode = session.mode,+ level = session.level,+ showMistakes = session.showMistakes,+ dailyStreak = session.streak,+ generating = true,+ generationFailed = false,+ )++ val size = if (daily) DAILY_SIZE else sizeForLevel(session.level)+ val seed = if (daily) DAILY_SEED_OFFSET + day else session.level.toLong()++ val puzzle = withContext(Dispatchers.Default) {+ val cached = if (daily) dailyPuzzle?.takeIf { it.first == day }?.second+ else casualPuzzle?.takeIf { it.first == session.level }?.second+ cached ?: NonogramGenerator.generateSeeded(size, seed)+ }++ if (puzzle == null) {+ _uiState.value = _uiState.value.copy(generating = false, generationFailed = true)+ return+ }+ if (daily) dailyPuzzle = day to puzzle else casualPuzzle = session.level to puzzle++ // Marks are collected separately so a tap redraws without regenerating the puzzle.+ observeMarks(session, puzzle, day)+ }++ /**+ * Streams the player's marks onto [puzzle].+ *+ * Daily marks are blanked whenever the stored day is not the day being played, so a stale write+ * from yesterday can never show up on today's board even if the rollover edit was interrupted.+ */+ private suspend fun observeMarks(session: Session, puzzle: NonogramPuzzle, day: Long) {+ val daily = session.mode == GameMode.DAILY+ val filledFlow = if (daily) dataStore.dailyFilledCells else dataStore.filledCells+ val crossedFlow = if (daily) dataStore.dailyCrossedCells else dataStore.crossedCells++ combine(filledFlow, crossedFlow, dataStore.dailyDay, dailyStore.lastCompletedDayFlow) {+ filled, crossed, storedDay, lastCompleted ->+ val stale = daily && storedDay != day+ Triple(+ if (stale) emptySet() else filled,+ if (stale) emptySet() else crossed,+ lastCompleted == day,+ )+ }.collectLatest { (filled, crossed, dailyDone) ->+ val game = NonogramGameState(+ puzzle = puzzle,+ filled = filled,+ crossed = crossed,+ mode = session.mode,+ level = session.level,+ )+ _uiState.value = _uiState.value.copy(+ game = game,+ generating = false,+ dailyDone = dailyDone,+ )+ if (game.isWon) onWin(game, daily, day)+ }+ }++ override fun tapCell(index: Int) {+ val game = _uiState.value.game ?: return+ if (game.isWon) return+ // Blank -> filled -> crossed -> blank, so one finger can reach every state.+ val next = when (game.markAt(index)) {+ CellMark.BLANK -> CellMark.FILLED+ CellMark.FILLED -> CellMark.CROSSED+ CellMark.CROSSED -> CellMark.BLANK+ }+ setMark(index, next)+ }++ override fun crossCell(index: Int) {+ val game = _uiState.value.game ?: return+ if (game.isWon) return+ val next =+ if (game.markAt(index) == CellMark.CROSSED) CellMark.BLANK else CellMark.CROSSED+ setMark(index, next)+ }++ private fun setMark(index: Int, mark: CellMark) {+ val daily = _uiState.value.mode == GameMode.DAILY+ viewModelScope.launch { dataStore.setMark(index, mark, daily) }+ }++ override fun nextLevel() {+ val state = _uiState.value+ if (state.mode == GameMode.DAILY) return+ viewModelScope.launch { dataStore.saveLevel(state.level + 1) }+ }++ override fun restartLevel() {+ val daily = _uiState.value.mode == GameMode.DAILY+ viewModelScope.launch { dataStore.clearMarks(daily) }+ }++ override fun setGameMode(mode: GameMode) {+ viewModelScope.launch { dataStore.setGameMode(mode) }+ }++ override fun setShowMistakes(enabled: Boolean) {+ viewModelScope.launch { dataStore.setShowMistakes(enabled) }+ }++ override fun setReminderEnabled(enabled: Boolean) {+ viewModelScope.launch {+ reminderSettings.setEnabled(enabled)+ rescheduleReminder(enabled, reminderMinutesOfDay.value)+ }+ }++ override fun setReminderTime(hour: Int, minute: Int) {+ viewModelScope.launch {+ val minutes = (hour * 60 + minute).toLong()+ reminderSettings.setMinutesOfDay(minutes)+ rescheduleReminder(reminderEnabled.value, minutes)+ }+ }++ private fun rescheduleReminder(enabled: Boolean, minutesOfDay: Long) {+ DailyPuzzleReminder.update(+ context = getApplication(),+ keyPrefix = DAILY_KEY_PREFIX,+ notificationId = REMINDER_NOTIFICATION_ID,+ enabled = enabled,+ hour = (minutesOfDay / 60).toInt(),+ minute = (minutesOfDay % 60).toInt(),+ )+ }++ fun dismissAchievementNotification() = achievementsManager.dismissNotification()++ /**+ * The one place a completed puzzle is recorded.+ *+ * Reached from the marks collector, so it can fire more than once for the same win as unrelated+ * flows re-emit. Everything it touches is idempotent for a given day: [DailyChallengeStore] treats+ * a repeat of the same day as a no-op, and unlocking an already-unlocked achievement does nothing.+ * The lifetime counter is the exception, so it is guarded.+ */+ private fun onWin(game: NonogramGameState, daily: Boolean, day: Long) {+ // Daily wins are keyed by day and casual wins by negated level, which cannot collide.+ val key = if (daily) day else -game.level.toLong()+ if (recordedWin == key) return+ recordedWin = key++ viewModelScope.launch {+ val total = dataStore.recordCompleted()+ val manager = achievementsManager+ manager.onAchievementUnlocked("first_puzzle")+ if (game.size >= BIG_PICTURE_SIZE) manager.onAchievementUnlocked("big_picture")+ if (!game.hasMistake) manager.onAchievementUnlocked("no_mistakes")+ manager.onProgressUpdated("puzzles_10", total)+ manager.onProgressUpdated("puzzles_50", total)++ if (daily) {+ manager.onAchievementUnlocked("first_daily")+ val streak = dailyStore.recordDayCompleted(day)+ DailyStreakReporter.report(getApplication(), "nonogram", streak, day)+ manager.onProgressUpdated("daily_streak_7", streak.current.toInt())+ manager.onProgressUpdated("daily_streak_30", streak.current.toInt())+ }+ }+ }++ /** Which win has already been banked, so a re-emitted flow cannot double-count it. */+ private var recordedWin: Long? = null++ companion object {+ /** Namespace shared by the daily-challenge store and its reminder. */+ const val DAILY_KEY_PREFIX = "nonogram_daily"++ private const val REMINDER_NOTIFICATION_ID = 5104++ /**+ * Keeps date-derived daily seeds away from the level-number seeds casual mode uses, and away+ * from the offsets the other games picked (500M pipes, 700M wordmaker, 900M unblockjam).+ */+ private const val DAILY_SEED_OFFSET = 1_100_000_000L++ /** Matches the "15x15" wording of the `big_picture` description. */+ private const val BIG_PICTURE_SIZE = 15+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGamePage.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGamePage.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGamePage.ktnew file mode 100644index 0000000000..074fd0d255--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGamePage.kt@@ -0,0 +1,28 @@+package com.vayunmathur.games.nonogram.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.games.nonogram.Route+import com.vayunmathur.games.nonogram.platform.NonogramViewModel+import com.vayunmathur.library.util.NavBackStack++/**+ * Binds [NonogramViewModel] to the stateless [NonogramGameScreen].+ *+ * The ViewModel already implements the actions contract, so this only has to collect state and supply+ * the two navigation callbacks the board cannot know about.+ */+@Composable+fun NonogramGamePage(+ backStack: NavBackStack<Route>,+ viewModel: NonogramViewModel,+) {+ val uiState by viewModel.uiState.collectAsState()+ NonogramGameScreen(+ state = uiState,+ actions = viewModel,+ onOpenSettings = { backStack.add(Route.Settings) },+ onOpenGameCenter = { backStack.add(Route.GameCenter) },+ )+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.ktnew file mode 100644index 0000000000..121f505506--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt@@ -0,0 +1,203 @@+package com.vayunmathur.games.nonogram.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+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.foundation.layout.widthIn+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.nonogram.R+import com.vayunmathur.games.nonogram.data.GameMode+import com.vayunmathur.games.nonogram.platform.NonogramGameActions+import com.vayunmathur.games.nonogram.platform.NonogramUiState+import com.vayunmathur.games.nonogram.ui.components.NonogramBoard+import com.vayunmathur.library.ui.AppBarAlignment+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.IconArrowDropDown+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconEmojiEvents+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior++/** Caps the board on tablets, where a full-width grid would give absurdly large cells. */+private val BoardMaxWidth = 460.dp++/**+ * The board, with no dependency on the ViewModel so it can be rendered from a `@Preview` — see+ * `src/screenshotTest`.+ */+@Composable+fun NonogramGameScreen(+ state: NonogramUiState,+ actions: NonogramGameActions,+ onOpenSettings: () -> Unit,+ onOpenGameCenter: () -> Unit,+) {+ val daily = state.mode == GameMode.DAILY+ AppScaffold(+ title = {+ ModeDropdown(+ mode = state.mode,+ level = state.level,+ onSelect = actions::setGameMode,+ )+ },+ alignment = AppBarAlignment.Center,+ actions = {+ IconButton(onClick = onOpenGameCenter) { IconEmojiEvents() }+ IconButton(onClick = onOpenSettings) { IconSettings() }+ },+ scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ Column(+ Modifier+ .fillMaxSize()+ .padding(padding)+ .padding(horizontal = Spacing.md),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(Spacing.md),+ ) {+ if (daily) {+ Text(+ stringResource(R.string.daily_streak, state.dailyStreak),+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }++ val game = state.game+ when {+ state.generationFailed -> Column(+ Modifier.fillMaxWidth(),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(Spacing.md),+ ) {+ Text(+ stringResource(R.string.generation_failed),+ color = MaterialTheme.colorScheme.error,+ textAlign = TextAlign.Center,+ )+ Button(onClick = { actions.restartLevel() }) {+ Text(stringResource(R.string.try_again))+ }+ }++ game == null -> Box(+ Modifier.fillMaxWidth().padding(Spacing.xxl),+ contentAlignment = Alignment.Center,+ ) { CircularProgressIndicator() }++ else -> {+ NonogramBoard(+ game = game,+ showMistakes = state.showMistakes,+ onTap = actions::tapCell,+ onLongPress = actions::crossCell,+ modifier = Modifier+ .widthIn(max = BoardMaxWidth)+ .fillMaxWidth(),+ )++ if (game.isWon) {+ Text(+ stringResource(R.string.solved),+ style = MaterialTheme.typography.titleLarge,+ color = MaterialTheme.colorScheme.primary,+ )+ if (daily) {+ Text(+ stringResource(R.string.daily_come_back_tomorrow),+ style = MaterialTheme.typography.bodyMedium,+ textAlign = TextAlign.Center,+ )+ } else {+ Button(+ onClick = { actions.nextLevel() },+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.next_level)) }+ }+ } else {+ if (game.filled.isEmpty() && game.crossed.isEmpty()) {+ Text(+ stringResource(R.string.how_to_play),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ OutlinedButton(onClick = { actions.restartLevel() }) {+ Text(stringResource(R.string.restart))+ }+ }+ }+ }+ }+ }+}++/**+ * The title doubles as the mode switch.+ *+ * There is only one board, so putting the mode where the title would go keeps the app bar to a single+ * control rather than adding a tab row for two options.+ */+@Composable+private fun ModeDropdown(+ mode: GameMode,+ level: Int,+ onSelect: (GameMode) -> Unit,+) {+ var expanded by remember { mutableStateOf(false) }+ Box {+ TextButton(onClick = { expanded = true }) {+ Text(+ when (mode) {+ GameMode.CASUAL -> stringResource(R.string.level_title, level)+ GameMode.DAILY -> stringResource(R.string.mode_daily)+ },+ style = MaterialTheme.typography.titleLarge,+ )+ IconArrowDropDown()+ }+ DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {+ for (option in GameMode.entries) {+ DropdownMenuItem(+ text = {+ Text(+ stringResource(+ when (option) {+ GameMode.CASUAL -> R.string.mode_casual+ GameMode.DAILY -> R.string.mode_daily+ }+ )+ )+ },+ onClick = {+ expanded = false+ onSelect(option)+ },+ )+ }+ }+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.ktnew file mode 100644index 0000000000..41a489baa8--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/SettingsPage.kt@@ -0,0 +1,83 @@+package com.vayunmathur.games.nonogram.ui++import android.Manifest+import android.os.Build+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.res.stringResource+import com.vayunmathur.games.nonogram.R+import com.vayunmathur.games.nonogram.platform.NonogramViewModel+import com.vayunmathur.games.nonogram.platform.SettingsActions+import com.vayunmathur.games.nonogram.platform.SettingsUiState+import com.vayunmathur.library.ui.BackupButtons+import com.vayunmathur.library.ui.DailyReminderSettingsSection+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberPermissionRequest++/** Binds [NonogramViewModel] to the stateless [SettingsScreen]. */+@Composable+fun SettingsPage(viewModel: NonogramViewModel, onBack: () -> Unit) {+ val uiState by viewModel.uiState.collectAsState()+ val reminderEnabled by viewModel.reminderEnabled.collectAsState()+ val reminderMinutes by viewModel.reminderMinutesOfDay.collectAsState()+ val requestNotifications = rememberPermissionRequest(Manifest.permission.POST_NOTIFICATIONS)++ SettingsScreen(+ state = SettingsUiState(+ showMistakes = uiState.showMistakes,+ reminderEnabled = reminderEnabled,+ reminderHour = (reminderMinutes / 60).toInt(),+ reminderMinute = (reminderMinutes % 60).toInt(),+ ),+ actions = object : SettingsActions {+ override fun setShowMistakes(enabled: Boolean) = viewModel.setShowMistakes(enabled)+ override fun setReminderEnabled(enabled: Boolean) {+ // Asked for lazily, on opt-in only, so the screen never blocks on a prompt.+ if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ requestNotifications()+ }+ viewModel.setReminderEnabled(enabled)+ }++ override fun setReminderTime(hour: Int, minute: Int) =+ viewModel.setReminderTime(hour, minute)+ },+ onBack = onBack,+ )+}++/** The settings screen, ViewModel-free so a preview can render it. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, onBack: () -> Unit) {+ DetailScaffold(+ title = stringResource(UiR.string.settings),+ onNavigateBack = onBack,+ actions = {+ BackupButtons(datastoreNames = listOf("settings", "datastore_default"))+ },+ scrollBehavior = appBarScrollBehavior(),+ ) {+ SettingsSection {+ SettingsSwitchRow(+ title = stringResource(R.string.show_mistakes),+ supportingText = stringResource(R.string.show_mistakes_description),+ checked = state.showMistakes,+ onCheckedChange = { actions.setShowMistakes(it) },+ )+ }+ DailyReminderSettingsSection(+ enabled = state.reminderEnabled,+ hour = state.reminderHour,+ minute = state.reminderMinute,+ onEnabledChange = { actions.setReminderEnabled(it) },+ onTimeChange = { hour, minute -> actions.setReminderTime(hour, minute) },+ )+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.ktnew file mode 100644index 0000000000..5d60fbde78--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt@@ -0,0 +1,285 @@+package com.vayunmathur.games.nonogram.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.TextUnit+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.games.nonogram.R+import com.vayunmathur.games.nonogram.data.CellMark+import com.vayunmathur.games.nonogram.data.NonogramGameState+import com.vayunmathur.library.ui.ColorScheme+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * The grid with its clues.+ *+ * Laid out as a two-by-two arrangement: an empty corner, the column clues across the top, the row+ * clues down the left, and the grid itself. The clue gutters are sized from the longest clue on that+ * axis so nothing is ever clipped, and everything scales off the cell size so a 5x5 and a 15x15 both+ * fill the available width.+ */+@Composable+fun NonogramBoard(+ game: NonogramGameState,+ showMistakes: Boolean,+ onTap: (Int) -> Unit,+ onLongPress: (Int) -> Unit,+ modifier: Modifier = Modifier,+) {+ val size = game.size+ // Widest clue list decides the gutter, so a row needing "3 1 2" is not cut off.+ val rowGutterCells = game.puzzle.rowClues.maxOf { it.size }.coerceAtLeast(1)+ val colGutterCells = game.puzzle.colClues.maxOf { it.size }.coerceAtLeast(1)++ BoxWithConstraints(modifier) {+ // The clue gutters are narrower than a cell: they only ever hold a one or two digit number.+ val cell: Dp = maxWidth / (size + rowGutterCells * CLUE_CELL_FRACTION)+ val clueCell = cell * CLUE_CELL_FRACTION+ // Sized from the clue slot, not the grid cell, and paired with a line height equal to the+ // slot. Without that a 15x15's slots are shorter than the text's natural line box, the clue+ // column overflows its fixed height, and the row nearest the grid is clipped in half.+ val fontSize = (clueCell.value * 0.78f).coerceIn(6f, 13f).sp+ val lineHeight = clueCell.value.sp++ Column {+ Row {+ // Empty corner where the two gutters meet.+ Box(Modifier.size(clueCell * rowGutterCells, clueCell * colGutterCells))+ ColumnClues(game, colGutterCells, cell, clueCell, fontSize, lineHeight)+ }+ Row {+ RowClues(game, rowGutterCells, cell, clueCell, fontSize, lineHeight)+ Grid(game, showMistakes, cell, onTap, onLongPress)+ }+ }+ }+}++@Composable+private fun ColumnClues(+ game: NonogramGameState,+ gutterCells: Int,+ cell: Dp,+ clueCell: Dp,+ fontSize: TextUnit,+ lineHeight: TextUnit,+) {+ Row {+ for (col in 0 until game.size) {+ val clues = game.puzzle.colClues[col]+ Column(+ Modifier.size(cell, clueCell * gutterCells),+ // Bottom-aligned so the last clue sits against the grid it describes.+ verticalArrangement = Arrangement.Bottom,+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ for (clue in clues.ifEmpty { listOf(0) }) {+ ClueText(clue, fontSize, lineHeight, Modifier.size(cell, clueCell))+ }+ }+ }+ }+}++@Composable+private fun RowClues(+ game: NonogramGameState,+ gutterCells: Int,+ cell: Dp,+ clueCell: Dp,+ fontSize: TextUnit,+ lineHeight: TextUnit,+) {+ Column {+ for (row in 0 until game.size) {+ val clues = game.puzzle.rowClues[row]+ Row(+ Modifier.size(clueCell * gutterCells, cell),+ // End-aligned for the same reason: the final clue abuts the grid.+ horizontalArrangement = Arrangement.End,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ for (clue in clues.ifEmpty { listOf(0) }) {+ ClueText(clue, fontSize, lineHeight, Modifier.size(clueCell, cell))+ }+ }+ }+ }+}++@Composable+private fun ClueText(+ clue: Int,+ fontSize: TextUnit,+ lineHeight: TextUnit,+ modifier: Modifier = Modifier,+) {+ Box(modifier, contentAlignment = Alignment.Center) {+ Text(+ text = clue.toString(),+ fontSize = fontSize,+ lineHeight = lineHeight,+ maxLines = 1,+ softWrap = false,+ fontWeight = FontWeight.Medium,+ textAlign = TextAlign.Center,+ color = if (clue == 0) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)+ else MaterialTheme.colorScheme.onSurface,+ )+ }+}++@Composable+private fun Grid(+ game: NonogramGameState,+ showMistakes: Boolean,+ cell: Dp,+ onTap: (Int) -> Unit,+ onLongPress: (Int) -> Unit,+) {+ val scheme = MaterialTheme.colorScheme+ Box {+ Column {+ for (row in 0 until game.size) {+ Row {+ for (col in 0 until game.size) {+ val index = row * game.size + col+ NonogramCell(+ game = game,+ index = index,+ showMistakes = showMistakes,+ onTap = { onTap(index) },+ onLongPress = { onLongPress(index) },+ modifier = Modifier.size(cell),+ )+ }+ }+ }+ }+ Box(+ Modifier+ .size(cell * game.size)+ .drawGridLines(game.size, scheme.outlineVariant, scheme.onSurface)+ )+ }+}++@Composable+private fun NonogramCell(+ game: NonogramGameState,+ index: Int,+ showMistakes: Boolean,+ onTap: () -> Unit,+ onLongPress: () -> Unit,+ modifier: Modifier = Modifier,+) {+ val scheme = MaterialTheme.colorScheme+ val haptics = LocalHapticFeedback.current+ val mark = game.markAt(index)+ val mistake = showMistakes && game.isMistake(index)++ val background = when {+ mistake -> scheme.error+ mark == CellMark.FILLED -> scheme.onSurface+ else -> Color.Transparent+ }++ val stateWord = when {+ mistake -> stringResource(R.string.cd_mistake)+ mark == CellMark.FILLED -> stringResource(R.string.cd_filled)+ mark == CellMark.CROSSED -> stringResource(R.string.cd_crossed)+ else -> stringResource(R.string.cd_blank)+ }+ val description = stringResource(+ R.string.cd_cell,+ index / game.size + 1,+ index % game.size + 1,+ stateWord,+ )++ Box(+ modifier+ .background(background)+ .pointerInput(index, game.isWon) {+ detectTapGestures(+ onTap = { onTap() },+ onLongPress = {+ haptics.performHapticFeedback(HapticFeedbackType.LongPress)+ onLongPress()+ },+ )+ }+ .clearAndSetSemantics { contentDescription = description },+ contentAlignment = Alignment.Center,+ ) {+ if (mark == CellMark.CROSSED) {+ Box(+ Modifier+ .fillMaxSize()+ .padding(CrossInset)+ .drawCross(scheme.onSurfaceVariant)+ )+ }+ }+}++/** Keeps the X clear of the cell borders so it reads as a mark rather than a filled square. */+private val CrossInset = 3.dp++private fun Modifier.drawCross(color: Color) = drawBehind {+ val stroke = 1.5.dp.toPx()+ drawLine(color, Offset(0f, 0f), Offset(size.width, size.height), stroke)+ drawLine(color, Offset(size.width, 0f), Offset(0f, size.height), stroke)+}++/**+ * Every cell edge, with a heavier stroke every five cells and around the outside.+ *+ * The five-cell grouping is the standard nonogram aid: it lets a player count along a long line+ * without losing their place. Drawn in one pass over the whole grid so shared edges are painted once.+ */+private fun Modifier.drawGridLines(size: Int, thin: Color, thick: Color) = drawBehind {+ val step = this.size.width / size+ val thinPx = 1.dp.toPx()+ val thickPx = 2f * thinPx++ for (i in 0..size) {+ val offset = i * step+ val heavy = i % GROUP == 0 || i == size+ val color = if (heavy) thick else thin+ val width = if (heavy) thickPx else thinPx+ drawLine(color, Offset(offset, 0f), Offset(offset, this.size.height), width)+ drawLine(color, Offset(0f, offset), Offset(this.size.width, offset), width)+ }+}++/** Cells per heavy guide line. */+private const val GROUP = 5++/** A clue slot's width as a fraction of a grid cell. Clues are digits, so they need less room. */+private const val CLUE_CELL_FRACTION = 0.62f
games/nonogram/src/main/res/values/strings.xml
diff --git a/games/nonogram/src/main/res/values/strings.xml b/games/nonogram/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..acc6b5e199--- /dev/null+++ b/games/nonogram/src/main/res/values/strings.xml@@ -0,0 +1,46 @@+<?xml version="1.0" encoding="utf-8"?>+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">+ <!-- Manifest / TopAppBar: App name. Noun, proper -->+ <string name="app_name" translatable="false">Nonogram</string>++ <!-- GameModeDropdown: Mode playing the numbered level progression. Adjective -->+ <string name="mode_casual">Levels</string>+ <!-- GameModeDropdown: Mode playing today's shared puzzle. Adjective -->+ <string name="mode_daily">Daily</string>++ <!-- NonogramGameScreen TopAppBar: Current level in the progression. %1$d = level number, e.g. 12 -->+ <string name="level_title">Level <xliff:g id="level" example="12">%1$d</xliff:g></string>+ <!-- NonogramGameScreen: Button advancing to the next level after a win. Verb phrase -->+ <string name="next_level">Next Level</string>+ <!-- NonogramGameScreen: Clears every mark on the current puzzle. Verb -->+ <string name="restart">Restart</string>+ <!-- NonogramGameScreen: Shown after finishing the daily, since there is only one per day. Sentence -->+ <string name="daily_come_back_tomorrow">Solved! Come back tomorrow for a new puzzle.</string>+ <!-- NonogramGameScreen: Celebratory line shown when a level is completed. Declarative -->+ <string name="solved">Solved!</string>+ <!-- DailyStatusBar: Current daily streak length. %1$d = consecutive days, e.g. 5 -->+ <string name="daily_streak">Streak: <xliff:g id="days" example="5">%1$d</xliff:g></string>+ <!-- NonogramGameScreen: Hint under a fresh board explaining the two gestures. Imperative sentence -->+ <string name="how_to_play">Tap to fill, tap again to cross out</string>++ <!-- NonogramGameScreen: Shown when no fair puzzle could be generated for this level. Sentence -->+ <string name="generation_failed">Could not build a puzzle for this level.</string>+ <!-- NonogramGameScreen: Retries generation after a failure. Verb -->+ <string name="try_again">Try Again</string>++ <!-- SettingsScreen: Toggle for highlighting cells filled in that should be blank. Noun phrase -->+ <string name="show_mistakes">Highlight mistakes</string>+ <!-- SettingsScreen: Explains what the highlight-mistakes toggle does. Sentence -->+ <string name="show_mistakes_description">Mark filled cells that do not belong to the picture.</string>++ <!-- NonogramBoard: Content description of a cell. %1$d = row number starting at 1, e.g. 4. %2$d = column number starting at 1, e.g. 6. %3$s = the cell's state word, e.g. Filled -->+ <string name="cd_cell">Row <xliff:g id="row" example="4">%1$d</xliff:g>, column <xliff:g id="column" example="6">%2$d</xliff:g>, <xliff:g id="state" example="Filled">%3$s</xliff:g></string>+ <!-- NonogramBoard: Cell state, painted as part of the picture. Verb past participle -->+ <string name="cd_filled">Filled</string>+ <!-- NonogramBoard: Cell state, ruled out by the player. Verb past participle -->+ <string name="cd_crossed">Crossed out</string>+ <!-- NonogramBoard: Cell state, untouched. Adjective -->+ <string name="cd_blank">Blank</string>+ <!-- NonogramBoard: Content description of a filled cell that does not belong to the picture. Noun -->+ <string name="cd_mistake">Mistake</string>+</resources>
games/nonogram/src/main/res/xml/data_extraction_rules.xml
diff --git a/games/nonogram/src/main/res/xml/data_extraction_rules.xml b/games/nonogram/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..8d0a7a9389--- /dev/null+++ b/games/nonogram/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,35 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ Nonogram. Audited state: filesDir/datastore/settings.preferences_pb, holding the+ current level, the filled and crossed cells on it, the daily board with the day+ it belongs to, and the show-mistakes preference; plus+ filesDir/datastore_default.preferences_pb, the shared DataStoreUtils file+ holding the DailyChallengeStore("nonogram_daily") streak, the daily reminder+ settings and the AchievementsManager unlocks. No SharedPreferences, no Room+ database, nothing written to external storage - achievements.json is a+ read-only APK asset and every puzzle is generated on device from its level+ number or the date. Back everything up; it is a few KB of pure user progress.+ SCOPE: nonogram declares android:backupAgent=".platform.AppBackupAgent" and+ does NOT set android:fullBackupOnly, so Android uses key/value backup and the+ <cloud-backup> section below is NOT consulted. Cloud content is exactly+ AppBackupAgent's datastoreNames = ["settings", "datastore_default"], which is+ the same data this file would have sent. <device-transfer> IS governed here,+ and these rules become the cloud control too if the backupAgent is ever+ removed.+-->+<data-extraction-rules>+ <cloud-backup>+ <include domain="root" path="." />+ <include domain="file" path="." />+ <include domain="database" path="." />+ <include domain="sharedpref" path="." />+ <include domain="external" path="." />+ </cloud-backup>+ <device-transfer>+ <include domain="root" path="." />+ <include domain="file" path="." />+ <include domain="database" path="." />+ <include domain="sharedpref" path="." />+ <include domain="external" path="." />+ </device-transfer>+</data-extraction-rules>
games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.kt
diff --git a/games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.kt b/games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.ktnew file mode 100644index 0000000000..89cb56b45b--- /dev/null+++ b/games/nonogram/src/screenshotTest/kotlin/com/vayunmathur/games/nonogram/MetadataPreviews.kt@@ -0,0 +1,130 @@+package com.vayunmathur.games.nonogram++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.games.nonogram.data.DAILY_SIZE+import com.vayunmathur.games.nonogram.data.GameMode+import com.vayunmathur.games.nonogram.data.NonogramGameState+import com.vayunmathur.games.nonogram.data.NonogramPuzzle+import com.vayunmathur.games.nonogram.data.sizeForLevel+import com.vayunmathur.games.nonogram.domain.NonogramGenerator+import com.vayunmathur.games.nonogram.platform.NonogramGameActions+import com.vayunmathur.games.nonogram.platform.NonogramUiState+import com.vayunmathur.games.nonogram.ui.NonogramGameScreen+import com.vayunmathur.library.ui.DynamicTheme++/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */+private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"++/**+ * The store listing images.+ *+ * Previews must be members of a class and carry both `@PreviewTest` and `@Preview`, or the screenshot+ * engine discovers no tests. The `PreviewN` names set the order they appear in the listing, because+ * the collector sorts by filename. Run `./gradlew :games:nonogram:metadata`.+ *+ * Puzzles come from [NonogramGenerator] with the same seeds the real levels use, so an image is a+ * genuine level rather than a hand-drawn approximation, and is reproducible from a clean checkout.+ * [NonogramGameScreen] has no polling `LaunchedEffect`, so a preview settles on the first frame.+ */+class MetadataPreviews {++ @PreviewTest+ @Preview(name = "1-level", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview1Level() {+ // Part-way through a 10x10, with some cells crossed out as a player would leave them.+ val puzzle = level(12)+ val correct = puzzle.solution.indices.filter { puzzle.solution[it] }+ val blanks = puzzle.solution.indices.filter { !puzzle.solution[it] }+ Board(+ game(+ puzzle = puzzle,+ level = 12,+ filled = correct.take(correct.size / 2).toSet(),+ crossed = blanks.take(blanks.size / 3).toSet(),+ )+ )+ }++ @PreviewTest+ @Preview(name = "2-solved", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview2Solved() {+ val puzzle = level(6)+ Board(+ game(+ puzzle = puzzle,+ level = 6,+ filled = puzzle.solution.indices.filter { puzzle.solution[it] }.toSet(),+ crossed = emptySet(),+ )+ )+ }++ @PreviewTest+ @Preview(name = "3-daily", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview3Daily() {+ // Dailies are always DAILY_SIZE, so the shot has to be that size to be honest.+ val puzzle = requireNotNull(NonogramGenerator.generateSeeded(DAILY_SIZE, seed = 20260824L))+ val correct = puzzle.solution.indices.filter { puzzle.solution[it] }+ Board(+ game(+ puzzle = puzzle,+ level = 1,+ filled = correct.take(correct.size / 3).toSet(),+ crossed = emptySet(),+ mode = GameMode.DAILY,+ ),+ streak = 6,+ )+ }++ @PreviewTest+ @Preview(name = "4-large", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview4Large() {+ // A later level, where the grid steps up to 15x15.+ Board(game(puzzle = level(25), level = 25, filled = emptySet(), crossed = emptySet()))+ }++ @Composable+ private fun Board(game: NonogramGameState, streak: Long = 0) {+ // Layoutlib has no wallpaper to sample, so Material You falls back to the default palette.+ DynamicTheme(darkTheme = true) {+ NonogramGameScreen(+ state = NonogramUiState(+ game = game,+ mode = game.mode,+ level = game.level,+ dailyStreak = streak,+ ),+ actions = NonogramGameActions.Noop,+ onOpenSettings = {},+ onOpenGameCenter = {},+ )+ }+ }++ /** The real puzzle for [level], so the preview shows a board the game would actually deal. */+ private fun level(level: Int): NonogramPuzzle =+ requireNotNull(NonogramGenerator.generateSeeded(sizeForLevel(level), level.toLong())) {+ "no puzzle for level $level"+ }++ private fun game(+ puzzle: NonogramPuzzle,+ level: Int,+ filled: Set<Int>,+ crossed: Set<Int>,+ mode: GameMode = GameMode.CASUAL,+ ) = NonogramGameState(+ puzzle = puzzle,+ filled = filled,+ crossed = crossed,+ mode = mode,+ level = level,+ )+}
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.ktnew file mode 100644index 0000000000..ca6ce5cea6--- /dev/null+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/data/NonogramGameStateTest.kt@@ -0,0 +1,106 @@+package com.vayunmathur.games.nonogram.data++import com.vayunmathur.games.nonogram.domain.puzzle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class NonogramGameStateTest {++ private val cross = puzzle(+ """+ .#.+ ###+ .#.+ """+ )++ private fun state(filled: Set<Int> = emptySet(), crossed: Set<Int> = emptySet()) =+ NonogramGameState(+ puzzle = cross,+ filled = filled,+ crossed = crossed,+ mode = GameMode.CASUAL,+ level = 1,+ )++ /** Indices of the cells that should be filled in [cross]. */+ private val answer = cross.solution.indices.filter { cross.solution[it] }.toSet()++ @Test+ fun aFreshBoardIsNotWon() {+ assertFalse(state().isWon)+ }++ @Test+ fun fillingExactlyTheSolutionWins() {+ assertTrue(state(filled = answer).isWon)+ }++ @Test+ fun crossesDoNotAffectTheWinCheck() {+ val blanks = cross.solution.indices.filterNot { cross.solution[it] }.toSet()+ assertTrue(state(filled = answer, crossed = blanks).isWon)+ assertTrue(state(filled = answer, crossed = emptySet()).isWon)+ }++ @Test+ fun aMissingCellIsNotAWin() {+ assertFalse(state(filled = answer - answer.first()).isWon)+ }++ @Test+ fun anExtraFilledCellIsNotAWin() {+ // Over-filling must not pass: the sets have to match, not merely cover the solution.+ val extra = cross.solution.indices.first { !cross.solution[it] }+ assertFalse(state(filled = answer + extra).isWon)+ }++ @Test+ fun aWrongFillIsReportedAsAMistake() {+ val wrong = cross.solution.indices.first { !cross.solution[it] }+ val s = state(filled = setOf(wrong))+ assertTrue(s.isMistake(wrong))+ assertTrue(s.hasMistake)+ }++ @Test+ fun aCorrectFillIsNotAMistake() {+ val right = answer.first()+ val s = state(filled = setOf(right))+ assertFalse(s.isMistake(right))+ assertFalse(s.hasMistake)+ }++ @Test+ fun aCrossedBlankIsNeverAMistake() {+ // Crosses are bookkeeping; being wrong about one is not the same as painting a wrong cell.+ val s = state(crossed = answer)+ assertFalse(s.hasMistake)+ }++ @Test+ fun markAtReportsWhatIsStored() {+ val s = state(filled = setOf(1), crossed = setOf(0))+ assertEquals(CellMark.FILLED, s.markAt(1))+ assertEquals(CellMark.CROSSED, s.markAt(0))+ assertEquals(CellMark.BLANK, s.markAt(2))+ }++ @Test+ fun levelSizeRampCoversTheThreeBoardSizes() {+ assertEquals(5, sizeForLevel(1))+ assertEquals(5, sizeForLevel(8))+ assertEquals(10, sizeForLevel(9))+ assertEquals(10, sizeForLevel(20))+ assertEquals(15, sizeForLevel(21))+ assertEquals(15, sizeForLevel(9999))+ }++ @Test+ fun theRampNeverShrinksAsLevelsGoUp() {+ val sizes = (1..60).map { sizeForLevel(it) }+ assertEquals(sizes, sizes.sorted(), "board size should only ever grow")+ }+}
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramGeneratorTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramGeneratorTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramGeneratorTest.ktnew file mode 100644index 0000000000..f36d1c6f62--- /dev/null+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramGeneratorTest.kt@@ -0,0 +1,91 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.NonogramPuzzle+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class NonogramGeneratorTest {++ @Test+ fun everyGeneratedPuzzleIsSolvableWithoutGuessing() {+ // The whole promise of the generator.+ for (size in listOf(5, 10, 15)) {+ val puzzle = assertNotNull(+ NonogramGenerator.generateSeeded(size, seed = 31L),+ "no ${size}x$size puzzle found",+ )+ assertTrue(+ NonogramSolver.isLineSolvable(size, puzzle.rowClues, puzzle.colClues),+ "${size}x$size needed guesswork",+ )+ }+ }++ @Test+ fun cluesMatchTheSolution() {+ val puzzle = assertNotNull(NonogramGenerator.generateSeeded(10, seed = 7L))+ val expected = NonogramPuzzle.from(puzzle.size, puzzle.solution)+ assertEquals(expected.rowClues, puzzle.rowClues)+ assertEquals(expected.colClues, puzzle.colClues)+ }++ @Test+ fun theSolvedGridEqualsTheIntendedPicture() {+ // Full determination implies uniqueness, so the recovered picture must be the generated one.+ val puzzle = assertNotNull(NonogramGenerator.generateSeeded(10, seed = 123L))+ val solved = assertNotNull(+ NonogramSolver.solve(puzzle.size, puzzle.rowClues, puzzle.colClues)+ )+ assertEquals(puzzle.solution, solved.map { it == CellState.FILLED })+ }++ @Test+ fun sameSeedGivesTheSamePuzzle() {+ // Saved progress is keyed by level number, so a level must never repaint itself.+ val first = assertNotNull(NonogramGenerator.generateSeeded(10, seed = 4242L))+ val second = assertNotNull(NonogramGenerator.generateSeeded(10, seed = 4242L))+ assertEquals(first.solution, second.solution)+ }++ @Test+ fun differentSeedsGiveDifferentPuzzles() {+ val first = assertNotNull(NonogramGenerator.generateSeeded(10, seed = 1L))+ val second = assertNotNull(NonogramGenerator.generateSeeded(10, seed = 2L))+ assertTrue(first.solution != second.solution)+ }++ @Test+ fun noPuzzleIsCompletelyBlank() {+ for (seed in 1L..25L) {+ val puzzle = assertNotNull(NonogramGenerator.generateSeeded(5, seed = seed))+ assertTrue(puzzle.filledCount > 0, "seed $seed produced an empty picture")+ }+ }++ @Test+ fun everySeedInAWideRangeYieldsAPuzzle() {+ // If generation failed even occasionally, a player would hit a level that cannot be loaded.+ for (level in 1L..40L) {+ val size = sizeFor(level.toInt())+ assertNotNull(+ NonogramGenerator.generateSeeded(size, seed = level),+ "level $level (${size}x$size) produced nothing",+ )+ }+ }++ @Test+ fun generateReturnsNullRatherThanLoopingWhenGivenNoAttempts() {+ assertEquals(null, NonogramGenerator.generate(10, Random(1), attempts = 0))+ }++ /** Mirrors the production level-to-size ramp closely enough to exercise all three sizes. */+ private fun sizeFor(level: Int): Int = when {+ level <= 8 -> 5+ level <= 20 -> 10+ else -> 15+ }+}
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramSolverTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramSolverTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramSolverTest.ktnew file mode 100644index 0000000000..c27a3d2ae9--- /dev/null+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramSolverTest.kt@@ -0,0 +1,169 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.NonogramPuzzle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class NonogramSolverTest {++ @Test+ fun cluesAreRunLengthsOfFilledCells() {+ assertEquals(listOf(2, 1), NonogramPuzzle.cluesFor("##.#.".toLine()))+ assertEquals(listOf(5), NonogramPuzzle.cluesFor("#####".toLine()))+ assertEquals(emptyList(), NonogramPuzzle.cluesFor(".....".toLine()))+ assertEquals(listOf(1, 1, 1), NonogramPuzzle.cluesFor("#.#.#".toLine()))+ }++ @Test+ fun aFullyDeterminedPuzzleIsSolvedExactly() {+ val puzzle = puzzle(+ """+ ##.##+ #.#.#+ .###.+ #.#.#+ ##.##+ """+ )+ val solved = assertNotNull(+ NonogramSolver.solve(puzzle.size, puzzle.rowClues, puzzle.colClues)+ )+ assertEquals(+ puzzle.solution,+ solved.map { it == CellState.FILLED },+ "line logic should recover the exact picture",+ )+ }++ @Test+ fun anAllBlankGridSolvesToAllEmpty() {+ val puzzle = puzzle(+ """+ ...+ ...+ ...+ """+ )+ val solved = assertNotNull(+ NonogramSolver.solve(puzzle.size, puzzle.rowClues, puzzle.colClues)+ )+ assertTrue(solved.all { it == CellState.EMPTY })+ }++ @Test+ fun anAllFilledGridSolvesToAllFilled() {+ val puzzle = puzzle(+ """+ ###+ ###+ ###+ """+ )+ assertTrue(NonogramSolver.isLineSolvable(puzzle.size, puzzle.rowClues, puzzle.colClues))+ }++ @Test+ fun contradictoryCluesReportNoSolution() {+ // A clue of 4 cannot fit in a line of 3.+ assertNull(+ NonogramSolver.solve(+ size = 3,+ rowClues = listOf(listOf(4), emptyList(), emptyList()),+ colClues = listOf(emptyList(), emptyList(), emptyList()),+ )+ )+ }++ @Test+ fun cluesThatDisagreeBetweenRowsAndColumnsReportNoSolution() {+ // Rows say one cell is filled, columns say none are.+ assertNull(+ NonogramSolver.solve(+ size = 2,+ rowClues = listOf(listOf(1), emptyList()),+ colClues = listOf(emptyList(), emptyList()),+ )+ )+ }++ @Test+ fun anAmbiguousPuzzleIsNotLineSolvable() {+ // The classic 2x2 checkerboard: both diagonals satisfy every clue, so nothing is determined.+ val rowClues = listOf(listOf(1), listOf(1))+ val colClues = listOf(listOf(1), listOf(1))+ assertTrue(+ !NonogramSolver.isLineSolvable(2, rowClues, colClues),+ "a puzzle with two valid pictures must be rejected",+ )+ // It is satisfiable, just not decidable - so solve() returns a grid rather than null.+ val solved = assertNotNull(NonogramSolver.solve(2, rowClues, colClues))+ assertTrue(solved.any { it == CellState.UNKNOWN })+ }++ @Test+ fun solvingIsIndependentOfLineOrder() {+ // Transposing a puzzle swaps its row and column clues; the picture should transpose with it.+ val puzzle = puzzle(+ """+ #..#+ ##..+ .##.+ #..#+ """+ )+ val solved = assertNotNull(+ NonogramSolver.solve(puzzle.size, puzzle.rowClues, puzzle.colClues)+ )+ val transposed = assertNotNull(+ NonogramSolver.solve(puzzle.size, puzzle.colClues, puzzle.rowClues)+ )+ val n = puzzle.size+ for (row in 0 until n) {+ for (col in 0 until n) {+ assertEquals(+ solved[row * n + col],+ transposed[col * n + row],+ "($row,$col) should mirror",+ )+ }+ }+ }++ @Test+ fun aRepeatingDiagonalPatternIsRejectedAsAmbiguous() {+ // Every row carries the same clue shifted by one, so the whole picture can slide. Line logic+ // cannot pin that down, and the generator is right to throw candidates like it away.+ val puzzle = puzzle(+ List(15) { row ->+ (0 until 15).joinToString("") { if ((row + it) % 3 == 0) "#" else "." }+ }.joinToString("\n")+ )+ // Satisfiable - it came from a real picture - but not decidable.+ assertNotNull(NonogramSolver.solve(puzzle.size, puzzle.rowClues, puzzle.colClues))+ assertTrue(+ !NonogramSolver.isLineSolvable(puzzle.size, puzzle.rowClues, puzzle.colClues),+ "a slidable pattern must not pass as line-solvable",+ )+ }++ @Test+ fun solvesAtTheLargestSizeTheGameOffers() {+ val puzzle = assertNotNull(NonogramGenerator.generateSeeded(15, seed = 15L))+ val solved = assertNotNull(NonogramSolver.solve(15, puzzle.rowClues, puzzle.colClues))+ assertEquals(puzzle.solution, solved.map { it == CellState.FILLED })+ }+}++/** `"##.#"` -> filled flags, so a test reads as the line it means. */+internal fun String.toLine(): List<Boolean> = map { it == '#' }++/** Builds a puzzle from an ASCII picture where `#` is filled. */+internal fun puzzle(picture: String): NonogramPuzzle {+ val rows = picture.trimIndent().lines().map { it.trim() }.filter { it.isNotEmpty() }+ val size = rows.size+ require(rows.all { it.length == size }) { "picture must be square" }+ return NonogramPuzzle.from(size, rows.flatMap { it.toLine() })+}
library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.ktindex 46c94eabdd..edecd22039 100644--- a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt+++ b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt@@ -39,6 +39,7 @@ private fun resolveGameMetadata( "logicgate" -> "Logic Gates" "sudoku" -> "Sudoku" "minesweeper" -> "Minesweeper"+ "nonogram" -> "Nonogram" else -> gameId.replaceFirstChar { it.uppercase() } }, description = null,
metadata_data/games-nonogram.md
diff --git a/metadata_data/games-nonogram.md b/metadata_data/games-nonogram.mdnew file mode 100644index 0000000000..2f1b046612--- /dev/null+++ b/metadata_data/games-nonogram.md@@ -0,0 +1,6 @@+A picture logic puzzle, with a new one every day++Fill the grid from the number clues to reveal the hidden picture. One level is+open at a time, plus a fresh daily puzzle shared by everyone on the same date.+Every puzzle is generated on device and checked to be solvable by reasoning+alone, so you never have to guess.
metadata_data/photos/games-nonogram/1.png
diff --git a/metadata_data/photos/games-nonogram/1.png b/metadata_data/photos/games-nonogram/1.pngnew file mode 100644index 0000000000..e3b37f651aBinary files /dev/null and b/metadata_data/photos/games-nonogram/1.png differ
metadata_data/photos/games-nonogram/2.png
diff --git a/metadata_data/photos/games-nonogram/2.png b/metadata_data/photos/games-nonogram/2.pngnew file mode 100644index 0000000000..feb8fcbcb9Binary files /dev/null and b/metadata_data/photos/games-nonogram/2.png differ
metadata_data/photos/games-nonogram/3.png
diff --git a/metadata_data/photos/games-nonogram/3.png b/metadata_data/photos/games-nonogram/3.pngnew file mode 100644index 0000000000..4ce1589292Binary files /dev/null and b/metadata_data/photos/games-nonogram/3.png differ
metadata_data/photos/games-nonogram/4.png
diff --git a/metadata_data/photos/games-nonogram/4.png b/metadata_data/photos/games-nonogram/4.pngnew file mode 100644index 0000000000..b423ee02bbBinary files /dev/null and b/metadata_data/photos/games-nonogram/4.png differ
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex bb2b5e0e08..53f0ab86c9 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -80,6 +80,7 @@ include(":games:logicgate") include(":games:voxels") include(":games:sudoku") include(":games:minesweeper")+include(":games:nonogram") include(":games:hub") include(":email") include(":weather")