arrows: new game with level progression, daily board, and redirectors
- Commit
a645f011afb24d94642ef793fdaf333e582dcdc5- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-24 03:59 UTC (3 months ago)
- Parents
c84b045
Diff
games/arrows/build.gradle.kts
diff --git a/games/arrows/build.gradle.kts b/games/arrows/build.gradle.ktsnew file mode 100644index 0000000000..736be71673--- /dev/null+++ b/games/arrows/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:arrows:metadata` task name either way.+ id("common-conventions-preview-metadata")+}++launcherIcon {+ symbol = "double_arrow"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.games.arrows"+ }+}++dependencies {+ implementation(project(":sdk:games"))+ implementation(project(":library:work"))+ implementation(libs.androidx.datastore.preferences)+}
games/arrows/src/main/AndroidManifest.xml
diff --git a/games/arrows/src/main/AndroidManifest.xml b/games/arrows/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..1d28acf67f--- /dev/null+++ b/games/arrows/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/arrows/src/main/assets/achievements.json
diff --git a/games/arrows/src/main/assets/achievements.json b/games/arrows/src/main/assets/achievements.jsonnew file mode 100644index 0000000000..f087a07a18--- /dev/null+++ b/games/arrows/src/main/assets/achievements.json@@ -0,0 +1,51 @@+[+ {+ "id": "first_board",+ "name": "All Clear",+ "description": "Clear your first board!"+ },+ {+ "id": "flawless",+ "name": "Not A Scratch",+ "description": "Clear a board without losing a single heart."+ },+ {+ "id": "first_block",+ "name": "Boxed In",+ "description": "Tap an arrow that has nowhere to go."+ },+ {+ "id": "through_the_looking_glass",+ "name": "Through The Looking Glass",+ "description": "Clear a board that has redirectors on it."+ },+ {+ "id": "first_daily",+ "name": "Daily Habit",+ "description": "Clear a daily board."+ },+ {+ "id": "boards_10",+ "name": "Traffic Control",+ "description": "Clear 10 boards.",+ "targetProgress": 10+ },+ {+ "id": "boards_50",+ "name": "Gridlock Breaker",+ "description": "Clear 50 boards.",+ "targetProgress": 50+ },+ {+ "id": "daily_streak_7",+ "name": "Week Streak",+ "description": "Clear the daily board 7 days in a row.",+ "targetProgress": 7+ },+ {+ "id": "daily_streak_30",+ "name": "Month Streak",+ "description": "Clear the daily board 30 days in a row.",+ "targetProgress": 30+ }+]
games/arrows/src/main/java/com/vayunmathur/games/arrows/MainActivity.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/MainActivity.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/MainActivity.ktnew file mode 100644index 0000000000..ef64bda74f--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/MainActivity.kt@@ -0,0 +1,22 @@+package com.vayunmathur.games.arrows++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.arrows.platform.ArrowsViewModel+import com.vayunmathur.library.ui.DynamicTheme++class MainActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ DynamicTheme {+ val viewModel: ArrowsViewModel = viewModel()+ Navigation(viewModel)+ }+ }+ }+}
games/arrows/src/main/java/com/vayunmathur/games/arrows/Navigation.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/Navigation.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/Navigation.ktnew file mode 100644index 0000000000..15a8dffe01--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/Navigation.kt@@ -0,0 +1,45 @@+package com.vayunmathur.games.arrows++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.arrows.platform.AppBackupAgent+import com.vayunmathur.games.arrows.platform.ArrowsViewModel+import com.vayunmathur.games.arrows.ui.ArrowsGamePage+import com.vayunmathur.games.arrows.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: ArrowsViewModel) {+ 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("arrows", viewModel.achievementsManager)+ Box(Modifier.fillMaxSize()) {+ MainNavigation(backStack) {+ entry<Route.Game> { ArrowsGamePage(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/arrows/src/main/java/com/vayunmathur/games/arrows/Route.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/Route.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/Route.ktnew file mode 100644index 0000000000..6d75f9a050--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/Route.kt@@ -0,0 +1,17 @@+package com.vayunmathur.games.arrows++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+ /** The only board there is: which one 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/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowModels.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowModels.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowModels.ktnew file mode 100644index 0000000000..67a33f9f11--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowModels.kt@@ -0,0 +1,173 @@+package com.vayunmathur.games.arrows.data++import kotlinx.serialization.Serializable++/** Which puzzle the player is looking at. Mirrors the nonogram split: a ladder, plus one a day. */+@Serializable+enum class GameMode { CASUAL, DAILY }++/** The four ways an arrow can travel. */+enum class Direction(val dRow: Int, val dCol: Int) {+ UP(-1, 0),+ RIGHT(0, 1),+ DOWN(1, 0),+ LEFT(0, -1);++ val opposite: Direction+ get() = when (this) {+ UP -> DOWN+ RIGHT -> LEFT+ DOWN -> UP+ LEFT -> RIGHT+ }+}++/**+ * A static tile that turns any arrow passing through it.+ *+ * Named for the diagonal they look like. Both are their own inverse, so an arrow entering a mirror+ * and one leaving it agree about which way the tile faces.+ */+enum class Mirror {+ /** `/` — swaps a horizontal heading for the upward one, and vice versa. */+ FORWARD,++ /** `\` — swaps a horizontal heading for the downward one, and vice versa. */+ BACK;++ fun reflect(direction: Direction): Direction = when (this) {+ FORWARD -> when (direction) {+ Direction.RIGHT -> Direction.UP+ Direction.UP -> Direction.RIGHT+ Direction.LEFT -> Direction.DOWN+ Direction.DOWN -> Direction.LEFT+ }++ BACK -> when (direction) {+ Direction.RIGHT -> Direction.DOWN+ Direction.DOWN -> Direction.RIGHT+ Direction.LEFT -> Direction.UP+ Direction.UP -> Direction.LEFT+ }+ }+}++/**+ * One arrow: a rigid multi-cell piece that occupies every cell it is drawn on.+ *+ * [cells] runs tail to head, and consecutive entries are orthogonally adjacent, so the piece is a+ * connected polyline. [direction] is where the arrowhead points, which is the heading the last+ * segment already has — that is why the head is `cells.last()` rather than a separate field.+ *+ * When tapped the piece travels head-first, the body following along the head's route, so the whole+ * arrow leaves by the path its head takes.+ */+data class ArrowPiece(+ val id: Int,+ val cells: List<Int>,+ val direction: Direction,+) {+ val head: Int get() = cells.last()+ val length: Int get() = cells.size+}++/**+ * A generated board.+ *+ * Guaranteed clearable: the generator builds it by adding arrows in the reverse of a working removal+ * order, so at least one sequence of taps empties it — see `ArrowsGenerator`.+ */+data class ArrowsPuzzle(+ val cols: Int,+ val rows: Int,+ val pieces: List<ArrowPiece>,+ val mirrors: Map<Int, Mirror> = emptyMap(),+) {+ val cellCount: Int get() = cols * rows++ fun contains(row: Int, col: Int): Boolean = row in 0 until rows && col in 0 until cols+}++/** How a tap turned out, so the ViewModel knows whether to spend a heart. */+enum class TapOutcome {+ /** The arrow flew off the board. */+ CLEARED,++ /** Something was in the way; the arrow stayed put. */+ BLOCKED,++ /** The tap did nothing at all — an already-cleared arrow, or a finished board. */+ IGNORED,+}++/**+ * A puzzle plus the player's progress on it.+ *+ * [removed] holds the ids of arrows already flown. [hearts] is the remaining margin for error;+ * reaching zero fails the level, which resets both.+ */+data class ArrowsGameState(+ val puzzle: ArrowsPuzzle,+ val removed: Set<Int>,+ val hearts: Int,+ val level: Int,+ val mode: GameMode,+ /** The arrow that was last blocked, so the board can flash it. -1 when nothing is flagged. */+ val blockedId: Int = -1,+) {+ val remaining: List<ArrowPiece> get() = puzzle.pieces.filterNot { it.id in removed }++ val isWon: Boolean get() = removed.size == puzzle.pieces.size++ val isFailed: Boolean get() = hearts <= 0 && !isWon++ val isOver: Boolean get() = isWon || isFailed++ /** Cell to arrow id, for every arrow still on the board. */+ val occupancy: Map<Int, Int>+ get() = buildMap {+ for (piece in remaining) for (cell in piece.cells) put(cell, piece.id)+ }++ fun pieceAt(cell: Int): ArrowPiece? = remaining.firstOrNull { cell in it.cells }+}++/** Hearts a level starts with. Three wrong taps and it resets. */+const val STARTING_HEARTS = 3++/** Board width and height for [level]. Grows in steps so early levels stay readable. */+fun boardSizeForLevel(level: Int): Pair<Int, Int> = when {+ level <= 5 -> 5 to 6+ level <= 15 -> 6 to 8+ level <= 30 -> 7 to 9+ else -> 8 to 10+}++/** How many arrows [level] should hold, scaled to the board it sits on. */+fun arrowCountForLevel(level: Int): Int {+ val (cols, rows) = boardSizeForLevel(level)+ val capacity = cols * rows+ // Roughly a fifth of the cells, since the average arrow is three or four cells long.+ return (capacity / 5 + level / 4).coerceAtMost(capacity / 4)+}++/**+ * Mirrors on [level].+ *+ * None before [MIRROR_FIRST_LEVEL]: the base mechanic — reading which arrow is boxed in by which — is+ * enough to learn on its own, and redirection only makes sense once that is second nature.+ */+fun mirrorCountForLevel(level: Int): Int =+ if (level < MIRROR_FIRST_LEVEL) 0 else ((level - MIRROR_FIRST_LEVEL) / 6 + 1).coerceAtMost(4)++/** First level that introduces redirectors. */+const val MIRROR_FIRST_LEVEL = 11++/** Daily boards are a fixed shape, so the challenge is comparable day to day. */+val DAILY_BOARD: Pair<Int, Int> = 7 to 9++/** Daily arrow count, matched to [DAILY_BOARD]. */+const val DAILY_ARROWS = 14++/** Dailies always include redirectors — the player opting into one is past the tutorial levels. */+const val DAILY_MIRRORS = 2
games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.ktnew file mode 100644index 0000000000..6a2394fb7c--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.kt@@ -0,0 +1,132 @@+package com.vayunmathur.games.arrows.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 which arrows have flown and how many hearts are left;+ * advancing clears both, so there is no level list and no way back. Daily progress is kept separately+ * and stamped with the day it belongs to, so yesterday's board can never bleed into today's.+ */+class ArrowsDataStore(private val context: Context) {++ val currentLevel: Flow<Int> = context.dataStore.data.map { it[LEVEL_KEY] ?: 1 }++ val removedArrows: Flow<Set<Int>> = context.dataStore.data.map { it[REMOVED_KEY].toIds() }++ val hearts: Flow<Int> = context.dataStore.data.map { it[HEARTS_KEY] ?: STARTING_HEARTS }++ val gameMode: Flow<GameMode> = context.dataStore.data.map { prefs ->+ prefs[GAME_MODE_KEY]?.let { runCatching { GameMode.valueOf(it) }.getOrNull() }+ ?: GameMode.CASUAL+ }++ /** Whether tapping a blocked arrow should preview why it cannot leave. */+ val showRoutes: Flow<Boolean> = context.dataStore.data.map { it[SHOW_ROUTES_KEY] ?: true }++ /** Lifetime count of cleared boards, which survives [saveLevel] resetting the current one. */+ val boardsCleared: Flow<Int> = context.dataStore.data.map { it[CLEARED_KEY] ?: 0 }++ // ---- Daily ----++ val dailyDay: Flow<Long> = context.dataStore.data.map { it[DAILY_DAY_KEY] ?: NO_DAY }+ val dailyRemoved: Flow<Set<Int>> = context.dataStore.data.map { it[DAILY_REMOVED_KEY].toIds() }+ val dailyHearts: Flow<Int> =+ context.dataStore.data.map { it[DAILY_HEARTS_KEY] ?: STARTING_HEARTS }++ suspend fun setGameMode(mode: GameMode) {+ context.dataStore.edit { it[GAME_MODE_KEY] = mode.name }+ }++ suspend fun setShowRoutes(enabled: Boolean) {+ context.dataStore.edit { it[SHOW_ROUTES_KEY] = enabled }+ }++ /**+ * Moves to [level] and resets the board in the same write.+ *+ * One edit rather than three, so a crash between them cannot leave the previous level's cleared+ * arrows or spent hearts attached to the new board.+ */+ suspend fun saveLevel(level: Int) {+ context.dataStore.edit { prefs ->+ prefs[LEVEL_KEY] = level+ prefs[REMOVED_KEY] = emptySet()+ prefs[HEARTS_KEY] = STARTING_HEARTS+ }+ }++ /** Puts every arrow back and restores the hearts, for a restart or a failed level. */+ suspend fun resetBoard(daily: Boolean) {+ context.dataStore.edit { prefs ->+ prefs[if (daily) DAILY_REMOVED_KEY else REMOVED_KEY] = emptySet()+ prefs[if (daily) DAILY_HEARTS_KEY else HEARTS_KEY] = STARTING_HEARTS+ }+ }++ /** Records the outcome of a tap: which arrows have gone, and what the hearts stand at. */+ suspend fun saveProgress(removed: Set<Int>, hearts: Int, daily: Boolean) {+ context.dataStore.edit { prefs ->+ prefs[if (daily) DAILY_REMOVED_KEY else REMOVED_KEY] =+ removed.mapTo(mutableSetOf()) { it.toString() }+ prefs[if (daily) DAILY_HEARTS_KEY else HEARTS_KEY] = hearts+ }+ }++ /** Bumps and returns the lifetime cleared count. */+ suspend fun recordCleared(): Int {+ var total = 0+ context.dataStore.edit { prefs ->+ total = (prefs[CLEARED_KEY] ?: 0) + 1+ prefs[CLEARED_KEY] = total+ }+ return total+ }++ /**+ * Rolls the daily board over to [day] if it is not already there.+ *+ * Resetting on rollover is what stops yesterday's cleared arrows appearing on today's board. 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_REMOVED_KEY] = emptySet()+ prefs[DAILY_HEARTS_KEY] = STARTING_HEARTS+ }+ }++ private companion object {+ val LEVEL_KEY = intPreferencesKey("current_level")+ val REMOVED_KEY = stringSetPreferencesKey("removed_arrows")+ val HEARTS_KEY = intPreferencesKey("hearts")+ val GAME_MODE_KEY = stringPreferencesKey("game_mode")+ val SHOW_ROUTES_KEY = booleanPreferencesKey("show_routes")+ val CLEARED_KEY = intPreferencesKey("boards_cleared")++ val DAILY_DAY_KEY = longPreferencesKey("daily_day")+ val DAILY_REMOVED_KEY = stringSetPreferencesKey("daily_removed_arrows")+ val DAILY_HEARTS_KEY = intPreferencesKey("daily_hearts")++ /** Sentinel for "no daily played yet"; distinct from epoch day 0, which is a real date. */+ const val NO_DAY = Long.MIN_VALUE+ }+}++/** Arrow ids are stored as strings because DataStore has no int-set type. */+private fun Set<String>?.toIds(): Set<Int> =+ this?.mapNotNullTo(mutableSetOf()) { it.toIntOrNull() } ?: emptySet()
games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.ktnew file mode 100644index 0000000000..0641c623b1--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsGenerator.kt@@ -0,0 +1,171 @@+package com.vayunmathur.games.arrows.domain++import com.vayunmathur.games.arrows.data.ArrowPiece+import com.vayunmathur.games.arrows.data.ArrowsPuzzle+import com.vayunmathur.games.arrows.data.Direction+import com.vayunmathur.games.arrows.data.Mirror+import kotlin.random.Random++/**+ * Builds a board by adding arrows in the reverse of a working removal order.+ *+ * The key idea: when a new arrow is placed, it is only kept if it could fly out past the arrows+ * already on the board. Do that repeatedly and the insertion order, reversed, *is* a solution — the+ * last arrow added can always leave first, then the one before it, and so on. Solvability is+ * therefore structural rather than something to test for and hope about, which matters because the+ * alternative (paint a board, then search for an order) fails for the overwhelming majority of random+ * layouts.+ *+ * A generated board can still have many solutions; nothing here tries to make the order unique.+ */+object ArrowsGenerator {++ /**+ * A clearable board, or null if [attempts] rounds never reached [minPieces].+ *+ * Mirrors are placed first and permanently: arrows may not sit on them, and they bend any route+ * that crosses them, so every subsequent exit check already accounts for them.+ */+ fun generate(+ cols: Int,+ rows: Int,+ targetPieces: Int,+ mirrorCount: Int,+ rng: Random,+ minPieces: Int = (targetPieces * 2) / 3,+ attempts: Int = DEFAULT_ATTEMPTS,+ ): ArrowsPuzzle? {+ repeat(attempts) {+ build(cols, rows, targetPieces, mirrorCount, rng)+ ?.takeIf { it.pieces.size >= minPieces }+ ?.let { return it }+ }+ return null+ }++ /**+ * A board for a given [seed], 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 board+ * however many rounds it takes — that is what lets saved progress stay valid.+ */+ fun generateSeeded(+ cols: Int,+ rows: Int,+ targetPieces: Int,+ mirrorCount: Int,+ seed: Long,+ rounds: Int = DEFAULT_ROUNDS,+ ): ArrowsPuzzle? {+ for (round in 0 until rounds) {+ generate(+ cols = cols,+ rows = rows,+ targetPieces = targetPieces,+ mirrorCount = mirrorCount,+ rng = Random(seed + round * SEED_STRIDE),+ )?.let { return it }+ }+ return null+ }++ private fun build(+ cols: Int,+ rows: Int,+ targetPieces: Int,+ mirrorCount: Int,+ rng: Random,+ ): ArrowsPuzzle? {+ val cellCount = cols * rows+ // Mirrors are kept off the border: one on an edge cell mostly deflects arrows straight back+ // out again, which reads as a decoration rather than an obstacle.+ val interior = (0 until cellCount).filter {+ val row = it / cols+ val col = it % cols+ row in 1 until rows - 1 && col in 1 until cols - 1+ }+ val mirrors = interior.shuffled(rng)+ .take(mirrorCount.coerceAtMost(interior.size))+ .associateWith { if (rng.nextBoolean()) Mirror.FORWARD else Mirror.BACK }++ val occupied = mirrors.keys.toMutableSet()+ val pieces = mutableListOf<ArrowPiece>()+ var failures = 0++ while (pieces.size < targetPieces && failures < MAX_CONSECUTIVE_FAILURES) {+ val candidate = randomPiece(cols, rows, occupied, pieces.size, rng)+ if (candidate == null) {+ failures+++ continue+ }+ // The board as it stands, which is exactly what this arrow must be able to escape past.+ val soFar = ArrowsPuzzle(cols, rows, pieces, mirrors)+ val path = ArrowsRules.exitPath(soFar, candidate.head, candidate.direction)+ val blockers = occupied+ if (path == null || path.any { it in blockers }) {+ failures+++ continue+ }+ pieces += candidate+ occupied += candidate.cells+ failures = 0+ }++ if (pieces.isEmpty()) return null+ return ArrowsPuzzle(cols, rows, pieces, mirrors)+ }++ /**+ * A random polyline of two to [MAX_LENGTH] cells that avoids [occupied] and itself.+ *+ * Walks from a random free cell, turning at random, and gives up rather than backtracking — a+ * failed walk is cheap and the caller simply tries again.+ */+ private fun randomPiece(+ cols: Int,+ rows: Int,+ occupied: Set<Int>,+ id: Int,+ rng: Random,+ ): ArrowPiece? {+ val free = (0 until cols * rows).filterNot { it in occupied }+ if (free.isEmpty()) return null++ val start = free.random(rng)+ val cells = mutableListOf(start)+ var heading = Direction.entries.random(rng)+ val targetLength = rng.nextInt(2, MAX_LENGTH + 1)++ while (cells.size < targetLength) {+ // Never immediately double back: that would put two cells of the piece on top of+ // each other, and the "polyline" would stop being one.+ val options = Direction.entries.filter { it != heading.opposite }.shuffled(rng)+ val step = options.firstNotNullOfOrNull { direction ->+ val row = cells.last() / cols + direction.dRow+ val col = cells.last() % cols + direction.dCol+ if (row !in 0 until rows || col !in 0 until cols) return@firstNotNullOfOrNull null+ val cell = row * cols + col+ if (cell in occupied || cell in cells) null else direction to cell+ } ?: break++ heading = step.first+ cells += step.second+ }++ // A single cell has no last segment, so there would be nothing for the arrowhead to follow.+ if (cells.size < 2) return null+ return ArrowPiece(id = id, cells = cells, direction = heading)+ }++ /** Longest arrow the generator will draw. Beyond this a piece dominates a small board. */+ private const val MAX_LENGTH = 5++ /** Give up on a board once this many placement attempts in a row have failed. */+ private const val MAX_CONSECUTIVE_FAILURES = 200++ private const val DEFAULT_ATTEMPTS = 24+ private const val DEFAULT_ROUNDS = 8++ /** Keeps per-round seeds far apart so consecutive rounds do not rebuild near-identical boards. */+ private const val SEED_STRIDE = 1_000_003L+}
games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsRules.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsRules.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsRules.ktnew file mode 100644index 0000000000..ada3a05983--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/domain/ArrowsRules.kt@@ -0,0 +1,123 @@+package com.vayunmathur.games.arrows.domain++import com.vayunmathur.games.arrows.data.ArrowPiece+import com.vayunmathur.games.arrows.data.ArrowsGameState+import com.vayunmathur.games.arrows.data.ArrowsPuzzle+import com.vayunmathur.games.arrows.data.Direction+import com.vayunmathur.games.arrows.data.GameMode+import com.vayunmathur.games.arrows.data.STARTING_HEARTS+import com.vayunmathur.games.arrows.data.TapOutcome++/**+ * The rules, as pure functions on a state.+ *+ * Kept out of the ViewModel so the travel simulation — the one thing that decides whether a tap is a+ * clean exit or a lost heart — can be unit tested without an Android dependency.+ */+object ArrowsRules {++ /**+ * The cells an arrow's head visits after leaving [from], heading [direction], until it is off the+ * board.+ *+ * Mirrors bend the route as the head enters them. Returns null if the head never gets out, which a+ * ring of mirrors can arrange; the caller treats that as impassable rather than looping forever.+ * The starting cell is not included, because the head is already there.+ */+ fun exitPath(puzzle: ArrowsPuzzle, from: Int, direction: Direction): List<Int>? {+ val path = mutableListOf<Int>()+ var row = from / puzzle.cols+ var col = from % puzzle.cols+ var heading = direction++ repeat(maxSteps(puzzle)) {+ row += heading.dRow+ col += heading.dCol+ if (!puzzle.contains(row, col)) return path++ val cell = row * puzzle.cols + col+ path.add(cell)+ puzzle.mirrors[cell]?.let { heading = it.reflect(heading) }+ }+ return null+ }++ /**+ * Whether [piece] can leave [state] right now.+ *+ * The body follows the head, so the only thing that can stop it is an occupied cell on the head's+ * route. The piece's own cells count as occupied too: normally the route leads away from its body+ * so this never comes up, but a mirror can turn an arrow back into itself, and letting it pass+ * through its own tail would be indefensible to a player watching it happen.+ */+ fun isBlocked(state: ArrowsGameState, piece: ArrowPiece): Boolean {+ val path = exitPath(state.puzzle, piece.head, piece.direction) ?: return true+ val occupied = state.occupancy+ return path.any { occupied.containsKey(it) }+ }++ /**+ * Applies a tap on the arrow with [pieceId].+ *+ * A clean exit removes it; a blocked one costs a heart and flags the arrow so the board can show+ * what went wrong. Running out of hearts is not handled here — [resetAfterFailure] is a separate+ * step, so the UI can show the failure before the board is rebuilt.+ */+ fun tap(state: ArrowsGameState, pieceId: Int): Pair<ArrowsGameState, TapOutcome> {+ if (state.isOver) return state to TapOutcome.IGNORED+ val piece = state.puzzle.pieces.firstOrNull { it.id == pieceId }+ ?: return state to TapOutcome.IGNORED+ if (piece.id in state.removed) return state to TapOutcome.IGNORED++ return if (isBlocked(state, piece)) {+ state.copy(hearts = state.hearts - 1, blockedId = piece.id) to TapOutcome.BLOCKED+ } else {+ state.copy(removed = state.removed + piece.id, blockedId = -1) to TapOutcome.CLEARED+ }+ }++ /** The same puzzle, back to a full board and full hearts. */+ fun resetAfterFailure(state: ArrowsGameState): ArrowsGameState =+ state.copy(removed = emptySet(), hearts = STARTING_HEARTS, blockedId = -1)++ /**+ * Every arrow that could leave right now.+ *+ * Used by the generator to confirm a board is still solvable, and by the hint in the UI.+ */+ fun clearableNow(state: ArrowsGameState): List<ArrowPiece> =+ state.remaining.filterNot { isBlocked(state, it) }++ /**+ * A removal order that empties the board, or null if none exists.+ *+ * Greedy and deliberately so: at every step it takes whichever arrow can currently leave. That is+ * sound here because removing an arrow only ever frees cells, so clearing one can never make+ * another impossible — no choice made along the way can be regretted, and no backtracking is+ * needed.+ */+ fun solve(puzzle: ArrowsPuzzle): List<Int>? {+ var state = ArrowsGameState(+ puzzle = puzzle,+ removed = emptySet(),+ hearts = STARTING_HEARTS,+ level = 0,+ mode = GameMode.CASUAL,+ )+ val order = mutableListOf<Int>()+ while (state.removed.size < puzzle.pieces.size) {+ val next = clearableNow(state).firstOrNull() ?: return null+ order.add(next.id)+ state = state.copy(removed = state.removed + next.id)+ }+ return order+ }++ /**+ * Step cap for [exitPath].+ *+ * A route that has taken more turns than there are cells must be circling, since a straight run+ * crosses the board in at most one dimension's worth of steps.+ */+ private fun maxSteps(puzzle: ArrowsPuzzle): Int = puzzle.cellCount * 4 + 8+}
games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/AppBackupAgent.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/AppBackupAgent.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..32afee1694--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/AppBackupAgent.kt@@ -0,0 +1,12 @@+package com.vayunmathur.games.arrows.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 board in progress, while the shared DataStoreUtils file holds the daily streak and the+ * achievement unlocks.+ */+ override val datastoreNames: List<String> get() = listOf("settings", "datastore_default")+}
games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManager.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManager.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManager.ktnew file mode 100644index 0000000000..cb1c5897c0--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManager.kt@@ -0,0 +1,42 @@+package com.vayunmathur.games.arrows.platform++import android.content.Context+import com.vayunmathur.games.arrows.data.ArrowsDataStore+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 ArrowsAchievementsManager(+ context: Context,+ json: String,+ private val dataStore: ArrowsDataStore,+ 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 board they clear.+ *+ * The reads are suspending, so this hands off to a coroutine rather than blocking. Anything about+ * how a single board was played — whether a heart was lost, whether it had mirrors — is gone once+ * the level advances, so those are unlocked from the clear handler instead.+ */+ override fun checkExistingAchievements() {+ CoroutineScope(Dispatchers.IO).launch {+ val total = dataStore.boardsCleared.first()+ if (total > 0) onAchievementUnlocked("first_board")+ onProgressUpdated("boards_10", total)+ onProgressUpdated("boards_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/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsUiContract.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsUiContract.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsUiContract.ktnew file mode 100644index 0000000000..e68d902f6e--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsUiContract.kt@@ -0,0 +1,54 @@+package com.vayunmathur.games.arrows.platform++import com.vayunmathur.games.arrows.data.ArrowsGameState+import com.vayunmathur.games.arrows.data.GameMode++/**+ * The UI contract between [ArrowsViewModel] 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 ArrowsGameActions {+ /** Sends the tapped arrow on its way, or spends a heart if it is boxed in. */+ fun tapArrow(pieceId: Int) {}++ fun nextLevel() {}+ fun restartLevel() {}+ fun setGameMode(mode: GameMode) {}++ companion object { val Noop: ArrowsGameActions = object : ArrowsGameActions {} }+}++/** What the board needs to draw itself. [game] is null only while a board is being generated. */+data class ArrowsUiState(+ val game: ArrowsGameState? = null,+ val mode: GameMode = GameMode.CASUAL,+ val level: Int = 1,+ val showRoutes: Boolean = true,+ val dailyStreak: Long = 0,+ /** True once today's daily has been cleared, 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 clearable board, so the board can offer a retry. */+ val generationFailed: Boolean = false,+)++interface SettingsActions {+ fun setShowRoutes(enabled: Boolean) {}+ fun setReminderEnabled(enabled: Boolean) {}+ fun setReminderTime(hour: Int, minute: Int) {}++ companion object { val Noop: SettingsActions = object : SettingsActions {} }+}++data class SettingsUiState(+ val showRoutes: Boolean = true,+ val reminderEnabled: Boolean = false,+ val reminderHour: Int = 20,+ val reminderMinute: Int = 0,+)
games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.ktnew file mode 100644index 0000000000..e0438a89d6--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt@@ -0,0 +1,320 @@+package com.vayunmathur.games.arrows.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.games.arrows.data.ArrowsDataStore+import com.vayunmathur.games.arrows.data.ArrowsGameState+import com.vayunmathur.games.arrows.data.ArrowsPuzzle+import com.vayunmathur.games.arrows.data.DAILY_ARROWS+import com.vayunmathur.games.arrows.data.DAILY_BOARD+import com.vayunmathur.games.arrows.data.DAILY_MIRRORS+import com.vayunmathur.games.arrows.data.GameMode+import com.vayunmathur.games.arrows.data.STARTING_HEARTS+import com.vayunmathur.games.arrows.data.TapOutcome+import com.vayunmathur.games.arrows.data.arrowCountForLevel+import com.vayunmathur.games.arrows.data.boardSizeForLevel+import com.vayunmathur.games.arrows.data.mirrorCountForLevel+import com.vayunmathur.games.arrows.domain.ArrowsGenerator+import com.vayunmathur.games.arrows.domain.ArrowsRules+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 board on screen and the progress behind it.+ *+ * Casual mode is a single level counter: clearing a board writes `level + 1` and resets it in one+ * DataStore edit, so there is no level list and no way back. Daily mode is one board per calendar day,+ * generated from the date, with its own progress stamped with the day it belongs to.+ *+ * Generation runs on [Dispatchers.Default]: building a board means repeatedly placing an arrow and+ * simulating its escape, which is fast but not free.+ */+class ArrowsViewModel(application: Application) : AndroidViewModel(application),+ ArrowsGameActions, SettingsActions {++ val dataStore = ArrowsDataStore(application)+ private val dailyStore = DailyChallengeStore(application, DAILY_KEY_PREFIX)+ private val reminderSettings = DailyReminderSettings(application, DAILY_KEY_PREFIX)++ private val _uiState = MutableStateFlow(ArrowsUiState())+ val uiState: StateFlow<ArrowsUiState> = _uiState.asStateFlow()++ /** Cached so flipping modes back and forth does not rebuild an identical board. */+ private var casualBoard: Pair<Int, ArrowsPuzzle>? = null+ private var dailyBoard: Pair<Long, ArrowsPuzzle>? = 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()+ ArrowsAchievementsManager(application, json, dataStore, dailyStore)+ }++ init {+ achievementsManager.checkExistingAchievements()++ viewModelScope.launch {+ combine(+ dataStore.gameMode,+ dataStore.currentLevel,+ dataStore.showRoutes,+ dailyStore.currentStreak,+ ) { mode, level, showRoutes, streak -> Session(mode, level, showRoutes, streak) }+ .collectLatest { session -> load(session) }+ }+ }++ /** The stored inputs that decide which board is on screen. */+ private data class Session(+ val mode: GameMode,+ val level: Int,+ val showRoutes: 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,+ showRoutes = session.showRoutes,+ dailyStreak = session.streak,+ generating = true,+ generationFailed = false,+ )++ val puzzle = withContext(Dispatchers.Default) {+ val cached = if (daily) dailyBoard?.takeIf { it.first == day }?.second+ else casualBoard?.takeIf { it.first == session.level }?.second+ cached ?: buildBoard(daily, session.level, day)+ }++ if (puzzle == null) {+ _uiState.value = _uiState.value.copy(generating = false, generationFailed = true)+ return+ }+ if (daily) dailyBoard = day to puzzle else casualBoard = session.level to puzzle++ observeProgress(session, puzzle, day)+ }++ private fun buildBoard(daily: Boolean, level: Int, day: Long): ArrowsPuzzle? =+ if (daily) {+ val (cols, rows) = DAILY_BOARD+ ArrowsGenerator.generateSeeded(+ cols = cols,+ rows = rows,+ targetPieces = DAILY_ARROWS,+ mirrorCount = DAILY_MIRRORS,+ seed = DAILY_SEED_OFFSET + day,+ )+ } else {+ val (cols, rows) = boardSizeForLevel(level)+ ArrowsGenerator.generateSeeded(+ cols = cols,+ rows = rows,+ targetPieces = arrowCountForLevel(level),+ mirrorCount = mirrorCountForLevel(level),+ seed = level.toLong(),+ )+ }++ /**+ * Streams the player's progress onto [puzzle].+ *+ * Daily progress is discarded 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 observeProgress(session: Session, puzzle: ArrowsPuzzle, day: Long) {+ val daily = session.mode == GameMode.DAILY+ val removedFlow = if (daily) dataStore.dailyRemoved else dataStore.removedArrows+ val heartsFlow = if (daily) dataStore.dailyHearts else dataStore.hearts++ combine(removedFlow, heartsFlow, dataStore.dailyDay, dailyStore.lastCompletedDayFlow) {+ removed, hearts, storedDay, lastCompleted ->+ val stale = daily && storedDay != day+ Progress(+ removed = if (stale) emptySet() else removed,+ hearts = if (stale) STARTING_HEARTS else hearts,+ dailyDone = lastCompleted == day,+ )+ }.collectLatest { progress ->+ // Ids that no longer exist are dropped: a board rebuilt after a code change could+ // otherwise be considered finished by leftover progress that does not match it.+ val valid = progress.removed.filterTo(mutableSetOf()) { id ->+ puzzle.pieces.any { it.id == id }+ }+ val game = ArrowsGameState(+ puzzle = puzzle,+ removed = valid,+ hearts = progress.hearts,+ level = session.level,+ mode = session.mode,+ blockedId = lastBlockedId,+ )+ _uiState.value = _uiState.value.copy(+ game = game,+ generating = false,+ dailyDone = progress.dailyDone,+ )+ if (game.isWon) onCleared(game, daily, day)+ }+ }++ private data class Progress(val removed: Set<Int>, val hearts: Int, val dailyDone: Boolean)++ /**+ * The arrow the last tap could not move.+ *+ * Kept here rather than persisted: it is a momentary bit of feedback about the tap just made, and+ * would be meaningless after a relaunch.+ */+ private var lastBlockedId: Int = -1++ override fun tapArrow(pieceId: Int) {+ val state = _uiState.value+ val game = state.game ?: return+ if (game.isOver) return++ val (next, outcome) = ArrowsRules.tap(game, pieceId)+ if (outcome == TapOutcome.IGNORED) return++ lastBlockedId = next.blockedId+ // Published immediately so the flash and the heart update land on this frame rather than+ // waiting for the DataStore write to come back round through the flow.+ _uiState.value = state.copy(game = next)++ val daily = state.mode == GameMode.DAILY+ viewModelScope.launch {+ dataStore.saveProgress(next.removed, next.hearts, daily)+ if (outcome == TapOutcome.BLOCKED) {+ achievementsManager.onAchievementUnlocked("first_block")+ }+ }+ }++ override fun nextLevel() {+ val state = _uiState.value+ if (state.mode == GameMode.DAILY) return+ lastBlockedId = -1+ viewModelScope.launch { dataStore.saveLevel(state.level + 1) }+ }++ override fun restartLevel() {+ val daily = _uiState.value.mode == GameMode.DAILY+ lastBlockedId = -1+ viewModelScope.launch { dataStore.resetBoard(daily) }+ }++ override fun setGameMode(mode: GameMode) {+ lastBlockedId = -1+ viewModelScope.launch { dataStore.setGameMode(mode) }+ }++ override fun setShowRoutes(enabled: Boolean) {+ viewModelScope.launch { dataStore.setShowRoutes(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 cleared board is recorded.+ *+ * Reached from the progress collector, so it can fire more than once for the same board as+ * unrelated flows re-emit. Everything it touches is idempotent for a given day, except the+ * lifetime counter, so that is guarded by [recordedClear].+ */+ private fun onCleared(game: ArrowsGameState, daily: Boolean, day: Long) {+ // Daily clears are keyed by day and casual ones by negated level, which cannot collide.+ val key = if (daily) day else -game.level.toLong()+ if (recordedClear == key) return+ recordedClear = key++ viewModelScope.launch {+ val total = dataStore.recordCleared()+ val manager = achievementsManager+ manager.onAchievementUnlocked("first_board")+ if (game.hearts == STARTING_HEARTS) manager.onAchievementUnlocked("flawless")+ if (game.puzzle.mirrors.isNotEmpty()) manager.onAchievementUnlocked("through_the_looking_glass")+ manager.onProgressUpdated("boards_10", total)+ manager.onProgressUpdated("boards_50", total)++ if (daily) {+ manager.onAchievementUnlocked("first_daily")+ val streak = dailyStore.recordDayCompleted(day)+ DailyStreakReporter.report(getApplication(), "arrows", streak, day)+ manager.onProgressUpdated("daily_streak_7", streak.current.toInt())+ manager.onProgressUpdated("daily_streak_30", streak.current.toInt())+ }+ }+ }++ /** Which clear has already been banked, so a re-emitted flow cannot double-count it. */+ private var recordedClear: Long? = null++ companion object {+ /** Namespace shared by the daily-challenge store and its reminder. */+ const val DAILY_KEY_PREFIX = "arrows_daily"++ private const val REMINDER_NOTIFICATION_ID = 5105++ /**+ * 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,+ * 1.1B nonogram).+ */+ private const val DAILY_SEED_OFFSET = 1_300_000_000L+ }+}
games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/ArrowsGamePage.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/ArrowsGamePage.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/ArrowsGamePage.ktnew file mode 100644index 0000000000..28e3ecabe2--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/ArrowsGamePage.kt@@ -0,0 +1,28 @@+package com.vayunmathur.games.arrows.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.games.arrows.Route+import com.vayunmathur.games.arrows.platform.ArrowsViewModel+import com.vayunmathur.library.util.NavBackStack++/**+ * Binds [ArrowsViewModel] to the stateless [ArrowsGameScreen].+ *+ * 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 ArrowsGamePage(+ backStack: NavBackStack<Route>,+ viewModel: ArrowsViewModel,+) {+ val uiState by viewModel.uiState.collectAsState()+ ArrowsGameScreen(+ state = uiState,+ actions = viewModel,+ onOpenSettings = { backStack.add(Route.Settings) },+ onOpenGameCenter = { backStack.add(Route.GameCenter) },+ )+}
games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/ArrowsGameScreen.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/ArrowsGameScreen.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/ArrowsGameScreen.ktnew file mode 100644index 0000000000..5ffce9f9c2--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/ArrowsGameScreen.kt@@ -0,0 +1,253 @@+package com.vayunmathur.games.arrows.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.size+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.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.arrows.R+import com.vayunmathur.games.arrows.data.GameMode+import com.vayunmathur.games.arrows.data.STARTING_HEARTS+import com.vayunmathur.games.arrows.platform.ArrowsGameActions+import com.vayunmathur.games.arrows.platform.ArrowsUiState+import com.vayunmathur.games.arrows.ui.components.ArrowsBoard+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.IconFavorite+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 = 420.dp++/**+ * The board, with no dependency on the ViewModel so it can be rendered from a `@Preview` — see+ * `src/screenshotTest`.+ */+@Composable+fun ArrowsGameScreen(+ state: ArrowsUiState,+ actions: ArrowsGameActions,+ 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 -> {+ Hearts(game.hearts)++ ArrowsBoard(+ game = game,+ showRoutes = state.showRoutes,+ onTapArrow = actions::tapArrow,+ modifier = Modifier+ .widthIn(max = BoardMaxWidth)+ .fillMaxWidth(),+ )++ when {+ game.isWon -> {+ Text(+ stringResource(R.string.board_cleared),+ 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)) }+ }+ }++ game.isFailed -> {+ Text(+ stringResource(R.string.out_of_hearts),+ style = MaterialTheme.typography.titleLarge,+ color = MaterialTheme.colorScheme.error,+ )+ Button(+ onClick = { actions.restartLevel() },+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.try_again)) }+ }++ else -> {+ if (game.removed.isEmpty() && game.hearts == STARTING_HEARTS) {+ Text(+ stringResource(R.string.how_to_play),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ )+ }+ OutlinedButton(onClick = { actions.restartLevel() }) {+ Text(stringResource(R.string.restart))+ }+ }+ }+ }+ }+ }+ }+}++/**+ * The hearts left.+ *+ * Spent hearts stay in place as hollow outlines rather than disappearing, so the row does not reflow+ * and the player can see at a glance how much margin is gone.+ */+@Composable+private fun Hearts(hearts: Int) {+ val description = pluralStringResource(R.plurals.cd_hearts, hearts.coerceAtLeast(0), hearts.coerceAtLeast(0))+ Row(+ Modifier.clearAndSetSemantics { contentDescription = description },+ horizontalArrangement = Arrangement.spacedBy(Spacing.xs),+ ) {+ repeat(STARTING_HEARTS) { index ->+ val spent = index >= hearts+ IconFavorite(+ Modifier.size(20.dp),+ tint = if (spent) MaterialTheme.colorScheme.surfaceContainerHighest+ else MaterialTheme.colorScheme.error,+ )+ }+ }+}++/**+ * 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/arrows/src/main/java/com/vayunmathur/games/arrows/ui/SettingsPage.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/SettingsPage.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/SettingsPage.ktnew file mode 100644index 0000000000..fb39947d1d--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/SettingsPage.kt@@ -0,0 +1,83 @@+package com.vayunmathur.games.arrows.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.arrows.R+import com.vayunmathur.games.arrows.platform.ArrowsViewModel+import com.vayunmathur.games.arrows.platform.SettingsActions+import com.vayunmathur.games.arrows.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 [ArrowsViewModel] to the stateless [SettingsScreen]. */+@Composable+fun SettingsPage(viewModel: ArrowsViewModel, 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(+ showRoutes = uiState.showRoutes,+ reminderEnabled = reminderEnabled,+ reminderHour = (reminderMinutes / 60).toInt(),+ reminderMinute = (reminderMinutes % 60).toInt(),+ ),+ actions = object : SettingsActions {+ override fun setShowRoutes(enabled: Boolean) = viewModel.setShowRoutes(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_routes),+ supportingText = stringResource(R.string.show_routes_description),+ checked = state.showRoutes,+ onCheckedChange = { actions.setShowRoutes(it) },+ )+ }+ DailyReminderSettingsSection(+ enabled = state.reminderEnabled,+ hour = state.reminderHour,+ minute = state.reminderMinute,+ onEnabledChange = { actions.setReminderEnabled(it) },+ onTimeChange = { hour, minute -> actions.setReminderTime(hour, minute) },+ )+ }+}
games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.ktnew file mode 100644index 0000000000..b7ffc952e8--- /dev/null+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.kt@@ -0,0 +1,249 @@+package com.vayunmathur.games.arrows.ui.components++import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+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.graphics.Path+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.StrokeJoin+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription+import com.vayunmathur.games.arrows.R+import com.vayunmathur.games.arrows.data.ArrowPiece+import com.vayunmathur.games.arrows.data.ArrowsGameState+import com.vayunmathur.games.arrows.data.Direction+import com.vayunmathur.games.arrows.data.Mirror+import com.vayunmathur.games.arrows.domain.ArrowsRules+import com.vayunmathur.library.ui.MaterialTheme++/**+ * The board.+ *+ * Painted in one [drawBehind] pass rather than as a composable per cell: an arrow spans several cells+ * and has to be a single continuous stroke with one arrowhead, which per-cell composables cannot+ * express. Taps anywhere along an arrow are resolved by arithmetic on the touch position, which is+ * both simpler and more accurate than hit-testing a stack of overlapping boxes.+ *+ * Because a canvas carries no semantics, one transparent box per arrow is laid over its head cell to+ * give screen readers something to find and activate.+ */+@Composable+fun ArrowsBoard(+ game: ArrowsGameState,+ showRoutes: Boolean,+ onTapArrow: (Int) -> Unit,+ modifier: Modifier = Modifier,+) {+ val scheme = MaterialTheme.colorScheme+ val arrowColor = scheme.onSurface+ val blockedColor = scheme.error+ val mirrorColor = scheme.tertiary+ val dotColor = scheme.outlineVariant+ val cols = game.puzzle.cols++ // The route the last blocked arrow tried to take, up to and including what stopped it. Computed+ // here rather than stored, because it is derivable from the board and would only go stale.+ val blockedRoute = if (!showRoutes || game.blockedId < 0) emptyList() else {+ game.puzzle.pieces.firstOrNull { it.id == game.blockedId }?.let { piece ->+ val occupied = game.occupancy+ ArrowsRules.exitPath(game.puzzle, piece.head, piece.direction)+ .orEmpty()+ .let { route ->+ val stop = route.indexOfFirst { it in occupied }+ if (stop < 0) route else route.take(stop + 1)+ }+ }.orEmpty()+ }++ BoxWithConstraints(modifier) {+ val cell = maxWidth / cols++ Box(+ Modifier+ .size(cell * cols, cell * game.puzzle.rows)+ .pointerInput(game.puzzle, game.removed, game.isOver) {+ detectTapGestures { offset ->+ val cellPx = size.width.toFloat() / cols+ val col = (offset.x / cellPx).toInt()+ val row = (offset.y / cellPx).toInt()+ if (!game.puzzle.contains(row, col)) return@detectTapGestures+ game.pieceAt(row * cols + col)?.let { onTapArrow(it.id) }+ }+ }+ .drawBehind {+ val cellPx = size.width / cols+ drawDots(game, cellPx, dotColor)+ for ((index, mirror) in game.puzzle.mirrors) {+ drawMirror(index, mirror, cols, cellPx, mirrorColor)+ }+ if (blockedRoute.isNotEmpty()) {+ drawRoute(blockedRoute, cols, cellPx, blockedColor)+ }+ for (piece in game.remaining) {+ val color = if (piece.id == game.blockedId) blockedColor else arrowColor+ drawArrow(piece, cols, cellPx, color)+ }+ }+ ) {+ // Semantics only: invisible, one per arrow, sitting on its head cell.+ for (piece in game.remaining) {+ val description = stringResource(+ R.string.cd_arrow,+ stringResource(piece.direction.spokenNameRes),+ piece.head / cols + 1,+ piece.head % cols + 1,+ )+ Box(+ Modifier+ .offset(x = cell * (piece.head % cols), y = cell * (piece.head / cols))+ .size(cell)+ .clickable { onTapArrow(piece.id) }+ .clearAndSetSemantics { contentDescription = description }+ )+ }+ // Redirectors are not interactive, but a screen reader still has to know they are there.+ val redirector = stringResource(R.string.cd_redirector)+ for (index in game.puzzle.mirrors.keys) {+ Box(+ Modifier+ .offset(x = cell * (index % cols), y = cell * (index / cols))+ .size(cell)+ .clearAndSetSemantics { contentDescription = redirector }+ )+ }+ }+ }+}++/**+ * Faint dots at cell centres.+ *+ * A full grid of lines would compete with the arrows, which are themselves thin strokes. Dots give+ * enough of a lattice to judge alignment without adding a second set of lines to read past. Skipped+ * wherever something is drawn, so a dot never shows through a stroke.+ */+private fun DrawScope.drawDots(game: ArrowsGameState, cell: Float, color: Color) {+ val radius = cell * 0.035f+ val occupied = game.occupancy+ for (row in 0 until game.puzzle.rows) {+ for (col in 0 until game.puzzle.cols) {+ val index = row * game.puzzle.cols + col+ if (index in occupied || index in game.puzzle.mirrors) continue+ drawCircle(+ color = color,+ radius = radius,+ center = Offset((col + 0.5f) * cell, (row + 0.5f) * cell),+ )+ }+ }+}++/** The tile's diagonal, drawn as the mirror it is named for. */+private fun DrawScope.drawMirror(cell: Int, mirror: Mirror, cols: Int, size: Float, color: Color) {+ val row = cell / cols+ val col = cell % cols+ val inset = size * 0.22f+ val left = col * size + inset+ val right = (col + 1) * size - inset+ val top = row * size + inset+ val bottom = (row + 1) * size - inset+ val (start, end) = when (mirror) {+ Mirror.FORWARD -> Offset(left, bottom) to Offset(right, top)+ Mirror.BACK -> Offset(left, top) to Offset(right, bottom)+ }+ drawLine(color, start, end, strokeWidth = size * 0.09f, cap = StrokeCap.Round)+}++/**+ * One arrow: its body as a single joined stroke, and an arrowhead at the head.+ *+ * The stroke runs through cell centres, so a turn in the polyline becomes a rounded corner. The tip+ * reaches past the head's centre by [HEAD_REACH] to leave room for the barbs while staying inside its+ * own cell rather than poking into the next one.+ */+private fun DrawScope.drawArrow(piece: ArrowPiece, cols: Int, cell: Float, color: Color) {+ val stroke = cell * 0.11f+ fun centre(index: Int) = Offset((index % cols + 0.5f) * cell, (index / cols + 0.5f) * cell)++ val head = centre(piece.head)+ val tip = Offset(+ head.x + piece.direction.dCol * cell * HEAD_REACH,+ head.y + piece.direction.dRow * cell * HEAD_REACH,+ )++ val path = Path().apply {+ val first = centre(piece.cells.first())+ moveTo(first.x, first.y)+ for (index in piece.cells.drop(1)) {+ val point = centre(index)+ lineTo(point.x, point.y)+ }+ lineTo(tip.x, tip.y)+ }+ drawPath(+ path = path,+ color = color,+ style = Stroke(width = stroke, cap = StrokeCap.Round, join = StrokeJoin.Round),+ )++ // Two barbs angled back from the tip. For an axis-aligned heading the perpendicular is just the+ // row and column components swapped, so no trigonometry is needed.+ val barb = cell * 0.26f+ val backRow = -piece.direction.dRow+ val backCol = -piece.direction.dCol+ val perpRow = piece.direction.dCol+ val perpCol = piece.direction.dRow+ for (side in intArrayOf(1, -1)) {+ drawLine(+ color = color,+ start = tip,+ end = Offset(+ tip.x + (backCol + perpCol * side) * barb,+ tip.y + (backRow + perpRow * side) * barb,+ ),+ strokeWidth = stroke,+ cap = StrokeCap.Round,+ )+ }+}++/** How far past the head cell's centre the tip reaches, as a fraction of a cell. */+private const val HEAD_REACH = 0.34f++/**+ * The route a blocked arrow tried to take, drawn as a trail of dots behind the arrows.+ *+ * Dots rather than a line, so it reads as an attempt rather than another arrow, and stops on the cell+ * that turned it back — which is the cell the player needs to look at.+ */+private fun DrawScope.drawRoute(route: List<Int>, cols: Int, cell: Float, color: Color) {+ val faded = color.copy(alpha = 0.55f)+ for (index in route) {+ drawCircle(+ color = faded,+ radius = cell * 0.09f,+ center = Offset((index % cols + 0.5f) * cell, (index / cols + 0.5f) * cell),+ )+ }+}++/** Spoken name for a direction, for the board's accessibility description. */+val Direction.spokenNameRes: Int+ get() = when (this) {+ Direction.UP -> R.string.cd_up+ Direction.DOWN -> R.string.cd_down+ Direction.LEFT -> R.string.cd_left+ Direction.RIGHT -> R.string.cd_right+ }
games/arrows/src/main/res/values/strings.xml
diff --git a/games/arrows/src/main/res/values/strings.xml b/games/arrows/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..0a74f3c9d1--- /dev/null+++ b/games/arrows/src/main/res/values/strings.xml@@ -0,0 +1,55 @@+<?xml version="1.0" encoding="utf-8"?>+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">+ <!-- Manifest / TopAppBar: App name. Noun, plural -->+ <string name="app_name" translatable="false">Arrows</string>++ <!-- GameModeDropdown: Mode playing the numbered level progression. Noun plural -->+ <string name="mode_casual">Levels</string>+ <!-- GameModeDropdown: Mode playing today's shared board. Adjective -->+ <string name="mode_daily">Daily</string>++ <!-- ArrowsGameScreen TopAppBar: Current level in the progression. %1$d = level number, e.g. 6 -->+ <string name="level_title">Level <xliff:g id="level" example="6">%1$d</xliff:g></string>+ <!-- ArrowsGameScreen: Button advancing to the next level after clearing the board. Verb phrase -->+ <string name="next_level">Next Level</string>+ <!-- ArrowsGameScreen: Puts every arrow back and restores the hearts. Verb -->+ <string name="restart">Restart</string>+ <!-- ArrowsGameScreen: Shown after clearing the daily, since there is only one per day. Sentence -->+ <string name="daily_come_back_tomorrow">Cleared! Come back tomorrow for a new board.</string>+ <!-- ArrowsGameScreen: Celebratory line shown when every arrow has flown. Declarative -->+ <string name="board_cleared">Board Cleared!</string>+ <!-- ArrowsGameScreen: Shown when the last heart is spent. Declarative, sympathetic -->+ <string name="out_of_hearts">Out of hearts!</string>+ <!-- ArrowsGameScreen: Retries the level after running out of hearts. Verb phrase -->+ <string name="try_again">Try Again</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>+ <!-- ArrowsGameScreen: Hint under a fresh board explaining the one gesture. Imperative sentence -->+ <string name="how_to_play">Tap an arrow to send it off the board</string>++ <!-- ArrowsGameScreen: Shown when no clearable board could be generated for this level. Sentence -->+ <string name="generation_failed">Could not build a board for this level.</string>++ <!-- SettingsScreen: Toggle for flashing the route a blocked arrow tried to take. Noun phrase -->+ <string name="show_routes">Show blocked routes</string>+ <!-- SettingsScreen: Explains what the show-routes toggle does. Sentence -->+ <string name="show_routes_description">Trace the path a blocked arrow tried to take.</string>++ <!-- ArrowsBoard: Content description of the hearts remaining. %1$d = hearts left, 0 to 3, e.g. 2 -->+ <plurals name="cd_hearts">+ <item quantity="one"><xliff:g id="count" example="1">%1$d</xliff:g> heart left</item>+ <item quantity="other"><xliff:g id="count" example="2">%1$d</xliff:g> hearts left</item>+ </plurals>+ <!-- ArrowsBoard: Content description of one arrow. %1$s = the direction it points, e.g. right. %2$d = row number starting at 1, e.g. 3. %3$d = column number starting at 1, e.g. 5 -->+ <string name="cd_arrow">Arrow pointing <xliff:g id="direction" example="right">%1$s</xliff:g> at row <xliff:g id="row" example="3">%2$d</xliff:g>, column <xliff:g id="column" example="5">%3$d</xliff:g></string>+ <!-- ArrowsBoard: Direction name, spoken in cd_arrow. Adverb -->+ <string name="cd_up">up</string>+ <!-- ArrowsBoard: Direction name, spoken in cd_arrow. Adverb -->+ <string name="cd_down">down</string>+ <!-- ArrowsBoard: Direction name, spoken in cd_arrow. Adverb -->+ <string name="cd_left">left</string>+ <!-- ArrowsBoard: Direction name, spoken in cd_arrow. Adverb -->+ <string name="cd_right">right</string>+ <!-- ArrowsBoard: Content description of a redirector tile that turns passing arrows. Noun -->+ <string name="cd_redirector">Redirector</string>+</resources>
games/arrows/src/main/res/xml/data_extraction_rules.xml
diff --git a/games/arrows/src/main/res/xml/data_extraction_rules.xml b/games/arrows/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..1250ccd176--- /dev/null+++ b/games/arrows/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,35 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ Arrows. Audited state: filesDir/datastore/settings.preferences_pb, holding the+ current level, which arrows have flown, the hearts left, the daily board with+ the day it belongs to, and the show-routes preference; plus+ filesDir/datastore_default.preferences_pb, the shared DataStoreUtils file+ holding the DailyChallengeStore("arrows_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 board is generated on device from its level+ number or the date. Back everything up; it is a few KB of pure user progress.+ SCOPE: arrows 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/arrows/src/screenshotTest/kotlin/com/vayunmathur/games/arrows/MetadataPreviews.kt
diff --git a/games/arrows/src/screenshotTest/kotlin/com/vayunmathur/games/arrows/MetadataPreviews.kt b/games/arrows/src/screenshotTest/kotlin/com/vayunmathur/games/arrows/MetadataPreviews.ktnew file mode 100644index 0000000000..0fad332d04--- /dev/null+++ b/games/arrows/src/screenshotTest/kotlin/com/vayunmathur/games/arrows/MetadataPreviews.kt@@ -0,0 +1,141 @@+package com.vayunmathur.games.arrows++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.games.arrows.data.ArrowsGameState+import com.vayunmathur.games.arrows.data.ArrowsPuzzle+import com.vayunmathur.games.arrows.data.DAILY_ARROWS+import com.vayunmathur.games.arrows.data.DAILY_BOARD+import com.vayunmathur.games.arrows.data.DAILY_MIRRORS+import com.vayunmathur.games.arrows.data.GameMode+import com.vayunmathur.games.arrows.data.STARTING_HEARTS+import com.vayunmathur.games.arrows.data.arrowCountForLevel+import com.vayunmathur.games.arrows.data.boardSizeForLevel+import com.vayunmathur.games.arrows.data.mirrorCountForLevel+import com.vayunmathur.games.arrows.domain.ArrowsGenerator+import com.vayunmathur.games.arrows.domain.ArrowsRules+import com.vayunmathur.games.arrows.platform.ArrowsGameActions+import com.vayunmathur.games.arrows.platform.ArrowsUiState+import com.vayunmathur.games.arrows.ui.ArrowsGameScreen+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:arrows:metadata`.+ *+ * Boards come from [ArrowsGenerator] 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. Positions+ * part-way through are reached by replaying real taps from [ArrowsRules.solve], so no image shows a+ * state the rules could not produce. [ArrowsGameScreen] 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() {+ // A few arrows already flown, and one tapped that had nowhere to go - so the shot shows the+ // blocked arrow in red with the route it tried to take dotted out ahead of it.+ val puzzle = level(7)+ Board(game(puzzle, level = 7, cleared = 3, blocked = true, hearts = STARTING_HEARTS - 1))+ }++ @PreviewTest+ @Preview(name = "2-mirrors", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview2Mirrors() {+ // Past the level that introduces redirectors, so the diagonals show up.+ val puzzle = level(18)+ Board(game(puzzle, level = 18, cleared = 4))+ }++ @PreviewTest+ @Preview(name = "3-daily", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview3Daily() {+ val (cols, rows) = DAILY_BOARD+ val puzzle = requireNotNull(+ ArrowsGenerator.generateSeeded(cols, rows, DAILY_ARROWS, DAILY_MIRRORS, seed = 20260824L)+ )+ Board(+ game(puzzle, level = 1, cleared = 5, mode = GameMode.DAILY, hearts = 2),+ streak = 4,+ )+ }++ @PreviewTest+ @Preview(name = "4-fresh", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview4Fresh() {+ Board(game(level(2), level = 2, cleared = 0))+ }++ @Composable+ private fun Board(game: ArrowsGameState, streak: Long = 0) {+ // Layoutlib has no wallpaper to sample, so Material You falls back to the default palette.+ DynamicTheme(darkTheme = true) {+ ArrowsGameScreen(+ state = ArrowsUiState(+ game = game,+ mode = game.mode,+ level = game.level,+ dailyStreak = streak,+ ),+ actions = ArrowsGameActions.Noop,+ onOpenSettings = {},+ onOpenGameCenter = {},+ )+ }+ }++ /** The real board for [level], so the preview shows one the game would actually deal. */+ private fun level(level: Int): ArrowsPuzzle {+ val (cols, rows) = boardSizeForLevel(level)+ return requireNotNull(+ ArrowsGenerator.generateSeeded(+ cols = cols,+ rows = rows,+ targetPieces = arrowCountForLevel(level),+ mirrorCount = mirrorCountForLevel(level),+ seed = level.toLong(),+ )+ ) { "no board for level $level" }+ }++ /**+ * A board with the first [cleared] arrows of a real solution already flown.+ *+ * Using the solver's order rather than an arbitrary subset means the remaining arrows are in a+ * position that could genuinely arise mid-game.+ */+ private fun game(+ puzzle: ArrowsPuzzle,+ level: Int,+ cleared: Int,+ mode: GameMode = GameMode.CASUAL,+ hearts: Int = STARTING_HEARTS,+ blocked: Boolean = false,+ ): ArrowsGameState {+ val order = ArrowsRules.solve(puzzle).orEmpty()+ val state = ArrowsGameState(+ puzzle = puzzle,+ removed = order.take(cleared).toSet(),+ hearts = hearts,+ level = level,+ mode = mode,+ )+ if (!blocked) return state+ // Flag an arrow that genuinely cannot move, so the red highlight and the dotted route are+ // showing something real rather than a state the rules would never produce.+ val stuck = state.remaining.firstOrNull { ArrowsRules.isBlocked(state, it) } ?: return state+ return state.copy(blockedId = stuck.id)+ }+}
games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsGeneratorTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsGeneratorTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsGeneratorTest.ktnew file mode 100644index 0000000000..e49d9b9331--- /dev/null+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsGeneratorTest.kt@@ -0,0 +1,173 @@+package com.vayunmathur.games.arrows.domain++import com.vayunmathur.games.arrows.data.DAILY_ARROWS+import com.vayunmathur.games.arrows.data.DAILY_BOARD+import com.vayunmathur.games.arrows.data.DAILY_MIRRORS+import com.vayunmathur.games.arrows.data.arrowCountForLevel+import com.vayunmathur.games.arrows.data.boardSizeForLevel+import com.vayunmathur.games.arrows.data.mirrorCountForLevel+import com.vayunmathur.games.arrows.data.MIRROR_FIRST_LEVEL+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class ArrowsGeneratorTest {++ @Test+ fun everyGeneratedBoardCanBeCleared() {+ // The whole promise of reverse construction.+ for (level in 1..40) {+ val puzzle = assertNotNull(generateFor(level), "level $level produced nothing")+ assertNotNull(+ ArrowsRules.solve(puzzle),+ "level $level (${puzzle.cols}x${puzzle.rows}, " ++ "${puzzle.pieces.size} arrows) has no clearing order",+ )+ }+ }++ @Test+ fun arrowsAreConnectedPolylinesThatDoNotOverlap() {+ for (level in listOf(1, 8, 20, 35)) {+ val puzzle = assertNotNull(generateFor(level))+ val seen = mutableSetOf<Int>()+ for (piece in puzzle.pieces) {+ assertTrue(piece.cells.size >= 2, "level $level arrow ${piece.id} is too short")+ assertEquals(+ piece.cells.size,+ piece.cells.distinct().size,+ "level $level arrow ${piece.id} crosses itself",+ )+ for (cell in piece.cells) {+ assertTrue(seen.add(cell), "level $level cell $cell used twice")+ }+ // Consecutive cells must be orthogonally adjacent.+ for (i in 0 until piece.cells.size - 1) {+ val a = piece.cells[i]+ val b = piece.cells[i + 1]+ val rowGap = kotlin.math.abs(a / puzzle.cols - b / puzzle.cols)+ val colGap = kotlin.math.abs(a % puzzle.cols - b % puzzle.cols)+ assertEquals(1, rowGap + colGap, "level $level arrow ${piece.id} is broken")+ }+ }+ }+ }++ @Test+ fun theArrowheadFollowsTheLastSegment() {+ for (level in listOf(3, 12, 25)) {+ val puzzle = assertNotNull(generateFor(level))+ for (piece in puzzle.pieces) {+ val previous = piece.cells[piece.cells.size - 2]+ val expectedRow = piece.head / puzzle.cols - previous / puzzle.cols+ val expectedCol = piece.head % puzzle.cols - previous % puzzle.cols+ assertEquals(expectedRow, piece.direction.dRow, "arrow ${piece.id} row")+ assertEquals(expectedCol, piece.direction.dCol, "arrow ${piece.id} col")+ }+ }+ }++ @Test+ fun arrowsNeverSitOnAMirror() {+ for (level in listOf(12, 20, 40)) {+ val puzzle = assertNotNull(generateFor(level))+ for (piece in puzzle.pieces) {+ for (cell in piece.cells) {+ assertTrue(cell !in puzzle.mirrors, "level $level arrow ${piece.id} on a mirror")+ }+ }+ }+ }++ @Test+ fun mirrorsOnlyAppearFromTheirIntroductoryLevel() {+ for (level in 1 until MIRROR_FIRST_LEVEL) {+ assertEquals(0, mirrorCountForLevel(level), "level $level should have no mirrors")+ assertTrue(assertNotNull(generateFor(level)).mirrors.isEmpty(), "level $level")+ }+ assertTrue(mirrorCountForLevel(MIRROR_FIRST_LEVEL) > 0)+ }++ @Test+ fun mirrorsAreNeverOnTheBorder() {+ // A mirror on an edge mostly deflects arrows straight back out, which reads as decoration.+ for (level in listOf(12, 25, 40)) {+ val puzzle = assertNotNull(generateFor(level))+ for (cell in puzzle.mirrors.keys) {+ val row = cell / puzzle.cols+ val col = cell % puzzle.cols+ assertTrue(row in 1 until puzzle.rows - 1, "level $level mirror row $row")+ assertTrue(col in 1 until puzzle.cols - 1, "level $level mirror col $col")+ }+ }+ }++ @Test+ fun sameSeedGivesTheSameBoard() {+ // Saved progress is keyed by level number, so a level must never rebuild itself differently.+ val first = assertNotNull(generateFor(17))+ val second = assertNotNull(generateFor(17))+ assertEquals(first.pieces, second.pieces)+ assertEquals(first.mirrors, second.mirrors)+ }++ @Test+ fun differentLevelsGiveDifferentBoards() {+ val first = assertNotNull(generateFor(5))+ val second = assertNotNull(generateFor(6))+ assertTrue(first.pieces != second.pieces)+ }++ @Test+ fun boardsHoldAWorthwhileNumberOfArrows() {+ for (level in 1..40) {+ val puzzle = assertNotNull(generateFor(level))+ val target = arrowCountForLevel(level)+ assertTrue(+ puzzle.pieces.size >= (target * 2) / 3,+ "level $level wanted ~$target arrows, got ${puzzle.pieces.size}",+ )+ }+ }++ @Test+ fun theDailyBoardIsGeneratedForAnyDay() {+ val (cols, rows) = DAILY_BOARD+ for (day in 20_300L..20_330L) {+ val puzzle = assertNotNull(+ ArrowsGenerator.generateSeeded(+ cols, rows, DAILY_ARROWS, DAILY_MIRRORS, seed = day,+ ),+ "no daily board for day $day",+ )+ assertNotNull(ArrowsRules.solve(puzzle), "daily $day is unsolvable")+ }+ }++ @Test+ fun generateGivesUpRatherThanLoopingWhenGivenNoAttempts() {+ assertEquals(+ null,+ ArrowsGenerator.generate(5, 5, 4, 0, Random(1), attempts = 0),+ )+ }++ @Test+ fun boardRampNeverShrinks() {+ val areas = (1..60).map { boardSizeForLevel(it).let { (c, r) -> c * r } }+ assertEquals(areas, areas.sorted(), "board area should only ever grow")+ }++ /** Uses the same size, count, mirror and seed rules the game uses for a real level. */+ private fun generateFor(level: Int) = boardSizeForLevel(level).let { (cols, rows) ->+ ArrowsGenerator.generateSeeded(+ cols = cols,+ rows = rows,+ targetPieces = arrowCountForLevel(level),+ mirrorCount = mirrorCountForLevel(level),+ seed = level.toLong(),+ )+ }+}
games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsRulesTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsRulesTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsRulesTest.ktnew file mode 100644index 0000000000..3175f778d2--- /dev/null+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/domain/ArrowsRulesTest.kt@@ -0,0 +1,227 @@+package com.vayunmathur.games.arrows.domain++import com.vayunmathur.games.arrows.data.ArrowPiece+import com.vayunmathur.games.arrows.data.ArrowsGameState+import com.vayunmathur.games.arrows.data.ArrowsPuzzle+import com.vayunmathur.games.arrows.data.Direction+import com.vayunmathur.games.arrows.data.GameMode+import com.vayunmathur.games.arrows.data.Mirror+import com.vayunmathur.games.arrows.data.STARTING_HEARTS+import com.vayunmathur.games.arrows.data.TapOutcome+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class ArrowsRulesTest {++ private val cols = 5+ private val rows = 5++ private fun at(row: Int, col: Int) = row * cols + col++ private fun puzzle(+ pieces: List<ArrowPiece>,+ mirrors: Map<Int, Mirror> = emptyMap(),+ ) = ArrowsPuzzle(cols, rows, pieces, mirrors)++ private fun state(+ puzzle: ArrowsPuzzle,+ removed: Set<Int> = emptySet(),+ hearts: Int = STARTING_HEARTS,+ ) = ArrowsGameState(puzzle, removed, hearts, level = 1, mode = GameMode.CASUAL)++ /** A two-cell arrow whose head is at (row, col) pointing [direction]. */+ private fun arrow(id: Int, row: Int, col: Int, direction: Direction): ArrowPiece {+ val head = at(row, col)+ val tail = at(row - direction.dRow, col - direction.dCol)+ return ArrowPiece(id, listOf(tail, head), direction)+ }++ @Test+ fun exitPathRunsStraightOffTheBoard() {+ val p = puzzle(emptyList())+ // From (2,2) heading right: (2,3), (2,4), then out.+ assertEquals(+ listOf(at(2, 3), at(2, 4)),+ ArrowsRules.exitPath(p, at(2, 2), Direction.RIGHT),+ )+ }++ @Test+ fun exitPathFromTheEdgeIsEmpty() {+ val p = puzzle(emptyList())+ assertEquals(emptyList(), ArrowsRules.exitPath(p, at(2, 4), Direction.RIGHT))+ }++ @Test+ fun aMirrorBendsTheRoute() {+ // A `/` at (2,3) turns a rightward arrow upward, so it leaves through the top.+ val p = puzzle(emptyList(), mapOf(at(2, 3) to Mirror.FORWARD))+ assertEquals(+ listOf(at(2, 3), at(1, 3), at(0, 3)),+ ArrowsRules.exitPath(p, at(2, 2), Direction.RIGHT),+ )+ }++ @Test+ fun backMirrorBendsTheOtherWay() {+ val p = puzzle(emptyList(), mapOf(at(2, 3) to Mirror.BACK))+ assertEquals(+ listOf(at(2, 3), at(3, 3), at(4, 3)),+ ArrowsRules.exitPath(p, at(2, 2), Direction.RIGHT),+ )+ }++ @Test+ fun mirrorsAreTheirOwnInverse() {+ for (mirror in Mirror.entries) {+ for (direction in Direction.entries) {+ assertEquals(+ direction,+ mirror.reflect(mirror.reflect(direction)),+ "${mirror.name} on ${direction.name}",+ )+ }+ }+ }++ @Test+ fun aRingOfMirrorsTrapsTheHeadAndReportsNoExit() {+ // Four mirrors at the corners of a square, oriented to hand the head on clockwise:+ // (1,1) sends UP->RIGHT, (1,3) RIGHT->DOWN, (3,3) DOWN->LEFT, (3,1) LEFT->UP.+ val ring = mapOf(+ at(1, 1) to Mirror.FORWARD,+ at(1, 3) to Mirror.BACK,+ at(3, 3) to Mirror.FORWARD,+ at(3, 1) to Mirror.BACK,+ )+ // Entering the ring along one of its sides, so the head joins the circuit.+ assertNull(ArrowsRules.exitPath(puzzle(emptyList(), ring), at(2, 1), Direction.UP))+ }++ @Test+ fun anUnobstructedArrowClears() {+ val piece = arrow(0, 2, 2, Direction.RIGHT)+ val (next, outcome) = ArrowsRules.tap(state(puzzle(listOf(piece))), 0)+ assertEquals(TapOutcome.CLEARED, outcome)+ assertTrue(next.isWon)+ assertEquals(STARTING_HEARTS, next.hearts, "a clean exit must not cost a heart")+ }++ @Test+ fun anArrowBlockedByAnotherCostsAHeart() {+ val mover = arrow(0, 2, 2, Direction.RIGHT)+ val blocker = arrow(1, 2, 4, Direction.UP)+ val s = state(puzzle(listOf(mover, blocker)))+ val (next, outcome) = ArrowsRules.tap(s, 0)+ assertEquals(TapOutcome.BLOCKED, outcome)+ assertEquals(STARTING_HEARTS - 1, next.hearts)+ assertEquals(0, next.blockedId)+ assertTrue(next.removed.isEmpty(), "a blocked arrow stays on the board")+ }++ @Test+ fun clearingTheBlockerFreesTheArrowBehindIt() {+ val mover = arrow(0, 2, 2, Direction.RIGHT)+ val blocker = arrow(1, 2, 4, Direction.UP)+ val p = puzzle(listOf(mover, blocker))+ assertTrue(ArrowsRules.isBlocked(state(p), mover))+ assertFalse(ArrowsRules.isBlocked(state(p, removed = setOf(1)), mover))+ }++ @Test+ fun anArrowIsNotBlockedByItsOwnBody() {+ // A four-cell arrow heading right, tail trailing behind it: nothing in the way.+ val piece = ArrowPiece(+ id = 0,+ cells = listOf(at(2, 0), at(2, 1), at(2, 2), at(2, 3)),+ direction = Direction.RIGHT,+ )+ assertFalse(ArrowsRules.isBlocked(state(puzzle(listOf(piece))), piece))+ }++ @Test+ fun anArrowTurnedBackIntoItselfIsBlocked() {+ // Head at (2,2) heading right. The mirrors walk it up, back along row 1, then down onto its+ // own tail at (2,1): RIGHT->UP at (2,3), UP->LEFT at (1,3), LEFT->DOWN at (1,1).+ val piece = ArrowPiece(+ id = 0,+ cells = listOf(at(2, 1), at(2, 2)),+ direction = Direction.RIGHT,+ )+ val mirrors = mapOf(+ at(2, 3) to Mirror.FORWARD,+ at(1, 3) to Mirror.BACK,+ at(1, 1) to Mirror.FORWARD,+ )+ val p = puzzle(listOf(piece), mirrors)+ // exitPath is purely geometric - it runs to the edge regardless of what is in the way - so+ // the check is that the route crosses the tail, and that isBlocked acts on it.+ val path = assertNotNull(ArrowsRules.exitPath(p, piece.head, piece.direction))+ assertTrue(at(2, 1) in path, "the route should cross the arrow's own tail: $path")+ assertTrue(ArrowsRules.isBlocked(state(p), piece))+ }++ @Test+ fun tapsOnClearedArrowsAndFinishedBoardsAreIgnored() {+ val piece = arrow(0, 2, 2, Direction.RIGHT)+ val p = puzzle(listOf(piece))+ val (afterWin, _) = ArrowsRules.tap(state(p), 0)+ assertEquals(TapOutcome.IGNORED, ArrowsRules.tap(afterWin, 0).second)++ val failed = state(p, hearts = 0)+ assertEquals(TapOutcome.IGNORED, ArrowsRules.tap(failed, 0).second)+ assertEquals(TapOutcome.IGNORED, ArrowsRules.tap(state(p), 99).second)+ }++ @Test+ fun runningOutOfHeartsFailsTheLevel() {+ val mover = arrow(0, 2, 2, Direction.RIGHT)+ val blocker = arrow(1, 2, 4, Direction.UP)+ var s = state(puzzle(listOf(mover, blocker)), hearts = 1)+ s = ArrowsRules.tap(s, 0).first+ assertTrue(s.isFailed)+ assertFalse(s.isWon)++ val reset = ArrowsRules.resetAfterFailure(s)+ assertEquals(STARTING_HEARTS, reset.hearts)+ assertTrue(reset.removed.isEmpty())+ assertFalse(reset.isFailed)+ }++ @Test+ fun aWonBoardIsNotAlsoAFailure() {+ // Hearts can hit zero on the tap that also finishes the board; winning takes precedence.+ val piece = arrow(0, 2, 2, Direction.RIGHT)+ val s = state(puzzle(listOf(piece)), removed = setOf(0), hearts = 0)+ assertTrue(s.isWon)+ assertFalse(s.isFailed)+ }++ @Test+ fun solveFindsAnOrderForASolvableBoard() {+ val a = arrow(0, 2, 2, Direction.RIGHT)+ val b = arrow(1, 2, 4, Direction.UP)+ val order = assertNotNull(ArrowsRules.solve(puzzle(listOf(a, b))))+ assertEquals(listOf(1, 0), order, "the blocker has to go first")+ }++ @Test+ fun solveReturnsNullWhenTwoArrowsBlockEachOther() {+ // Facing each other across the board, each one's route runs into the other.+ val left = ArrowPiece(0, listOf(at(2, 0), at(2, 1)), Direction.RIGHT)+ val right = ArrowPiece(1, listOf(at(2, 4), at(2, 3)), Direction.LEFT)+ assertNull(ArrowsRules.solve(puzzle(listOf(left, right))))+ }++ @Test+ fun clearableNowListsOnlyTheArrowsThatCanLeave() {+ val mover = arrow(0, 2, 2, Direction.RIGHT)+ val blocker = arrow(1, 2, 4, Direction.UP)+ val free = ArrowsRules.clearableNow(state(puzzle(listOf(mover, blocker))))+ assertEquals(listOf(1), free.map { it.id })+ }+}
games/hub/src/main/AndroidManifest.xml
diff --git a/games/hub/src/main/AndroidManifest.xml b/games/hub/src/main/AndroidManifest.xmlindex 02dca58ff7..aa0a37870c 100644--- a/games/hub/src/main/AndroidManifest.xml+++ b/games/hub/src/main/AndroidManifest.xml@@ -20,6 +20,7 @@ <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.arrows" /> <package android:name="com.vayunmathur.games" /> <intent> <action android:name="android.intent.action.MAIN" />
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 edecd22039..b233aa9538 100644--- a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt+++ b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt@@ -40,6 +40,7 @@ private fun resolveGameMetadata( "sudoku" -> "Sudoku" "minesweeper" -> "Minesweeper" "nonogram" -> "Nonogram"+ "arrows" -> "Arrows" else -> gameId.replaceFirstChar { it.uppercase() } }, description = null,
metadata_data/games-arrows.md
diff --git a/metadata_data/games-arrows.md b/metadata_data/games-arrows.mdnew file mode 100644index 0000000000..b5e8b22428--- /dev/null+++ b/metadata_data/games-arrows.md@@ -0,0 +1,6 @@+A tidy-up puzzle about the order you clear things in++Every arrow flies off the board in the direction it points, but only if nothing is+in its way. Work out which one can go first. One level is open at a time, plus a+fresh daily board, and later levels add redirectors that bend an arrow's path.+Every board is built so that it can be cleared.
metadata_data/photos/games-arrows/1.png
diff --git a/metadata_data/photos/games-arrows/1.png b/metadata_data/photos/games-arrows/1.pngnew file mode 100644index 0000000000..b5b94197c9Binary files /dev/null and b/metadata_data/photos/games-arrows/1.png differ
metadata_data/photos/games-arrows/2.png
diff --git a/metadata_data/photos/games-arrows/2.png b/metadata_data/photos/games-arrows/2.pngnew file mode 100644index 0000000000..2e2aec4692Binary files /dev/null and b/metadata_data/photos/games-arrows/2.png differ
metadata_data/photos/games-arrows/3.png
diff --git a/metadata_data/photos/games-arrows/3.png b/metadata_data/photos/games-arrows/3.pngnew file mode 100644index 0000000000..5b95fdfef1Binary files /dev/null and b/metadata_data/photos/games-arrows/3.png differ
metadata_data/photos/games-arrows/4.png
diff --git a/metadata_data/photos/games-arrows/4.png b/metadata_data/photos/games-arrows/4.pngnew file mode 100644index 0000000000..52d2339560Binary files /dev/null and b/metadata_data/photos/games-arrows/4.png differ
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 53f0ab86c9..ee11a476c0 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -81,6 +81,7 @@ include(":games:voxels") include(":games:sudoku") include(":games:minesweeper") include(":games:nonogram")+include(":games:arrows") include(":games:hub") include(":email") include(":weather")