Add Logic Gate game: NAND to 8-bit CPU puzzle
- Commit
74cc616f3d4a0e66e0ce285873d5688f53729db0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-22 20:07 UTC (4 months ago)
- Parents
3340bff
Starts with only NAND gate, 18 levels across 5 chapters: - Foundation: NOT, AND, OR, XOR, NOR, XNOR - Routing: MUX, DMUX, MUX4 - Arithmetic: HalfAdder, FullAdder, Adder4, Adder8 - Memory: DFF, Bit, Reg8 - CPU: ALU8, CPU8 capstone Features: - Interactive canvas: drag gates, tap output->input to wire, long-press to delete - Live truth-table validation with sampled evaluation for large buses (16-input adders use 256 random vectors) - NAND-cost scoring vs optimal, star ratings - Persistent circuits per level via DataStore - Unlocked chips become inventory for later levels - Achievements, backup agent, chapter progression Builds via :games:logicgate:assembleDebug (74MB debug APK verified)
Diff
games/logicgate/build.gradle.kts
diff --git a/games/logicgate/build.gradle.kts b/games/logicgate/build.gradle.ktsnew file mode 100644index 0000000000..de580b21f0--- /dev/null+++ b/games/logicgate/build.gradle.kts@@ -0,0 +1,16 @@+plugins {+ id("common-conventions-app")+ id("common-conventions-metadata")+}++launcherIcon {+ symbol = "memory"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.games.logicgate"+ }+}++dependencies {}
games/logicgate/src/main/AndroidManifest.xml
diff --git a/games/logicgate/src/main/AndroidManifest.xml b/games/logicgate/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..a5e7620c16--- /dev/null+++ b/games/logicgate/src/main/AndroidManifest.xml@@ -0,0 +1,25 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <application+ android:allowBackup="true"+ android:backupAgent=".util.AppBackupAgent"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">+ <activity+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:name=".MainActivity"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>+ </application>++</manifest>
games/logicgate/src/main/assets/achievements.json
diff --git a/games/logicgate/src/main/assets/achievements.json b/games/logicgate/src/main/assets/achievements.jsonnew file mode 100644index 0000000000..70e66a269f--- /dev/null+++ b/games/logicgate/src/main/assets/achievements.json@@ -0,0 +1,15 @@+[+ {"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"}+]
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.ktnew file mode 100644index 0000000000..704ff5a0d5--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt@@ -0,0 +1,213 @@+package com.vayunmathur.games.logicgate++import android.os.Bundle+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.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.*+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.TruthTableView+import com.vayunmathur.games.logicgate.util.AppBackupAgent+import com.vayunmathur.games.logicgate.util.EvalStatus+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.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+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ LogicGateTheme {+ val vm: LogicViewModel = viewModel()+ Navigation(vm)+ }+ }+ }+}++@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+}++@Composable+fun Navigation(viewModel: LogicViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.Chapters)+ 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.Game> {+ GameScreen(backStack, viewModel, it.levelId)+ }+ entry<Route.GameCenter> {+ GameCenterScreen(+ backupAgent = AppBackupAgent(),+ manager = viewModel.achievementsManager,+ onBack = { backStack.pop() }+ )+ }+ }+ newAchievement?.let {+ AchievementNotification(it) { viewModel.dismissAchievement() }+ }+ }+}++@Composable+fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelId: String) {+ val level = Levels.get(levelId)+ val uiState by viewModel.uiState.collectAsState()+ val unlocked by viewModel.unlockedChips.collectAsState()+ val completed by viewModel.completedIds.collectAsState()++ LaunchedEffect(levelId) {+ viewModel.selectLevel(levelId)+ }++ // If current loaded level mismatches, loading+ val isCurrent = uiState.currentLevelId == levelId++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text("${level.displayName} ${if (levelId in completed) "✓" else ""}", fontSize = 16.sp) },+ navigationIcon = { IconNavigation(backStack) },+ actions = {+ Button(onClick = { viewModel.toggleTruthTable() }, modifier = Modifier.padding(end = 4.dp)) {+ Text(if (uiState.showTruthTable) "Hide TT" else "Show TT", fontSize = 11.sp)+ }+ }+ )+ },+ bottomBar = {+ if (isCurrent) {+ InventoryBar(+ allowed = level.allowedChipIds,+ unlockedChips = unlocked,+ onAddGate = { viewModel.addGate(it) },+ modifier = Modifier.fillMaxWidth()+ )+ }+ }+ ) { padding ->+ if (!isCurrent) {+ Box(Modifier.fillMaxSize().padding(padding), contentAlignment = androidx.compose.ui.Alignment.Center) {+ Text("Loading...")+ }+ return@Scaffold+ }++ 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.Error -> "Error: ${status.msg}"+ is EvalStatus.Cycle -> "Cycle detected: ${status.ids.take(3).joinToString()}"+ else -> "Wire inputs → gates → outputs"+ }+ 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)+ ) {+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ Column(Modifier.weight(1f)) {+ Text(statusText, fontSize = 12.sp, color = statusColor)+ Text(level.description, fontSize = 10.sp, color = Color(0xFF94A3B8))+ if (level.hint.isNotEmpty()) {+ Text("Hint: ${level.hint}", fontSize = 10.sp, color = Color(0xFF64748B))+ }+ }+ Row(horizontalArrangement = 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) }+ }+ val nandCost = uiState.circuit.gates.sumOf { com.vayunmathur.games.logicgate.data.ChipLibrary.get(it.chipId).nandCost }+ Card(modifier = Modifier.padding(start = 4.dp)) {+ Text(" ${nandCost}N ", fontSize = 11.sp, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp))+ }+ }+ }+ }++ 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))+ )+ }+ }+ }+ }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.ktnew file mode 100644index 0000000000..37414a821f--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt@@ -0,0 +1,298 @@+package com.vayunmathur.games.logicgate.data++/**+ * Core definitions for all chips.+ * Each chip is a functional block with named pins and a pure boolean evaluation.+ * NAND is primitive (cost 1). Everything else's cost is flattened NAND count.+ */++data class ChipDef(+ val id: String,+ val displayName: String,+ val inputs: List<String>,+ val outputs: List<String>,+ val nandCost: Int,+ val description: String,+ val category: ChipCategory,+ val eval: (List<Boolean>) -> List<Boolean>+) {+ val inputCount: Int get() = inputs.size+ val outputCount: Int get() = outputs.size+}++enum class ChipCategory { PRIMITIVE, FOUNDATION, ROUTING, ARITH, MEMORY, CPU }++object ChipLibrary {++ private fun b(v: Boolean) = v++ val NAND = ChipDef(+ id = "NAND",+ displayName = "NAND",+ inputs = listOf("a", "b"),+ outputs = listOf("out"),+ nandCost = 1,+ description = "Primitive: NOT (A AND B)",+ category = ChipCategory.PRIMITIVE,+ eval = { inp -> listOf(!(inp[0] && inp[1])) }+ )++ val NOT = ChipDef(+ id = "NOT",+ displayName = "NOT",+ inputs = listOf("in"),+ outputs = listOf("out"),+ nandCost = 1,+ description = "Inverter: NAND(a,a)",+ category = ChipCategory.FOUNDATION,+ eval = { inp -> listOf(!inp[0]) }+ )++ val AND = ChipDef(+ id = "AND",+ displayName = "AND",+ inputs = listOf("a", "b"),+ outputs = listOf("out"),+ nandCost = 2,+ description = "Conjunction",+ category = ChipCategory.FOUNDATION,+ eval = { inp -> listOf(inp[0] && inp[1]) }+ )++ val OR = ChipDef(+ id = "OR",+ displayName = "OR",+ inputs = listOf("a", "b"),+ outputs = listOf("out"),+ nandCost = 3,+ description = "Disjunction",+ category = ChipCategory.FOUNDATION,+ eval = { inp -> listOf(inp[0] || inp[1]) }+ )++ val XOR = ChipDef(+ id = "XOR",+ displayName = "XOR",+ inputs = listOf("a", "b"),+ outputs = listOf("out"),+ nandCost = 4,+ description = "Exclusive OR",+ category = ChipCategory.FOUNDATION,+ eval = { inp -> listOf(inp[0] xor inp[1]) }+ )++ val NOR = ChipDef(+ id = "NOR",+ displayName = "NOR",+ inputs = listOf("a", "b"),+ outputs = listOf("out"),+ nandCost = 4,+ description = "NOT OR",+ category = ChipCategory.FOUNDATION,+ eval = { inp -> listOf(!(inp[0] || inp[1])) }+ )++ val XNOR = ChipDef(+ id = "XNOR",+ displayName = "XNOR",+ inputs = listOf("a", "b"),+ outputs = listOf("out"),+ nandCost = 5,+ description = "NOT XOR",+ category = ChipCategory.FOUNDATION,+ eval = { inp -> listOf(!(inp[0] xor inp[1])) }+ )++ val MUX = ChipDef(+ id = "MUX",+ displayName = "MUX",+ inputs = listOf("a", "b", "sel"),+ outputs = listOf("out"),+ nandCost = 4,+ description = "If sel then b else a",+ category = ChipCategory.ROUTING,+ eval = { inp ->+ val a = inp[0]; val b = inp[1]; val sel = inp[2]+ listOf(if (sel) b else a)+ }+ )++ val DMUX = ChipDef(+ id = "DMUX",+ displayName = "DMUX",+ inputs = listOf("in", "sel"),+ outputs = listOf("a", "b"),+ nandCost = 3,+ description = "Demultiplex: route in to a or b",+ category = ChipCategory.ROUTING,+ eval = { inp ->+ val inn = inp[0]; val sel = inp[1]+ if (sel) listOf(false, inn) else listOf(inn, false)+ }+ )++ val MUX4 = ChipDef(+ id = "MUX4",+ displayName = "MUX4",+ inputs = listOf("a", "b", "c", "d", "sel0", "sel1"),+ outputs = listOf("out"),+ nandCost = 12,+ description = "4-way mux, sel1 sel0 = 00:a 01:b 10:c 11:d",+ category = ChipCategory.ROUTING,+ eval = { inp ->+ val sel = (if (inp[5]) 2 else 0) + (if (inp[4]) 1 else 0)+ listOf(inp[sel])+ }+ )++ val HALF_ADDER = ChipDef(+ id = "HALF_ADDER",+ displayName = "HalfAdder",+ inputs = listOf("a", "b"),+ outputs = listOf("sum", "carry"),+ nandCost = 6,+ description = "sum = a XOR b, carry = a AND b",+ category = ChipCategory.ARITH,+ eval = { inp ->+ val a = inp[0]; val b = inp[1]+ listOf(a xor b, a && b)+ }+ )++ val FULL_ADDER = ChipDef(+ id = "FULL_ADDER",+ displayName = "FullAdder",+ inputs = listOf("a", "b", "cin"),+ outputs = listOf("sum", "cout"),+ nandCost = 14,+ description = "Full adder with carry in/out",+ category = ChipCategory.ARITH,+ eval = { inp ->+ val a = inp[0]; val b = inp[1]; val cin = inp[2]+ val sum = a xor b xor cin+ val cout = (a && b) || (b && cin) || (a && cin)+ listOf(sum, cout)+ }+ )++ // 2-bit adder for progression (4-bit uses many FullAdders, truth table explosion - we handle via multi-bit API)+ val ADDER_4 = ChipDef(+ id = "ADDER_4",+ displayName = "Adder4",+ inputs = listOf("a0","a1","a2","a3","b0","b1","b2","b3"),+ outputs = listOf("s0","s1","s2","s3","cout"),+ nandCost = 56,+ description = "4-bit ripple-carry adder",+ category = ChipCategory.ARITH,+ eval = { inp ->+ val a = bitsToInt(inp.slice(0..3))+ val b = bitsToInt(inp.slice(4..7))+ val sum = a + b+ intToBits(sum, 4) + listOf(sum >= 16)+ }+ )++ val ADDER_8 = ChipDef(+ id = "ADDER_8",+ displayName = "Adder8",+ inputs = (0..7).map { "a$it" } + (0..7).map { "b$it" },+ outputs = (0..7).map { "s$it" } + listOf("cout"),+ nandCost = 112,+ description = "8-bit ripple-carry adder",+ category = ChipCategory.ARITH,+ eval = { inp ->+ val a = bitsToInt(inp.slice(0..7))+ val b = bitsToInt(inp.slice(8..15))+ val sum = a + b+ intToBits(sum, 8) + listOf(sum >= 256)+ }+ )++ val DFF = ChipDef(+ id = "DFF",+ displayName = "DFF",+ inputs = listOf("d", "clk"),+ outputs = listOf("q"),+ nandCost = 6,+ description = "D Flip-Flop (primitive for memory)",+ category = ChipCategory.MEMORY,+ eval = { inp -> listOf(inp[0]) } // sequential handled specially, combinational sees wire-through+ )++ val BIT = ChipDef(+ id = "BIT",+ displayName = "Bit",+ inputs = listOf("in", "load"),+ outputs = listOf("out"),+ nandCost = 12,+ description = "1-bit register, load=1 stores in",+ category = ChipCategory.MEMORY,+ eval = { inp -> listOf(inp[0]) }+ )++ val REGISTER_8 = ChipDef(+ id = "REG_8",+ displayName = "Reg8",+ inputs = (0..7).map { "in$it" } + listOf("load"),+ outputs = (0..7).map { "out$it" },+ nandCost = 96,+ description = "8-bit register",+ category = ChipCategory.MEMORY,+ eval = { inp -> inp.slice(0..7) }+ )++ val ALU_8 = ChipDef(+ id = "ALU_8",+ displayName = "ALU",+ inputs = (0..7).map { "a$it" } + (0..7).map { "b$it" } + listOf("op0","op1"),+ outputs = (0..7).map { "out$it" } + listOf("zero","carry"),+ nandCost = 200,+ description = "ALU: op 00=ADD 01=AND 10=OR 11=XOR",+ category = ChipCategory.CPU,+ eval = { inp ->+ val a = bitsToInt(inp.slice(0..7))+ val b = bitsToInt(inp.slice(8..15))+ val op = (if (inp[17]) 2 else 0) + (if (inp[16]) 1 else 0)+ val result = when (op) {+ 0 -> a + b+ 1 -> a and b+ 2 -> a or b+ else -> a xor b+ } and 0xFF+ intToBits(result, 8) + listOf(result == 0, result > 255 || op == 0 && a + b >= 256)+ }+ )++ val CPU_8 = ChipDef(+ id = "CPU_8",+ displayName = "CPU",+ inputs = (0..7).map { "in$it" } + listOf("clk", "reset"),+ outputs = (0..7).map { "out$it" } + (0..7).map { "addr$it" } + listOf("write"),+ nandCost = 2000,+ description = "Simple 8-bit CPU",+ category = ChipCategory.CPU,+ eval = { inp -> List(17) { false } }+ )++ // All chips map+ val all: Map<String, ChipDef> = listOf(+ NAND, NOT, AND, OR, XOR, NOR, XNOR,+ MUX, DMUX, MUX4,+ HALF_ADDER, FULL_ADDER, ADDER_4, ADDER_8,+ DFF, BIT, REGISTER_8,+ ALU_8, CPU_8+ ).associateBy { it.id }++ fun get(id: String): ChipDef = all[id] ?: error("Unknown chip $id")++ // Helper for bit conversion+ fun bitsToInt(bits: List<Boolean>): Int {+ var v = 0+ bits.forEachIndexed { i, bit -> if (bit) v = v or (1 shl i) }+ return v+ }++ fun intToBits(value: Int, width: Int): List<Boolean> {+ return List(width) { i -> (value shr i) and 1 == 1 }+ }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.ktnew file mode 100644index 0000000000..4a5214f542--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt@@ -0,0 +1,252 @@+package com.vayunmathur.games.logicgate.data++/**+ * Circuit representation:+ * - Inputs: "__IN_<idx>"+ * - Gates: placed chips with generated unique ids+ * - Wires: connections from (sourceId, outputIdx) to (destId, inputIdx)+ * - OutputMappings: final outputs resolved+ */++data class PlacedChip(+ val instanceId: String,+ val chipId: String,+ val x: Float = 0f,+ val y: Float = 0f+)++data class WireEnd(val instanceId: String, val pinIndex: Int)++data class Wire(+ val id: String,+ val from: WireEnd,+ val to: WireEnd+)++data class OutputMapping(+ val outputIndex: Int,+ val from: WireEnd+)++data class Circuit(+ val gates: List<PlacedChip> = emptyList(),+ val wires: List<Wire> = emptyList(),+ val outputMappings: List<OutputMapping> = emptyList()+) {+ fun totalNandCost(): Int = gates.sumOf { ChipLibrary.get(it.chipId).nandCost }+}++sealed class EvalResult {+ data class Success(val rows: List<List<Boolean>>) : EvalResult()+ data class Error(val message: String) : EvalResult()+ data class Cycle(val ids: List<String>) : EvalResult()+}++object CircuitEvaluator {++ private sealed class ComboEval {+ data class Ok(val outputs: List<Boolean>) : ComboEval()+ data class Err(val msg: String) : ComboEval()+ data class Cycle(val ids: List<String>) : ComboEval()+ }++ /** Evaluate circuit for all input combos, but sample if inputCount > 10 to avoid explosion. */+ fun evaluate(level: LevelDef, circuit: Circuit): EvalResult {+ val inputCount = level.inputs.size+ // If circuit has structural issues we still try one combo first to surface errors fast+ val quickCheck = evalCombo(level, circuit, List(inputCount) { false })+ if (quickCheck is ComboEval.Err) return EvalResult.Error(quickCheck.msg)+ if (quickCheck is ComboEval.Cycle) return EvalResult.Cycle(quickCheck.ids)++ val combos = if (inputCount <= 10) {+ (0 until (1 shl inputCount)).toList()+ } else {+ // Sample: exhaustive for low bits + random+ val sampleSize = 256+ val rnd = java.util.Random(1234)+ val set = LinkedHashSet<Int>()+ // include edges+ set.add(0); set.add((1 shl minOf(inputCount, 20)) - 1)+ while (set.size < sampleSize) {+ var v = 0+ for (b in 0 until inputCount) if (rnd.nextBoolean()) v = v or (1 shl b)+ // clamp if inputCount > 30 we limited loops but still sample via bits+ if (inputCount > 30) v = rnd.nextInt(1 shl 18)+ set.add(v)+ }+ set.toList()+ }++ val results = mutableListOf<List<Boolean>>()+ for (combo in combos) {+ val inputVals = List(inputCount) { i ->+ if (i < 30) ((combo shr i) and 1) == 1 else false+ }+ when (val r = evalCombo(level, circuit, inputVals)) {+ is ComboEval.Ok -> results.add(r.outputs)+ is ComboEval.Err -> return EvalResult.Error("Combo ${formatCombo(inputVals)}: ${r.msg}")+ is ComboEval.Cycle -> return EvalResult.Cycle(r.ids)+ }+ }+ return EvalResult.Success(results)+ }++ /** For full truth table comparison, generate expected rows matching the same sampled combos */+ fun evaluateFullCorrectness(level: LevelDef, circuit: Circuit): Pair<Boolean, List<Int>> {+ val targetDef = ChipLibrary.get(level.targetChipId)+ val inputCount = level.inputs.size+ val outputCount = level.outputs.size++ val combos: List<Int> = if (inputCount <= 10) {+ (0 until (1 shl inputCount)).toList()+ } else {+ val sampleSize = 256+ val rnd = java.util.Random(1234)+ val set = LinkedHashSet<Int>()+ set.add(0)+ while (set.size < sampleSize) {+ var v = 0+ for (b in 0 until minOf(inputCount, 18)) if (rnd.nextBoolean()) v = v or (1 shl b)+ if (inputCount > 18) {+ for (b in 18 until inputCount) if (rnd.nextBoolean()) v = v or (1 shl (b % 18)) // overflow guard+ // Actually re-generate full bits sampled+ }+ set.add(v)+ }+ set.toList()+ }++ // For large input counts we can't use combo as int for >30 bits; generate bit lists directly in sampled mode+ val testVectors: List<List<Boolean>> = if (inputCount <= 10) {+ combos.map { c -> List(inputCount) { i -> ((c shr i) and 1) == 1 } }+ } else {+ val rnd = java.util.Random(1234)+ val vs = mutableListOf<List<Boolean>>()+ vs.add(List(inputCount) { false })+ vs.add(List(inputCount) { true })+ vs.add(List(inputCount) { it % 2 == 0 })+ while (vs.size < 256) {+ vs.add(List(inputCount) { rnd.nextBoolean() })+ }+ vs+ }++ val expectedRows = testVectors.map { vec -> targetDef.eval(vec).take(outputCount) }+ val actualRows = mutableListOf<List<Boolean>>()++ for ((idx, vec) in testVectors.withIndex()) {+ when (val r = evalCombo(level, circuit, vec)) {+ is ComboEval.Ok -> actualRows.add(r.outputs)+ else -> return false to listOf(idx) // structure error = incorrect+ }+ }++ val failing = mutableListOf<Int>()+ for (i in expectedRows.indices) {+ if (i >= actualRows.size || expectedRows[i] != actualRows[i]) failing.add(i)+ }+ return (failing.isEmpty()) to failing+ }++ fun isCorrect(level: LevelDef, circuit: Circuit): Pair<Boolean, List<Int>> = evaluateFullCorrectness(level, circuit)++ private fun evalCombo(level: LevelDef, circuit: Circuit, inputVals: List<Boolean>): ComboEval {+ val computed = mutableMapOf<String, List<Boolean>>()+ inputVals.forEachIndexed { idx, v -> computed["__IN_$idx"] = listOf(v) }++ val deps = mutableMapOf<String, MutableSet<String>>()+ val incoming = mutableMapOf<String, MutableMap<Int, WireEnd>>()+ circuit.gates.forEach { g ->+ deps[g.instanceId] = mutableSetOf()+ incoming[g.instanceId] = mutableMapOf()+ }+ for (w in circuit.wires) {+ val srcId = w.from.instanceId+ val dstId = w.to.instanceId+ if (dstId.startsWith("__OUT_")) continue+ if (incoming.containsKey(dstId)) {+ incoming[dstId]!![w.to.pinIndex] = w.from+ if (!srcId.startsWith("__IN_")) deps[dstId]?.add(srcId)+ }+ }++ val order = topoSort(circuit.gates.map { it.instanceId }, deps)+ ?: return ComboEval.Cycle(circuit.gates.map { it.instanceId })++ for (gid in order) {+ val placed = circuit.gates.find { it.instanceId == gid } ?: continue+ val chipDef = ChipLibrary.get(placed.chipId)+ val inputs = mutableListOf<Boolean>()+ for (pinIdx in 0 until chipDef.inputCount) {+ val srcEnd = incoming[gid]?.get(pinIdx)+ if (srcEnd == null) {+ return ComboEval.Err("Gate ${chipDef.displayName}[${chipDef.inputs.getOrElse(pinIdx) { "in$pinIdx" }}] unconnected")+ }+ val srcVals = computed[srcEnd.instanceId]+ if (srcVals == null) return ComboEval.Err("Source ${srcEnd.instanceId} not yet computed (cycle?)")+ inputs.add(if (srcEnd.pinIndex < srcVals.size) srcVals[srcEnd.pinIndex] else false)+ }+ val outVals = try {+ chipDef.eval(inputs)+ } catch (e: Exception) {+ return ComboEval.Err("Eval ${chipDef.id}: ${e.message}")+ }+ computed[gid] = outVals+ }++ val outMap = circuit.outputMappings.associateBy { it.outputIndex }+ val outputs = mutableListOf<Boolean>()+ for (oi in 0 until level.outputs.size) {+ val mapping = outMap[oi] ?: return ComboEval.Err("Output ${level.outputs[oi]} not connected")+ val srcVals = computed[mapping.from.instanceId]+ ?: return ComboEval.Err("Output ${level.outputs[oi]} source not computed")+ outputs.add(if (mapping.from.pinIndex < srcVals.size) srcVals[mapping.from.pinIndex] else false)+ }+ return ComboEval.Ok(outputs)+ }++ private fun topoSort(nodes: List<String>, deps: Map<String, Set<String>>): List<String>? {+ val inDegree = mutableMapOf<String, Int>()+ nodes.forEach { inDegree[it] = deps[it]?.size ?: 0 }+ val outEdges = mutableMapOf<String, MutableList<String>>()+ nodes.forEach { outEdges[it] = mutableListOf() }+ deps.forEach { (node, depSet) ->+ depSet.forEach { dep -> outEdges.getOrPut(dep) { mutableListOf() }.add(node) }+ }+ val q = ArrayDeque<String>()+ inDegree.filter { it.value == 0 }.keys.forEach { q.add(it) }+ val order = mutableListOf<String>()+ while (q.isNotEmpty()) {+ val n = q.removeFirst()+ order.add(n)+ outEdges[n]?.forEach { m ->+ inDegree[m] = (inDegree[m] ?: 1) - 1+ if (inDegree[m] == 0) q.add(m)+ }+ }+ return if (order.size == nodes.size) order else null+ }++ fun generateTruthTable(target: ChipDef, inputCount: Int, outputCount: Int, limit: Int = 256): List<List<Boolean>> {+ val total = if (inputCount <= 10) (1 shl inputCount) else minOf(limit, 1 shl minOf(inputCount, 20))+ if (inputCount <= 10) {+ return (0 until total).map { c ->+ val inp = List(inputCount) { i -> ((c shr i) and 1) == 1 }+ target.eval(inp).take(outputCount)+ }+ } else {+ // Sampled truth table for large gates+ val rnd = java.util.Random(42)+ val vectors = mutableListOf<List<Boolean>>()+ vectors.add(List(inputCount) { false })+ vectors.add(List(inputCount) { true })+ vectors.add(List(inputCount) { it % 2 == 0 })+ while (vectors.size < minOf(limit, total)) {+ vectors.add(List(inputCount) { rnd.nextBoolean() })+ }+ return vectors.map { inp -> target.eval(inp).take(outputCount) }+ }+ }++ fun formatCombo(bits: List<Boolean>): String = bits.joinToString("") { if (it) "1" else "0" }+}
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.ktnew file mode 100644index 0000000000..52fff5962c--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt@@ -0,0 +1,304 @@+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.+ */++enum class ChapterId { FOUNDATION, ROUTING, ARITH, MEMORY, CPU }++data class Chapter(+ val id: ChapterId,+ val name: String,+ val desc: String,+ val levelIds: List<String>+)++data class LevelDef(+ val id: String,+ val displayName: String,+ 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+)++object Levels {+ val all: List<LevelDef> = listOf(+ // FOUNDATION+ LevelDef(+ id = "NOT",+ displayName = "NOT Gate",+ 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)",+ 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"+ ),+ LevelDef(+ id = "AND",+ displayName = "AND Gate",+ chapter = ChapterId.FOUNDATION,+ description = "Build AND: out = a & b",+ hint = "NAND then NOT. Or NAND(a,b) -> invert.",+ 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"+ ),+ LevelDef(+ id = "OR",+ displayName = "OR Gate",+ chapter = ChapterId.FOUNDATION,+ description = "Build OR: out = a | b",+ hint = "De Morgan: OR = NOT(NOT a AND NOT b) = 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"+ ),+ LevelDef(+ id = "XOR",+ displayName = "XOR Gate",+ 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) ...",+ 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"+ ),+ LevelDef(+ id = "NOR",+ displayName = "NOR Gate",+ chapter = ChapterId.FOUNDATION,+ description = "Build NOR: out = !(a | b)",+ hint = "OR then NOT — or 4 NANDs directly.",+ inputs = listOf("a", "b"),+ outputs = listOf("out"),+ targetChipId = "NOR",+ allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR"),+ optimalNands = 4,+ unlocksChipId = "NOR"+ ),+ LevelDef(+ id = "XNOR",+ displayName = "XNOR Gate",+ chapter = ChapterId.FOUNDATION,+ description = "Build XNOR: equality check",+ 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"+ ),+ // ROUTING+ LevelDef(+ id = "MUX",+ displayName = "Multiplexer",+ chapter = ChapterId.ROUTING,+ description = "If sel=0 out=a else out=b",+ hint = "MUX = (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"+ ),+ LevelDef(+ id = "DMUX",+ displayName = "Demux",+ chapter = ChapterId.ROUTING,+ description = "Route in to a if sel=0 else b",+ hint = "a = in & !sel, b = in & sel",+ inputs = listOf("in", "sel"),+ outputs = listOf("a", "b"),+ targetChipId = "DMUX",+ allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX"),+ optimalNands = 3,+ unlocksChipId = "DMUX"+ ),+ LevelDef(+ id = "MUX4",+ displayName = "4-Way MUX",+ chapter = ChapterId.ROUTING,+ description = "sel1 sel0: 00->a 01->b 10->c 11->d",+ hint = "Build from 3 MUXes or direct logic.",+ 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"+ ),+ // 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!",+ 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"+ ),+ 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.",+ 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"+ ),+ LevelDef(+ id = "ADDER_4",+ displayName = "4-Bit Adder",+ chapter = ChapterId.ARITH,+ description = "Add two 4-bit numbers: a0..a3 + b0..b3",+ hint = "Chain 4 FullAdders ripple-carry style.",+ 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"+ ),+ LevelDef(+ id = "ADDER_8",+ displayName = "8-Bit Adder",+ chapter = ChapterId.ARITH,+ description = "Add two 8-bit numbers. Carry out indicates overflow.",+ hint = "Chain 8 FullAdders. Low bits: a0,b0 are LSB.",+ 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"+ ),+ // MEMORY+ LevelDef(+ id = "DFF",+ displayName = "D Flip-Flop",+ chapter = ChapterId.MEMORY,+ description = "On clock tick, Q = D. Foundation of memory.",+ hint = "NAND latch with clock gating. For this simulator, we model combinationally.",+ 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"+ ),+ LevelDef(+ id = "BIT",+ displayName = "1-Bit Register",+ 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.",+ inputs = listOf("in", "load"),+ outputs = listOf("out"),+ targetChipId = "BIT",+ allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU_8" && it != "REGISTER_8" && it != "ALU_8" }.toList(),+ optimalNands = 12,+ unlocksChipId = "BIT"+ ),+ LevelDef(+ id = "REG_8",+ displayName = "8-Bit Register",+ chapter = ChapterId.MEMORY,+ description = "8-bit register with load control. 8 BITs in parallel.",+ hint = "8x BIT sharing load signal.",+ 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"+ ),+ // CPU+ LevelDef(+ id = "ALU_8",+ displayName = "ALU (8-bit)",+ 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.",+ 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"+ ),+ LevelDef(+ id = "CPU_8",+ displayName = "8-Bit 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!",+ 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"+ )+ )++ 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.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 }),+ )++ val byId: Map<String, LevelDef> = all.associateBy { it.id }+ fun get(id: String): LevelDef = byId[id] ?: error("Unknown level $id")+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressRepository.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressRepository.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressRepository.ktnew file mode 100644index 0000000000..fe1bd4e5ae--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressRepository.kt@@ -0,0 +1,32 @@+package com.vayunmathur.games.logicgate.data++import android.content.Context+import com.vayunmathur.library.util.LevelStatsRepository++class LogicProgressRepository(context: Context) : LevelStatsRepository(context, "logicgate_stats") {+ fun getCompletedLevelIds(): Set<String> = getLevelStats().keys++ fun isLevelComplete(id: String): Boolean = getLevelStats().containsKey(id)++ fun bestNandCount(levelId: String): Int? = getLevelStats()[levelId]?.bestScore++ // we reuse bestScore as nand count (lower is better, but LevelStatsRepository keeps min)+ // so storing nand count directly works++ fun unlockedChipIds(): Set<String> {+ val completed = getCompletedLevelIds()+ val chips = mutableSetOf("NAND")+ for (lvlId in completed) {+ val lvl = Levels.byId[lvlId] ?: continue+ lvl.unlocksChipId?.let { chips.add(it) }+ }+ return chips+ }++ fun totalCompleted(): Int = getLevelStats().size++ fun incCircuitsChecked() = incrementCounter("circuits_checked")+ fun getCircuitsChecked(): Int = getCounter("circuits_checked")++ fun setChipHintUsed(chipId: String) = incrementCounter("hint_$chipId")+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.ktnew file mode 100644index 0000000000..baffde16fe--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt@@ -0,0 +1,253 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size as GeomSize+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.drawText+import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.unit.sp+import com.vayunmathur.games.logicgate.data.*+import kotlin.math.max++data class GateRect(val chip: PlacedChip, val left: Float, val top: Float, val width: Float, val height: Float) {+ fun inputPos(i: Int, count: Int): Offset {+ if (count == 0) return Offset(left, top + height / 2f)+ val gap = height / (count + 1)+ return Offset(left, top + gap * (i + 1))+ }+ fun outputPos(i: Int, count: Int): Offset {+ if (count == 0) return Offset(left + width, top + height / 2f)+ val gap = height / (count + 1)+ return Offset(left + width, top + gap * (i + 1))+ }+ fun contains(p: Offset): Boolean = p.x in left..left + width && p.y in top..top + height+}++@Composable+fun CircuitCanvas(+ level: LevelDef,+ gates: List<PlacedChip>,+ wires: List<Wire>,+ outputMaps: List<OutputMapping>,+ wiringFrom: WireEnd?,+ onStartWiringOutput: (WireEnd) -> Unit,+ onCompleteWiringInput: (WireEnd) -> Unit,+ onGateDrag: (String, Float, Float) -> Unit,+ onGateLongPress: (String) -> Unit,+ modifier: Modifier = Modifier+) {+ val textMeasurer = rememberTextMeasurer()+ val chipDefs = gates.associate { it.instanceId to ChipLibrary.get(it.chipId) }++ fun computeRects(): List<GateRect> {+ return gates.map { g ->+ val def = ChipLibrary.get(g.chipId)+ val w = 120f+ val h = max(56f, 20f * max(def.inputCount, def.outputCount) + 24f)+ GateRect(g, g.x, g.y, w, h)+ }+ }++ var rects by remember(gates) { mutableStateOf(computeRects()) }+ // keep in sync+ rects = computeRects()+ val rectById = rects.associateBy { it.chip.instanceId }++ fun inputSourcePos(idx: Int): Offset {+ val spacing = 52f+ return Offset(22f, 70f + idx * spacing)+ }+ fun outputSinkPos(idx: Int): Offset {+ val spacing = 52f+ return Offset(760f, 70f + idx * spacing)+ }++ fun hitOutputPin(pos: Offset): WireEnd? {+ // check external inputs+ for ((i, _) in level.inputs.withIndex()) {+ if ((pos - inputSourcePos(i)).getDistance() < 18f) return WireEnd("__IN_$i", 0)+ }+ for (gr in rects) {+ val def = ChipLibrary.get(gr.chip.chipId)+ for (j in 0 until def.outputCount) {+ if ((pos - gr.outputPos(j, def.outputCount)).getDistance() < 16f) {+ return WireEnd(gr.chip.instanceId, j)+ }+ }+ }+ return null+ }++ fun hitInputPin(pos: Offset): WireEnd? {+ for (gr in rects) {+ val def = ChipLibrary.get(gr.chip.chipId)+ for (j in 0 until def.inputCount) {+ if ((pos - gr.inputPos(j, def.inputCount)).getDistance() < 16f) {+ return WireEnd(gr.chip.instanceId, j)+ }+ }+ }+ for ((i, _) in level.outputs.withIndex()) {+ if ((pos - outputSinkPos(i)).getDistance() < 18f) return WireEnd("__OUT_$i", 0)+ }+ return null+ }++ fun hitGate(pos: Offset): PlacedChip? {+ for (gr in rects.reversed()) if (gr.contains(pos)) return gr.chip+ return null+ }++ Canvas(+ modifier = modifier+ .fillMaxSize()+ .background(Color(0xFF101820))+ .pointerInput(rects, wiringFrom) {+ detectTapGestures(+ onTap = { tapPos ->+ if (wiringFrom != null) {+ val dest = hitInputPin(tapPos)+ if (dest != null) {+ onCompleteWiringInput(dest)+ }+ } else {+ val src = hitOutputPin(tapPos)+ if (src != null) onStartWiringOutput(src)+ }+ },+ onLongPress = { lp ->+ hitGate(lp)?.let { onGateLongPress(it.instanceId) }+ }+ )+ }+ .pointerInput(rects) {+ detectDragGestures(+ onDragStart = { /* handled below via move */ },+ onDrag = { change, dragAmount ->+ change.consume()+ val gate = hitGate(change.position - dragAmount) ?: hitGate(change.position)+ if (gate != null) {+ val cur = rectById[gate.instanceId] ?: return@detectDragGestures+ val nx = (cur.left + dragAmount.x).coerceIn(0f, 820f - cur.width)+ val ny = (cur.top + dragAmount.y).coerceIn(0f, 1600f - cur.height)+ onGateDrag(gate.instanceId, nx, ny)+ }+ }+ )+ }+ ) {+ // grid+ val step = 22f+ var x = 0f+ while (x < size.width) {+ var y = 0f+ while (y < size.height) {+ drawCircle(Color.White.copy(alpha = 0.05f), 0.9f, Offset(x, y))+ y += step+ }+ x += step+ }++ // helper resolvers+ fun resolveSource(end: WireEnd): Offset? {+ if (end.instanceId.startsWith("__IN_")) {+ val idx = end.instanceId.removePrefix("__IN_").toIntOrNull() ?: return null+ return inputSourcePos(idx)+ }+ val gr = rectById[end.instanceId] ?: return null+ val def = chipDefs[end.instanceId] ?: return null+ return gr.outputPos(end.pinIndex.coerceIn(0, max(0, def.outputCount - 1)), def.outputCount)+ }+ fun resolveSink(end: WireEnd): Offset? {+ if (end.instanceId.startsWith("__OUT_")) {+ val idx = end.instanceId.removePrefix("__OUT_").toIntOrNull() ?: return null+ return outputSinkPos(idx)+ }+ val gr = rectById[end.instanceId] ?: return null+ val def = chipDefs[end.instanceId] ?: return null+ return gr.inputPos(end.pinIndex.coerceIn(0, max(0, def.inputCount - 1)), def.inputCount)+ }++ // wires+ for (w in wires) {+ val from = resolveSource(w.from) ?: continue+ val to = resolveSink(w.to) ?: continue+ drawWire(from, to, Color(0xFF7ED8B6))+ }+ for (om in outputMaps) {+ val from = resolveSource(om.from) ?: continue+ val to = outputSinkPos(om.outputIndex)+ drawWire(from, to, Color(0xFFFDE68A))+ }++ // input nodes+ for ((i, name) in level.inputs.withIndex()) {+ val p = inputSourcePos(i)+ val isActive = wiringFrom?.instanceId == "__IN_$i"+ drawCircle(if (isActive) Color.Yellow else Color(0xFF38BDF8), 11f, p)+ drawCircle(Color.Black, 4f, p)+ drawText(textMeasurer, text = name, topLeft = p + Offset(16f, -8f), style = TextStyle(Color.White, 12.sp))+ }+ for ((i, name) in level.outputs.withIndex()) {+ val p = outputSinkPos(i)+ drawCircle(Color(0xFFF87171), 11f, p)+ drawCircle(Color.Black, 4f, p)+ drawText(textMeasurer, text = name, topLeft = p + Offset(-48f - name.length * 2, -8f), style = TextStyle(Color.White, 12.sp))+ }++ // gates+ for (gr in rects) {+ val def = ChipLibrary.get(gr.chip.chipId)+ val boxColor = when (def.category) {+ ChipCategory.PRIMITIVE -> Color(0xFF1E3A4A)+ ChipCategory.FOUNDATION -> Color(0xFF2A9D8F)+ ChipCategory.ROUTING -> Color(0xFFE9C46A)+ ChipCategory.ARITH -> Color(0xFFF4A261)+ ChipCategory.MEMORY -> Color(0xFF9A7DFF)+ ChipCategory.CPU -> Color(0xFFFF4D6D)+ }+ drawRect(boxColor, Offset(gr.left, gr.top), GeomSize(gr.width, gr.height))+ drawRect(Color.White.copy(alpha = 0.25f), Offset(gr.left, gr.top), GeomSize(gr.width, gr.height), style = Stroke(1f))+ drawText(textMeasurer, text = def.displayName, topLeft = Offset(gr.left + 6f, gr.top + 4f), style = TextStyle(if (def.category == ChipCategory.ROUTING) Color.Black else Color.White, 11.sp))+ drawText(textMeasurer, text = "${def.nandCost}N", topLeft = Offset(gr.left + gr.width - 28f, gr.top + 4f), style = TextStyle(Color.White.copy(alpha = 0.7f), 9.sp))++ for (j in 0 until def.inputCount) {+ val pp = gr.inputPos(j, def.inputCount)+ drawCircle(Color.White, 5.5f, pp)+ val lbl = def.inputs[j]+ drawText(textMeasurer, text = lbl, topLeft = pp + Offset(8f, -6f), style = TextStyle(Color.White.copy(alpha = 0.8f), 8.sp))+ }+ for (j in 0 until def.outputCount) {+ val pp = gr.outputPos(j, def.outputCount)+ val isSrc = wiringFrom?.instanceId == gr.chip.instanceId && wiringFrom.pinIndex == j+ drawCircle(if (isSrc) Color.Yellow else Color(0xFFA7F3D0), 5.5f, pp)+ val lbl = def.outputs[j]+ drawText(textMeasurer, text = lbl, topLeft = pp + Offset(-22f, -6f), style = TextStyle(Color.White.copy(alpha = 0.8f), 8.sp))+ }+ }+ }+}++private fun DrawScope.drawWire(from: Offset, to: Offset, color: Color) {+ val midX = (from.x + to.x) * 0.5f+ drawLine(color, from, Offset(midX, from.y), strokeWidth = 2.8f)+ drawLine(color, Offset(midX, from.y), Offset(midX, to.y), strokeWidth = 2.8f)+ drawLine(color, Offset(midX, to.y), to, strokeWidth = 2.8f)+ // arrow endpoint+ drawCircle(color, 3f, to)+}
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.ktnew file mode 100644index 0000000000..8c8f10bd72--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt@@ -0,0 +1,244 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.foundation.background+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.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+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.sp+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.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import androidx.compose.runtime.collectAsState+import com.vayunmathur.games.logicgate.util.LogicViewModel+import com.vayunmathur.library.util.NavBackStack++@Composable+fun ChapterListScreen(+ 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)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(16.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ 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))+ }+ Text("$doneCount/${chapter.levelIds.size}", style = MaterialTheme.typography.titleMedium)+ }+ }+ }+ item {+ Spacer(Modifier.height(16.dp))+ Button(onClick = { backStack.add(com.vayunmathur.games.logicgate.Route.GameCenter) }, modifier = Modifier.fillMaxWidth()) {+ Text("Achievements")+ }+ }+ }+}++@Composable+fun LevelListScreen(+ chapterId: ChapterId,+ backStack: NavBackStack<com.vayunmathur.games.logicgate.Route>,+ viewModel: LogicViewModel+) {+ 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)+ }+ }+ }+ }+ item { Spacer(Modifier.height(24.dp)) }+ }+ }+}++@Composable+fun TruthTableView(+ level: LevelDef,+ failingRows: List<Int>,+ modifier: Modifier = Modifier+) {+ val target = ChipLibrary.get(level.targetChipId)+ val tableRows: List<List<Boolean>> = if (level.inputs.size <= 8) {+ 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) }+ }+ // 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) {+ Row {+ level.inputs.take(6).forEach { Text(it.take(3), Modifier.width(28.dp), fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF7DD3FC)) }+ if (level.inputs.size > 6) Text("…", Modifier.width(16.dp), fontSize = 9.sp, color = Color.Gray)+ Text(" | ", fontSize = 9.sp, color = Color.Gray)+ 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 ->+ 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)+ }+ 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))+ }+ if (isFail) Text(" ✗", fontSize = 10.sp, color = Color(0xFFFF8A80))+ }+ }+ } else {+ Text("Truth table (sampled ${tableRows.size} cases from ${1 shl minOf(level.inputs.size, 20)} combos)", fontSize = 9.sp, color = Color.Gray)+ Spacer(Modifier.height(6.dp))+ tableRows.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)) {+ outVals.forEach { v ->+ Text(if (v) "1" else "0", Modifier.width(18.dp), fontSize = 10.sp, color = if (isFail) Color(0xFFFF8A80) else Color(0xFF86EFAC))+ }+ if (isFail) Text(" ✗", fontSize = 10.sp, color = Color(0xFFFF8A80))+ }+ }+ }+ 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)+ }+ }+}++@Composable+fun InventoryBar(+ allowed: List<String>,+ unlockedChips: Set<String>,+ onAddGate: (String) -> Unit,+ 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))+ 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) {+ ChipCategory.PRIMITIVE -> Color(0xFF1E3A4A)+ ChipCategory.FOUNDATION -> Color(0xFF14532D)+ ChipCategory.ROUTING -> Color(0xFF713F12)+ ChipCategory.ARITH -> Color(0xFF7C2D12)+ ChipCategory.MEMORY -> Color(0xFF3B0764)+ ChipCategory.CPU -> Color(0xFF881337)+ }+ Box(+ modifier = Modifier+ .background(color, RoundedCornerShape(8.dp))+ .clickable { onAddGate(chipId) }+ .padding(horizontal = 10.dp, vertical = 6.dp),+ contentAlignment = Alignment.Center+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(def.displayName, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White)+ Text("${def.nandCost}N ${def.inputs.size}→${def.outputs.size}", fontSize = 9.sp, color = Color.White.copy(alpha = 0.6f))+ }+ }+ }+ }+ }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Theme.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Theme.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Theme.ktnew file mode 100644index 0000000000..f29b5656de--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Theme.kt@@ -0,0 +1,27 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.graphics.Color+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.darkColorScheme++private val LogicDark = darkColorScheme(+ primary = Color(0xFF7FD8BE),+ secondary = Color(0xFF2A3B4C),+ tertiary = Color(0xFFD7A8FF),+ background = Color(0xFF0E141B),+ surface = Color(0xFF1B242F),+ onPrimary = Color(0xFF00382E),+ onSecondary = Color.White,+ onTertiary = Color.Black,+ onBackground = Color(0xFFD9E2EC),+ onSurface = Color(0xFFD9E2EC),+ primaryContainer = Color(0xFF1F4D44),+ secondaryContainer = Color(0xFF233140),+ error = Color(0xFFFF8A80)+)++@Composable+fun LogicGateTheme(content: @Composable () -> Unit) {+ MaterialTheme(colorScheme = LogicDark, content = content)+}
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.ktnew file mode 100644index 0000000000..12d0f66a98--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/Achievements.kt@@ -0,0 +1,19 @@+package com.vayunmathur.games.logicgate.util++import android.content.Context+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)+ }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.ktnew file mode 100644index 0000000000..56ed1d383a--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.kt@@ -0,0 +1,10 @@+package com.vayunmathur.games.logicgate.util++import com.vayunmathur.library.util.BaseBackupAgent++class AppBackupAgent : BaseBackupAgent() {+ override val prefNames: List<String>+ get() = listOf("logicgate_stats")+ override val datastoreNames: List<String>+ get() = listOf("logic_gate_datastore")+}
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.ktnew file mode 100644index 0000000000..73385cfdc9--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt@@ -0,0 +1,299 @@+package com.vayunmathur.games.logicgate.util++import android.app.Application+import android.content.Context+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.games.logicgate.data.*+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import java.util.UUID+import kotlin.math.max+import kotlin.random.Random++// Serializable persistence of circuit per level+@Serializable+data class PersistedWire(val id: String, val fromInstance: String, val fromPin: Int, val toInstance: String, val toPin: Int)+@Serializable+data class PersistedGate(val instanceId: String, val chipId: String, val x: Float, val y: Float)+@Serializable+data class PersistedOutputMap(val outputIndex: Int, val fromInstance: String, val fromPin: Int)+@Serializable+data class PersistedCircuit(val gates: List<PersistedGate>, val wires: List<PersistedWire>, val outputs: List<PersistedOutputMap>)+@Serializable+data class AllSavedCircuits(val map: Map<String, PersistedCircuit> = emptyMap())++data class UiState(+ val selectedChapter: ChapterId = ChapterId.FOUNDATION,+ val currentLevelId: String? = null,+ val circuit: Circuit = Circuit(),+ val evalStatus: EvalStatus = EvalStatus.Idle,+ val selectedGateInstanceId: String? = null,+ val wiringFrom: WireEnd? = null,+ val showTruthTable: Boolean = true+)++sealed class EvalStatus {+ object Idle : EvalStatus()+ data class Ok(val passingRows: Int, val totalRows: Int, val isFullyCorrect: Boolean, val failingRows: List<Int>) : EvalStatus()+ data class Error(val msg: String) : EvalStatus()+ data class Cycle(val ids: List<String>) : EvalStatus()+}++class LogicViewModel(application: Application) : AndroidViewModel(application) {+ private val repo = LogicProgressRepository(application)+ private val ds = DataStoreUtils.getInstance(application)+ private val ctx: Context get() = getApplication()++ val achievementsManager: LogicAchievementsManager = run {+ val json = try {+ ctx.assets.open("achievements.json").bufferedReader().use { it.readText() }+ } catch (_: Exception) { "[]" }+ LogicAchievementsManager(ctx, json, repo)+ }++ private val _completedIds = MutableStateFlow(repo.getCompletedLevelIds())+ val completedIds: StateFlow<Set<String>> = _completedIds.asStateFlow()++ private val _bestNands = MutableStateFlow<Map<String, Int>>(repo.getLevelStats().mapValues { it.value.bestScore })+ val bestNands: StateFlow<Map<String, Int>> = _bestNands.asStateFlow()++ private val _unlockedChips = MutableStateFlow(repo.unlockedChipIds())+ val unlockedChips: StateFlow<Set<String>> = _unlockedChips.asStateFlow()++ private val _uiState = MutableStateFlow(UiState())+ val uiState: StateFlow<UiState> = _uiState.asStateFlow()++ private val _nextLevelEvent = MutableSharedFlow<String>(extraBufferCapacity = 1)+ val nextLevelEvent: SharedFlow<String> = _nextLevelEvent.asSharedFlow()++ // persisted circuits cache+ private var allCircuits: MutableMap<String, Circuit> = mutableMapOf()++ init {+ viewModelScope.launch(Dispatchers.IO) {+ loadAllCircuits()+ achievementsManager.checkExistingAchievements()+ }+ }++ private fun loadAllCircuits() {+ val raw = ds.getString(KEY_CIRCUITS) ?: return+ try {+ val parsed = Json.decodeFromString<AllSavedCircuits>(raw)+ parsed.map.forEach { (lvlId, pc) ->+ allCircuits[lvlId] = pc.toCircuit()+ }+ } catch (_: Exception) { /* ignore */ }+ }++ private fun saveAllCircuits() {+ val toSave = AllSavedCircuits(allCircuits.mapValues { it.value.toPersisted() })+ val json = Json.encodeToString(toSave)+ viewModelScope.launch(Dispatchers.IO) {+ ds.setString(KEY_CIRCUITS, json)+ }+ }++ fun selectLevel(levelId: String) {+ val loaded = allCircuits[levelId] ?: Circuit()+ _uiState.update {+ it.copy(currentLevelId = levelId, circuit = loaded, evalStatus = EvalStatus.Idle, wiringFrom = null, selectedGateInstanceId = null)+ }+ evaluateCurrent()+ }++ fun selectChapter(id: ChapterId) {+ _uiState.update { it.copy(selectedChapter = id) }+ }++ fun addGate(chipId: String) {+ val state = _uiState.value+ val newId = "G_${UUID.randomUUID().toString().take(6)}"+ val chipDef = ChipLibrary.get(chipId)+ // auto layout: random pile but near center+ val existingCount = state.circuit.gates.size+ val gate = PlacedChip(newId, chipId, x = 80f + (existingCount % 4) * 140f, y = 100f + (existingCount / 4) * 110f)+ val newCircuit = state.circuit.copy(gates = state.circuit.gates + gate)+ updateCircuit(newCircuit)+ }++ fun removeGate(instanceId: String) {+ val s = _uiState.value.circuit+ val newGates = s.gates.filterNot { it.instanceId == instanceId }+ val newWires = s.wires.filterNot { it.from.instanceId == instanceId || it.to.instanceId == instanceId }+ val newOuts = s.outputMappings.filterNot { it.from.instanceId == instanceId }+ updateCircuit(s.copy(gates = newGates, wires = newWires, outputMappings = newOuts))+ }++ fun clearCircuit() {+ updateCircuit(Circuit())+ }++ fun onGateMoved(instanceId: String, x: Float, y: Float) {+ val s = _uiState.value.circuit+ val newGates = s.gates.map { if (it.instanceId == instanceId) it.copy(x = x, y = y) else it }+ // don't trigger eval on move+ val lvlId = _uiState.value.currentLevelId+ if (lvlId != null) {+ allCircuits[lvlId] = s.copy(gates = newGates)+ saveAllCircuits()+ }+ _uiState.update { it.copy(circuit = it.circuit.copy(gates = newGates)) }+ }++ fun startWiring(from: WireEnd) {+ _uiState.update { it.copy(wiringFrom = from) }+ }++ fun cancelWiring() {+ _uiState.update { it.copy(wiringFrom = null) }+ }++ /**+ * Complete a wiring attempt.+ * Rules:+ * - If to is __OUT_<idx>, create OutputMapping+ * - Else if to is gate input, create wire (allow fan-out, single driver per pin? we allow overwriting)+ */+ fun completeWiring(to: WireEnd) {+ val from = _uiState.value.wiringFrom ?: return+ val s = _uiState.value.circuit+ if (from.instanceId == to.instanceId) { _uiState.update { it.copy(wiringFrom = null) }; return }++ if (to.instanceId.startsWith("__OUT_")) {+ val outIdx = to.instanceId.removePrefix("__OUT_").toIntOrNull() ?: run { _uiState.update { it.copy(wiringFrom = null) }; return }+ val existing = s.outputMappings.filterNot { it.outputIndex == outIdx }+ val newMap = existing + OutputMapping(outIdx, from)+ updateCircuit(s.copy(outputMappings = newMap))+ } else {+ // destination is gate input or (allow wiring INTO __IN_? no)+ // Remove any existing wire to that destination pin (only one driver per input pin)+ val existingWires = s.wires.filterNot { it.to == to }+ val newWire = Wire(+ id = "W_${UUID.randomUUID().toString().take(6)}",+ from = from,+ to = to+ )+ updateCircuit(s.copy(wires = existingWires + newWire))+ }+ _uiState.update { it.copy(wiringFrom = null) }+ }++ fun removeWire(wireId: String) {+ val s = _uiState.value.circuit+ updateCircuit(s.copy(wires = s.wires.filterNot { it.id == wireId }))+ }++ fun removeOutputMapping(outIdx: Int) {+ val s = _uiState.value.circuit+ updateCircuit(s.copy(outputMappings = s.outputMappings.filterNot { it.outputIndex == outIdx }))+ }++ private fun updateCircuit(newCircuit: Circuit) {+ val lvlId = _uiState.value.currentLevelId+ if (lvlId != null) {+ allCircuits[lvlId] = newCircuit+ saveAllCircuits()+ }+ _uiState.update { it.copy(circuit = newCircuit) }+ evaluateCurrent()+ }++ fun evaluateCurrent() {+ val state = _uiState.value+ val lvlId = state.currentLevelId ?: return+ val level = Levels.get(lvlId)+ val circuit = state.circuit+ val evalResult = CircuitEvaluator.evaluate(level, circuit)+ val (fullyCorrect, failing) = CircuitEvaluator.isCorrect(level, circuit)+ when (evalResult) {+ is EvalResult.Error -> _uiState.update { it.copy(evalStatus = EvalStatus.Error(evalResult.message)) }+ is EvalResult.Cycle -> _uiState.update { it.copy(evalStatus = EvalStatus.Cycle(evalResult.ids)) }+ is EvalResult.Success -> {+ val total = if (level.inputs.size <= 10) (1 shl level.inputs.size) else evalResult.rows.size+ val passing = total - failing.size+ _uiState.update { it.copy(evalStatus = EvalStatus.Ok(passing, total, fullyCorrect, failing)) }+ if (fullyCorrect) {+ onLevelWon(level, circuit)+ }+ }+ }+ }++ private fun onLevelWon(level: LevelDef, circuit: Circuit) {+ val cost = circuit.totalNandCost()+ viewModelScope.launch {+ withContext(Dispatchers.IO) {+ repo.updateBestScore(level.id, cost)+ }+ _completedIds.value = repo.getCompletedLevelIds()+ _bestNands.value = repo.getLevelStats().mapValues { it.value.bestScore }+ _unlockedChips.value = repo.unlockedChipIds()++ repo.incCircuitsChecked()+ achievementsManager.onAchievementUnlocked("first_gate")+ 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()}")+ }+ achievementsManager.onAchievementUnlocked("${level.id.lowercase()}_complete")++ // cache next level+ val chapterLevelIds = Levels.chapters.find { it.id == level.chapter }?.levelIds ?: emptyList()+ val idx = chapterLevelIds.indexOf(level.id)+ if (idx >= 0 && idx < chapterLevelIds.lastIndex) {+ val nextId = chapterLevelIds[idx + 1]+ _nextLevelEvent.tryEmit(nextId)+ } else {+ // next chapter first uncompleted+ val nextChapterIdx = Levels.chapters.indexOfFirst { it.id == level.chapter } + 1+ if (nextChapterIdx < Levels.chapters.size) {+ val nextChap = Levels.chapters[nextChapterIdx]+ _nextLevelEvent.tryEmit(nextChap.levelIds.first())+ }+ }+ }+ }++ fun toggleTruthTable() {+ _uiState.update { it.copy(showTruthTable = !it.showTruthTable) }+ }++ fun dismissAchievement() = achievementsManager.dismissNotification()++ companion object {+ private const val KEY_CIRCUITS = "logicgate_circuits_v1"+ }+}++private fun PersistedCircuit.toCircuit(): Circuit {+ return Circuit(+ gates = gates.map { PlacedChip(it.instanceId, it.chipId, it.x, it.y) },+ wires = wires.map { Wire(it.id, WireEnd(it.fromInstance, it.fromPin), WireEnd(it.toInstance, it.toPin)) },+ outputMappings = outputs.map { OutputMapping(it.outputIndex, WireEnd(it.fromInstance, it.fromPin)) }+ )+}+private fun Circuit.toPersisted(): PersistedCircuit {+ return PersistedCircuit(+ gates = gates.map { PersistedGate(it.instanceId, it.chipId, it.x, it.y) },+ wires = wires.map { PersistedWire(it.id, it.from.instanceId, it.from.pinIndex, it.to.instanceId, it.to.pinIndex) },+ outputs = outputMappings.map { PersistedOutputMap(it.outputIndex, it.from.instanceId, it.from.pinIndex) }+ )+}
games/logicgate/src/main/res/values/strings.xml
diff --git a/games/logicgate/src/main/res/values/strings.xml b/games/logicgate/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..74a7783a8a--- /dev/null+++ b/games/logicgate/src/main/res/values/strings.xml@@ -0,0 +1,24 @@+<resources>+ <string name="app_name">Logic Gate</string>+ <string name="chapters">Chapters</string>+ <string name="levels">Levels</string>+ <string name="canvas">Canvas</string>+ <string name="trash">Delete</string>+ <string name="clear">Clear</string>+ <string name="undo">Undo</string>+ <string name="redo">Redo</string>+ <string name="check">Check</string>+ <string name="level_complete">Level Complete!</string>+ <string name="level_failed">Check Failed</string>+ <string name="optimal">Optimal: %1$d Gates</string>+ <string name="your_gates">Your Gates: %1$d</string>+ <string name="nand_count">NANDs: %1$d</string>+ <string name="truth_table">Truth Table</string>+ <string name="info">Info</string>+ <string name="inventory">Inventory</string>+ <string name="chips">Chips</string>+ <string name="settings">Settings</string>+ <string name="next">Next</string>+ <string name="prev">Prev</string>+ <string name="hint">Hint</string>+</resources>
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex f0909c1a08..09aceeee60 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -58,6 +58,7 @@ include(":clock") include(":games:alchemist") include(":games:pipes") include(":games:solitaire")+include(":games:logicgate") include(":email") include(":weather") include(":messages")