Modern Apps git

← Modern-Apps.git

Logic Gate: gated DAG progression with vertical timeline

Commit
d0ac71c1a02db73ffaec34fcac52ea3dea0ba463
Author
Vayun Mathur <[email protected]>
When
2026-07-22 20:50 UTC (4 months ago)
Parents
1119a08
- DAG PREREQS: max 2 open levels at any time via Levels.prereqs
  branches: NOR/XNOR (after XOR), DMUX/MUX4 (after MUX), FULL_ADDER/ADDER_4 (after HALF_ADDER)
- timelineRows defines vertical layout, 1 or 2 circles per row
- ProgressionScreen: vertically scrollable Scaffold with TopAppBar + achievements star (standard game pattern)
  - Thick 10dp rounded bar per chapter (FOUNDATION/ROUTING/ARITH/MEMORY/CPU) with name + progress counter
  - Circular level nodes (68dp) showing name, PLAY/LOCK/★★★, NAND cost or prereq hint
  - Canvas connectors: RowToRow, MergeIntoChapter, BranchOutOfChapter
    teal #7FD8BE when prereq satisfied/completed, dark #374151 when locked, 6px thick
  - Locked nodes non-clickable, available/completed open Game(levelId)
- Route now: Progression (root) -> Game -> GameCenter, no more chapter selector list
- Achievements fixed to count per chapter + optimal_5 via actual DAG progress, standard GameCenterScreen with AppBackupAgent
- Verifies at most 2 parallel open via design

Diff

games/logicgate/src/main/assets/achievements.json
diff --git a/games/logicgate/src/main/assets/achievements.json b/games/logicgate/src/main/assets/achievements.jsonindex 70e66a269f..f1c00cdb06 100644--- a/games/logicgate/src/main/assets/achievements.json+++ b/games/logicgate/src/main/assets/achievements.json@@ -1,15 +1,10 @@ [   {"id": "first_gate", "name": "First Light", "description": "Complete your first gate"},-  {"id": "not_complete", "name": "Inverter", "description": "Build NOT from NAND"},-  {"id": "and_complete", "name": "Conjunction", "description": "Build AND"},-  {"id": "or_complete", "name": "Disjunction", "description": "Build OR"},-  {"id": "xor_complete", "name": "Difference Engine", "description": "Build XOR"},-  {"id": "foundation_complete", "name": "Foundation", "description": "Complete Foundation chapter", "targetProgress": 6},-  {"id": "routing_complete", "name": "Router", "description": "Complete Routing chapter", "targetProgress": 3},-  {"id": "arith_complete", "name": "Arithmetician", "description": "Complete Arithmetic chapter", "targetProgress": 4},-  {"id": "memory_complete", "name": "Mnemosyne", "description": "Complete Memory chapter", "targetProgress": 3},-  {"id": "all_levels", "name": "NAND to CPU", "description": "Build the 8-bit CPU", "targetProgress": 18},-  {"id": "optimal_not", "name": "Optimal NOT", "description": "NOT with optimal NANDs"},-  {"id": "optimal_xor", "name": "Optimal XOR", "description": "XOR with optimal NANDs"},-  {"id": "cpu_complete", "name": "Computer", "description": "Complete CPU level"}+  {"id": "foundation_complete", "name": "Foundation", "description": "Complete Foundation chapter (6 levels)", "targetProgress": 6},+  {"id": "routing_complete", "name": "Router", "description": "Complete Routing chapter (3 levels)", "targetProgress": 3},+  {"id": "arith_complete", "name": "Arithmetician", "description": "Complete Arithmetic chapter (4 levels)", "targetProgress": 4},+  {"id": "memory_complete", "name": "Mnemosyne", "description": "Complete Memory chapter (3 levels)", "targetProgress": 3},+  {"id": "cpu_complete", "name": "CPU Architect", "description": "Complete CPU chapter (2 levels)", "targetProgress": 2},+  {"id": "optimal_5", "name": "Perfectionist", "description": "Build 5 levels with optimal NAND count", "targetProgress": 5},+  {"id": "all_levels", "name": "NAND to CPU", "description": "Complete all 18 levels and build the 8-bit CPU", "targetProgress": 18} ]
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.ktindex 704ff5a0d5..20c8a1e224 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt@@ -5,20 +5,33 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.background-import androidx.compose.foundation.layout.*+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.*+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import com.vayunmathur.games.logicgate.data.Levels-import com.vayunmathur.games.logicgate.ui.ChapterListScreen import com.vayunmathur.games.logicgate.ui.CircuitCanvas import com.vayunmathur.games.logicgate.ui.InventoryBar import com.vayunmathur.games.logicgate.ui.LogicGateTheme+import com.vayunmathur.games.logicgate.ui.ProgressionScreen import com.vayunmathur.games.logicgate.ui.TruthTableView import com.vayunmathur.games.logicgate.util.AppBackupAgent import com.vayunmathur.games.logicgate.util.EvalStatus@@ -26,9 +39,9 @@ import com.vayunmathur.games.logicgate.util.LogicViewModel import com.vayunmathur.library.ui.AchievementNotification import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBar@@ -53,31 +66,25 @@ class MainActivity : ComponentActivity() {  @Serializable sealed interface Route : NavKey {-    @Serializable data object Chapters : Route-    @Serializable data class LevelList(val chapterName: String) : Route-    @Serializable data class Game(val levelId: String) : Route-    @Serializable data object GameCenter : Route+    @Serializable+    data object Progression : Route++    @Serializable+    data class Game(val levelId: String) : Route++    @Serializable+    data object GameCenter : Route }  @Composable fun Navigation(viewModel: LogicViewModel) {-    val backStack = rememberNavBackStack<Route>(Route.Chapters)+    val backStack = rememberNavBackStack<Route>(Route.Progression)     val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState() -    LaunchedEffect(Unit) {-        viewModel.nextLevelEvent.collect { nextId ->-            // auto advance? show snackbar-ish – for now do nothing auto, let user click next-        }-    }-     Box(Modifier.fillMaxSize()) {         MainNavigation(backStack) {-            entry<Route.Chapters> {-                ChapterListScreen(backStack, viewModel)-            }-            entry<Route.LevelList> {-                val cid = try { com.vayunmathur.games.logicgate.data.ChapterId.valueOf(it.chapterName) } catch (_: Exception) { com.vayunmathur.games.logicgate.data.ChapterId.FOUNDATION }-                com.vayunmathur.games.logicgate.ui.LevelListScreen(cid, backStack, viewModel)+            entry<Route.Progression> {+                ProgressionScreen(backStack, viewModel)             }             entry<Route.Game> {                 GameScreen(backStack, viewModel, it.levelId)@@ -90,12 +97,16 @@ fun Navigation(viewModel: LogicViewModel) {                 )             }         }+         newAchievement?.let {-            AchievementNotification(it) { viewModel.dismissAchievement() }+            AchievementNotification(it) {+                viewModel.dismissAchievement()+            }         }     } } +@OptIn(ExperimentalMaterial3Api::class) @Composable fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelId: String) {     val level = Levels.get(levelId)@@ -107,7 +118,6 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI         viewModel.selectLevel(levelId)     } -    // If current loaded level mismatches, loading     val isCurrent = uiState.currentLevelId == levelId      Scaffold(@@ -134,7 +144,10 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI         }     ) { padding ->         if (!isCurrent) {-            Box(Modifier.fillMaxSize().padding(padding), contentAlignment = androidx.compose.ui.Alignment.Center) {+            Box(+                Modifier.fillMaxSize().padding(padding),+                contentAlignment = androidx.compose.ui.Alignment.Center+            ) {                 Text("Loading...")             }             return@Scaffold@@ -143,23 +156,26 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI         Column(             Modifier.fillMaxSize().padding(padding).background(Color(0xFF0B1218))         ) {-            // Status bar             val status = uiState.evalStatus             val statusText = when (status) {-                is EvalStatus.Ok -> if (status.isFullyCorrect) "✓ CORRECT — ${uiState.circuit.gates.sumOf { com.vayunmathur.games.logicgate.data.ChipLibrary.get(it.chipId).nandCost }}N / ${level.optimalNands}N optimal" else "${status.passingRows}/${status.totalRows} passing — ${status.failingRows.size} failing"+                is EvalStatus.Ok -> if (status.isFullyCorrect) "✓ CORRECT — ${uiState.circuit.gates.sumOf { com.vayunmathur.games.logicgate.data.ChipLibrary.get(it.chipId).nandCost }}N / ${level.optimalNands}N optimal"+                else "${status.passingRows}/${status.totalRows} passing — ${status.failingRows.size} failing"+                 is EvalStatus.Error -> "Error: ${status.msg}"-                is EvalStatus.Cycle -> "Cycle detected: ${status.ids.take(3).joinToString()}"-                else -> "Wire inputs → gates → outputs"+                is EvalStatus.Cycle -> "Cycle: ${status.ids.take(3).joinToString()}"+                else -> "Wire inputs → gates → outputs • Drag to move • Long-press to delete"             }             val statusColor = when {                 status is EvalStatus.Ok && status.isFullyCorrect -> Color(0xFF22C55E)                 status is EvalStatus.Ok && status.passingRows > 0 -> Color(0xFFFBBF24)                 else -> Color(0xFF94A3B8)             }+             Box(-                Modifier.fillMaxWidth().background(Color(0xFF16202B)).padding(horizontal = 12.dp, vertical = 6.dp)+                Modifier.fillMaxWidth().background(Color(0xFF16202B))+                    .padding(horizontal = 12.dp, vertical = 6.dp)             ) {-                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+                Row(Modifier.fillMaxWidth(), horizontalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceBetween) {                     Column(Modifier.weight(1f)) {                         Text(statusText, fontSize = 12.sp, color = statusColor)                         Text(level.description, fontSize = 10.sp, color = Color(0xFF94A3B8))@@ -167,7 +183,7 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                             Text("Hint: ${level.hint}", fontSize = 10.sp, color = Color(0xFF64748B))                         }                     }-                    Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+                    Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {                         Button(onClick = { viewModel.clearCircuit() }) { Text("Clear", fontSize = 10.sp) }                         if (uiState.wiringFrom != null) {                             Button(onClick = { viewModel.cancelWiring() }) { Text("Cancel Wire", fontSize = 10.sp) }@@ -180,32 +196,58 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                 }             } -            Row(Modifier.weight(1f).fillMaxWidth()) {-                // Canvas scrollable area-                Box(-                    Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState())-                ) {-                    CircuitCanvas(-                        level = level,-                        gates = uiState.circuit.gates,-                        wires = uiState.circuit.wires,-                        outputMaps = uiState.circuit.outputMappings,-                        wiringFrom = uiState.wiringFrom,-                        onStartWiringOutput = { viewModel.startWiring(it) },-                        onCompleteWiringInput = { viewModel.completeWiring(it) },-                        onGateDrag = { id, x, y -> viewModel.onGateMoved(id, x, y) },-                        onGateLongPress = { id -> viewModel.removeGate(id) },-                        modifier = Modifier.fillMaxWidth().height(900.dp)-                    )-                }--                if (uiState.showTruthTable) {-                    val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()-                    TruthTableView(-                        level = level,-                        failingRows = failing,-                        modifier = Modifier.width(200.dp).fillMaxHeight().background(Color(0xFF0E141B))-                    )+            BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {+                val wide = maxWidth > maxHeight+                if (wide) {+                    Row(Modifier.fillMaxSize()) {+                        Box(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState())) {+                            CircuitCanvas(+                                level = level,+                                gates = uiState.circuit.gates,+                                wires = uiState.circuit.wires,+                                outputMaps = uiState.circuit.outputMappings,+                                wiringFrom = uiState.wiringFrom,+                                onStartWiringOutput = { viewModel.startWiring(it) },+                                onCompleteWiringInput = { viewModel.completeWiring(it) },+                                onGateDrag = { id, x, y -> viewModel.onGateMoved(id, x, y) },+                                onGateLongPress = { id -> viewModel.removeGate(id) },+                                modifier = Modifier.fillMaxWidth().height(900.dp)+                            )+                        }+                        if (uiState.showTruthTable) {+                            val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()+                            TruthTableView(+                                level = level,+                                failingRows = failing,+                                modifier = Modifier.width(210.dp).fillMaxHeight().background(Color(0xFF0E141B))+                            )+                        }+                    }+                } else {+                    Column(Modifier.fillMaxSize()) {+                        if (uiState.showTruthTable) {+                            val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()+                            TruthTableView(+                                level = level,+                                failingRows = failing,+                                modifier = Modifier.fillMaxWidth().height(180.dp).background(Color(0xFF0E141B))+                            )+                        }+                        Box(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {+                            CircuitCanvas(+                                level = level,+                                gates = uiState.circuit.gates,+                                wires = uiState.circuit.wires,+                                outputMaps = uiState.circuit.outputMappings,+                                wiringFrom = uiState.wiringFrom,+                                onStartWiringOutput = { viewModel.startWiring(it) },+                                onCompleteWiringInput = { viewModel.completeWiring(it) },+                                onGateDrag = { id, x, y -> viewModel.onGateMoved(id, x, y) },+                                onGateLongPress = { id -> viewModel.removeGate(id) },+                                modifier = Modifier.fillMaxWidth().height(900.dp)+                            )+                        }+                    }                 }             }         }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.ktindex 52fff5962c..3ee5e88a1b 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt@@ -1,9 +1,8 @@ package com.vayunmathur.games.logicgate.data  /**- * Level progression: NAND -> foundations -> routing -> arithmetic -> memory -> CPU- * Each level defines I/O interface and expected truth table computed from reference chip.- * Player must wire available chips to satisfy that truth table with minimal NAND cost.+ * Level progression DAG: max 2 open at any time, chapters separated.+ * Prereqs define unlock. Visual layout rows defined below for timeline.  */  enum class ChapterId { FOUNDATION, ROUTING, ARITH, MEMORY, CPU }@@ -21,125 +20,125 @@ data class LevelDef(     val chapter: ChapterId,     val description: String,     val hint: String,-    /** inputs exposed to player circuit (names) */     val inputs: List<String>,-    /** outputs expected (names) */     val outputs: List<String>,-    /** underlying target chip whose truth table we validate against */     val targetChipId: String,-    /** chips allowed in inventory (including NAND always) - unlocked chips */     val allowedChipIds: List<String>,-    /** optimal flattened NAND count for 3 stars */     val optimalNands: Int,-    /** narrative */     val flavor: String = "",-    /** wether this level IS the gate introduction (unlocks its chip) */-    val unlocksChipId: String? = null+    val unlocksChipId: String? = null,+    val prereqs: List<String> = emptyList() )  object Levels {     val all: List<LevelDef> = listOf(-        // FOUNDATION         LevelDef(             id = "NOT",-            displayName = "NOT Gate",+            displayName = "NOT",             chapter = ChapterId.FOUNDATION,-            description = "Build NOT using only NAND. Output is inverse of input.",-            hint = "Tie both NAND inputs together: NAND(in,in) = NOT(in)",+            description = "Build NOT using only NAND.",+            hint = "NAND(in,in) = NOT(in)",             inputs = listOf("in"),             outputs = listOf("out"),             targetChipId = "NOT",             allowedChipIds = listOf("NAND"),             optimalNands = 1,-            flavor = "Everything starts with NAND. Can you make the simplest gate?",-            unlocksChipId = "NOT"+            flavor = "Everything starts with NAND.",+            unlocksChipId = "NOT",+            prereqs = emptyList()         ),         LevelDef(             id = "AND",-            displayName = "AND Gate",+            displayName = "AND",             chapter = ChapterId.FOUNDATION,             description = "Build AND: out = a & b",-            hint = "NAND then NOT. Or NAND(a,b) -> invert.",+            hint = "NAND then NOT.",             inputs = listOf("a", "b"),             outputs = listOf("out"),             targetChipId = "AND",             allowedChipIds = listOf("NAND", "NOT"),             optimalNands = 2,-            flavor = "NOT unlocked! Now combine to get AND.",-            unlocksChipId = "AND"+            flavor = "NOT unlocked! Now combine.",+            unlocksChipId = "AND",+            prereqs = listOf("NOT")         ),         LevelDef(             id = "OR",-            displayName = "OR Gate",+            displayName = "OR",             chapter = ChapterId.FOUNDATION,             description = "Build OR: out = a | b",-            hint = "De Morgan: OR = NOT(NOT a AND NOT b) = NAND(NOT a, NOT b)",+            hint = "De Morgan: NAND(NOT a, NOT b)",             inputs = listOf("a", "b"),             outputs = listOf("out"),             targetChipId = "OR",             allowedChipIds = listOf("NAND", "NOT", "AND"),             optimalNands = 3,             flavor = "De Morgan is your friend.",-            unlocksChipId = "OR"+            unlocksChipId = "OR",+            prereqs = listOf("AND")         ),         LevelDef(             id = "XOR",-            displayName = "XOR Gate",+            displayName = "XOR",             chapter = ChapterId.FOUNDATION,-            description = "Build XOR: out = a ^ b (different?)",-            hint = "XOR can be 4 NANDs: (a NAND b) NAND (a NAND (a NAND b)) NAND ((a NAND b) NAND b) ...",+            description = "Build XOR: out = a ^ b",+            hint = "4 NANDs tricky build.",             inputs = listOf("a", "b"),             outputs = listOf("out"),             targetChipId = "XOR",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR"),             optimalNands = 4,-            flavor = "The tricky one. XOR is key to addition.",-            unlocksChipId = "XOR"+            flavor = "The key to addition.",+            unlocksChipId = "XOR",+            prereqs = listOf("OR")         ),         LevelDef(             id = "NOR",-            displayName = "NOR Gate",+            displayName = "NOR",             chapter = ChapterId.FOUNDATION,             description = "Build NOR: out = !(a | b)",-            hint = "OR then NOT — or 4 NANDs directly.",+            hint = "OR then NOT.",             inputs = listOf("a", "b"),             outputs = listOf("out"),             targetChipId = "NOR",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR"),             optimalNands = 4,-            unlocksChipId = "NOR"+            unlocksChipId = "NOR",+            prereqs = listOf("XOR")         ),         LevelDef(             id = "XNOR",-            displayName = "XNOR Gate",+            displayName = "XNOR",             chapter = ChapterId.FOUNDATION,-            description = "Build XNOR: equality check",+            description = "Build XNOR: equality",             hint = "XOR then NOT.",             inputs = listOf("a", "b"),             outputs = listOf("out"),             targetChipId = "XNOR",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "NOR"),             optimalNands = 5,-            unlocksChipId = "XNOR"+            unlocksChipId = "XNOR",+            prereqs = listOf("XOR")         ),         // ROUTING         LevelDef(             id = "MUX",-            displayName = "Multiplexer",+            displayName = "MUX",             chapter = ChapterId.ROUTING,-            description = "If sel=0 out=a else out=b",-            hint = "MUX = (a & !sel) | (b & sel)",+            description = "If sel=0 out=a else b",+            hint = "(a & !sel) | (b & sel)",             inputs = listOf("a", "b", "sel"),             outputs = listOf("out"),             targetChipId = "MUX",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR"),             optimalNands = 4,-            flavor = "First routing primitive — choose between two signals.",-            unlocksChipId = "MUX"+            flavor = "Choose between signals.",+            unlocksChipId = "MUX",+            prereqs = listOf("NOR", "XNOR")         ),         LevelDef(             id = "DMUX",-            displayName = "Demux",+            displayName = "DMUX",             chapter = ChapterId.ROUTING,             description = "Route in to a if sel=0 else b",             hint = "a = in & !sel, b = in & sel",@@ -148,157 +147,191 @@ object Levels {             targetChipId = "DMUX",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX"),             optimalNands = 3,-            unlocksChipId = "DMUX"+            unlocksChipId = "DMUX",+            prereqs = listOf("MUX")         ),         LevelDef(             id = "MUX4",-            displayName = "4-Way MUX",+            displayName = "MUX4",             chapter = ChapterId.ROUTING,             description = "sel1 sel0: 00->a 01->b 10->c 11->d",-            hint = "Build from 3 MUXes or direct logic.",+            hint = "3 MUXes.",             inputs = listOf("a", "b", "c", "d", "sel0", "sel1"),             outputs = listOf("out"),             targetChipId = "MUX4",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "DMUX"),             optimalNands = 12,-            unlocksChipId = "MUX4"+            unlocksChipId = "MUX4",+            prereqs = listOf("MUX")         ),         // ARITH         LevelDef(             id = "HALF_ADDER",             displayName = "Half Adder",             chapter = ChapterId.ARITH,-            description = "Add two bits: sum=a^b carry=a&b",-            hint = "You've already built XOR and AND!",+            description = "sum=a^b carry=a&b",+            hint = "XOR + AND",             inputs = listOf("a", "b"),             outputs = listOf("sum", "carry"),             targetChipId = "HALF_ADDER",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX"),             optimalNands = 6,-            flavor = "The start of arithmetic — 1-bit addition without carry in.",-            unlocksChipId = "HALF_ADDER"+            flavor = "1-bit addition.",+            unlocksChipId = "HALF_ADDER",+            prereqs = listOf("DMUX", "MUX4")         ),         LevelDef(             id = "FULL_ADDER",             displayName = "Full Adder",             chapter = ChapterId.ARITH,-            description = "Add with carry: sum=a^b^cin, cout majority.",-            hint = "Use two half-adders + OR for cout, or optimized 14-NAND version.",+            description = "Add with carry",+            hint = "Two half-adders + OR",             inputs = listOf("a", "b", "cin"),             outputs = listOf("sum", "cout"),             targetChipId = "FULL_ADDER",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "HALF_ADDER"),             optimalNands = 14,-            flavor = "Chainable adder — the brick of all binary addition.",-            unlocksChipId = "FULL_ADDER"+            flavor = "Brick of binary addition.",+            unlocksChipId = "FULL_ADDER",+            prereqs = listOf("HALF_ADDER")         ),         LevelDef(             id = "ADDER_4",-            displayName = "4-Bit Adder",+            displayName = "Adder4",             chapter = ChapterId.ARITH,-            description = "Add two 4-bit numbers: a0..a3 + b0..b3",-            hint = "Chain 4 FullAdders ripple-carry style.",+            description = "Add two 4-bit numbers",+            hint = "Chain FullAdders",             inputs = listOf("a0","a1","a2","a3","b0","b1","b2","b3"),             outputs = listOf("s0","s1","s2","s3","cout"),             targetChipId = "ADDER_4",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "HALF_ADDER", "FULL_ADDER"),             optimalNands = 56,-            unlocksChipId = "ADDER_4"+            unlocksChipId = "ADDER_4",+            prereqs = listOf("HALF_ADDER")         ),         LevelDef(             id = "ADDER_8",-            displayName = "8-Bit Adder",+            displayName = "Adder8",             chapter = ChapterId.ARITH,-            description = "Add two 8-bit numbers. Carry out indicates overflow.",-            hint = "Chain 8 FullAdders. Low bits: a0,b0 are LSB.",+            description = "Add two 8-bit numbers",+            hint = "Chain 8 FullAdders",             inputs = (0..7).map { "a$it" } + (0..7).map { "b$it" },             outputs = (0..7).map { "s$it" } + listOf("cout"),             targetChipId = "ADDER_8",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "HALF_ADDER", "FULL_ADDER", "ADDER_4"),             optimalNands = 112,-            flavor = "First 8-bit component! This will be the heart of our CPU.",-            unlocksChipId = "ADDER_8"+            flavor = "Heart of CPU.",+            unlocksChipId = "ADDER_8",+            prereqs = listOf("FULL_ADDER", "ADDER_4")         ),         // MEMORY         LevelDef(             id = "DFF",-            displayName = "D Flip-Flop",+            displayName = "DFF",             chapter = ChapterId.MEMORY,-            description = "On clock tick, Q = D. Foundation of memory.",-            hint = "NAND latch with clock gating. For this simulator, we model combinationally.",+            description = "On tick, Q = D",+            hint = "NAND latch combinational sim.",             inputs = listOf("d", "clk"),             outputs = listOf("q"),             targetChipId = "DFF",             allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX"),             optimalNands = 6,-            flavor = "Time enters the picture. This is how computers remember.",-            unlocksChipId = "DFF"+            flavor = "Time enters.",+            unlocksChipId = "DFF",+            prereqs = listOf("ADDER_8")         ),         LevelDef(             id = "BIT",-            displayName = "1-Bit Register",+            displayName = "Bit",             chapter = ChapterId.MEMORY,-            description = "If load=1 store in, else keep. Out always holds value.",-            hint = "MUX + DFF: MUX picks new or old, DFF stores.",+            description = "If load=1 store in",+            hint = "MUX + DFF",             inputs = listOf("in", "load"),             outputs = listOf("out"),             targetChipId = "BIT",-            allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU_8" && it != "REGISTER_8" && it != "ALU_8" }.toList(),+            allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU_8" && it != "REG_8" && it != "ALU_8" }.toList(),             optimalNands = 12,-            unlocksChipId = "BIT"+            unlocksChipId = "BIT",+            prereqs = listOf("DFF")         ),         LevelDef(             id = "REG_8",-            displayName = "8-Bit Register",+            displayName = "Reg8",             chapter = ChapterId.MEMORY,-            description = "8-bit register with load control. 8 BITs in parallel.",-            hint = "8x BIT sharing load signal.",+            description = "8-bit register with load",+            hint = "8x BIT sharing load",             inputs = (0..7).map { "in$it" } + listOf("load"),             outputs = (0..7).map { "out$it" },             targetChipId = "REG_8",             allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU_8" && it != "ALU_8" }.toList(),             optimalNands = 96,-            unlocksChipId = "REG_8"+            unlocksChipId = "REG_8",+            prereqs = listOf("BIT")         ),         // CPU         LevelDef(             id = "ALU_8",-            displayName = "ALU (8-bit)",+            displayName = "ALU",             chapter = ChapterId.CPU,-            description = "op 00=ADD 01=AND 10=OR 11=XOR, plus zero & carry flags",-            hint = "Mux between ADDER_8, AND, OR, XOR results using op bits.",+            description = "op 00=ADD 01=AND 10=OR 11=XOR + flags",+            hint = "Mux between results",             inputs = (0..7).map { "a$it" } + (0..7).map { "b$it" } + listOf("op0","op1"),             outputs = (0..7).map { "out$it" } + listOf("zero","carry"),             targetChipId = "ALU_8",             allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU_8" }.toList(),             optimalNands = 200,-            flavor = "The brain's calculator — does all logic & arithmetic.",-            unlocksChipId = "ALU_8"+            flavor = "Calculator of CPU.",+            unlocksChipId = "ALU_8",+            prereqs = listOf("REG_8")         ),         LevelDef(             id = "CPU_8",-            displayName = "8-Bit CPU",+            displayName = "CPU",             chapter = ChapterId.CPU,-            description = "Simplified 8-bit CPU: fetch-decode-execute cycle",-            hint = "Combine ALU, Registers, MUX for data paths. This is the capstone!",+            description = "8-bit CPU capstone",+            hint = "ALU + Registers + MUX",             inputs = (0..7).map { "in$it" } + listOf("clk", "reset"),             outputs = (0..7).map { "out$it" } + (0..7).map { "addr$it" } + listOf("write"),             targetChipId = "CPU_8",             allowedChipIds = ChipLibrary.all.keys.toList(),             optimalNands = 2000,-            flavor = "You started with NAND. You now have a computer. Well done.",-            unlocksChipId = "CPU_8"+            flavor = "NAND to computer. Done.",+            unlocksChipId = "CPU_8",+            prereqs = listOf("ALU_8")         )     )      val chapters: List<Chapter> = listOf(-        Chapter(ChapterId.FOUNDATION, "Foundation", "From NAND build the basic gates", all.filter { it.chapter == ChapterId.FOUNDATION }.map { it.id }),-        Chapter(ChapterId.ROUTING, "Routing", "Select and steer signals", all.filter { it.chapter == ChapterId.ROUTING }.map { it.id }),+        Chapter(ChapterId.FOUNDATION, "Foundation", "Build basic gates", all.filter { it.chapter == ChapterId.FOUNDATION }.map { it.id }),+        Chapter(ChapterId.ROUTING, "Routing", "Steer signals", all.filter { it.chapter == ChapterId.ROUTING }.map { it.id }),         Chapter(ChapterId.ARITH, "Arithmetic", "Make numbers add", all.filter { it.chapter == ChapterId.ARITH }.map { it.id }),-        Chapter(ChapterId.MEMORY, "Memory", "Give your circuit a memory", all.filter { it.chapter == ChapterId.MEMORY }.map { it.id }),-        Chapter(ChapterId.CPU, "CPU", "The final machine", all.filter { it.chapter == ChapterId.CPU }.map { it.id }),+        Chapter(ChapterId.MEMORY, "Memory", "Remember", all.filter { it.chapter == ChapterId.MEMORY }.map { it.id }),+        Chapter(ChapterId.CPU, "CPU", "The machine", all.filter { it.chapter == ChapterId.CPU }.map { it.id }),     )      val byId: Map<String, LevelDef> = all.associateBy { it.id }     fun get(id: String): LevelDef = byId[id] ?: error("Unknown level $id")++    // Timeline rows for progression UI (1 or 2 nodes per row, max 2 open)+    val timelineRows: List<List<String>> = listOf(+        listOf("NOT"),+        listOf("AND"),+        listOf("OR"),+        listOf("XOR"),+        listOf("NOR", "XNOR"),+        listOf("MUX"),+        listOf("DMUX", "MUX4"),+        listOf("HALF_ADDER"),+        listOf("FULL_ADDER", "ADDER_4"),+        listOf("ADDER_8"),+        listOf("DFF"),+        listOf("BIT"),+        listOf("REG_8"),+        listOf("ALU_8"),+        listOf("CPU_8")+    )++    fun availableLevels(completed: Set<String>): Set<String> {+        return all.filter { it.id !in completed && it.prereqs.all { p -> p in completed } }.map { it.id }.toSet()+    } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.ktindex 8c8f10bd72..5a3df6e68f 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt@@ -1,138 +1,517 @@ package com.vayunmathur.games.logicgate.ui +import androidx.compose.foundation.Canvas import androidx.compose.foundation.background+import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.*-import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp+import androidx.compose.ui.res.painterResource+import com.vayunmathur.games.logicgate.data.ChapterId import com.vayunmathur.games.logicgate.data.ChipCategory import com.vayunmathur.games.logicgate.data.ChipLibrary-import com.vayunmathur.games.logicgate.data.Levels-import com.vayunmathur.games.logicgate.data.LevelDef-import com.vayunmathur.games.logicgate.data.ChapterId import com.vayunmathur.games.logicgate.data.CircuitEvaluator+import com.vayunmathur.games.logicgate.data.LevelDef+import com.vayunmathur.games.logicgate.data.Levels+import com.vayunmathur.games.logicgate.util.LogicViewModel import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text-import androidx.compose.runtime.collectAsState-import com.vayunmathur.games.logicgate.util.LogicViewModel+import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.util.NavBackStack+import kotlin.math.min++private sealed class TimelineItem {+    data class ChapterHeader(val chapterId: ChapterId) : TimelineItem()+    data class LevelRow(val levelIds: List<String>) : TimelineItem()+}++private fun buildTimelineItems(): List<TimelineItem> {+    val items = mutableListOf<TimelineItem>()+    var lastChapter: ChapterId? = null+    for (row in Levels.timelineRows) {+        if (row.isEmpty()) continue+        val firstId = row.first()+        val chapter = Levels.byId[firstId]?.chapter ?: continue+        if (chapter != lastChapter) {+            items.add(TimelineItem.ChapterHeader(chapter))+            lastChapter = chapter+        }+        items.add(TimelineItem.LevelRow(row))+    }+    return items+} +@OptIn(ExperimentalMaterial3Api::class) @Composable-fun ChapterListScreen(+fun ProgressionScreen(     backStack: NavBackStack<com.vayunmathur.games.logicgate.Route>,     viewModel: LogicViewModel ) {     val completed by viewModel.completedIds.collectAsState()-    LazyColumn(-        modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(16.dp),-        verticalArrangement = Arrangement.spacedBy(12.dp)-    ) {-        item {-            Text("Logic Gate", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold, modifier = Modifier.padding(vertical = 8.dp))-            Text("Start with NAND. End with a computer.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f))-            Spacer(Modifier.height(4.dp))-            Text("Tap input/output dots to wire • Drag gates to move • Long-press gate to delete", style = MaterialTheme.typography.labelSmall, color = Color(0xFF94A3B8))-            Spacer(Modifier.height(8.dp))-        }-        items(Levels.chapters) { chapter ->-            val doneCount = chapter.levelIds.count { it in completed }-            Card(-                modifier = Modifier.fillMaxWidth().clickable { backStack.add(com.vayunmathur.games.logicgate.Route.LevelList(chapter.id.name)) },-                colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surface)+    val bestNands by viewModel.bestNands.collectAsState()+    val available = Levels.availableLevels(completed)+    val timelineItems = buildTimelineItems()++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("Logic Gate", fontWeight = FontWeight.Bold) },+                actions = {+                    IconButton(onClick = { backStack.add(com.vayunmathur.games.logicgate.Route.GameCenter) }) {+                        Icon(+                            painterResource(id = android.R.drawable.btn_star_big_on),+                            contentDescription = "Achievements"+                        )+                    }+                }+            )+        }+    ) { paddingValues ->+        BoxWithConstraints(+            modifier = Modifier+                .fillMaxSize()+                .padding(paddingValues)+                .background(MaterialTheme.colorScheme.background)+        ) {+            val sideOffset: Dp = 88.dp+            val nodeSize: Dp = 68.dp+            val connectorH: Dp = 38.dp+            val chapterH: Dp = 58.dp+            val scroll = rememberScrollState()++            Column(+                modifier = Modifier+                    .fillMaxSize()+                    .verticalScroll(scroll),+                horizontalAlignment = Alignment.CenterHorizontally             ) {-                Row(-                    modifier = Modifier.fillMaxWidth().padding(16.dp),-                    horizontalArrangement = Arrangement.SpaceBetween,-                    verticalAlignment = Alignment.CenterVertically+                Spacer(Modifier.height(12.dp))+                Text(+                    "Start with NAND. End with a computer.",+                    style = MaterialTheme.typography.bodySmall,+                    color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),+                    modifier = Modifier.padding(horizontal = 16.dp)+                )+                Spacer(Modifier.height(4.dp))+                Text(+                    "Tap to play • Locked levels need prerequisites • Lines show dependencies",+                    style = MaterialTheme.typography.labelSmall,+                    color = Color(0xFF94A3B8),+                    modifier = Modifier.padding(horizontal = 16.dp)+                )+                Spacer(Modifier.height(16.dp))++                for (idx in timelineItems.indices) {+                    val item = timelineItems[idx]+                    when (item) {+                        is TimelineItem.ChapterHeader -> {+                            // Connector from previous row into this chapter bar (merge)+                            if (idx > 0) {+                                val prev = timelineItems[idx - 1]+                                if (prev is TimelineItem.LevelRow) {+                                    // Determine if any next level depends on prev – always draw merge visually+                                    MergeIntoChapterConnector(+                                        fromRow = prev,+                                        sideOffset = sideOffset,+                                        height = connectorH,+                                        completed = completed+                                    )+                                }+                            }++                            ChapterDivider(+                                chapterId = item.chapterId,+                                completedCount = Levels.chapters.find { it.id == item.chapterId }?.levelIds?.count { it in completed } ?: 0,+                                totalCount = Levels.chapters.find { it.id == item.chapterId }?.levelIds?.size ?: 0,+                                modifier = Modifier+                                    .fillMaxWidth()+                                    .height(chapterH)+                                    .padding(horizontal = 12.dp)+                            )++                            // Connector out of chapter into next row+                            if (idx + 1 < timelineItems.size) {+                                val next = timelineItems[idx + 1]+                                if (next is TimelineItem.LevelRow) {+                                    BranchOutOfChapterConnector(+                                        toRow = next,+                                        sideOffset = sideOffset,+                                        height = connectorH,+                                        completed = completed+                                    )+                                }+                            }+                        }++                        is TimelineItem.LevelRow -> {+                            LevelRowContent(+                                row = item,+                                completed = completed,+                                available = available,+                                bestNands = bestNands,+                                nodeSize = nodeSize,+                                sideOffset = sideOffset,+                                onClickLevel = { lvlId ->+                                    if (lvlId in completed || lvlId in available) {+                                        backStack.add(com.vayunmathur.games.logicgate.Route.Game(lvlId))+                                    }+                                }+                            )++                            // Connector to next level row (skip if next is header)+                            if (idx + 1 < timelineItems.size) {+                                val next = timelineItems[idx + 1]+                                if (next is TimelineItem.LevelRow) {+                                    RowToRowConnector(+                                        fromRow = item,+                                        toRow = next,+                                        sideOffset = sideOffset,+                                        height = connectorH,+                                        completed = completed+                                    )+                                }+                            }+                        }+                    }+                }++                Spacer(Modifier.height(24.dp))+                Card(+                    modifier = Modifier+                        .fillMaxWidth()+                        .padding(horizontal = 16.dp)                 ) {-                    Column(Modifier.weight(1f)) {-                        Text(chapter.name, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)-                        Text(chapter.desc, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f))+                    Column(Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {+                        Text(+                            "${completed.size} / ${Levels.all.size} completed",+                            style = MaterialTheme.typography.titleMedium,+                            fontWeight = FontWeight.Bold,+                            color = Color(0xFF7FD8BE)+                        )+                        Spacer(Modifier.height(8.dp))+                        Text(+                            "Progress is gated: you must finish prerequisites to unlock next. At most 2 paths run in parallel (NOR/XNOR, DMUX/MUX4, FULL_ADDER/ADDER_4). Each chapter starts with a thick bar.",+                            style = MaterialTheme.typography.bodySmall,+                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)+                        )                     }-                    Text("$doneCount/${chapter.levelIds.size}", style = MaterialTheme.typography.titleMedium)                 }+                Spacer(Modifier.height(32.dp))             }         }-        item {-            Spacer(Modifier.height(16.dp))-            Button(onClick = { backStack.add(com.vayunmathur.games.logicgate.Route.GameCenter) }, modifier = Modifier.fillMaxWidth()) {-                Text("Achievements")+    }+}++@Composable+private fun ChapterDivider(chapterId: ChapterId, completedCount: Int, totalCount: Int, modifier: Modifier = Modifier) {+    val chapter = Levels.chapters.find { it.id == chapterId } ?: return+    Column(modifier = modifier, verticalArrangement = Arrangement.Center) {+        Box(+            modifier = Modifier+                .fillMaxWidth()+                .height(10.dp)+                .clip(RoundedCornerShape(6.dp))+                .background(Color(0xFF7FD8BE).copy(alpha = 0.95f))+        )+        Spacer(Modifier.height(6.dp))+        Row(+            Modifier.fillMaxWidth(),+            horizontalArrangement = Arrangement.SpaceBetween,+            verticalAlignment = Alignment.CenterVertically+        ) {+            Text(+                "${chapter.name.uppercase()} — ${chapter.desc}",+                fontSize = 13.sp,+                fontWeight = FontWeight.ExtraBold,+                letterSpacing = 0.8.sp,+                color = Color(0xFF7FD8BE),+                modifier = Modifier.padding(start = 4.dp)+            )+            Text(+                "$completedCount/$totalCount",+                fontSize = 11.sp,+                fontWeight = FontWeight.Bold,+                color = Color(0xFF94A3B8)+            )+        }+    }+}++@Composable+private fun LevelRowContent(+    row: TimelineItem.LevelRow,+    completed: Set<String>,+    available: Set<String>,+    bestNands: Map<String, Int>,+    nodeSize: Dp,+    sideOffset: Dp,+    onClickLevel: (String) -> Unit+) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .height(120.dp),+        horizontalArrangement = Arrangement.Center,+        verticalAlignment = Alignment.CenterVertically+    ) {+        if (row.levelIds.size == 1) {+            LevelNode(+                levelId = row.levelIds[0],+                isCompleted = row.levelIds[0] in completed,+                isAvailable = row.levelIds[0] in available,+                bestNand = bestNands[row.levelIds[0]],+                size = nodeSize,+                onClick = onClickLevel+            )+        } else {+            row.levelIds.forEachIndexed { idx, lvlId ->+                LevelNode(+                    levelId = lvlId,+                    isCompleted = lvlId in completed,+                    isAvailable = lvlId in available,+                    bestNand = bestNands[lvlId],+                    size = nodeSize,+                    onClick = onClickLevel+                )+                if (idx == 0) Spacer(Modifier.width(56.dp))             }         }     } }  @Composable-fun LevelListScreen(-    chapterId: ChapterId,-    backStack: NavBackStack<com.vayunmathur.games.logicgate.Route>,-    viewModel: LogicViewModel+private fun LevelNode(+    levelId: String,+    isCompleted: Boolean,+    isAvailable: Boolean,+    bestNand: Int?,+    size: Dp,+    onClick: (String) -> Unit ) {-    val chapter = Levels.chapters.find { it.id == chapterId } ?: return-    val completed by viewModel.completedIds.collectAsState()-    val best by viewModel.bestNands.collectAsState()-    Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {-        Row(Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically) {-            Button(onClick = { backStack.pop() }) { Text("Back") }-            Spacer(Modifier.width(12.dp))-            Text(chapter.name, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)-        }-        LazyColumn(Modifier.fillMaxSize().padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {-            items(chapter.levelIds) { lvlId ->-                val def = Levels.get(lvlId)-                val done = lvlId in completed-                val nands = best[lvlId]-                val isOptimal = done && (nands ?: 999) <= def.optimalNands-                Card(-                    modifier = Modifier.fillMaxWidth().clickable { backStack.add(com.vayunmathur.games.logicgate.Route.Game(lvlId)) },-                    colors = CardDefaults.cardColors(-                        when {-                            isOptimal -> Color(0xFF1B3A2F)-                            done -> Color(0xFF1E2E24)-                            else -> MaterialTheme.colorScheme.surface-                        }-                    )-                ) {-                    Column(Modifier.padding(14.dp)) {-                        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {-                            Text(def.displayName, fontWeight = FontWeight.Bold, color = if (done) Color(0xFF7FD8BE) else MaterialTheme.colorScheme.onSurface)-                            Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {-                                if (done) {-                                    val star = if (isOptimal) "★★★" else if ((nands ?: 999) <= def.optimalNands * 1.5) "★★" else "★"-                                    Text("$star ${nands ?: "?"}N / ${def.optimalNands}N", fontSize = 12.sp, color = Color(0xFF7FD8BE))-                                }-                                if (done) Text("✓", fontSize = 12.sp) else Text("○", fontSize = 12.sp, color = Color.Gray)-                            }-                        }-                        Text(def.description, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f), maxLines = 2)-                        if (def.flavor.isNotEmpty()) {-                            Spacer(Modifier.height(4.dp))-                            Text(def.flavor, fontSize = 11.sp, color = Color(0xFF9CA3AF), fontStyle = FontStyle.Italic)-                        }+    val def = Levels.byId[levelId] ?: return+    val isLocked = !isCompleted && !isAvailable++    val bg = when {+        isCompleted && (bestNand ?: 999) <= def.optimalNands -> Color(0xFF0F3D2E)+        isCompleted -> Color(0xFF1E3A2F)+        isAvailable -> Color(0xFF1B2E41)+        else -> Color(0xFF242A33)+    }+    val borderCol = when {+        isCompleted -> Color(0xFF22C55E)+        isAvailable -> Color(0xFF7FD8BE)+        else -> Color(0xFF4B5563)+    }+    val borderW = if (isAvailable) 3.5.dp else 2.dp++    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.widthIn(min = 96.dp)) {+        Box(+            modifier = Modifier+                .size(size)+                .clip(CircleShape)+                .background(bg)+                .border(borderW, borderCol, CircleShape)+                .clickable(enabled = !isLocked) { onClick(levelId) },+            contentAlignment = Alignment.Center+        ) {+            Column(horizontalAlignment = Alignment.CenterHorizontally) {+                Text(+                    def.displayName.take(7),+                    fontSize = 11.sp,+                    fontWeight = FontWeight.ExtraBold,+                    color = when {+                        isLocked -> Color(0xFF6B7280)+                        isCompleted -> Color(0xFF86EFAC)+                        else -> Color.White                     }+                )+                Spacer(Modifier.height(2.dp))+                if (isLocked) {+                    Text("LOCK", fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF6B7280))+                } else if (isCompleted) {+                    val star = if ((bestNand ?: 999) <= def.optimalNands) "★★★" else if ((bestNand ?: 999) <= (def.optimalNands * 1.5).toInt()) "★★" else "★"+                    Text(star, fontSize = 10.sp, color = Color(0xFFFDE68A))+                } else {+                    Text("PLAY", fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF7FD8BE))+                }+            }+        }+        Spacer(Modifier.height(6.dp))+        Text(+            def.displayName,+            fontSize = 12.sp,+            fontWeight = FontWeight.SemiBold,+            color = if (isLocked) Color(0xFF6B7280) else MaterialTheme.colorScheme.onBackground+        )+        when {+            isCompleted && bestNand != null -> {+                Text(+                    "${bestNand}N / ${def.optimalNands}N",+                    fontSize = 10.sp,+                    color = if (bestNand <= def.optimalNands) Color(0xFF22C55E) else Color(0xFF94A3B8)+                )+            }+            isLocked -> {+                val need = def.prereqs.joinToString(", ") { Levels.byId[it]?.displayName ?: it }+                Text(+                    "needs $need",+                    fontSize = 9.sp,+                    color = Color(0xFF6B7280),+                    modifier = Modifier.padding(horizontal = 4.dp)+                )+            }+            isAvailable -> {+                Text(+                    "${def.optimalNands}N optimal",+                    fontSize = 10.sp,+                    color = Color(0xFF7FD8BE).copy(alpha = 0.8f)+                )+            }+        }+    }+}++@Composable+private fun RowToRowConnector(+    fromRow: TimelineItem.LevelRow,+    toRow: TimelineItem.LevelRow,+    sideOffset: Dp,+    height: Dp,+    completed: Set<String>+) {+    Canvas(+        modifier = Modifier+            .fillMaxWidth()+            .height(height)+    ) {+        val cx = center.x+        val leftX = cx - sideOffset.toPx()+        val rightX = cx + sideOffset.toPx()++        fun xFor(id: String, row: TimelineItem.LevelRow): Float {+            return if (row.levelIds.size == 1) cx+            else if (row.levelIds[0] == id) leftX else rightX+        }++        // Draw each dependency edge fromRow -> toRow+        for (toId in toRow.levelIds) {+            val def = Levels.byId[toId] ?: continue+            val toX = xFor(toId, toRow)+            var hasEdge = false+            for (pr in def.prereqs) {+                if (pr in fromRow.levelIds) {+                    hasEdge = true+                    val fromX = xFor(pr, fromRow)+                    val bothDone = pr in completed && (toId in completed || pr in completed)+                    drawLine(+                        color = if (bothDone) Color(0xFF7FD8BE) else Color(0xFF374151),+                        start = Offset(fromX, 0f),+                        end = Offset(toX, size.height),+                        strokeWidth = 6f+                    )+                }+            }+            // If this row's only prereq is in fromRow but we already handled, nothing extra+            if (!hasEdge && fromRow.levelIds.size == 1 && toRow.levelIds.size == 1) {+                // fallback for linear chain where prereq is immediate predecessor+                val fromId = fromRow.levelIds[0]+                if (def.prereqs.contains(fromId)) {+                    drawLine(+                        color = if (fromId in completed) Color(0xFF7FD8BE) else Color(0xFF374151),+                        start = Offset(cx, 0f),+                        end = Offset(cx, size.height),+                        strokeWidth = 6f+                    )                 }             }-            item { Spacer(Modifier.height(24.dp)) }         }     } } +@Composable+private fun MergeIntoChapterConnector(+    fromRow: TimelineItem.LevelRow,+    sideOffset: Dp,+    height: Dp,+    completed: Set<String>+) {+    Canvas(modifier = Modifier.fillMaxWidth().height(height)) {+        val cx = center.x+        val leftX = cx - sideOffset.toPx()+        val rightX = cx + sideOffset.toPx()++        fun xFor(id: String): Float {+            return if (fromRow.levelIds.size == 1) cx+            else if (fromRow.levelIds[0] == id) leftX else rightX+        }++        for (id in fromRow.levelIds) {+            drawLine(+                color = if (id in completed) Color(0xFF7FD8BE) else Color(0xFF374151),+                start = Offset(xFor(id), 0f),+                end = Offset(cx, size.height),+                strokeWidth = 6f+            )+        }+    }+}++@Composable+private fun BranchOutOfChapterConnector(+    toRow: TimelineItem.LevelRow,+    sideOffset: Dp,+    height: Dp,+    completed: Set<String>+) {+    Canvas(modifier = Modifier.fillMaxWidth().height(height)) {+        val cx = center.x+        val leftX = cx - sideOffset.toPx()+        val rightX = cx + sideOffset.toPx()++        fun xFor(id: String): Float {+            return if (toRow.levelIds.size == 1) cx+            else if (toRow.levelIds[0] == id) leftX else rightX+        }++        for (id in toRow.levelIds) {+            val def = Levels.byId[id] ?: continue+            val unlocked = def.prereqs.all { it in completed }+            drawLine(+                color = if (unlocked) Color(0xFF7FD8BE) else Color(0xFF374151),+                start = Offset(cx, 0f),+                end = Offset(xFor(id), size.height),+                strokeWidth = 6f+            )+        }+    }+}++// --- TruthTable + Inventory (kept minimal, game screen) ---+ @Composable fun TruthTableView(     level: LevelDef,@@ -140,18 +519,17 @@ fun TruthTableView(     modifier: Modifier = Modifier ) {     val target = ChipLibrary.get(level.targetChipId)-    val tableRows: List<List<Boolean>> = if (level.inputs.size <= 8) {+    val rows = if (level.inputs.size <= 10) {         CircuitEvaluator.generateTruthTable(target, level.inputs.size, level.outputs.size, limit = 64)     } else {-        // sampled display         val rnd = java.util.Random(1)-        val vecs = mutableListOf<List<Boolean>>()-        vecs.add(List(level.inputs.size) { false })-        vecs.add(List(level.inputs.size) { true })-        repeat(20) { vecs.add(List(level.inputs.size) { rnd.nextBoolean() }) }-        vecs.map { inp -> target.eval(inp).take(level.outputs.size) }+        val vecs = mutableListOf<List<Boolean>>().apply {+            add(List(level.inputs.size) { false })+            add(List(level.inputs.size) { true })+            repeat(20) { add(List(level.inputs.size) { rnd.nextBoolean() }) }+        }+        vecs.map { target.eval(it).take(level.outputs.size) }     }-    // Input labels for sampled mode: show index     val scroll = rememberScrollState()     Column(modifier = modifier.verticalScroll(scroll).background(Color(0xFF0E141B), RoundedCornerShape(8.dp)).padding(8.dp)) {         if (level.inputs.size <= 10) {@@ -162,19 +540,15 @@ fun TruthTableView(                 level.outputs.take(5).forEach { Text(it.take(4), Modifier.width(36.dp), fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFFFDE68A)) }             }             Spacer(Modifier.height(4.dp))-            tableRows.forEachIndexed { idx, outVals ->+            rows.forEachIndexed { idx, outVals ->                 val isFail = idx in failingRows                 val bg = if (isFail) Color(0x44FF4444) else Color.Transparent-                Row(-                    modifier = Modifier.fillMaxWidth().background(bg, RoundedCornerShape(4.dp)).padding(vertical = 1.dp)-                ) {-                    if (level.inputs.size <= 10) {-                        for (b in 0 until minOf(level.inputs.size, 6)) {-                            val v = ((idx shr b) and 1) == 1-                            Text(if (v) "1" else "0", Modifier.width(28.dp), fontSize = 10.sp, color = Color.White)-                        }-                        if (level.inputs.size > 6) Text("…", Modifier.width(16.dp), fontSize = 10.sp, color = Color.Gray)+                Row(Modifier.fillMaxWidth().background(bg, RoundedCornerShape(4.dp)).padding(vertical = 1.dp)) {+                    for (b in 0 until minOf(level.inputs.size, 6)) {+                        val v = ((idx shr b) and 1) == 1+                        Text(if (v) "1" else "0", Modifier.width(28.dp), fontSize = 10.sp, color = Color.White)                     }+                    if (level.inputs.size > 6) Text("…", Modifier.width(16.dp), fontSize = 10.sp)                     Text(" | ", fontSize = 10.sp, color = Color.Gray)                     outVals.take(5).forEach { v ->                         Text(if (v) "1" else "0", Modifier.width(36.dp), fontSize = 10.sp, color = if (isFail) Color(0xFFFF8A80) else Color(0xFF86EFAC))@@ -183,12 +557,11 @@ fun TruthTableView(                 }             }         } else {-            Text("Truth table (sampled ${tableRows.size} cases from ${1 shl minOf(level.inputs.size, 20)} combos)", fontSize = 9.sp, color = Color.Gray)+            Text("Sampled ${rows.size} cases", fontSize = 9.sp, color = Color.Gray)             Spacer(Modifier.height(6.dp))-            tableRows.take(24).forEachIndexed { idx, outVals ->+            rows.take(24).forEachIndexed { idx, outVals ->                 val isFail = idx in failingRows-                val bg = if (isFail) Color(0x44FF4444) else Color.Transparent-                Row(Modifier.background(bg, RoundedCornerShape(4.dp)).padding(vertical = 1.dp)) {+                Row(Modifier.background(if (isFail) Color(0x44FF4444) else Color.Transparent, RoundedCornerShape(4.dp)).padding(vertical = 1.dp)) {                     outVals.forEach { v ->                         Text(if (v) "1" else "0", Modifier.width(18.dp), fontSize = 10.sp, color = if (isFail) Color(0xFFFF8A80) else Color(0xFF86EFAC))                     }@@ -196,13 +569,8 @@ fun TruthTableView(                 }             }         }-        Spacer(Modifier.height(8.dp))-        if (failingRows.isNotEmpty()) {-            Text("${failingRows.size} failing case(s) highlighted", fontSize = 10.sp, color = Color(0xFFFF8A80))-        }-        if (level.inputs.size > 10) {-            Text("Large bus: validation samples 256 random cases", fontSize = 9.sp, color = Color.Gray)-        }+        if (failingRows.isNotEmpty()) Spacer(Modifier.height(6.dp))+        if (failingRows.isNotEmpty()) Text("${failingRows.size} failing", fontSize = 10.sp, color = Color(0xFFFF8A80))     } } @@ -214,11 +582,11 @@ fun InventoryBar(     modifier: Modifier = Modifier ) {     Column(modifier.background(Color(0xFF151E28), RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp)).padding(8.dp)) {-        Text("Tap chip to place  •  Tap dot → dot to wire  •  Long-press gate to delete", fontSize = 10.sp, color = Color(0xFF94A3B8), modifier = Modifier.padding(bottom = 6.dp))+        Text("Tap chip to place • Tap dot→dot to wire • Long-press to delete", fontSize = 10.sp, color = Color(0xFF94A3B8), modifier = Modifier.padding(bottom = 6.dp))         LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {             items(allowed.filter { it in unlockedChips }.sortedBy { ChipLibrary.get(it).nandCost }) { chipId ->                 val def = ChipLibrary.get(chipId)-                val color = when (def.category) {+                val col = when (def.category) {                     ChipCategory.PRIMITIVE -> Color(0xFF1E3A4A)                     ChipCategory.FOUNDATION -> Color(0xFF14532D)                     ChipCategory.ROUTING -> Color(0xFF713F12)@@ -227,10 +595,7 @@ fun InventoryBar(                     ChipCategory.CPU -> Color(0xFF881337)                 }                 Box(-                    modifier = Modifier-                        .background(color, RoundedCornerShape(8.dp))-                        .clickable { onAddGate(chipId) }-                        .padding(horizontal = 10.dp, vertical = 6.dp),+                    modifier = Modifier.background(col, RoundedCornerShape(8.dp)).clickable { onAddGate(chipId) }.padding(horizontal = 10.dp, vertical = 6.dp),                     contentAlignment = Alignment.Center                 ) {                     Column(horizontalAlignment = Alignment.CenterHorizontally) {
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/Achievements.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/Achievements.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/Achievements.ktindex 12d0f66a98..f41a304b34 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/Achievements.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/Achievements.kt@@ -1,19 +1,36 @@ package com.vayunmathur.games.logicgate.util  import android.content.Context+import com.vayunmathur.games.logicgate.data.ChapterId+import com.vayunmathur.games.logicgate.data.Levels import com.vayunmathur.games.logicgate.data.LogicProgressRepository import com.vayunmathur.library.util.AchievementsManager  class LogicAchievementsManager(context: Context, json: String, private val repo: LogicProgressRepository) : AchievementsManager(context, json) {     override fun checkExistingAchievements() {-        val completed = repo.totalCompleted()-        if (completed > 0) onAchievementUnlocked("first_gate")-        onProgressUpdated("foundation_complete", if (completed >= 3) completed else 0)-        onProgressUpdated("routing_complete", if (completed >= 7) completed else 0)-        onProgressUpdated("arith_complete", if (completed >= 11) completed else 0)-        onProgressUpdated("memory_complete", if (completed >= 14) completed else 0)-        onProgressUpdated("cpu_complete", completed)-        onProgressUpdated("optimal_5", repo.getLevelStats().count { it.value.bestScore <= (com.vayunmathur.games.logicgate.data.Levels.byId[it.key]?.optimalNands ?: 999) })-        onProgressUpdated("all_levels", completed)+        val stats = repo.getLevelStats()+        val completedIds = stats.keys+        if (completedIds.isNotEmpty()) onAchievementUnlocked("first_gate")++        val optimalCount = completedIds.count { id ->+            val best = stats[id]?.bestScore ?: 9999+            val optimal = Levels.byId[id]?.optimalNands ?: 9999+            best <= optimal+        }++        onProgressUpdated("optimal_5", optimalCount)+        onProgressUpdated("all_levels", completedIds.size)++        Levels.chapters.forEach { ch ->+            val count = completedIds.count { Levels.byId[it]?.chapter == ch.id }+            val key = when (ch.id) {+                ChapterId.FOUNDATION -> "foundation_complete"+                ChapterId.ROUTING -> "routing_complete"+                ChapterId.ARITH -> "arith_complete"+                ChapterId.MEMORY -> "memory_complete"+                ChapterId.CPU -> "cpu_complete"+            }+            onProgressUpdated(key, count)+        }     } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.ktindex 73385cfdc9..02eb97f4be 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt@@ -247,13 +247,25 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) {              repo.incCircuitsChecked()             achievementsManager.onAchievementUnlocked("first_gate")+            val allCompleted = _completedIds.value+            val optimalCount = _completedIds.value.mapNotNull { id -> Levels.byId[id] }.count { ld ->+                val best = _bestNands.value[ld.id] ?: 9999+                best <= ld.optimalNands+            }+            achievementsManager.onProgressUpdated("optimal_5", optimalCount)             achievementsManager.onProgressUpdated("all_levels", repo.totalCompleted())-            achievementsManager.onProgressUpdated("foundation_complete", _completedIds.value.count { Levels.byId[it]?.chapter == ChapterId.FOUNDATION })-            achievementsManager.onProgressUpdated("arith_complete", _completedIds.value.count { Levels.byId[it]?.chapter == ChapterId.ARITH })-            if (cost <= level.optimalNands) {-                achievementsManager.onAchievementUnlocked("optimal_${level.id.lowercase()}")+            // per chapter progress+            Levels.chapters.forEach { ch ->+                val count = allCompleted.count { Levels.byId[it]?.chapter == ch.id }+                val key = when (ch.id) {+                    ChapterId.FOUNDATION -> "foundation_complete"+                    ChapterId.ROUTING -> "routing_complete"+                    ChapterId.ARITH -> "arith_complete"+                    ChapterId.MEMORY -> "memory_complete"+                    ChapterId.CPU -> "cpu_complete"+                }+                achievementsManager.onProgressUpdated(key, count)             }-            achievementsManager.onAchievementUnlocked("${level.id.lowercase()}_complete")              // cache next level             val chapterLevelIds = Levels.chapters.find { it.id == level.chapter }?.levelIds ?: emptyList()