Modern Apps git

← Modern-Apps.git

games/pipes + astronomy: first ktlint/rustfmt-formatted modules (pilot)

Commit
1e2c8d2295315e70e3cccf7a3c867f10796de531
Author
Vayun Mathur <[email protected]>
When
2026-12-01 01:51 UTC (5 days ago)
Parents
c21c592
games/pipes is the Kotlin pilot for the new formatter: all
56 files passed through ktlintFormat (+3,180/-1,539,
formatter output only), reaching ktlintCheck green and
idempotent on re-run. Three manual residue fixes came with
it, none behavioural: a var PACKS renamed to packs
(property-naming, 20 references), a doubled KDoc merged, and
a no-op comment-only if reduced to a comment. The format did
surface one real interaction: vertical expansion pushed
PipesViewModelTest.drawExtendCommitUndoAndRestart from 44 to
74 lines, over detekt's 60-line LongMethod threshold, so the
test is split into drawExtendCommitAndRecommitKeepsSingleMove
and undoAndRestartClearCommittedPath with identical
assertions.

astronomy's Rust crate is the rustfmt pilot (5 hunks across
lib.rs/projection.rs, tests green, ./check astronomy now
reports rustfmt clean under the blocking mode). Verified:
:games:pipes:testDevUnitTest 135 tests, :lint 0 errors,
ktlintCheck/detekt green, ./format and ./format --check rc 0.

Diff

astronomy/src/main/rust/src/lib.rs
diff --git a/astronomy/src/main/rust/src/lib.rs b/astronomy/src/main/rust/src/lib.rsindex 2764ae0a1e..353bf374ae 100644--- a/astronomy/src/main/rust/src/lib.rs+++ b/astronomy/src/main/rust/src/lib.rs@@ -50,13 +50,7 @@ mod tests {         // A few (ra, dec) pairs, one lst/lat.         let lst = 1.234;         let lat = 0.71; // ~40.7 deg N-        let cases = [-            (0.0, 0.0),-            (1.0, 0.5),-            (3.5, -0.3),-            (5.9, 1.2),-            (2.0, -1.0),-        ];+        let cases = [(0.0, 0.0), (1.0, 0.5), (3.5, -0.3), (5.9, 1.2), (2.0, -1.0)];         let radec: Vec<f64> = cases.iter().flat_map(|&(ra, dec)| [ra, dec]).collect();         let out = batch_radec_to_altaz(&radec, lst, lat);         assert_eq!(out.len(), cases.len() * 2);@@ -103,7 +97,11 @@ mod tests {         assert!((up[1] as f64) < h / 2.0, "higher object should be above center, got y={}", up[1]);         // Higher azimuth (toward east) -> right of center (larger x).         let east = batch_project(&[ten, 0.0], 0.0, 0.0, 60.0, w, h, 0.0);-        assert!((east[0] as f64) > w / 2.0, "east object should be right of center, got x={}", east[0]);+        assert!(+            (east[0] as f64) > w / 2.0,+            "east object should be right of center, got x={}",+            east[0]+        );         assert!((east[1] as f64 - h / 2.0).abs() < 1e-3, "east: y should stay centered");     } @@ -185,7 +183,9 @@ mod jni_bindings {     /// `[x0,y0,...]` pixels (NaN,NaN for culled points), or null on error.     #[no_mangle]     #[allow(clippy::too_many_arguments)]-    pub extern "system" fn Java_com_vayunmathur_astronomy_domain_AstronomyNative_batchProject<'l>(+    pub extern "system" fn Java_com_vayunmathur_astronomy_domain_AstronomyNative_batchProject<+        'l,+    >(         mut env: EnvUnowned<'l>,         _class: JClass<'l>,         altaz: JDoubleArray<'l>,
astronomy/src/main/rust/src/projection.rs
diff --git a/astronomy/src/main/rust/src/projection.rs b/astronomy/src/main/rust/src/projection.rsindex 2771c90553..dad52b7a35 100644--- a/astronomy/src/main/rust/src/projection.rs+++ b/astronomy/src/main/rust/src/projection.rs@@ -100,10 +100,7 @@ impl Projector {         let sin_r = self.rotation_rad.sin();         let xr = x * cos_r - y * sin_r;         let yr = x * sin_r + y * cos_r;-        (-            (self.screen_w / 2.0 + xr) as f32,-            (self.screen_h / 2.0 + yr) as f32,-        )+        ((self.screen_w / 2.0 + xr) as f32, (self.screen_h / 2.0 + yr) as f32)     }      /// Mirrors `StereographicProjection.project`: returns `None` when culled.@@ -128,14 +125,8 @@ pub fn batch_project(     screen_h: f64,     rotation_rad: f64, ) -> Vec<f32> {-    let p = Projector::new(-        center_az_rad,-        center_alt_rad,-        fov_deg,-        screen_w,-        screen_h,-        rotation_rad,-    );+    let p =+        Projector::new(center_az_rad, center_alt_rad, fov_deg, screen_w, screen_h, rotation_rad);     let n = altaz.len() / 2;     let mut out = Vec::with_capacity(n * 2);     for i in 0..n {
games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/FullE2eTest.kt
diff --git a/games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/FullE2eTest.kt b/games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/FullE2eTest.ktindex 2a661dc893..73df217af5 100644--- a/games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/FullE2eTest.kt+++ b/games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/FullE2eTest.kt@@ -8,12 +8,12 @@ import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until-import java.io.IOException import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith+import java.io.IOException  /**  * Full e2e test: launches the app, grants every requested permission, and@@ -29,7 +29,6 @@ import org.junit.runner.RunWith  */ @RunWith(AndroidJUnit4::class) class FullE2eTest {-     @Test     fun launch_grantsPermissions_showsPackList() {         val instrumentation = InstrumentationRegistry.getInstrumentation()@@ -64,11 +63,12 @@ class FullE2eTest {         packageManager: PackageManager,         packageName: String,     ) {-        val info = try {-            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)-        } catch (e: PackageManager.NameNotFoundException) {-            throw AssertionError("package $packageName not installed", e)-        }+        val info =+            try {+                packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+            } catch (e: PackageManager.NameNotFoundException) {+                throw AssertionError("package $packageName not installed", e)+            }         for (permission in info.requestedPermissions.orEmpty()) {             try {                 uiAutomation.executeShellCommand("pm grant $packageName $permission").close()@@ -101,9 +101,10 @@ class FullE2eTest {          * have no pm-grantable permission, but the shell can flip their appops.          * Ignored where the appop does not exist; the gate assertion reports it.          */-        private val SPECIAL_ACCESS_COMMANDS = arrayOf(-            "appops set %s SCHEDULE_EXACT_ALARM allow",-            "appops set %s USE_FULL_SCREEN_INTENT allow",-        )+        private val SPECIAL_ACCESS_COMMANDS =+            arrayOf(+                "appops set %s SCHEDULE_EXACT_ALARM allow",+                "appops set %s USE_FULL_SCREEN_INTENT allow",+            )     } }
games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/GamePlayTest.kt
diff --git a/games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/GamePlayTest.kt b/games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/GamePlayTest.ktindex 346c7095e6..3f746971bb 100644--- a/games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/GamePlayTest.kt+++ b/games/pipes/src/androidTest/java/com/vayunmathur/games/pipes/ui/GamePlayTest.kt@@ -8,12 +8,12 @@ import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until-import java.io.IOException import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith+import java.io.IOException  /**  * Journey test: launches pipes, opens the first pack and level, taps Undo,@@ -30,7 +30,6 @@ import org.junit.runner.RunWith  */ @RunWith(AndroidJUnit4::class) class GamePlayTest {-     @Test     fun play_openFirstLevel_tapUndo_boardStays() {         val instrumentation = InstrumentationRegistry.getInstrumentation()@@ -87,11 +86,12 @@ class GamePlayTest {         packageManager: PackageManager,         packageName: String,     ) {-        val info = try {-            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)-        } catch (e: PackageManager.NameNotFoundException) {-            throw AssertionError("package $packageName not installed", e)-        }+        val info =+            try {+                packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+            } catch (e: PackageManager.NameNotFoundException) {+                throw AssertionError("package $packageName not installed", e)+            }         for (permission in info.requestedPermissions.orEmpty()) {             try {                 uiAutomation.executeShellCommand("pm grant $packageName $permission").close()@@ -129,9 +129,10 @@ class GamePlayTest {          * have no pm-grantable permission, but the shell can flip their appops.          * Ignored where the appop does not exist; the gate assertion reports it.          */-        private val SPECIAL_ACCESS_COMMANDS = arrayOf(-            "appops set %s SCHEDULE_EXACT_ALARM allow",-            "appops set %s USE_FULL_SCREEN_INTENT allow",-        )+        private val SPECIAL_ACCESS_COMMANDS =+            arrayOf(+                "appops set %s SCHEDULE_EXACT_ALARM allow",+                "appops set %s USE_FULL_SCREEN_INTENT allow",+            )     } }
games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.ktindex 0bdf286166..118b5fac3c 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.kt@@ -14,8 +14,8 @@ import com.vayunmathur.games.pipes.ui.PackScreen import com.vayunmathur.games.pipes.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.FullscreenPage+import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.OpenSettingsIfRequested import com.vayunmathur.library.util.rememberNavBackStack
games/pipes/src/main/java/com/vayunmathur/games/pipes/Route.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/Route.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/Route.ktindex 04fc285a3d..85ed174172 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/Route.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/Route.kt@@ -9,21 +9,34 @@ sealed interface Route : NavKey {     /** Singleton holding pack selector state and operations. */     @Serializable     data object PackSelector : Route+     /** Immutable value describing level selector; carries packIndex. */     @Serializable-    data class LevelSelector(val packIndex: Int) : Route+    data class LevelSelector(+        val packIndex: Int,+    ) : Route+     /** Immutable value describing game; carries packIndex, levelIndex. */     @Serializable-    data class Game(val packIndex: Int, val levelIndex: Int) : Route+    data class Game(+        val packIndex: Int,+        val levelIndex: Int,+    ) : Route+     /** Singleton holding daily selector state and operations. */     @Serializable     data object DailySelector : Route+     /** Immutable value describing daily game; carries levelIndex. */     @Serializable-    data class DailyGame(val levelIndex: Int) : Route+    data class DailyGame(+        val levelIndex: Int,+    ) : Route+     /** Singleton holding game center state and operations. */     @Serializable     data object GameCenter : Route+     /** Singleton holding settings state and operations. */     @Serializable     data object Settings : Route
games/pipes/src/main/java/com/vayunmathur/games/pipes/data/CompletedLevelsRepository.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/CompletedLevelsRepository.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/CompletedLevelsRepository.ktindex 33897c0619..776aafeec0 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/CompletedLevelsRepository.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/CompletedLevelsRepository.kt@@ -4,7 +4,10 @@ import android.content.Context import com.vayunmathur.library.util.LevelStatsRepository  /** Completed Levels Repository: a context implementation for completed levels repository. */-class CompletedLevelsRepository(context: Context) : LevelStatsRepository(context) {+class CompletedLevelsRepository(+    context: Context,+) : LevelStatsRepository(context) {     fun incrementTotalPipesPlaced() = incrementCounter("total_pipes")+     fun getTotalPipesPlaced(): Int = getCounter("total_pipes") }
games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.ktindex d289103f2f..249a9595ff 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/PipeModels.kt@@ -2,21 +2,30 @@ package com.vayunmathur.games.pipes.data  import android.content.Context import kotlinx.serialization.json.Json+import kotlinx.serialization.json.float import kotlinx.serialization.json.int import kotlinx.serialization.json.intOrNull-import kotlinx.serialization.json.float import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive  /** Immutable value describing cell pos; carries row, col. */-data class CellPos(val row: Int, val col: Int)+data class CellPos(+    val row: Int,+    val col: Int,+)  /** Immutable value describing render pos; carries x, y. */-data class RenderPos(val x: Float, val y: Float)+data class RenderPos(+    val x: Float,+    val y: Float,+)  /** Immutable value describing endpoint pair; carries colorIndex, cells. */-data class EndpointPair(val colorIndex: Int, val cells: List<CellPos>)+data class EndpointPair(+    val colorIndex: Int,+    val cells: List<CellPos>,+)  /** Immutable value describing level data. */ data class LevelData(@@ -30,57 +39,66 @@ data class LevelData(     val bridges: Set<CellPos>,     val optimalMoves: Int,     val portals: Map<CellPos, CellPos> = emptyMap(),-    val grid: String = "square"+    val grid: String = "square", )  /** Immutable value describing level pack. */ data class LevelPack(     val name: String,     val shape: String,-    val levels: List<LevelData>+    val levels: List<LevelData>, ) {     /** Shared constants and helpers for LevelPack. */     companion object {-        private val PACK_FILES = listOf(-            "packs/5x5.json",-            "packs/6x6.json",-            "packs/7x7.json",-            "packs/8x8.json",-            "packs/9x9.json",-            "packs/10x10.json",-            "packs/11x11.json",-            "packs/12x12.json",-            "packs/13x13.json",-            "packs/14x14.json",-            "packs/tower.json",-            "packs/hourglass.json",-            "packs/blob.json",-            "packs/inkblot.json",-            "packs/walls.json",-            "packs/blockers.json",-            "packs/bridges.json",-            "packs/hexes.json",-            "packs/portals.json",-            "packs/triplets.json",-            "packs/wrap.json"-        )--        var PACKS: List<LevelPack> = listOf()+        private val PACK_FILES =+            listOf(+                "packs/5x5.json",+                "packs/6x6.json",+                "packs/7x7.json",+                "packs/8x8.json",+                "packs/9x9.json",+                "packs/10x10.json",+                "packs/11x11.json",+                "packs/12x12.json",+                "packs/13x13.json",+                "packs/14x14.json",+                "packs/tower.json",+                "packs/hourglass.json",+                "packs/blob.json",+                "packs/inkblot.json",+                "packs/walls.json",+                "packs/blockers.json",+                "packs/bridges.json",+                "packs/hexes.json",+                "packs/portals.json",+                "packs/triplets.json",+                "packs/wrap.json",+            )++        var packs: List<LevelPack> = listOf()             private set          fun init(context: Context) {-            PACKS = PACK_FILES.map { filename ->-                packFromJson(context.assets.open(filename).bufferedReader().readText())-            }+            packs =+                PACK_FILES.map { filename ->+                    packFromJson(+                        context.assets+                            .open(filename)+                            .bufferedReader()+                            .readText(),+                    )+                }         }     } } -private fun rectangularCells(rows: Int, cols: Int): Set<CellPos> {-    return buildSet {+private fun rectangularCells(+    rows: Int,+    cols: Int,+): Set<CellPos> =+    buildSet {         for (r in 0 until rows) for (c in 0 until cols) add(CellPos(r, c))     }-}  internal fun computeAdjacency(cells: Set<CellPos>): Map<CellPos, List<CellPos>> {     val dirs = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1)@@ -96,32 +114,31 @@ internal fun computeAdjacency(cells: Set<CellPos>): Map<CellPos, List<CellPos>>  * Six-neighbour adjacency for odd-r offset hex grids (same [CellPos] coords as squares).  * Even rows use W/E + NW/NE/SW/SE shifted left, odd rows shifted right. Filters to [cells].  */-internal fun computeHexAdjacency(cells: Set<CellPos>): Map<CellPos, List<CellPos>> {-    return cells.associateWith { cell ->+internal fun computeHexAdjacency(cells: Set<CellPos>): Map<CellPos, List<CellPos>> =+    cells.associateWith { cell ->         val even = cell.row % 2 == 0-        val dirs = if (even) {-            listOf(-1 to -1, -1 to 0, 0 to -1, 0 to 1, 1 to -1, 1 to 0)-        } else {-            listOf(-1 to 0, -1 to 1, 0 to -1, 0 to 1, 1 to 0, 1 to 1)-        }+        val dirs =+            if (even) {+                listOf(-1 to -1, -1 to 0, 0 to -1, 0 to 1, 1 to -1, 1 to 0)+            } else {+                listOf(-1 to 0, -1 to 1, 0 to -1, 0 to 1, 1 to 0, 1 to 1)+            }         dirs.mapNotNull { (dr, dc) ->             val neighbor = CellPos(cell.row + dr, cell.col + dc)             if (neighbor in cells) neighbor else null         }     }-}  /**  * Staggered pixel centers for odd-r hex grids: x = col + 0.5 * (row parity), y = row * 0.866.  * Consumed via [LevelData.renderPositions]; keeps logic in [CellPos] while drawing honeycomb.  */-internal fun hexRenderPositions(cells: Set<CellPos>): Map<CellPos, RenderPos> {-    return cells.associateWith { cell ->+internal fun hexRenderPositions(cells: Set<CellPos>): Map<CellPos, RenderPos> =+    cells.associateWith { cell ->         val x = cell.col + 0.5f * (cell.row and 1)         val y = cell.row * 0.8660254f         RenderPos(x, y)     }-}  /** True when a level needs the custom-topology path (solver exemption, hex art, portal rings). */ fun LevelData.isCustomTopology(): Boolean {@@ -162,13 +179,26 @@ private fun levelFromJson(json: kotlinx.serialization.json.JsonObject): LevelDat     val fullAdjacency = mergedAdjacency(adjacency, cells, portals, extraEdges)     val renderPositions = renderPositionsFromJson(json, cells, grid)     val endpoints = endpointsFromJson(json)-    val bridges = json["bridges"]?.jsonArray?.map {-        val arr = it.jsonArray-        CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)-    }?.toSet() ?: emptySet()+    val bridges =+        json["bridges"]+            ?.jsonArray+            ?.map {+                val arr = it.jsonArray+                CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)+            }?.toSet() ?: emptySet()     val optimalMoves = json["optimalMoves"]!!.jsonPrimitive.int     return LevelData(-        id, rows, cols, cells, fullAdjacency, renderPositions, endpoints, bridges, optimalMoves, portals, grid,+        id,+        rows,+        cols,+        cells,+        fullAdjacency,+        renderPositions,+        endpoints,+        bridges,+        optimalMoves,+        portals,+        grid,     ) } @@ -177,37 +207,46 @@ private fun cellsFromJson(     json: kotlinx.serialization.json.JsonObject,     rows: Int,     cols: Int,-): Set<CellPos> = json["cells"]?.jsonArray?.map {-    val arr = it.jsonArray-    CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)-}?.toSet() ?: rectangularCells(rows, cols)+): Set<CellPos> =+    json["cells"]+        ?.jsonArray+        ?.map {+            val arr = it.jsonArray+            CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)+        }?.toSet() ?: rectangularCells(rows, cols)  /** Declared adjacency, or the grid-derived adjacency when omitted. */ private fun adjacencyFromJson(     json: kotlinx.serialization.json.JsonObject,     cells: Set<CellPos>,     grid: String,-): Map<CellPos, List<CellPos>> = json["adjacency"]?.jsonObject?.map { (key, value) ->-    val parts = key.split(",")-    val cell = CellPos(parts[0].toInt(), parts[1].toInt())-    val neighbors = value.jsonArray.map {-        val arr = it.jsonArray-        CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)-    }-    cell to neighbors-}?.toMap() ?: if (grid == "hex") computeHexAdjacency(cells) else computeAdjacency(cells)+): Map<CellPos, List<CellPos>> =+    json["adjacency"]+        ?.jsonObject+        ?.map { (key, value) ->+            val parts = key.split(",")+            val cell = CellPos(parts[0].toInt(), parts[1].toInt())+            val neighbors =+                value.jsonArray.map {+                    val arr = it.jsonArray+                    CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)+                }+            cell to neighbors+        }?.toMap() ?: if (grid == "hex") computeHexAdjacency(cells) else computeAdjacency(cells)  /** Bidirectional cell pairs declared under [key] ("portals" / "extraEdges"). */ private fun pairsFromJson(     json: kotlinx.serialization.json.JsonObject,     key: String,-): List<Pair<CellPos, CellPos>> = json[key]?.jsonArray?.flatMap { pair ->-    val ends = pair.jsonArray.map { c ->-        val arr = c.jsonArray-        CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)-    }-    if (ends.size == 2) listOf(ends[0] to ends[1], ends[1] to ends[0]) else emptyList()-} ?: emptyList()+): List<Pair<CellPos, CellPos>> =+    json[key]?.jsonArray?.flatMap { pair ->+        val ends =+            pair.jsonArray.map { c ->+                val arr = c.jsonArray+                CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)+            }+        if (ends.size == 2) listOf(ends[0] to ends[1], ends[1] to ends[0]) else emptyList()+    } ?: emptyList()  /** Base adjacency unioned with portals and extra edges. */ private fun mergedAdjacency(@@ -233,22 +272,26 @@ private fun renderPositionsFromJson(     json: kotlinx.serialization.json.JsonObject,     cells: Set<CellPos>,     grid: String,-): Map<CellPos, RenderPos>? = json["renderPositions"]?.jsonObject?.map { (key, value) ->-    val parts = key.split(",")-    val cell = CellPos(parts[0].toInt(), parts[1].toInt())-    val posObj = value.jsonObject-    val pos = RenderPos(posObj["x"]!!.jsonPrimitive.float, posObj["y"]!!.jsonPrimitive.float)-    cell to pos-}?.toMap() ?: if (grid == "hex") hexRenderPositions(cells) else null+): Map<CellPos, RenderPos>? =+    json["renderPositions"]+        ?.jsonObject+        ?.map { (key, value) ->+            val parts = key.split(",")+            val cell = CellPos(parts[0].toInt(), parts[1].toInt())+            val posObj = value.jsonObject+            val pos = RenderPos(posObj["x"]!!.jsonPrimitive.float, posObj["y"]!!.jsonPrimitive.float)+            cell to pos+        }?.toMap() ?: if (grid == "hex") hexRenderPositions(cells) else null  /** Endpoint pairs, colour defaulting to declaration order. */ private fun endpointsFromJson(json: kotlinx.serialization.json.JsonObject): List<EndpointPair> =     json["endpoints"]!!.jsonArray.mapIndexed { index, endpoint ->         val epObj = endpoint.jsonObject         val colorIndex = epObj["color"]?.jsonPrimitive?.intOrNull ?: index-        val epCells = epObj["cells"]!!.jsonArray.map { c ->-            val arr = c.jsonArray-            CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)-        }+        val epCells =+            epObj["cells"]!!.jsonArray.map { c ->+                val arr = c.jsonArray+                CellPos(arr[0].jsonPrimitive.int, arr[1].jsonPrimitive.int)+            }         EndpointPair(colorIndex, epCells)     }
games/pipes/src/main/java/com/vayunmathur/games/pipes/data/ProgressRepository.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/ProgressRepository.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/ProgressRepository.ktindex 70a32a3e38..a892336d35 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/ProgressRepository.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/data/ProgressRepository.kt@@ -14,12 +14,17 @@ import kotlinx.serialization.json.jsonPrimitive  * level_stats, whose size feeds the achievements) and capped to the [MAX_LEVELS] most  * recently saved levels; a won or restarted level drops its entry.  */-class ProgressRepository(context: Context) {+class ProgressRepository(+    context: Context,+) {     private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)      fun load(levelId: String): String? = prefs.getString(key(levelId), null) -    fun save(levelId: String, encoded: String) {+    fun save(+        levelId: String,+        encoded: String,+    ) {         val order = (recent() - levelId) + levelId         prefs.edit {             putString(key(levelId), encoded)@@ -36,9 +41,10 @@ class ProgressRepository(context: Context) {         }     } -    private fun recent(): List<String> = runCatching {-        Json.parseToJsonElement(prefs.getString(ORDER_KEY, null) ?: "[]").jsonArray.map { it.jsonPrimitive.content }-    }.getOrDefault(emptyList())+    private fun recent(): List<String> =+        runCatching {+            Json.parseToJsonElement(prefs.getString(ORDER_KEY, null) ?: "[]").jsonArray.map { it.jsonPrimitive.content }+        }.getOrDefault(emptyList())      private fun encodeOrder(ids: List<String>) = JsonArray(ids.map { JsonPrimitive(it) }).toString() 
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.ktindex b6fec9b2f2..a1a700dbb1 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/BoardState.kt@@ -16,14 +16,18 @@ data class BoardState(  /** Pure edits on a [BoardState]. */ object BoardEdits {-     /**      * [base] with [color]'s line replaced by [stroke] (or removed, when the stroke is shorter      * than two cells). Any other colour's line that the stroke crosses outside a bridge is      * cut just before the crossing, keeping the part attached to the dot it was drawn from;      * a remnant shorter than two cells is dropped.      */-    fun applyStroke(level: LevelData, base: BoardState, color: Int, stroke: List<CellPos>): BoardState {+    fun applyStroke(+        level: LevelData,+        base: BoardState,+        color: Int,+        stroke: List<CellPos>,+    ): BoardState {         val strokeCells = stroke.toSet()         val paths = mutableMapOf<Int, List<CellPos>>()         for ((c, path) in base.paths) {@@ -56,11 +60,12 @@ object BoardEdits {         }         for ((cell, colors) in crossers) {             val previous = prior[cell]-            out[cell] = if (previous != null && previous in colors) {-                previous-            } else {-                colors.firstOrNull { it != newest } ?: colors.first()-            }+            out[cell] =+                if (previous != null && previous in colors) {+                    previous+                } else {+                    colors.firstOrNull { it != newest } ?: colors.first()+                }         }         return out     }@@ -69,17 +74,24 @@ object BoardEdits { /** Pure questions about how far a [BoardState] is from solved. */ object BoardStatus {     /** Every colour's line joins its dots (all of them, for triplets). */-    fun everyPairConnected(level: LevelData, state: BoardState): Boolean =+    fun everyPairConnected(+        level: LevelData,+        state: BoardState,+    ): Boolean =         level.endpoints.all { StrokeRules.isComplete(level, it.colorIndex, state.paths[it.colorIndex].orEmpty()) }      /** Solved: every pair connected and every cell covered. */-    fun isSolved(level: LevelData, state: BoardState): Boolean =-        state.cellOwner.size == level.cells.size && everyPairConnected(level, state)+    fun isSolved(+        level: LevelData,+        state: BoardState,+    ): Boolean = state.cellOwner.size == level.cells.size && everyPairConnected(level, state)      /**      * Every pair is connected but some cells are still empty: the one state where the      * board looks finished yet does not count, so the player needs telling.      */-    fun needsFill(level: LevelData, state: BoardState): Boolean =-        state.cellOwner.size < level.cells.size && everyPairConnected(level, state)+    fun needsFill(+        level: LevelData,+        state: BoardState,+    ): Boolean = state.cellOwner.size < level.cells.size && everyPairConnected(level, state) }
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.ktindex d85364f8b1..4f55991806 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/DailyLevels.kt@@ -17,10 +17,12 @@ import kotlin.random.Random  * `ShippedPacksTest` holds them to it.  */ object DailyLevels {-     const val LEVELS_PER_DAY = 5 -    fun levelId(day: Long, index: Int) = "daily_${day}_$index"+    fun levelId(+        day: Long,+        index: Int,+    ) = "daily_${day}_$index"      /**      * Null only when the shipped packs have not been loaded yet, or hold too few levels to fill a@@ -31,18 +33,22 @@ object DailyLevels {      * every daily must force a full board (issue #552), which only the solver can certify.      * Classic boards with holes (blockers) validate fine and stay eligible.      */-    fun packFor(day: Long, pool: List<LevelData> = defaultPool()): LevelPack? {+    fun packFor(+        day: Long,+        pool: List<LevelData> = defaultPool(),+    ): LevelPack? {         val classic = pool.filter { !it.isCustomTopology() }         if (classic.size < LEVELS_PER_DAY) return null-        val chosen = classic-            .shuffled(Random(SEED_OFFSET + day))-            .take(LEVELS_PER_DAY)-            .sortedBy { it.cells.size }-            .mapIndexed { index, level -> level.copy(id = levelId(day, index)) }+        val chosen =+            classic+                .shuffled(Random(SEED_OFFSET + day))+                .take(LEVELS_PER_DAY)+                .sortedBy { it.cells.size }+                .mapIndexed { index, level -> level.copy(id = levelId(day, index)) }         return LevelPack(name = "daily_$day", shape = "square", levels = chosen)     } -    private fun defaultPool(): List<LevelData> = LevelPack.PACKS.flatMap { it.levels }+    private fun defaultPool(): List<LevelData> = LevelPack.packs.flatMap { it.levels }      private const val SEED_OFFSET = 500_000_000L }
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.ktindex 8030c366d2..995e695632 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/LevelGenerator.kt@@ -4,9 +4,9 @@ import com.vayunmathur.games.pipes.data.CellPos import com.vayunmathur.games.pipes.data.EndpointPair import com.vayunmathur.games.pipes.data.LevelData import com.vayunmathur.games.pipes.data.computeAdjacency+import java.util.Locale import kotlin.math.roundToInt import kotlin.random.Random-import java.util.Locale  /**  * Builds levels by carving a board into pipe paths and keeping only their endpoints.@@ -19,12 +19,13 @@ import java.util.Locale  * meet-in-the-middle construction has a far better hit rate.  */ object LevelGenerator {--    fun rectangularCells(rows: Int, cols: Int): Set<CellPos> {-        return buildSet {+    fun rectangularCells(+        rows: Int,+        cols: Int,+    ): Set<CellPos> =+        buildSet {             for (r in 0 until rows) for (c in 0 until cols) add(CellPos(r, c))         }-    }      /**      * Carves [cells] into pipe paths seeded by [seed], returning null if no attempt produced a@@ -43,7 +44,7 @@ object LevelGenerator {         bridges: Set<CellPos> = emptySet(),         renderPositions: Map<CellPos, com.vayunmathur.games.pipes.data.RenderPos>? = null,         portals: Map<CellPos, CellPos> = emptyMap(),-        grid: String = "square"+        grid: String = "square",     ): LevelData? {         val rows = cells.maxOf { it.row } + 1         val cols = cells.maxOf { it.col } + 1@@ -51,9 +52,10 @@ object LevelGenerator {         for (attempt in 0 until 50) {             val carved = carveCover(cells, adjacency, Random(seed + attempt), earlyStopProb) ?: continue             val paths = splitUntilUniquelySolvable(carved, cells, maxFlows, adjacency) ?: continue-            val endpoints = paths.mapIndexed { index, path ->-                EndpointPair(index, listOf(path.first(), path.last()))-            }+            val endpoints =+                paths.mapIndexed { index, path ->+                    EndpointPair(index, listOf(path.first(), path.last()))+                }             return LevelData(                 id = id,                 rows = rows,@@ -65,7 +67,7 @@ object LevelGenerator {                 bridges = bridges,                 optimalMoves = endpoints.size,                 portals = portals,-                grid = grid+                grid = grid,             )         }         return null@@ -90,16 +92,18 @@ object LevelGenerator {         // Custom topologies (hex degree-6, wrap long-range edges, bridges, portals) are out of         // scope for NumberlinkSolver, which assumes the 4-neighbour grid. Only gate square boards         // on uniqueness; variant packs are hand-authored and exempt.-        val isSquare = adjacency.all { (cell, neighbors) ->-            neighbors.toSet() == computeAdjacency(cells)[cell]?.toSet()-        }+        val isSquare =+            adjacency.all { (cell, neighbors) ->+                neighbors.toSet() == computeAdjacency(cells)[cell]?.toSet()+            }         var paths = carved         while (paths.size <= maxFlows) {             if (!shortPairViolation(paths)) {                 if (!isSquare) return paths-                val endpoints = paths.mapIndexed { index, path ->-                    EndpointPair(index, listOf(path.first(), path.last()))-                }+                val endpoints =+                    paths.mapIndexed { index, path ->+                        EndpointPair(index, listOf(path.first(), path.last()))+                    }                 val verdict = NumberlinkSolver.classify(cells, endpoints)                 if (verdict == NumberlinkSolver.Verdict.UNIQUE) return paths                 // NONE is impossible (the carve is a solution) and UNDECIDED means the search gave@@ -115,10 +119,11 @@ object LevelGenerator {      * [shortPairViolation] floor.      */     private fun splitLongestFlow(paths: List<List<CellPos>>): List<List<CellPos>>? {-        val index = paths.indices-            .filter { paths[it].size >= 2 * MIN_SPLIT_LENGTH }-            .maxByOrNull { paths[it].size }-            ?: return null+        val index =+            paths.indices+                .filter { paths[it].size >= 2 * MIN_SPLIT_LENGTH }+                .maxByOrNull { paths[it].size }+                ?: return null         val path = paths[index]         val half = path.size / 2         return paths.subList(0, index) +@@ -139,7 +144,7 @@ object LevelGenerator {         cells: Set<CellPos>,         adjacency: Map<CellPos, List<CellPos>>,         random: Random,-        earlyStopProb: Float+        earlyStopProb: Float,     ): List<List<CellPos>>? {         var unmarked = cells.toSet()         val paths = mutableListOf<List<CellPos>>()@@ -155,12 +160,14 @@ object LevelGenerator {                 remaining.remove(start)                  while (remaining.isNotEmpty()) {-                    val neighbors = (adjacency[path.last()] ?: emptyList())-                        .filter { it in remaining }-                        .shuffled(random)-                    val next = neighbors.firstOrNull { candidate ->-                        isStillConnected(remaining - candidate, adjacency)-                    } ?: break+                    val neighbors =+                        (adjacency[path.last()] ?: emptyList())+                            .filter { it in remaining }+                            .shuffled(random)+                    val next =+                        neighbors.firstOrNull { candidate ->+                            isStillConnected(remaining - candidate, adjacency)+                        } ?: break                     path.add(next)                     remaining.remove(next)                     if (path.size >= 3 && random.nextFloat() < earlyStopProb) break@@ -181,7 +188,7 @@ object LevelGenerator {     private fun pickStart(         unmarked: Set<CellPos>,         adjacency: Map<CellPos, List<CellPos>>,-        random: Random+        random: Random,     ): CellPos {         val candidates = unmarked.sortedWith(compareBy({ it.row }, { it.col })).shuffled(random)         return candidates.firstOrNull { isStillConnected(unmarked - it, adjacency) }@@ -200,7 +207,10 @@ object LevelGenerator {         return false     } -    private fun isStillConnected(cells: Set<CellPos>, adjacency: Map<CellPos, List<CellPos>>): Boolean {+    private fun isStillConnected(+        cells: Set<CellPos>,+        adjacency: Map<CellPos, List<CellPos>>,+    ): Boolean {         if (cells.size <= 1) return true         val start = cells.first()         val visited = mutableSetOf(start)@@ -234,10 +244,11 @@ object LevelGenerator {         bridges: Set<CellPos> = emptySet(),         renderPositions: Map<CellPos, com.vayunmathur.games.pipes.data.RenderPos>? = null,         portals: Map<CellPos, CellPos> = emptyMap(),-        grid: String = "square"-    ): List<LevelData> = (0 until levelCount).mapNotNull { i ->-        val currentSeed = seed + i * 100-        val id = "${name.replace("×", "x").replace(" ", "_")}_${String.format(Locale.ROOT, "%03d", i + 1)}"-        generateLevel(cells, adjacency, maxFlows, currentSeed, id, 0.25f, bridges, renderPositions, portals, grid)-    }+        grid: String = "square",+    ): List<LevelData> =+        (0 until levelCount).mapNotNull { i ->+            val currentSeed = seed + i * 100+            val id = "${name.replace("×", "x").replace(" ", "_")}_${String.format(Locale.ROOT, "%03d", i + 1)}"+            generateLevel(cells, adjacency, maxFlows, currentSeed, id, 0.25f, bridges, renderPositions, portals, grid)+        } }
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.ktindex e10b606fb5..83a7c6d416 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/NumberlinkSolver.kt@@ -23,7 +23,6 @@ import com.vayunmathur.games.pipes.data.EndpointPair  * from exponential in the cell count to exponential in the board width.  */ internal object NumberlinkSolver {-     enum class Verdict {         /** Exactly one solution, so a covering carve is the only way to join the pairs. */         UNIQUE,@@ -134,14 +133,27 @@ internal object NumberlinkSolver {                 val cy = cellY[i]                 // numbersByPosition is in row-major order; everything below indexes by walk order.                 table[i] = numbersByPosition[cy * cols + cx]-                start[i] = if (cy > 0) key(cx, cy - 1) else if (cx > 0) key(cx - 1, cy) else 0+                start[i] =+                    if (cy > 0) {+                        key(cx, cy - 1)+                    } else if (cx > 0) {+                        key(cx - 1, cy)+                    } else {+                        0+                    }             }             start[size] = size         } -        private fun key(x: Int, y: Int) = keys[y * cols + x]+        private fun key(+            x: Int,+            y: Int,+        ) = keys[y * cols + x] -        private fun isOutside(x: Int, y: Int) = x < 0 || x >= cols || y < 0 || y >= rows+        private fun isOutside(+            x: Int,+            y: Int,+        ) = x < 0 || x >= cols || y < 0 || y >= rows          fun classify(): Verdict {             for (k in 0 until size) if (table[k] == HOLE) mates[k] = INTERIOR@@ -222,7 +234,10 @@ internal object NumberlinkSolver {          * Joins the two cells with an edge, or returns false if that breaks a rule. Either way the          * caller must [undo] back to its mark, because a rejected join still edited [mates].          */-        private fun unite(cell1: Int, cell2: Int): Boolean {+        private fun unite(+            cell1: Int,+            cell2: Int,+        ): Boolean {             val end1 = mates[cell1]             val end2 = mates[cell2]             // A cell with two edges already cannot take a third.@@ -243,7 +258,10 @@ internal object NumberlinkSolver {             return true         } -        private fun setMate(cell: Int, value: Int) {+        private fun setMate(+            cell: Int,+            value: Int,+        ) {             val previous = mates[cell]             if (previous == value) return             undoCell[undoTop] = cell
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/ProgressCodec.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/ProgressCodec.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/ProgressCodec.ktindex cee5927908..767cf12a3e 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/ProgressCodec.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/ProgressCodec.kt@@ -27,11 +27,12 @@ data class SavedProgress( object ProgressCodec {     private const val VERSION = 1 -    fun encode(progress: SavedProgress): String = buildJsonObject {-        put("v", VERSION)-        put("s", encodeState(progress.state))-        put("h", JsonArray(progress.history.map { encodeState(it) }))-    }.toString()+    fun encode(progress: SavedProgress): String =+        buildJsonObject {+            put("v", VERSION)+            put("s", encodeState(progress.state))+            put("h", JsonArray(progress.history.map { encodeState(it) }))+        }.toString()      /**      * Decodes [json] for [level], or null when it is unreadable or does not fit the level@@ -39,33 +40,60 @@ object ProgressCodec {      * touching another colour's dot, two lines sharing a cell outside a bridge).      * A level whose layout changed under a saved game then simply starts fresh.      */-    fun decode(json: String, level: LevelData): SavedProgress? = runCatching {-        val root = Json.parseToJsonElement(json).jsonObject-        if (root["v"]?.jsonPrimitive?.int != VERSION) return null-        val state = decodeState(root.getValue("s").jsonObject, level) ?: return null-        val history = root.getValue("h").jsonArray.map { decodeState(it.jsonObject, level) ?: return null }-        SavedProgress(state, history)-    }.getOrNull()+    fun decode(+        json: String,+        level: LevelData,+    ): SavedProgress? =+        runCatching {+            val root = Json.parseToJsonElement(json).jsonObject+            if (root["v"]?.jsonPrimitive?.int != VERSION) return null+            val state = decodeState(root.getValue("s").jsonObject, level) ?: return null+            val history = root.getValue("h").jsonArray.map { decodeState(it.jsonObject, level) ?: return null }+            SavedProgress(state, history)+        }.getOrNull() -    private fun encodeState(state: BoardState): JsonObject = buildJsonObject {-        put("p", buildJsonObject {-            for ((color, path) in state.paths.entries.sortedBy { it.key }) {-                put(color.toString(), buildJsonArray { for (c in path) { add(c.row); add(c.col) } })-            }-        })-        val pathCells = state.paths.values.flatten().groupingBy { it }.eachCount()-        put("o", buildJsonObject {-            for ((cell, owner) in state.cellOwner) {-                if ((pathCells[cell] ?: 0) > 1) put("${cell.row},${cell.col}", owner)-            }-        })-    }+    private fun encodeState(state: BoardState): JsonObject =+        buildJsonObject {+            put(+                "p",+                buildJsonObject {+                    for ((color, path) in state.paths.entries.sortedBy { it.key }) {+                        put(+                            color.toString(),+                            buildJsonArray {+                                for (c in path) {+                                    add(c.row)+                                    add(c.col)+                                }+                            },+                        )+                    }+                },+            )+            val pathCells =+                state.paths.values+                    .flatten()+                    .groupingBy { it }+                    .eachCount()+            put(+                "o",+                buildJsonObject {+                    for ((cell, owner) in state.cellOwner) {+                        if ((pathCells[cell] ?: 0) > 1) put("${cell.row},${cell.col}", owner)+                    }+                },+            )+        } -    private fun decodeState(obj: JsonObject, level: LevelData): BoardState? {+    private fun decodeState(+        obj: JsonObject,+        level: LevelData,+    ): BoardState? {         val colors = level.endpoints.map { it.colorIndex }.toSet()-        val paths = obj.getValue("p").jsonObject.mapKeys { it.key.toInt() }.mapValues { (_, v) ->-            v.jsonArray.map { it.jsonPrimitive.int }.chunked(2) { (r, c) -> CellPos(r, c) }-        }+        val paths =+            obj.getValue("p").jsonObject.mapKeys { it.key.toInt() }.mapValues { (_, v) ->+                v.jsonArray.map { it.jsonPrimitive.int }.chunked(2) { (r, c) -> CellPos(r, c) }+            }         for ((color, path) in paths) {             if (color !in colors || path.size < 2 || path.any { it !in level.cells }) return null             if (path.toSet().size != path.size) return null@@ -77,14 +105,19 @@ object ProgressCodec {         // the under-pipe owning it). BoardStatus.isSolved trusts that invariant — it only         // counts owners and checks each pair is joined — so lines that share a cell would         // restore as a board that reads as solved while its pipes overlap.-        val coverCounts = paths.values.flatten().groupingBy { it }.eachCount()+        val coverCounts =+            paths.values+                .flatten()+                .groupingBy { it }+                .eachCount()         if (coverCounts.any { (cell, count) -> count > 1 && (cell !in level.bridges || count > 2) }) {             return null         }-        val bridgeOwners = obj["o"]?.jsonObject.orEmpty().entries.associate { (k, v) ->-            val (r, c) = k.split(",").map { it.toInt() }-            CellPos(r, c) to v.jsonPrimitive.int-        }+        val bridgeOwners =+            obj["o"]?.jsonObject.orEmpty().entries.associate { (k, v) ->+                val (r, c) = k.split(",").map { it.toInt() }+                CellPos(r, c) to v.jsonPrimitive.int+            }         return BoardState(paths, BoardEdits.owners(level, paths, bridgeOwners))     } }
games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.ktindex 0dcedd6a5e..89aead15bc 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/domain/StrokeRules.kt@@ -12,7 +12,6 @@ import kotlin.math.abs  * never onto another colour's dot.  */ object StrokeRules {-     /**      * The stroke after the finger enters [cell].      *@@ -35,17 +34,24 @@ object StrokeRules {         val idx = path.indexOf(cell)         if (idx >= 0) return path.subList(0, idx + 1).toList()         if (isValidStep(level, color, path, cell)) return path + cell-        val via = level.adjacency[path.last()].orEmpty().filter { n ->-            cell in level.adjacency[n].orEmpty() &&-                isValidStep(level, color, path, n) &&-                !isComplete(level, color, path + n) &&-                isValidStep(level, color, path + n, cell)-        }.minByOrNull { n -> if (owners[n].let { it == null || it == color }) 0 else 1 }+        val via =+            level.adjacency[path.last()]+                .orEmpty()+                .filter { n ->+                    cell in level.adjacency[n].orEmpty() &&+                        isValidStep(level, color, path, n) &&+                        !isComplete(level, color, path + n) &&+                        isValidStep(level, color, path + n, cell)+                }.minByOrNull { n -> if (owners[n].let { it == null || it == color }) 0 else 1 }         return if (via != null) path + via + cell else path     }      /** Whether [path] has reached its partner dot (pairs) or visited every dot (triplets). */-    fun isComplete(level: LevelData, color: Int, path: List<CellPos>): Boolean {+    fun isComplete(+        level: LevelData,+        color: Int,+        path: List<CellPos>,+    ): Boolean {         val endpointCells = level.endpoints.find { it.colorIndex == color }?.cells ?: return false         if (path.isEmpty() || path.first() !in endpointCells || path.last() !in endpointCells) return false         if (path.first() == path.last()) return false@@ -73,8 +79,11 @@ object StrokeRules {         return isStraightThroughBridge(level, path, cell)     } -    private fun isForeignEndpoint(level: LevelData, color: Int, cell: CellPos): Boolean =-        level.endpoints.any { it.colorIndex != color && cell in it.cells }+    private fun isForeignEndpoint(+        level: LevelData,+        color: Int,+        cell: CellPos,+    ): Boolean = level.endpoints.any { it.colorIndex != color && cell in it.cells }      /**      * Bridges read as an overpass only when both pipes run straight through. When the path@@ -82,7 +91,11 @@ object StrokeRules {      * on the crossing. Long-range exits (portal/wrap jumps) are not grid lines and skip      * the check.      */-    private fun isStraightThroughBridge(level: LevelData, path: List<CellPos>, cell: CellPos): Boolean {+    private fun isStraightThroughBridge(+        level: LevelData,+        path: List<CellPos>,+        cell: CellPos,+    ): Boolean {         val origin = path.lastOrNull() ?: return true         if (origin !in level.bridges || path.size < 2) return true         if (abs(cell.row - origin.row) + abs(cell.col - origin.col) != 1) return true
games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesAchievementsManager.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesAchievementsManager.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesAchievementsManager.ktindex 6d9e9e5fb2..c70bb20001 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesAchievementsManager.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesAchievementsManager.kt@@ -12,9 +12,8 @@ import kotlinx.coroutines.launch class PipesAchievementsManager(     context: Context,     json: String,-    private val repository: CompletedLevelsRepository+    private val repository: CompletedLevelsRepository, ) : AchievementsManager(context, json) {-     private val dailyStore = DailyChallengeStore(context, "pipes_daily")      override fun checkExistingAchievements() {
games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.ktindex a32133b850..226055c8e8 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.kt@@ -10,9 +10,8 @@ import com.vayunmathur.games.pipes.data.LevelData  * so they can be rendered by a `@Preview` — which is what the store listing images are  * generated from. It lives in `util` rather than next to the screens so the dependency  * runs one way: the screens depend on `util`, and the ViewModel implements [PipesActions].- */--/** One row of the pack selector. Flattened to plain counts so the screen needs neither the+ *+ * One row of the pack selector. Flattened to plain counts so the screen needs neither the  * asset-loaded packs nor the stats repository.  */ data class PackProgress(@@ -56,10 +55,15 @@ data class GameBoardUiState(  */ interface PipesActions {     fun startDraw(cell: CellPos) {}+     fun extendPath(cell: CellPos) {}+     fun commitDraw() {}+     fun onUndo() {}+     fun onRestart() {}+     /** Shared constants and helpers for PipesActions. */     companion object {         val Noop: PipesActions = object : PipesActions {}@@ -77,8 +81,13 @@ data class SettingsUiState( /** Settings callbacks. Same no-op-default arrangement as [PipesActions]. */ interface SettingsActions {     fun setColorblind(enabled: Boolean) {}+     fun setReminderEnabled(enabled: Boolean) {}-    fun setReminderTime(hour: Int, minute: Int) {}++    fun setReminderTime(+        hour: Int,+        minute: Int,+    ) {}      /** Shared constants and helpers for SettingsActions. */     companion object {
games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.ktindex 896b7794e4..51e25597c2 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt@@ -5,6 +5,9 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.games.pipes.data.CellPos import com.vayunmathur.games.pipes.data.CompletedLevelsRepository+import com.vayunmathur.games.pipes.data.LevelData+import com.vayunmathur.games.pipes.data.LevelPack+import com.vayunmathur.games.pipes.data.ProgressRepository import com.vayunmathur.games.pipes.domain.BoardEdits import com.vayunmathur.games.pipes.domain.BoardState import com.vayunmathur.games.pipes.domain.BoardStatus@@ -12,17 +15,14 @@ import com.vayunmathur.games.pipes.domain.DailyLevels import com.vayunmathur.games.pipes.domain.ProgressCodec import com.vayunmathur.games.pipes.domain.SavedProgress import com.vayunmathur.games.pipes.domain.StrokeRules-import com.vayunmathur.games.pipes.data.LevelData-import com.vayunmathur.games.pipes.data.LevelPack-import com.vayunmathur.games.pipes.data.ProgressRepository-import com.vayunmathur.library.util.LevelStats 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 com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.LevelStats import com.vayunmathur.library.util.LevelStatsRepository+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@@ -56,17 +56,23 @@ data class PipesUiState( )  /** Pipes View Model: a application implementation for pipes view model. */-class PipesViewModel(application: Application) : AndroidViewModel(application), PipesActions {-+class PipesViewModel(+    application: Application,+) : AndroidViewModel(application),+    PipesActions {     val repository: CompletedLevelsRepository = CompletedLevelsRepository(application)      private val progress = ProgressRepository(application) -    val achievementsManager: AchievementsManager = run {-        val json = application.assets.open("achievements.json")-            .bufferedReader().use { it.readText() }-        PipesAchievementsManager(application, json, repository)-    }+    val achievementsManager: AchievementsManager =+        run {+            val json =+                application.assets+                    .open("achievements.json")+                    .bufferedReader()+                    .use { it.readText() }+            PipesAchievementsManager(application, json, repository)+        }      private val _uiState = MutableStateFlow(PipesUiState())     val uiState: StateFlow<PipesUiState> = _uiState.asStateFlow()@@ -97,8 +103,9 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),     private val _dailyStats = MutableStateFlow(dailyRepository.getLevelStats())     val dailyStats: StateFlow<Map<String, LevelStats>> = _dailyStats.asStateFlow() -    val dailyStreak: StateFlow<Long> = dailyStore.currentStreak-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0L)+    val dailyStreak: StateFlow<Long> =+        dailyStore.currentStreak+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0L)      /** How many of today's daily levels are solved. Derived from the IDs, so it needs no pack. */     val dailyCompleted: StateFlow<Int> =@@ -107,8 +114,10 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),                 .count { stats.containsKey(DailyLevels.levelId(day, it)) }         }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0) -    val colorblind: StateFlow<Boolean> = ds.booleanFlow(KEY_COLORBLIND)-        .stateIn(viewModelScope, SharingStarted.Eagerly, ds.getBoolean(KEY_COLORBLIND, false))+    val colorblind: StateFlow<Boolean> =+        ds+            .booleanFlow(KEY_COLORBLIND)+            .stateIn(viewModelScope, SharingStarted.Eagerly, ds.getBoolean(KEY_COLORBLIND, false))      fun setColorblind(value: Boolean) {         viewModelScope.launch { ds.setBoolean(KEY_COLORBLIND, value) }@@ -116,11 +125,13 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),      private val reminderSettings = DailyReminderSettings(application, DAILY_KEY_PREFIX) -    val reminderEnabled: StateFlow<Boolean> = reminderSettings.enabled-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)+    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 reminderMinutesOfDay: StateFlow<Long> =+        reminderSettings.minutesOfDay+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DailyPuzzleReminder.DEFAULT_MINUTES_OF_DAY)      fun setReminderEnabled(enabled: Boolean) {         viewModelScope.launch {@@ -129,7 +140,10 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),         }     } -    fun setReminderTime(hour: Int, minute: Int) {+    fun setReminderTime(+        hour: Int,+        minute: Int,+    ) {         viewModelScope.launch {             val minutes = (hour * 60 + minute).toLong()             reminderSettings.setMinutesOfDay(minutes)@@ -137,7 +151,10 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),         }     } -    private fun rescheduleReminder(enabled: Boolean, minutesOfDay: Long) {+    private fun rescheduleReminder(+        enabled: Boolean,+        minutesOfDay: Long,+    ) {         DailyPuzzleReminder.update(             context = getApplication(),             keyPrefix = DAILY_KEY_PREFIX,@@ -178,13 +195,17 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),             .mapTo(mutableSetOf()) { DailyLevels.levelId(day, it) }      /** Resolves a pack index to its levels, covering both shipped packs and the daily pack. */-    private fun levelsFor(packIndex: Int): List<LevelData>? = when (packIndex) {-        DAILY_PACK_INDEX -> _dailyPack.value?.levels-        in LevelPack.PACKS.indices -> LevelPack.PACKS[packIndex].levels-        else -> null-    }+    private fun levelsFor(packIndex: Int): List<LevelData>? =+        when (packIndex) {+            DAILY_PACK_INDEX -> _dailyPack.value?.levels+            in LevelPack.packs.indices -> LevelPack.packs[packIndex].levels+            else -> null+        } -    fun loadLevel(packIndex: Int, levelIndex: Int) {+    fun loadLevel(+        packIndex: Int,+        levelIndex: Int,+    ) {         val levelData = levelsFor(packIndex)?.getOrNull(levelIndex) ?: return         val current = _uiState.value         // Same-index reloads are a no-op only while they resolve to the same board. The@@ -194,16 +215,19 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),         if (current.packIndex == packIndex &&             current.levelIndex == levelIndex &&             current.levelData == levelData-        ) return+        ) {+            return+        }         // Resume where the player left this level (Back, level arrows, process death).         val saved = progress.load(levelData.id)?.let { ProgressCodec.decode(it, levelData) }-        _uiState.value = PipesUiState(-            packIndex = packIndex,-            levelIndex = levelIndex,-            levelData = levelData,-            gameState = saved?.state ?: PipesGameState(),-            history = saved?.history.orEmpty(),-        )+        _uiState.value =+            PipesUiState(+                packIndex = packIndex,+                levelIndex = levelIndex,+                levelData = levelData,+                gameState = saved?.state ?: PipesGameState(),+                history = saved?.history.orEmpty(),+            )     }      /** Saves the level's board after a move, or forgets it once it is empty again or won. */@@ -241,16 +265,17 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),         val endpointColor = levelData.endpoints.find { ep -> cell in ep.cells }?.colorIndex          val base = s.gameState-        val (color, stroke) = if (endpointColor != null) {-            // Grabbing an endpoint restarts that color, but its current line only breaks-            // once the drag leaves the dot (see extendPath), so a stray tap is harmless.-            endpointColor to listOf(cell)-        } else {-            val ownerColor = base.cellOwner[cell] ?: return-            val idx = base.paths[ownerColor]?.indexOf(cell) ?: -1-            if (idx < 0) return-            ownerColor to base.paths.getValue(ownerColor).take(idx + 1)-        }+        val (color, stroke) =+            if (endpointColor != null) {+                // Grabbing an endpoint restarts that color, but its current line only breaks+                // once the drag leaves the dot (see extendPath), so a stray tap is harmless.+                endpointColor to listOf(cell)+            } else {+                val ownerColor = base.cellOwner[cell] ?: return+                val idx = base.paths[ownerColor]?.indexOf(cell) ?: -1+                if (idx < 0) return+                ownerColor to base.paths.getValue(ownerColor).take(idx + 1)+            }         _uiState.update {             it.copy(                 activeColor = color,@@ -294,11 +319,12 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),          val newPath = s.activePath         val preDrawState = s.preDrawState ?: s.gameState-        val newGameState = if (s.leftStart) {-            BoardEdits.applyStroke(levelData, preDrawState, activeColor, newPath)-        } else {-            preDrawState-        }+        val newGameState =+            if (s.leftStart) {+                BoardEdits.applyStroke(levelData, preDrawState, activeColor, newPath)+            } else {+                preDrawState+            }         // Only a stroke that changed the board is a move: a tap, or a redraw of the same         // line, leaves the move count and the undo history alone.         val counts = newGameState != preDrawState@@ -345,10 +371,11 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),         }          viewModelScope.launch {-            val refreshed = withContext(Dispatchers.IO) {-                repository.updateBestScore(level.id, moves)-                repository.getLevelStats()-            }+            val refreshed =+                withContext(Dispatchers.IO) {+                    repository.updateBestScore(level.id, moves)+                    repository.getLevelStats()+                }             _levelStats.value = refreshed              achievementsManager.onAchievementUnlocked("first_flow")@@ -357,7 +384,7 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),             if (moves <= level.optimalMoves) {                 achievementsManager.onAchievementUnlocked("optimal_win")             }-            val pack0 = LevelPack.PACKS[0]+            val pack0 = LevelPack.packs[0]             val pack0Completed = pack0.levels.count { refreshed.containsKey(it.id) }             if (pack0Completed >= pack0.levels.size) {                 achievementsManager.onAchievementUnlocked("all_5x5")@@ -366,13 +393,18 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),     }      /** Daily wins record into the separate store, and extend the streak once the day is cleared. */-    private fun onDailyLevelWon(levelId: String, moves: Int, optimalMoves: Int) {+    private fun onDailyLevelWon(+        levelId: String,+        moves: Int,+        optimalMoves: Int,+    ) {         val day = _dailyDay.value         viewModelScope.launch {-            val refreshed = withContext(Dispatchers.IO) {-                dailyRepository.updateBestScore(levelId, moves)-                dailyRepository.getLevelStats()-            }+            val refreshed =+                withContext(Dispatchers.IO) {+                    dailyRepository.updateBestScore(levelId, moves)+                    dailyRepository.getLevelStats()+                }             _dailyStats.value = refreshed              achievementsManager.onAchievementUnlocked("first_flow")@@ -381,8 +413,9 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),                 achievementsManager.onAchievementUnlocked("optimal_win")             } -            val dayComplete = (0 until DailyLevels.LEVELS_PER_DAY)-                .all { refreshed.containsKey(DailyLevels.levelId(day, it)) }+            val dayComplete =+                (0 until DailyLevels.LEVELS_PER_DAY)+                    .all { refreshed.containsKey(DailyLevels.levelId(day, it)) }             if (dayComplete) {                 val streak = dailyStore.recordDayCompleted(day)                 achievementsManager.onProgressUpdated("daily_streak_7", streak.best.toInt())@@ -402,7 +435,7 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),                 gameState = it.history.last(),                 history = it.history.dropLast(1),                 activeColor = null,-                activePath = emptyList()+                activePath = emptyList(),             )         }         persistProgress()@@ -417,7 +450,7 @@ class PipesViewModel(application: Application) : AndroidViewModel(application),                 history = emptyList(),                 isLevelWon = false,                 activeColor = null,-                activePath = emptyList()+                activePath = emptyList(),             )         }         persistProgress()
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardCellSemantics.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardCellSemantics.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardCellSemantics.ktindex 2e1d3cef45..5148aece7f 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardCellSemantics.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardCellSemantics.kt@@ -48,7 +48,10 @@ fun BoardCellSemantics(     onCommitDraw: () -> Unit = {}, ) {     val cellDp = with(LocalDensity.current) { geometry.cellSizePx.toDp() }-    val dots = geometry.levelData.endpoints.flatMap { ep -> ep.cells.map { it to ep.colorIndex } }.toMap()+    val dots =+        geometry.levelData.endpoints+            .flatMap { ep -> ep.cells.map { it to ep.colorIndex } }+            .toMap()     val startLabel = stringResource(R.string.board_action_start_pipe)     val extendLabel = stringResource(R.string.board_action_extend_pipe)     val finishLabel = stringResource(R.string.board_action_finish_pipe)@@ -68,30 +71,58 @@ fun BoardCellSemantics(                         contentDescription = description                         if (isLevelWon) return@semantics                         if (drawing) stateDescription = drawingLabel-                        val actions = buildList {-                            if (drawing) {-                                add(CustomAccessibilityAction(extendLabel) { onExtendPath(cell); true })-                                add(CustomAccessibilityAction(finishLabel) { onCommitDraw(); true })+                        val actions =+                            buildList {+                                if (drawing) {+                                    add(+                                        CustomAccessibilityAction(extendLabel) {+                                            onExtendPath(cell)+                                            true+                                        },+                                    )+                                    add(+                                        CustomAccessibilityAction(finishLabel) {+                                            onCommitDraw()+                                            true+                                        },+                                    )+                                }+                                if (canStart) {+                                    add(+                                        CustomAccessibilityAction(startLabel) {+                                            onStartDraw(cell)+                                            true+                                        },+                                    )+                                }                             }-                            if (canStart) {-                                add(CustomAccessibilityAction(startLabel) { onStartDraw(cell); true })-                            }-                        }                         if (actions.isNotEmpty()) customActions = actions                         // Double-tap does the primary thing for the current phase:                         // start a stroke, or grow the open one into this cell.                         when {-                            drawing -> onClick(extendLabel) { onExtendPath(cell); true }-                            canStart -> onClick(startLabel) { onStartDraw(cell); true }+                            drawing ->+                                onClick(extendLabel) {+                                    onExtendPath(cell)+                                    true+                                }+                            canStart ->+                                onClick(startLabel) {+                                    onStartDraw(cell)+                                    true+                                }                         }-                    }+                    },             )         }     } }  @Composable-private fun cellDescription(cell: CellPos, dotColor: Int?, owner: Int?): String {+private fun cellDescription(+    cell: CellPos,+    dotColor: Int?,+    owner: Int?,+): String {     val row = cell.row + 1     val col = cell.col + 1     return when {
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.ktindex ed3079cb05..41eb727e8c 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/BoardGeometry.kt@@ -13,7 +13,9 @@ import kotlin.math.ceil  * Computed once per level: scanning every cell for the bounding box is cheap once, but  * the board recomposes on every drag step, so it must not run per frame.  */-class BoardLayout(val levelData: LevelData) {+class BoardLayout(+    val levelData: LevelData,+) {     /** Board side length in cells: the canvas is square and fits this many cells across. */     val maxDim: Float @@ -25,14 +27,15 @@ class BoardLayout(val levelData: LevelData) {     init {         val positions = levelData.renderPositions?.filterKeys { it in levelData.cells }?.values         val hasPositions = levelData.renderPositions != null && levelData.cells.isNotEmpty()-        val (contentW, contentH) = if (hasPositions && !positions.isNullOrEmpty()) {-            (positions.maxOf { it.x } - positions.minOf { it.x } + 1f) to-                (positions.maxOf { it.y } - positions.minOf { it.y } + 1f)-        } else if (hasPositions) {-            1f to 1f-        } else {-            levelData.cols.toFloat() to levelData.rows.toFloat()-        }+        val (contentW, contentH) =+            if (hasPositions && !positions.isNullOrEmpty()) {+                (positions.maxOf { it.x } - positions.minOf { it.x } + 1f) to+                    (positions.maxOf { it.y } - positions.minOf { it.y } + 1f)+            } else if (hasPositions) {+                1f to 1f+            } else {+                levelData.cols.toFloat() to levelData.rows.toFloat()+            }         // Hex rows overlap vertically (0.866 spacing) so shrink slightly to avoid clipping.         val hexShrink = if (levelData.grid == "hex") 0.92f else 1f         val effectiveMaxDim = maxOf(contentW, contentH, 1f) / hexShrink@@ -78,21 +81,30 @@ class BoardLayout(val levelData: LevelData) {  * Every touch handler must use the geometry of the size the board is drawn at *now*:  * rebuild this whenever [cellSizePx] changes (rotation, fold, window resize).  */-class BoardGeometry(val layout: BoardLayout, val cellSizePx: Float) {+class BoardGeometry(+    val layout: BoardLayout,+    val cellSizePx: Float,+) {     val levelData: LevelData get() = layout.levelData     val isHex: Boolean = layout.levelData.grid == "hex" -    val cellRects: Map<CellPos, Rect> = layout.levelData.cells.associateWith { cell ->-        val o = layout.origin(cell)-        Rect(Offset(o.x * cellSizePx, o.y * cellSizePx), Size(cellSizePx, cellSizePx))-    }+    val cellRects: Map<CellPos, Rect> =+        layout.levelData.cells.associateWith { cell ->+            val o = layout.origin(cell)+            Rect(Offset(o.x * cellSizePx, o.y * cellSizePx), Size(cellSizePx, cellSizePx))+        } -    val boardBounds: Rect = if (cellRects.isEmpty()) Rect.Zero else Rect(-        left = cellRects.values.minOf { it.left },-        top = cellRects.values.minOf { it.top },-        right = cellRects.values.maxOf { it.right },-        bottom = cellRects.values.maxOf { it.bottom },-    )+    val boardBounds: Rect =+        if (cellRects.isEmpty()) {+            Rect.Zero+        } else {+            Rect(+                left = cellRects.values.minOf { it.left },+                top = cellRects.values.minOf { it.top },+                right = cellRects.values.maxOf { it.right },+                bottom = cellRects.values.maxOf { it.bottom },+            )+        }      fun hitTest(offset: Offset): CellPos? {         if (!isHex) {@@ -119,12 +131,13 @@ class BoardGeometry(val layout: BoardLayout, val cellSizePx: Float) {     fun hitTestDrag(offset: Offset): CellPos? {         hitTest(offset)?.let { return it }         if (cellRects.isEmpty() || boardBounds.contains(offset)) return null-        return cellRects.entries.minWithOrNull(-            compareBy(-                { squaredDistanceToRect(it.value, offset) },-                { (it.value.center - offset).getDistanceSquared() },-            )-        )?.key+        return cellRects.entries+            .minWithOrNull(+                compareBy(+                    { squaredDistanceToRect(it.value, offset) },+                    { (it.value.center - offset).getDistanceSquared() },+                ),+            )?.key     }      /**@@ -133,7 +146,10 @@ class BoardGeometry(val layout: BoardLayout, val cellSizePx: Float) {      * path returns to it). Touch events arrive far apart on a fast swipe; feeding only      * their end points to the stroke skipped cells and stalled it.      */-    fun cellsAlong(from: Offset, to: Offset): List<CellPos> {+    fun cellsAlong(+        from: Offset,+        to: Offset,+    ): List<CellPos> {         if (cellSizePx <= 0f) return listOfNotNull(hitTestDrag(to))         val distance = (to - from).getDistance()         val steps = ceil(distance / (cellSizePx * SAMPLE_FRACTION)).toInt().coerceIn(1, MAX_SAMPLES)@@ -155,7 +171,10 @@ class BoardGeometry(val layout: BoardLayout, val cellSizePx: Float) {     } } -private fun squaredDistanceToRect(rect: Rect, point: Offset): Float {+private fun squaredDistanceToRect(+    rect: Rect,+    point: Offset,+): Float {     val dx = maxOf(rect.left - point.x, 0f, point.x - rect.right)     val dy = maxOf(rect.top - point.y, 0f, point.y - rect.bottom)     return dx * dx + dy * dy
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/DailyLevelScreen.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/DailyLevelScreen.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/DailyLevelScreen.ktindex 8c80f3cff0..c6301e3025 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/DailyLevelScreen.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/DailyLevelScreen.kt@@ -28,21 +28,58 @@ import com.vayunmathur.library.ui.CardDefaults import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconStar-import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ui.R as UiR  @OptIn(ExperimentalMaterial3Api::class) @Composable-fun DailyLevelScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel) {+fun DailyLevelScreen(+    backStack: NavBackStack<Route>,+    viewModel: PipesViewModel,+) {     val dailyPack by viewModel.dailyPack.collectAsState()     val dailyStats by viewModel.dailyStats.collectAsState()     LaunchedEffect(Unit) { viewModel.refreshDaily() }-    AppScaffold(title = stringResource(UiR.string.daily_challenge), backStack = backStack, isRefreshing = dailyPack?.levels == null) { paddingValues ->+    AppScaffold(+        title = stringResource(UiR.string.daily_challenge),+        backStack = backStack,+        isRefreshing =+            dailyPack?.levels == null,+    ) { paddingValues ->         val levels = dailyPack?.levels-        if (levels == null) { return@AppScaffold }-        LazyVerticalGrid(GridCells.Adaptive(88.dp), Modifier.fillMaxSize(), contentPadding = paddingValues + PaddingValues(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 0.dp), verticalArrangement = Arrangement.spacedBy(12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {-            itemsIndexed(levels) { index, levelData -> Card(Modifier.fillMaxWidth().clickable { backStack.add(Route.DailyGame(index)) }, colors = CardDefaults.cardColors(com.vayunmathur.library.ui.MaterialTheme.colorScheme.surface)) { Box(Modifier.fillMaxSize().padding(8.dp)) { Text("${index + 1}", Modifier.align(Alignment.Center)); val levelStat = dailyStats[levelData.id]; Box(Modifier.size(20.dp).align(Alignment.CenterEnd), Alignment.Center) { when { levelStat == null -> return@Box; levelStat.bestScore <= levelData.optimalMoves -> IconStar(); else -> IconCheck() } } } } }+        if (levels == null) {+            return@AppScaffold+        }+        LazyVerticalGrid(+            GridCells.Adaptive(88.dp),+            Modifier.fillMaxSize(),+            contentPadding =+                paddingValues + PaddingValues(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 0.dp),+            verticalArrangement = Arrangement.spacedBy(12.dp),+            horizontalArrangement = Arrangement.spacedBy(12.dp),+        ) {+            itemsIndexed(levels) { index, levelData ->+                Card(+                    Modifier.fillMaxWidth().clickable {+                        backStack.add(Route.DailyGame(index))+                    },+                    colors = CardDefaults.cardColors(com.vayunmathur.library.ui.MaterialTheme.colorScheme.surface),+                ) {+                    Box(Modifier.fillMaxSize().padding(8.dp)) {+                        Text("${index + 1}", Modifier.align(Alignment.Center))+                        val levelStat = dailyStats[levelData.id]+                        Box(Modifier.size(20.dp).align(Alignment.CenterEnd), Alignment.Center) {+                            when {+                                levelStat ==+                                    null -> return@Box+                                levelStat.bestScore <= levelData.optimalMoves -> IconStar()+                                else -> IconCheck()+                            }+                        }+                    }+                }+            }         }     } }
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.ktindex 0b30097288..1bc1a29d26 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt@@ -43,176 +43,203 @@ fun GameBoard(     onCommitDraw: () -> Unit,     isLevelWon: Boolean,     modifier: Modifier = Modifier,-    colorblind: Boolean = false+    colorblind: Boolean = false, ) {     BoxWithConstraints(modifier = modifier, contentAlignment = Alignment.Center) {-    val boardSize = minOf(maxWidth, maxHeight)-    // Layout and pixel geometry are cached: the board recomposes on every drag step, and-    // rescanning every cell for bounds and rects each time is wasted work.-    val layout = remember(levelData) { BoardLayout(levelData) }-    val cellSizeDp = boardSize / layout.maxDim-    val cellSizePx = with(LocalDensity.current) { cellSizeDp.toPx() }-    val geometry = remember(layout, cellSizePx) { BoardGeometry(layout, cellSizePx) }-    val cellRects = geometry.cellRects-    val isHex = geometry.isHex-    val labelPaint = remember { ColorLabelPaint() }-    // The gesture coroutine outlives recompositions, so it must never read values captured-    // at launch: it restarts whenever the geometry changes (rotation, fold, resize), and-    // reads the callbacks through rememberUpdatedState.-    val currentStartDraw by rememberUpdatedState(onStartDraw)-    val currentExtendPath by rememberUpdatedState(onExtendPath)-    val currentCommitDraw by rememberUpdatedState(onCommitDraw)-    val connected = levelData.endpoints.count {-        StrokeRules.isComplete(levelData, it.colorIndex, gameState.paths[it.colorIndex].orEmpty())-    }-    val summary = stringResource(-        R.string.board_summary, levelData.rows, levelData.cols,-        connected, levelData.endpoints.size, gameState.cellOwner.size, levelData.cells.size,-    )--    Canvas(-        modifier = Modifier-            .size(boardSize)-            .testTag(GAME_BOARD_TAG)-            // Strokes start at the board's edge cells, which on a full-width board sit in-            // the system back-gesture zone; claim the board so they draw instead of exiting.-            .systemGestureExclusion()-            .semantics { contentDescription = summary }-            .pointerInput(geometry, isLevelWon) {-                if (isLevelWon) return@pointerInput-                // One stroke per gesture, driven only by the first finger: a second finger-                // used to restart the stroke mid-drag (and re-snapshot undo); now it is ignored.-                awaitEachGesture {-                    val down = awaitFirstDown()-                    down.consume()-                    val start = geometry.hitTest(down.position) ?: return@awaitEachGesture-                    currentStartDraw(start)-                    var last = down.position-                    try {-                        while (true) {-                            val event = awaitPointerEvent()-                            val change = event.changes.firstOrNull { it.id == down.id }-                            event.changes.forEach { it.consume() }-                            if (change == null || !change.pressed) break-                            // Walk every sample since the last event (batched historical-                            // points too), cell by cell, so fast strokes never skip cells.-                            for (p in change.historical.map { it.position } + change.position) {-                                geometry.cellsAlong(last, p).forEach { currentExtendPath(it) }-                                last = p+        val boardSize = minOf(maxWidth, maxHeight)+        // Layout and pixel geometry are cached: the board recomposes on every drag step, and+        // rescanning every cell for bounds and rects each time is wasted work.+        val layout = remember(levelData) { BoardLayout(levelData) }+        val cellSizeDp = boardSize / layout.maxDim+        val cellSizePx = with(LocalDensity.current) { cellSizeDp.toPx() }+        val geometry = remember(layout, cellSizePx) { BoardGeometry(layout, cellSizePx) }+        val cellRects = geometry.cellRects+        val isHex = geometry.isHex+        val labelPaint = remember { ColorLabelPaint() }+        // The gesture coroutine outlives recompositions, so it must never read values captured+        // at launch: it restarts whenever the geometry changes (rotation, fold, resize), and+        // reads the callbacks through rememberUpdatedState.+        val currentStartDraw by rememberUpdatedState(onStartDraw)+        val currentExtendPath by rememberUpdatedState(onExtendPath)+        val currentCommitDraw by rememberUpdatedState(onCommitDraw)+        val connected =+            levelData.endpoints.count {+                StrokeRules.isComplete(levelData, it.colorIndex, gameState.paths[it.colorIndex].orEmpty())+            }+        val summary =+            stringResource(+                R.string.board_summary,+                levelData.rows,+                levelData.cols,+                connected,+                levelData.endpoints.size,+                gameState.cellOwner.size,+                levelData.cells.size,+            )++        Canvas(+            modifier =+                Modifier+                    .size(boardSize)+                    .testTag(GAME_BOARD_TAG)+                    // Strokes start at the board's edge cells, which on a full-width board sit in+                    // the system back-gesture zone; claim the board so they draw instead of exiting.+                    .systemGestureExclusion()+                    .semantics { contentDescription = summary }+                    .pointerInput(geometry, isLevelWon) {+                        if (isLevelWon) return@pointerInput+                        // One stroke per gesture, driven only by the first finger: a second finger+                        // used to restart the stroke mid-drag (and re-snapshot undo); now it is ignored.+                        awaitEachGesture {+                            val down = awaitFirstDown()+                            down.consume()+                            val start = geometry.hitTest(down.position) ?: return@awaitEachGesture+                            currentStartDraw(start)+                            var last = down.position+                            try {+                                while (true) {+                                    val event = awaitPointerEvent()+                                    val change = event.changes.firstOrNull { it.id == down.id }+                                    event.changes.forEach { it.consume() }+                                    if (change == null || !change.pressed) break+                                    // Walk every sample since the last event (batched historical+                                    // points too), cell by cell, so fast strokes never skip cells.+                                    for (p in change.historical.map { it.position } + change.position) {+                                        geometry.cellsAlong(last, p).forEach { currentExtendPath(it) }+                                        last = p+                                    }+                                }+                            } finally {+                                // Also on cancellation (the board resized mid-stroke): never leave a+                                // stroke open in the ViewModel.+                                currentCommitDraw()                             }                         }-                    } finally {-                        // Also on cancellation (the board resized mid-stroke): never leave a-                        // stroke open in the ViewModel.-                        currentCommitDraw()-                    }+                    },+        ) {+            for (cell in levelData.cells) {+                val rect = cellRects[cell] ?: continue+                if (isHex) {+                    drawHexCell(rect.center, cellSizePx * 0.52f)+                } else {+                    drawEmptyCell(rect)                 }             }-    ) {-        for (cell in levelData.cells) {-            val rect = cellRects[cell] ?: continue-            if (isHex) {-                drawHexCell(rect.center, cellSizePx * 0.52f)-            } else {-                drawEmptyCell(rect)-            }-        } -        // Portal pads sit under any pipe.-        for (portalCell in levelData.portals.keys) {-            val rect = cellRects[portalCell] ?: continue-            drawPortalRing(rect)-        }+            // Portal pads sit under any pipe.+            for (portalCell in levelData.portals.keys) {+                val rect = cellRects[portalCell] ?: continue+                drawPortalRing(rect)+            } -        val displayPaths = if (activeColor != null) gameState.paths + (activeColor to activePath) else gameState.paths+            val displayPaths =+                if (activeColor !=+                    null+                ) {+                    gameState.paths + (activeColor to activePath)+                } else {+                    gameState.paths+                } -        val jumpExits = mutableListOf<Triple<CellPos, Direction, androidx.compose.ui.graphics.Color>>()-        // Colour-blind mode letters every other inner cell of each pipe, not just the dots,-        // so two similar colours can be told apart anywhere along their lines.-        val pipeLabels = mutableListOf<Triple<Rect, Offset, Int>>()+            val jumpExits = mutableListOf<Triple<CellPos, Direction, androidx.compose.ui.graphics.Color>>()+            // Colour-blind mode letters every other inner cell of each pipe, not just the dots,+            // so two similar colours can be told apart anywhere along their lines.+            val pipeLabels = mutableListOf<Triple<Rect, Offset, Int>>() -        for ((colorIndex, path) in displayPaths) {-            if (path.isEmpty()) continue-            val color = PIPE_COLORS[colorIndex % PIPE_COLORS.size]+            for ((colorIndex, path) in displayPaths) {+                if (path.isEmpty()) continue+                val color = PIPE_COLORS[colorIndex % PIPE_COLORS.size] -            for (i in path.indices) {-                val cell = path[i]-                val rect = cellRects[cell] ?: continue-                if (isHex) {-                    val connections = buildSet {-                        if (i > 0) hexDirOrNull(cellRects, cell, path[i - 1])?.let { add(it) }-                        if (i < path.lastIndex) hexDirOrNull(cellRects, cell, path[i + 1])?.let { add(it) }-                    }-                    drawHexPipeSegment(rect.center, cellSizePx * 0.5f, connections, color)-                    if (colorblind && i % 2 == 1 && i < path.lastIndex) {-                        pipeLabels += Triple(rect, rect.center, colorIndex)-                    }-                } else {-                    val connections = buildSet {-                        if (i > 0) stepOrJump(levelData, cell, path[i - 1], color, jumpExits)?.let { add(it) }-                        if (i < path.lastIndex) stepOrJump(levelData, cell, path[i + 1], color, jumpExits)?.let { add(it) }-                    }-                    drawPipeSegment(rect, connections, color)-                    if (colorblind && i % 2 == 1 && i < path.lastIndex) {-                        pipeLabels += Triple(rect, pipeLabelAnchor(rect, connections), colorIndex)+                for (i in path.indices) {+                    val cell = path[i]+                    val rect = cellRects[cell] ?: continue+                    if (isHex) {+                        val connections =+                            buildSet {+                                if (i > 0) hexDirOrNull(cellRects, cell, path[i - 1])?.let { add(it) }+                                if (i < path.lastIndex) hexDirOrNull(cellRects, cell, path[i + 1])?.let { add(it) }+                            }+                        drawHexPipeSegment(rect.center, cellSizePx * 0.5f, connections, color)+                        if (colorblind && i % 2 == 1 && i < path.lastIndex) {+                            pipeLabels += Triple(rect, rect.center, colorIndex)+                        }+                    } else {+                        val connections =+                            buildSet {+                                if (i > 0) stepOrJump(levelData, cell, path[i - 1], color, jumpExits)?.let { add(it) }+                                if (i <+                                    path.lastIndex+                                ) {+                                    stepOrJump(levelData, cell, path[i + 1], color, jumpExits)?.let { add(it) }+                                }+                            }+                        drawPipeSegment(rect, connections, color)+                        if (colorblind && i % 2 == 1 && i < path.lastIndex) {+                            pipeLabels += Triple(rect, pipeLabelAnchor(rect, connections), colorIndex)+                        }                     }                 }             }-        } -        // Wrap jumps: dot at the board edge the pipe exits through. Portal jumps get no-        // marker — the ring above already explains the teleport.-        for ((cell, side, color) in jumpExits) {-            if (cell in levelData.portals) continue-            val rect = cellRects[cell] ?: continue-            drawWrapMarker(rect, side, color)-        }+            // Wrap jumps: dot at the board edge the pipe exits through. Portal jumps get no+            // marker — the ring above already explains the teleport.+            for ((cell, side, color) in jumpExits) {+                if (cell in levelData.portals) continue+                val rect = cellRects[cell] ?: continue+                drawWrapMarker(rect, side, color)+            } -        // Bridges: the second crosser humps over the first owner's pipe.-        for (bridge in levelData.bridges) {-            val rect = cellRects[bridge] ?: continue-            val owner = gameState.cellOwner[bridge]-            val over = displayPaths.entries.firstOrNull { (c, path) ->-                bridge in path && (owner == null || c != owner)-            }?.key-            if (over != null) {-                drawBridgeHump(rect, PIPE_COLORS[over % PIPE_COLORS.size])+            // Bridges: the second crosser humps over the first owner's pipe.+            for (bridge in levelData.bridges) {+                val rect = cellRects[bridge] ?: continue+                val owner = gameState.cellOwner[bridge]+                val over =+                    displayPaths.entries+                        .firstOrNull { (c, path) ->+                            bridge in path && (owner == null || c != owner)+                        }?.key+                if (over != null) {+                    drawBridgeHump(rect, PIPE_COLORS[over % PIPE_COLORS.size])+                }             }-        } -        for ((rect, anchor, colorIndex) in pipeLabels) {-            drawColorLabel(rect, colorIndex, labelPaint, center = anchor, textScale = PIPE_LABEL_SCALE)-        }+            for ((rect, anchor, colorIndex) in pipeLabels) {+                drawColorLabel(rect, colorIndex, labelPaint, center = anchor, textScale = PIPE_LABEL_SCALE)+            } -        for (ep in levelData.endpoints) {-            val color = PIPE_COLORS[ep.colorIndex % PIPE_COLORS.size]-            for (cell in ep.cells) {-                val rect = cellRects[cell] ?: continue-                drawEndpointBall(rect, color)-                if (colorblind) drawColorLabel(rect, ep.colorIndex, labelPaint)+            for (ep in levelData.endpoints) {+                val color = PIPE_COLORS[ep.colorIndex % PIPE_COLORS.size]+                for (cell in ep.cells) {+                    val rect = cellRects[cell] ?: continue+                    drawEndpointBall(rect, color)+                    if (colorblind) drawColorLabel(rect, ep.colorIndex, labelPaint)+                }             }         }-    }-    BoardCellSemantics(-        geometry, gameState, boardSize,-        activeColor = activeColor,-        isLevelWon = isLevelWon,-        onStartDraw = onStartDraw,-        onExtendPath = onExtendPath,-        onCommitDraw = onCommitDraw,-    )+        BoardCellSemantics(+            geometry,+            gameState,+            boardSize,+            activeColor = activeColor,+            isLevelWon = isLevelWon,+            onStartDraw = onStartDraw,+            onExtendPath = onExtendPath,+            onCommitDraw = onCommitDraw,+        )     } } -private fun directionBetween(from: CellPos, to: CellPos): Direction? {-    return when {+private fun directionBetween(+    from: CellPos,+    to: CellPos,+): Direction? =+    when {         to.row < from.row -> Direction.UP         to.row > from.row -> Direction.DOWN         to.col < from.col -> Direction.LEFT         to.col > from.col -> Direction.RIGHT         else -> null     }-}  /**  * Adjacent step → its side. Long-range edge (wrap/portal) → side facing the board edge, plus a@@ -229,13 +256,17 @@ private fun stepOrJump(         if (kotlin.math.abs(neighbor.row - cell.row) + kotlin.math.abs(neighbor.col - cell.col) == 1) return it     }     // Long-range: pick the side toward the nearest board edge from the cell's draw position.-    val pos = levelData.renderPositions?.get(cell) ?: com.vayunmathur.games.pipes.data.RenderPos(cell.col.toFloat(), cell.row.toFloat())-    val edgeDistances = listOf(-        Direction.LEFT to pos.x,-        Direction.RIGHT to (levelData.cols - 1 - pos.x),-        Direction.UP to pos.y,-        Direction.DOWN to (levelData.rows - 1 - pos.y)-    )+    val pos =+        levelData.renderPositions?.get(cell)+            ?: com.vayunmathur.games.pipes.data+                .RenderPos(cell.col.toFloat(), cell.row.toFloat())+    val edgeDistances =+        listOf(+            Direction.LEFT to pos.x,+            Direction.RIGHT to (levelData.cols - 1 - pos.x),+            Direction.UP to pos.y,+            Direction.DOWN to (levelData.rows - 1 - pos.y),+        )     val side = edgeDistances.minByOrNull { it.second }?.first ?: return null     jumpExits.add(Triple(cell, side, color))     return side
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoardScreen.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoardScreen.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoardScreen.ktindex eff2638000..e93bb8717f 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoardScreen.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoardScreen.kt@@ -27,8 +27,6 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.games.pipes.R import com.vayunmathur.games.pipes.platform.GameBoardUiState import com.vayunmathur.games.pipes.platform.PipesActions-import com.vayunmathur.library.ui.game.LevelPickerBox-import com.vayunmathur.library.ui.game.MovesBox import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.ConfirmDialog@@ -36,6 +34,8 @@ import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.game.LevelPickerBox+import com.vayunmathur.library.ui.game.MovesBox import com.vayunmathur.library.ui.R as UiR  /**@@ -52,39 +52,100 @@ fun GameBoardScreen(     onBackToPacks: () -> Unit = onBack, ) {     var showRestartConfirm by remember { mutableStateOf(false) }-    if (showRestartConfirm) { RestartConfirmDialog(onConfirm = { actions.onRestart() }, onDismiss = { showRestartConfirm = false }) }+    if (showRestartConfirm) {+        RestartConfirmDialog(onConfirm = { actions.onRestart() }, onDismiss = {+            showRestartConfirm =+                false+        })+    }     AppScaffold(title = "", onNavigateBack = onBack) { innerPadding ->         Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {-            val infoBoxes = @Composable { LevelPickerBox(levelIndex = state.levelIndex, onLevelChange = onLevelChange, isCompleted = state.isCompleted, maxLevelIndex = state.maxLevelIndex); MovesBox(moves = state.moves, bestScore = state.bestScore, optimalMoves = state.levelData.optimalMoves) }+            val infoBoxes = @Composable {+                LevelPickerBox(+                    levelIndex = state.levelIndex,+                    onLevelChange = onLevelChange,+                    isCompleted = state.isCompleted,+                    maxLevelIndex = state.maxLevelIndex,+                )+                MovesBox(moves = state.moves, bestScore = state.bestScore, optimalMoves = state.levelData.optimalMoves)+            }             val actionButtons = @Composable {                 if (!state.isLevelWon) {-                    Button(onClick = { actions.onUndo() }, enabled = state.canUndo) { Text(stringResource(UiR.string.undo)) }-                    Button(onClick = { showRestartConfirm = true }, enabled = state.canUndo) { Text(stringResource(UiR.string.restart)) }+                    Button(+                        onClick = { actions.onUndo() },+                        enabled = state.canUndo,+                    ) { Text(stringResource(UiR.string.undo)) }+                    Button(+                        onClick = { showRestartConfirm = true },+                        enabled = state.canUndo,+                    ) { Text(stringResource(UiR.string.restart)) }                 } else if (state.levelIndex < state.maxLevelIndex) {-                    Button(onClick = { onLevelChange(state.levelIndex + 1) }) { Text(stringResource(UiR.string.next_level)) }+                    Button(+                        onClick = { onLevelChange(state.levelIndex + 1) },+                    ) { Text(stringResource(UiR.string.next_level)) }                 } else {                     // Last level of the pack: Undo/Restart are gone, so never leave this row empty.                     Button(onClick = onBackToPacks) { Text(stringResource(R.string.back_to_packs)) }                 }             }             val status = @Composable { StatusLine(state) }-            val board = @Composable { boardModifier: Modifier -> GameBoard(levelData = state.levelData, gameState = state.gameState, activeColor = state.activeColor, activePath = state.activePath, onStartDraw = actions::startDraw, onExtendPath = actions::extendPath, onCommitDraw = actions::commitDraw, isLevelWon = state.isLevelWon, colorblind = state.colorblind, modifier = boardModifier) }+            val board = @Composable { boardModifier: Modifier ->+                GameBoard(+                    levelData = state.levelData,+                    gameState = state.gameState,+                    activeColor = state.activeColor,+                    activePath = state.activePath,+                    onStartDraw = actions::startDraw,+                    onExtendPath = actions::extendPath,+                    onCommitDraw = actions::commitDraw,+                    isLevelWon = state.isLevelWon,+                    colorblind = state.colorblind,+                    modifier = boardModifier,+                )+            }             BoxWithConstraints(modifier = Modifier.fillMaxSize().padding(innerPadding).padding(16.dp)) {                 if (maxWidth > maxHeight) {-                    Row(modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {-                        Box(modifier = Modifier.weight(1f).fillMaxHeight(), contentAlignment = Alignment.Center) { board(Modifier.fillMaxSize()) }-                        Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {+                    Row(+                        modifier = Modifier.fillMaxSize(),+                        horizontalArrangement = Arrangement.spacedBy(16.dp),+                        verticalAlignment = Alignment.CenterVertically,+                    ) {+                        Box(modifier = Modifier.weight(1f).fillMaxHeight(), contentAlignment = Alignment.Center) {+                            board(Modifier.fillMaxSize())+                        }+                        Column(+                            horizontalAlignment = Alignment.CenterHorizontally,+                            verticalArrangement = Arrangement.spacedBy(16.dp),+                        ) {                             infoBoxes()                             status()                             Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { actionButtons() }                         }                     }                 } else {-                    Column(modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {-                        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically) { infoBoxes() }-                        Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { board(Modifier.fillMaxSize()) }+                    Column(+                        modifier = Modifier.fillMaxSize(),+                        horizontalAlignment = Alignment.CenterHorizontally,+                        verticalArrangement = Arrangement.spacedBy(16.dp),+                    ) {+                        Row(+                            modifier = Modifier.fillMaxWidth(),+                            horizontalArrangement = Arrangement.SpaceAround,+                            verticalAlignment = Alignment.CenterVertically,+                        ) {+                            infoBoxes()+                        }+                        Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {+                            board(Modifier.fillMaxSize())+                        }                         status()-                        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) { actionButtons() }+                        Row(+                            modifier = Modifier.fillMaxWidth(),+                            horizontalArrangement = Arrangement.SpaceEvenly,+                            verticalAlignment = Alignment.CenterVertically,+                        ) {+                            actionButtons()+                        }                     }                 }             }@@ -121,6 +182,17 @@ private fun StatusLine(state: GameBoardUiState) { }  @Composable-private fun RestartConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) {-    ConfirmDialog(title = stringResource(R.string.restart_confirm_title), message = stringResource(R.string.restart_confirm_message), confirmLabel = stringResource(UiR.string.restart), dismissLabel = stringResource(UiR.string.cancel), destructive = true, onConfirm = onConfirm, onDismiss = onDismiss)+private fun RestartConfirmDialog(+    onConfirm: () -> Unit,+    onDismiss: () -> Unit,+) {+    ConfirmDialog(+        title = stringResource(R.string.restart_confirm_title),+        message = stringResource(R.string.restart_confirm_message),+        confirmLabel = stringResource(UiR.string.restart),+        dismissLabel = stringResource(UiR.string.cancel),+        destructive = true,+        onConfirm = onConfirm,+        onDismiss = onDismiss,+    ) }
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameScreen.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameScreen.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameScreen.ktindex 206ae912cd..e543711f19 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameScreen.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameScreen.kt@@ -18,7 +18,12 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack  @Composable-fun GameScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, packIndex: Int, levelIndex: Int) {+fun GameScreen(+    backStack: NavBackStack<Route>,+    viewModel: PipesViewModel,+    packIndex: Int,+    levelIndex: Int,+) {     val uiState by viewModel.uiState.collectAsState()     val packStats by viewModel.levelStats.collectAsState()     val dailyStats by viewModel.dailyStats.collectAsState()@@ -27,13 +32,62 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, packIn     val isDaily = packIndex == PipesViewModel.DAILY_PACK_INDEX     // A restored back stack can carry a pack index this build no longer     // has; treat it like a not-yet-loaded pack instead of crashing.-    val levels = if (isDaily) dailyPack?.levels else LevelPack.PACKS.getOrNull(packIndex)?.levels+    val levels = if (isDaily) dailyPack?.levels else LevelPack.packs.getOrNull(packIndex)?.levels     val levelStats = if (isDaily) dailyStats else packStats     LaunchedEffect(isDaily) { if (isDaily) viewModel.refreshDaily() }     LaunchedEffect(packIndex, levelIndex, levels) { viewModel.loadLevel(packIndex, levelIndex) }     val levelData = levels?.getOrNull(levelIndex)-    if (levels == null || levelData == null) { Box(Modifier.fillMaxSize(), Alignment.Center) { Text("Loading\u2026") }; return }+    if (levels == null ||+        levelData == null+    ) {+        Box(Modifier.fillMaxSize(), Alignment.Center) { Text("Loading\u2026") }+        return+    }     val isReady = uiState.packIndex == packIndex && uiState.levelIndex == levelIndex && uiState.levelData != null     val currentLevelStats = levelStats[levelData.id]-    GameBoardScreen(state = GameBoardUiState(levelData = if (isReady) uiState.levelData!! else levelData, levelIndex = levelIndex, maxLevelIndex = levels.lastIndex, gameState = if (isReady) uiState.gameState else PipesGameState(), activeColor = if (isReady && uiState.leftStart) uiState.activeColor else null, activePath = if (isReady) uiState.activePath else emptyList(), isLevelWon = isReady && uiState.isLevelWon, isCompleted = currentLevelStats != null, colorblind = colorblind, moves = if (isReady) viewModel.getCurrentMoves() else 0, bestScore = currentLevelStats?.bestScore, canUndo = isReady && uiState.history.isNotEmpty(), showFillHint = isReady && !uiState.isLevelWon && uiState.activeColor == null && BoardStatus.needsFill(levelData, uiState.gameState)), actions = viewModel, onBack = { backStack.pop() }, onBackToPacks = { while (backStack.backStack.size > 1 && backStack.last() !is Route.PackSelector) backStack.pop() }, onLevelChange = { newIndex -> val clamped = newIndex.coerceIn(0, levels.lastIndex); backStack.setLast(if (isDaily) Route.DailyGame(clamped) else Route.Game(packIndex, clamped)) })+    GameBoardScreen(+        state =+            GameBoardUiState(+                levelData = if (isReady) uiState.levelData!! else levelData,+                levelIndex = levelIndex,+                maxLevelIndex = levels.lastIndex,+                gameState = if (isReady) uiState.gameState else PipesGameState(),+                activeColor =+                    if (isReady &&+                        uiState.leftStart+                    ) {+                        uiState.activeColor+                    } else {+                        null+                    },+                activePath = if (isReady) uiState.activePath else emptyList(),+                isLevelWon =+                    isReady && uiState.isLevelWon,+                isCompleted = currentLevelStats != null,+                colorblind = colorblind,+                moves = if (isReady) viewModel.getCurrentMoves() else 0,+                bestScore = currentLevelStats?.bestScore,+                canUndo =+                    isReady && uiState.history.isNotEmpty(),+                showFillHint =+                    isReady &&+                        !uiState.isLevelWon &&+                        uiState.activeColor == null &&+                        BoardStatus.needsFill(levelData, uiState.gameState),+            ),+        actions = viewModel,+        onBack = { backStack.pop() },+        onBackToPacks = {+            while (backStack.backStack.size >+                1 &&+                backStack.last() !is Route.PackSelector+            ) {+                backStack.pop()+            }+        },+        onLevelChange = { newIndex ->+            val clamped = newIndex.coerceIn(0, levels.lastIndex)+            backStack.setLast(if (isDaily) Route.DailyGame(clamped) else Route.Game(packIndex, clamped))+        },+    ) }
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/LevelScreen.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/LevelScreen.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/LevelScreen.ktindex 1062c86878..ab05d2e07f 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/LevelScreen.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/LevelScreen.kt@@ -26,23 +26,28 @@ import com.vayunmathur.games.pipes.data.LevelPack import com.vayunmathur.games.pipes.platform.PipesViewModel import com.vayunmathur.games.pipes.ui.components.LevelThumbnail import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CardDefaults import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconStar+import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.LevelStats import com.vayunmathur.library.util.NavBackStack  @OptIn(ExperimentalMaterial3Api::class) @Composable-fun LevelScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, packIndex: Int) {+fun LevelScreen(+    backStack: NavBackStack<Route>,+    viewModel: PipesViewModel,+    packIndex: Int,+) {     // See GameScreen: a stale restored pack index must not crash composition.-    val pack = LevelPack.PACKS.getOrNull(packIndex) ?: run {-        Box(Modifier.fillMaxSize(), Alignment.Center) { Text("Loading\u2026") }-        return-    }+    val pack =+        LevelPack.packs.getOrNull(packIndex) ?: run {+            Box(Modifier.fillMaxSize(), Alignment.Center) { Text("Loading\u2026") }+            return+        }     val levelStats by viewModel.levelStats.collectAsState()     AppScaffold(         title = stringResource(R.string.level_selector),@@ -51,12 +56,14 @@ fun LevelScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, packI         LazyVerticalGrid(             GridCells.Adaptive(GRID_CELL_MIN_DP.dp),             Modifier.fillMaxSize(),-            contentPadding = paddingValues + PaddingValues(-                start = GRID_PADDING_DP.dp,-                top = GRID_PADDING_DP.dp,-                end = GRID_PADDING_DP.dp,-                bottom = 0.dp,-            ),+            contentPadding =+                paddingValues ++                    PaddingValues(+                        start = GRID_PADDING_DP.dp,+                        top = GRID_PADDING_DP.dp,+                        end = GRID_PADDING_DP.dp,+                        bottom = 0.dp,+                    ),             verticalArrangement = Arrangement.spacedBy(GRID_SPACING_DP.dp),             horizontalArrangement = Arrangement.spacedBy(GRID_SPACING_DP.dp),         ) {@@ -81,9 +88,10 @@ private fun LevelCell( ) {     Card(         Modifier.fillMaxWidth().clickable(onClick = onOpen),-        colors = CardDefaults.cardColors(-            com.vayunmathur.library.ui.MaterialTheme.colorScheme.surface,-        ),+        colors =+            CardDefaults.cardColors(+                com.vayunmathur.library.ui.MaterialTheme.colorScheme.surface,+            ),     ) {         Box(Modifier.fillMaxSize().padding(CELL_PADDING_DP.dp)) {             if (levelData.cells.size < levelData.rows * levelData.cols) {
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackListScreen.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackListScreen.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackListScreen.ktindex d1493802ad..0cbd29acba 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackListScreen.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackListScreen.kt@@ -10,29 +10,72 @@ import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.games.pipes.R import com.vayunmathur.games.pipes.platform.DailyProgress import com.vayunmathur.games.pipes.platform.PackProgress-import com.vayunmathur.library.ui.game.DailyChallengeCard-import com.vayunmathur.library.ui.game.GameTopBarActions import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CardDefaults import com.vayunmathur.library.ui.DetailLazyColumn import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.game.DailyChallengeCard+import com.vayunmathur.library.ui.game.GameTopBarActions  @OptIn(ExperimentalMaterial3Api::class) @Composable-fun PackListScreen(packs: List<PackProgress>, onOpenPack: (Int) -> Unit, onOpenSettings: () -> Unit, onOpenGameCenter: () -> Unit, daily: DailyProgress? = null, onOpenDaily: () -> Unit = {}) {-    DetailLazyColumn(title = stringResource(R.string.pack_selector), actions = { GameTopBarActions(onOpenGameCenter = onOpenGameCenter, onOpenSettings = onOpenSettings) }) {-        daily?.let { item { DailyChallengeCard(day = it.day, completed = it.completed, total = it.total, streak = it.streak, onOpen = onOpenDaily) } }-        itemsIndexed(packs) { index, pack -> Card(Modifier.clickable { onOpenPack(index) }, colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface)) { Row(Modifier.fillMaxWidth().padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { Column { Text(pack.name, style = MaterialTheme.typography.headlineMedium); Text(pack.shape.replaceFirstChar { it.uppercase() }, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)) }; Text("${pack.completed}/${pack.total}", style = MaterialTheme.typography.titleMedium) } } }+fun PackListScreen(+    packs: List<PackProgress>,+    onOpenPack: (Int) -> Unit,+    onOpenSettings: () -> Unit,+    onOpenGameCenter: () -> Unit,+    daily: DailyProgress? = null,+    onOpenDaily: () -> Unit = {},+) {+    DetailLazyColumn(title = stringResource(R.string.pack_selector), actions = {+        GameTopBarActions(onOpenGameCenter = onOpenGameCenter, onOpenSettings = onOpenSettings)+    }) {+        daily?.let {+            item {+                DailyChallengeCard(+                    day = it.day,+                    completed = it.completed,+                    total = it.total,+                    streak = it.streak,+                    onOpen = onOpenDaily,+                )+            }+        }+        itemsIndexed(packs) { index, pack ->+            Card(+                Modifier.clickable {+                    onOpenPack(index)+                },+                colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface),+            ) {+                Row(+                    Modifier.fillMaxWidth().padding(16.dp),+                    horizontalArrangement = Arrangement.SpaceBetween,+                    verticalAlignment = Alignment.CenterVertically,+                ) {+                    Column {+                        Text(pack.name, style = MaterialTheme.typography.headlineMedium)+                        Text(+                            pack.shape.replaceFirstChar {+                                it.uppercase()+                            },+                            style = MaterialTheme.typography.bodyMedium,+                            color =+                                MaterialTheme.colorScheme.onSurface.copy(+                                    alpha = 0.6f,+                                ),+                        )+                    }+                    Text("${pack.completed}/${pack.total}", style = MaterialTheme.typography.titleMedium)+                }+            }+        }     } }
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackScreen.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackScreen.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackScreen.ktindex 44813bdc1e..4cb9382810 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackScreen.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PackScreen.kt@@ -12,14 +12,35 @@ import com.vayunmathur.games.pipes.platform.PipesViewModel import com.vayunmathur.library.util.NavBackStack  @Composable-fun PackScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel, onOpenGameCenter: () -> Unit) {+fun PackScreen(+    backStack: NavBackStack<Route>,+    viewModel: PipesViewModel,+    onOpenGameCenter: () -> Unit,+) {     val levelStats by viewModel.levelStats.collectAsState()     val dailyCompleted by viewModel.dailyCompleted.collectAsState()     val dailyDay by viewModel.dailyDay.collectAsState()     val dailyStreak by viewModel.dailyStreak.collectAsState()     PackListScreen(-        daily = DailyProgress(day = dailyDay, completed = dailyCompleted, total = DailyLevels.LEVELS_PER_DAY, streak = dailyStreak),-        packs = LevelPack.PACKS.map { pack -> PackProgress(name = pack.name, shape = pack.shape, completed = pack.levels.count { levelStats.containsKey(it.id) }, total = pack.levels.size) },+        daily =+            DailyProgress(+                day = dailyDay,+                completed = dailyCompleted,+                total = DailyLevels.LEVELS_PER_DAY,+                streak = dailyStreak,+            ),+        packs =+            LevelPack.packs.map { pack ->+                PackProgress(+                    name = pack.name,+                    shape = pack.shape,+                    completed =+                        pack.levels.count {+                            levelStats.containsKey(it.id)+                        },+                    total = pack.levels.size,+                )+            },         onOpenDaily = { backStack.add(Route.DailySelector) },         onOpenPack = { backStack.add(Route.LevelSelector(it)) },         onOpenSettings = { backStack.add(Route.Settings) },
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeColors.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeColors.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeColors.ktindex 3d9e66c2c7..974b593081 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeColors.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeColors.kt@@ -9,29 +9,30 @@ import androidx.compose.ui.graphics.Color  * the first 17 is now about 12 dE00 apart (Bright Teal/Cyan); the previous order put  * Blue/Light Blue (7.6) and Green/Lime (10) in the same board.  */-val PIPE_COLORS = listOf(-    Color(0xFFE53935),   // Red-    Color(0xFF43A047),   // Green-    Color(0xFF1E88E5),   // Blue-    Color(0xFFFDD835),   // Yellow-    Color(0xFF00E5FF),   // Bright Cyan-    Color(0xFFFF8F00),   // Orange-    Color(0xFFAB47BC),   // Magenta-    Color(0xFF26A69A),   // Bright Teal-    Color(0xFF9E9D24),   // Olive-    Color(0xFFEC407A),   // Pink-    Color(0xFF3949AB),   // Indigo-    Color(0xFF8D6E63),   // Maroon-    Color(0xFF546E7A),   // Blue Grey-    Color(0xFFFFB300),   // Amber-    Color(0xFFC0CA33),   // Chartreuse-    Color(0xFF00ACC1),   // Cyan-    Color(0xFF6D4C41),   // Brown-    Color(0xFFF4511E),   // Deep Orange-    Color(0xFF7CB342),   // Lime-    Color(0xFF00897B),   // Teal-    Color(0xFF8E24AA),   // Purple-    Color(0xFF5E35B1),   // Deep Purple-    Color(0xFFD81B60),   // Raspberry-    Color(0xFF039BE5),   // Light Blue-)+val PIPE_COLORS =+    listOf(+        Color(0xFFE53935), // Red+        Color(0xFF43A047), // Green+        Color(0xFF1E88E5), // Blue+        Color(0xFFFDD835), // Yellow+        Color(0xFF00E5FF), // Bright Cyan+        Color(0xFFFF8F00), // Orange+        Color(0xFFAB47BC), // Magenta+        Color(0xFF26A69A), // Bright Teal+        Color(0xFF9E9D24), // Olive+        Color(0xFFEC407A), // Pink+        Color(0xFF3949AB), // Indigo+        Color(0xFF8D6E63), // Maroon+        Color(0xFF546E7A), // Blue Grey+        Color(0xFFFFB300), // Amber+        Color(0xFFC0CA33), // Chartreuse+        Color(0xFF00ACC1), // Cyan+        Color(0xFF6D4C41), // Brown+        Color(0xFFF4511E), // Deep Orange+        Color(0xFF7CB342), // Lime+        Color(0xFF00897B), // Teal+        Color(0xFF8E24AA), // Purple+        Color(0xFF5E35B1), // Deep Purple+        Color(0xFFD81B60), // Raspberry+        Color(0xFF039BE5), // Light Blue+    )
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.ktindex 6afbe0520d..da7b79cf5d 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/PipeRenderer.kt@@ -15,29 +15,42 @@ enum class Direction { UP, DOWN, LEFT, RIGHT } /** Six pipe exits for pointy-top hex cells (screen coords, y down): E=0°, SE=60°, SW=120°, W=180°, NW=240°, NE=300°. */ enum class HexDirection { E, SE, SW, W, NW, NE } -fun hexDirectionBetween(fromX: Float, fromY: Float, toX: Float, toY: Float): HexDirection {+fun hexDirectionBetween(+    fromX: Float,+    fromY: Float,+    toX: Float,+    toY: Float,+): HexDirection {     val angle = Math.toDegrees(kotlin.math.atan2((toY - fromY).toDouble(), (toX - fromX).toDouble()))     val sector = ((kotlin.math.floor((angle + 30) / 60).toInt() % 6) + 6) % 6     return HexDirection.entries[sector] } -private fun hexCorner(hexCenter: Offset, radius: Float, index: Int): Offset {+private fun hexCorner(+    hexCenter: Offset,+    radius: Float,+    index: Int,+): Offset {     // Pointy-top vertices at 270° (top) + k*60°.     val angle = Math.toRadians((270 + index * 60).toDouble())     return Offset(         (hexCenter.x + radius * kotlin.math.cos(angle)).toFloat(),-        (hexCenter.y + radius * kotlin.math.sin(angle)).toFloat()+        (hexCenter.y + radius * kotlin.math.sin(angle)).toFloat(),     ) } -fun DrawScope.drawHexCell(hexCenter: Offset, radius: Float) {-    val path = androidx.compose.ui.graphics.Path().apply {-        for (i in 0 until 6) {-            val p = hexCorner(hexCenter, radius, i)-            if (i == 0) moveTo(p.x, p.y) else lineTo(p.x, p.y)+fun DrawScope.drawHexCell(+    hexCenter: Offset,+    radius: Float,+) {+    val path =+        androidx.compose.ui.graphics.Path().apply {+            for (i in 0 until 6) {+                val p = h

Diff truncated.