logicgate: rebuild the editor and app on the new simulator
- Commit
cc1e0ef7eba680184fad9f9a7f8d11bd96fe0d93- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-01 18:25 UTC (1 month ago)
- Parents
a1131ba
Replaces every old source file in the app (canvas, inventory, panels,
LogicEngine, wiring, Turing screens) with a fresh UI on the domain
layer from the previous commit. Fresh start: progress and drafts use
new storage keys (logicgate2_stats prefs, logicgate2_circuits in the
shared DataStore) and old data is ignored.
Why: the old editor placed gates by dragging only, with a fragile 45
degree check deciding tray drag vs scroll; panning needed two fingers;
zoom/fit buttons did nothing; a touch within ~40dp of a wire deleted
it on finger-down; pins were 12-14dp; the world was clamped to
+/-4000px; the game screen used a raw Scaffold; every gate was a box.
Editor (ui/, ui/canvas/):
- One Canvas in world coordinates with a single gesture state machine:
drag from a pin draws a wire (compatible pins highlight; a width
mismatch shakes the pin and suggests the converter chip, e.g.
"8-bit -> 1-bit: add a SPLIT 8"), drag a body moves it on a grid,
drag empty space pans, two fingers pinch-zoom about the centroid.
Nothing edits on finger-down. Unbounded world; fit frames all nodes.
- Alchemy-style chip handling: pull a chip up out of the tray to place
it (sideways swipes still scroll), or tap it to drop it mid-view.
Carrying a gate turns the bottom area into a trash zone; dropping it
there deletes it. A selection bar also offers delete.
- Classic gate shapes for AND/OR/NOT/NAND/NOR/XOR/XNOR, boxes with pin
names for the rest; buses drawn thicker, colour-coded by width, with
hex value tags; 1-bit wires light up when high.
- Test panel: pass/fail status ("first failure: 1 XOR 1 = 0"), cost
and stars; expands to every row's title and actual output. Tapping
a row probes it onto the wires; sequential levels step tick by tick.
- Tap a level input to flip it (bus inputs open a bit/stepper dialog).
- Level brief sheet on first visit, completion overlay with stars and
cost vs par, chaptered level map with locks, stars and best cost.
- AppScaffold throughout; animations via library.ui helpers.
Platform/data: LogicViewModel keeps a 50-step undo/redo stack of
immutable circuits and re-verifies on Dispatchers.Default after each
edit (debounced, cancelling older runs). CircuitStore debounces draft
saves on its own scope so the last edit lands after the screen
closes. New lg2_* achievements derived from stored best costs; the
game registers with the Games Hub (adds :sdk:games). Locale string
files are emptied; the English strings are rewritten.
Verified: testDevUnitTest (camera round-trips, hit-test priority pin >
body > wire, placement, drag-to-trash deletes gates but not level
pins), ./check games/logicgate (detekt + lint clean), androidTest
compiles. The rewritten UiAutomator journey test opens NOT, taps NAND
and checks undo removes it; not yet run on a device.Diff
games/logicgate/build.gradle.kts
diff --git a/games/logicgate/build.gradle.kts b/games/logicgate/build.gradle.ktsindex 3d67c59bcc..5b14db2e6d 100644--- a/games/logicgate/build.gradle.kts+++ b/games/logicgate/build.gradle.kts@@ -15,4 +15,6 @@ android { } } -dependencies {}+dependencies {+ implementation(project(":sdk:games"))+}
games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.kt
diff --git a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.kt b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.ktindex 626be927f4..3774113c15 100644--- a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.kt+++ b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.kt@@ -1,133 +1,89 @@ package com.vayunmathur.games.logicgate.ui -import android.app.UiAutomation import android.content.Intent-import android.content.pm.PackageManager import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until-import java.io.IOException+import java.util.regex.Pattern import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull-import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith /**- * Journey test: launches logicgate, opens the first level from the map, taps- * the editor undo button, and asserts the editor stays put rather than- * navigating away or crashing.+ * Journey test: open the first level from the map, tap NAND in the chip tray, see the circuit+ * cost go up by one gate, then undo it back down. *- * LogicGate boots into the progression map (Route.Progression); the first- * level is always unlocked so its node carries the stable PLAY label, and the- * editor top bar carries the level name plus the stable undo glyph. The undo- * tap is a no-op on a fresh circuit, which is exactly what makes it safe.- *- * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on- * hidden InputManager APIs that no longer exist on current releases, so every- * compose-rule test dies before its first line. Text polling works for Compose- * and non-Compose screens alike.+ * The board is a single canvas with no per-gate semantics, so the cost readout in the test+ * panel ("N NAND") is what proves a gate landed. The level brief opens on a first visit and is+ * dismissed if present. */ @RunWith(AndroidJUnit4::class) class GamePlayTest { @Test- fun play_openFirstLevel_tapUndo_editorStays() {+ fun play_openNot_placeNand_undoRemovesIt() { val instrumentation = InstrumentationRegistry.getInstrumentation() val device = UiDevice.getInstance(instrumentation) val targetContext = instrumentation.targetContext val packageName = targetContext.packageName - grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)- val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName) assertNotNull("no launcher intent for $packageName", intent) intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) targetContext.startActivity(intent) - // Past the permission screen: the gate wall never appears and the- // progression subtitle is showing.- assertNull(- "permission gate is showing; grants did not clear it",- device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),- )- assertNotNull(- "level map never appeared; the app may have crashed on launch",- device.wait(Until.findObject(By.text(PROGRESSION_SUBTITLE)), CONTENT_TIMEOUT_MS),- )- // Play action: open the first level, whose node always offers PLAY.- val play = device.wait(Until.findObject(By.text(LEVEL_PLAY_LABEL)), CONTENT_TIMEOUT_MS)- assertNotNull("no playable level node; the level map did not load its nodes", play)- play!!.click()- // Editor is showing: its top bar carries the undo glyph, which the map- // never draws, so it proves the navigation landed in the editor.- val board = device.wait(Until.findObject(By.text(EDITOR_UNDO_GLYPH)), CONTENT_TIMEOUT_MS)- assertNotNull("circuit editor never appeared; tapping play may not have navigated", board)+ val level = device.wait(Until.findObject(By.text(FIRST_LEVEL)), TIMEOUT_MS)+ assertNotNull("level map never showed the first level", level)+ level!!.click()++ device.wait(Until.findObject(By.text(START_BUILDING)), BRIEF_TIMEOUT_MS)?.click()+ assertNotNull("editor never appeared", device.wait(Until.findObject(By.desc(UNDO)), TIMEOUT_MS))++ // Undo any draft left by an earlier run so the count starts from an empty board.+ while (device.findObject(cost(0)) == null) {+ val undo = device.findObject(By.desc(UNDO)) ?: break+ if (!undo.isEnabled) break+ undo.click()+ device.waitForIdle()+ }++ val before = costShown(device)+ val nand = device.wait(Until.findObject(By.descStartsWith(NAND_CARD)), TIMEOUT_MS)+ assertNotNull("chip tray has no NAND", nand)+ nand!!.click() assertNotNull(- "first level title missing; the editor may have opened the wrong level",- device.wait(Until.findObject(By.text(FIRST_LEVEL_NAME)), CONTENT_TIMEOUT_MS),+ "placing a NAND did not raise the cost",+ device.wait(Until.findObject(cost(before + 1)), TIMEOUT_MS), )- // One interaction: tap undo (a no-op on a fresh circuit) and confirm- // the editor is still there.- board!!.click()++ device.findObject(By.desc(UNDO)).click() assertNotNull(- "editor left after tapping undo; the app may have crashed on interaction",- device.wait(Until.findObject(By.text(FIRST_LEVEL_NAME)), CONTENT_TIMEOUT_MS),+ "undo did not remove the NAND",+ device.wait(Until.findObject(cost(before)), TIMEOUT_MS), )- // Still alive in front: the process did not crash after the interaction. assertEquals(packageName, device.currentPackageName) } - private fun grantAllRequestedPermissions(- uiAutomation: UiAutomation,- packageManager: PackageManager,- packageName: String,- ) {- val info = try {- packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)- } catch (e: PackageManager.NameNotFoundException) {- throw AssertionError("package $packageName not installed", e)- }- for (permission in info.requestedPermissions.orEmpty()) {- try {- uiAutomation.executeShellCommand("pm grant $packageName $permission").close()- } catch (ignored: SecurityException) {- // Not a headlessly grantable permission: nothing to do.- } catch (ignored: IOException) {- // Shell pipe failed: the permission stays ungranted and the- // content assertions below report it.- }- }- for (command in SPECIAL_ACCESS_COMMANDS) {- try {- uiAutomation.executeShellCommand(command.format(packageName)).close()- } catch (ignored: SecurityException) {- // Appop missing on this release: the gate assertion reports it.- } catch (ignored: IOException) {- // Shell pipe failed: the gate assertion below reports it.- }- }+ /** The test panel header merges its texts, so match the cost anywhere inside it. */+ private fun cost(n: Int) = By.text(Pattern.compile("(.*\\D)?$n NAND(\\D.*)?", Pattern.DOTALL))++ private fun costShown(device: UiDevice): Int {+ val label = device.wait(Until.findObject(By.text(COST_PATTERN)), TIMEOUT_MS)+ assertNotNull("no cost readout in the test panel", label)+ val match = COST_PATTERN.matcher(label!!.text)+ return if (match.matches()) match.group(1)!!.toInt() else error("unreadable cost: ${label.text}") } private companion object {- private const val CONTENT_TIMEOUT_MS = 15_000L- private const val GATE_TIMEOUT_MS = 5_000L- private const val PROGRESSION_SUBTITLE = "Start with NAND. End with a computer."- private const val LEVEL_PLAY_LABEL = "PLAY"- private const val FIRST_LEVEL_NAME = "NOT"- private const val EDITOR_UNDO_GLYPH = "↩"- private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"-- /**- * Special access behind some apps' gates: exact alarms + full-screen intent- * have no pm-grantable permission, but the shell can flip their appops.- * Ignored where the appop does not exist; the gate assertion reports it.- */- private val SPECIAL_ACCESS_COMMANDS = arrayOf(- "appops set %s SCHEDULE_EXACT_ALARM allow",- "appops set %s USE_FULL_SCREEN_INTENT allow",- )+ private const val TIMEOUT_MS = 15_000L+ private const val BRIEF_TIMEOUT_MS = 3_000L+ private const val FIRST_LEVEL = "NOT"+ private const val START_BUILDING = "Start building"+ private const val UNDO = "Undo"+ private const val NAND_CARD = "NAND, costs"+ private val COST_PATTERN: Pattern = Pattern.compile("(?:.*\\D)?(\\d+) NAND(?:\\D.*)?", Pattern.DOTALL) } }
games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/LaunchNoCrashTest.kt
diff --git a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/LaunchNoCrashTest.kt b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/LaunchNoCrashTest.ktindex 5e5cf00a8c..a29c592f0e 100644--- a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/LaunchNoCrashTest.kt+++ b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/LaunchNoCrashTest.kt@@ -16,16 +16,11 @@ import org.junit.Test import org.junit.runner.RunWith /**- * Launch-no-crash test: launches the app, grants every requested permission, and- * asserts it gets past the permission screen onto the level map.+ * Launch-no-crash test: launches the app, grants every requested permission, and asserts it+ * reaches the level map, marked by its stable tagline. *- * LogicGate boots into the progression map, so the marker asserts the stable- * NAND-to-computer subtitle rather than any level-node state.- *- * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on- * hidden InputManager APIs that no longer exist on current releases, so every- * compose-rule test dies before its first line. Text polling works for Compose- * and non-Compose screens alike.+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on hidden+ * InputManager APIs that no longer exist on current releases. */ @RunWith(AndroidJUnit4::class) class LaunchNoCrashTest {@@ -44,17 +39,14 @@ class LaunchNoCrashTest { intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) targetContext.startActivity(intent) - // Past the permission screen: the gate wall never appears and the- // progression subtitle is showing. assertNull( "permission gate is showing; grants did not clear it", device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS), ) assertNotNull( "level map never appeared; the app may have crashed on launch",- device.wait(Until.findObject(By.text(PROGRESSION_SUBTITLE)), CONTENT_TIMEOUT_MS),+ device.wait(Until.findObject(By.text(TAGLINE)), CONTENT_TIMEOUT_MS), )- // Still alive in front: the process did not crash after painting content. assertEquals(packageName, device.currentPackageName) } @@ -74,17 +66,7 @@ class LaunchNoCrashTest { } catch (ignored: SecurityException) { // Not a headlessly grantable permission: nothing to do. } catch (ignored: IOException) {- // Shell pipe failed: the permission stays ungranted and the- // content assertions below report it.- }- }- for (command in SPECIAL_ACCESS_COMMANDS) {- try {- uiAutomation.executeShellCommand(command.format(packageName)).close()- } catch (ignored: SecurityException) {- // Appop missing on this release: the gate assertion reports it.- } catch (ignored: IOException) {- // Shell pipe failed: the gate assertion below reports it.+ // Shell pipe failed: the content assertions below report it. } } }@@ -92,17 +74,7 @@ class LaunchNoCrashTest { private companion object { private const val CONTENT_TIMEOUT_MS = 15_000L private const val GATE_TIMEOUT_MS = 5_000L- private const val PROGRESSION_SUBTITLE = "Start with NAND. End with a computer."+ private const val TAGLINE = "Start with NAND. End with a computer." private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"-- /**- * Special access behind some apps' gates: exact alarms + full-screen intent- * have no pm-grantable permission, but the shell can flip their appops.- * Ignored where the appop does not exist; the gate assertion reports it.- */- private val SPECIAL_ACCESS_COMMANDS = arrayOf(- "appops set %s SCHEDULE_EXACT_ALARM allow",- "appops set %s USE_FULL_SCREEN_INTENT allow",- ) } }
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 1a5a41ca8e..787907bf19 100644--- a/games/logicgate/src/main/assets/achievements.json+++ b/games/logicgate/src/main/assets/achievements.json@@ -1,9 +1,9 @@ [- {"id": "first_gate", "name": "First Light", "description": "Complete your first gate"},- {"id": "foundation_complete", "name": "Foundation", "description": "Complete Foundation chapter (6 levels)", "targetProgress": 6},- {"id": "routing_complete", "name": "Router", "description": "Complete Routing chapter (12 levels)", "targetProgress": 12},- {"id": "arith_complete", "name": "Arithmetician", "description": "Complete Arithmetic chapter (6 levels)", "targetProgress": 6},- {"id": "memory_complete", "name": "Mnemosyne", "description": "Complete Memory chapter (8 levels)", "targetProgress": 8},- {"id": "cpu_complete", "name": "CPU Architect", "description": "Complete CPU chapter (4 levels)", "targetProgress": 4},- {"id": "all_levels", "name": "NAND to CPU", "description": "Complete all 36 levels and build the stored-program computer", "targetProgress": 36}+ {"id": "lg2_first_circuit", "name": "First Light", "description": "Solve your first circuit"},+ {"id": "lg2_basics", "name": "Gatekeeper", "description": "Finish the Basics chapter", "targetProgress": 6},+ {"id": "lg2_routing", "name": "Router", "description": "Finish the Routing & buses chapter", "targetProgress": 5},+ {"id": "lg2_arith", "name": "Arithmetician", "description": "Finish the Arithmetic chapter", "targetProgress": 8},+ {"id": "lg2_memory", "name": "Total Recall", "description": "Finish the Memory chapter", "targetProgress": 6},+ {"id": "lg2_computer", "name": "NAND to Computer", "description": "Run three programs on a computer you built from NAND"},+ {"id": "lg2_three_stars_10", "name": "Efficiency Expert", "description": "Earn three stars on 10 levels", "targetProgress": 10} ]
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 c0b8e5a123..aba66640ce 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@@ -6,6 +6,7 @@ import com.vayunmathur.games.logicgate.platform.LogicViewModel import com.vayunmathur.games.logicgate.ui.LogicGateTheme import com.vayunmathur.library.ui.MaActivity +/** Single activity hosting the level map and the editor. */ class MainActivity : MaActivity() { @Composable override fun AppTheme(content: @Composable () -> Unit) {
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.ktindex 58f6a49737..8916e7ff00 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt@@ -12,6 +12,7 @@ import com.vayunmathur.games.logicgate.ui.ProgressionPage import com.vayunmathur.library.ui.AchievementNotification import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.util.FullscreenPage+import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack @@ -19,6 +20,7 @@ import com.vayunmathur.library.util.rememberNavBackStack fun Navigation(viewModel: LogicViewModel) { val backStack = rememberNavBackStack<Route>(Route.Progression) val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()+ GameHubComposeHook("logicgate", viewModel.achievementsManager) Box(modifier = Modifier.fillMaxSize()) { MainNavigation(backStack) { entry<Route.Progression> { ProgressionPage(backStack, viewModel) }@@ -26,7 +28,7 @@ fun Navigation(viewModel: LogicViewModel) { entry<Route.GameCenter> { GameCenterScreen( manager = viewModel.achievementsManager,- onBack = { backStack.pop() }+ onBack = { backStack.pop() }, ) } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.ktindex beb41db8c9..a9c96df9c7 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt@@ -3,9 +3,15 @@ package com.vayunmathur.games.logicgate import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable +/** Navigation destinations. */ @Serializable sealed interface Route : NavKey {+ /** The level map. */ @Serializable data object Progression : Route++ /** The circuit editor for one level. */ @Serializable data class Game(val levelId: String) : Route++ /** Achievements. */ @Serializable data object GameCenter : Route }
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.ktdeleted file mode 100644index c0f659dcde..0000000000--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt+++ /dev/null@@ -1,467 +0,0 @@-package com.vayunmathur.games.logicgate.data--/**- * Bus-enabled chip library.- * Width 1 = bit thin green 0xFF7ED8B6, 4 = nibble orange 0xFFF59E0B, 8 = byte thick blue 0xFF60A5FA.- * JOIN = Expander bits->bus thick zero cost, SPLIT = Contractor bus->bits.- */--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 inputWidths: List<Int> = inputs.map { 1 },- val outputWidths: List<Int> = outputs.map { 1 },- val eval: (List<Boolean>) -> List<Boolean>-) {- val inputCount: Int get() = inputs.size- val outputCount: Int get() = outputs.size- val totalInputBits: Int get() = inputWidths.sum()- val totalOutputBits: Int get() = outputWidths.sum()- val isSequential: Boolean get() = category == ChipCategory.MEMORY || category == ChipCategory.CPU- val isBus: Boolean get() = inputWidths.any { it > 1 } || outputWidths.any { it > 1 }- fun inputPinBitOffset(pin: Int): Int = inputWidths.take(pin).sum()- fun outputPinBitOffset(pin: Int): Int = outputWidths.take(pin).sum()- fun inputPinWidth(pin: Int): Int = inputWidths.getOrElse(pin) { 1 }- fun outputPinWidth(pin: Int): Int = outputWidths.getOrElse(pin) { 1 }- fun inputPinLabelFull(pin: Int): String {- val w = inputPinWidth(pin)- return if (w == 1) inputs[pin] else "${inputs[pin]}[${w}]"- }- fun outputPinLabelFull(pin: Int): String {- val w = outputPinWidth(pin)- return if (w == 1) outputs[pin] else "${outputs[pin]}[${w}]"- }- fun dominantBusWidth(): Int = (inputWidths + outputWidths).maxOrNull() ?: 1-}--enum class ChipCategory { PRIMITIVE, FOUNDATION, ROUTING, BUS, ARITH, MEMORY, CPU }--object ChipLibrary {- val NAND = ChipDef(- "NAND", "NAND", listOf("a", "b"), listOf("out"), 1,- "Primitive NOT(AND)", ChipCategory.PRIMITIVE,- eval = { inp -> listOf(!(inp[0] && inp[1])) }- )- val NOT = ChipDef(- "NOT", "NOT", listOf("in"), listOf("out"), 1,- "NOT=NAND(a,a)", ChipCategory.FOUNDATION,- eval = { inp -> listOf(!inp[0]) }- )- val AND = ChipDef(- "AND", "AND", listOf("a", "b"), listOf("out"), 2,- "AND", ChipCategory.FOUNDATION,- eval = { inp -> listOf(inp[0] && inp[1]) }- )- val OR = ChipDef(- "OR", "OR", listOf("a", "b"), listOf("out"), 3,- "OR", ChipCategory.FOUNDATION,- eval = { inp -> listOf(inp[0] || inp[1]) }- )- val XOR = ChipDef(- "XOR", "XOR", listOf("a", "b"), listOf("out"), 4,- "XOR", ChipCategory.FOUNDATION,- eval = { inp -> listOf(inp[0] xor inp[1]) }- )- val NOR = ChipDef(- "NOR", "NOR", listOf("a", "b"), listOf("out"), 4,- "NOR for SR latch", ChipCategory.FOUNDATION,- eval = { inp -> listOf(!(inp[0] || inp[1])) }- )- val XNOR = ChipDef(- "XNOR", "XNOR", listOf("a", "b"), listOf("out"), 5,- "XNOR equality", ChipCategory.FOUNDATION,- eval = { inp -> listOf(!(inp[0] xor inp[1])) }- )-- val MUX = ChipDef(- "MUX", "MUX", listOf("a", "b", "sel"), listOf("out"), 4,- "sel?b:a", ChipCategory.ROUTING,- eval = { inp -> listOf(if (inp[2]) inp[1] else inp[0]) }- )- val DMUX = ChipDef(- "DMUX", "DMUX", listOf("in", "sel"), listOf("a", "b"), 3,- "in->a|b", ChipCategory.ROUTING,- eval = { inp ->- val inn = inp[0]- val sel = inp[1]- if (sel) listOf(false, inn) else listOf(inn, false)- }- )- val MUX4 = ChipDef(- "MUX4", "MUX4", listOf("a", "b", "c", "d", "sel0", "sel1"), listOf("out"), 12,- "4-way mux", ChipCategory.ROUTING,- eval = { inp ->- val sel = (if (inp[5]) 2 else 0) + (if (inp[4]) 1 else 0)- listOf(inp[sel])- }- )- val DMUX4 = ChipDef(- "DMUX4", "DMUX4", listOf("in", "sel0", "sel1"), listOf("a", "b", "c", "d"), 8,- "Address -> one cell – RAM decoder core", ChipCategory.ROUTING,- eval = { inp ->- val inn = inp[0]- val sel = (if (inp[2]) 2 else 0) + (if (inp[1]) 1 else 0)- List(4) { i -> i == sel && inn }- }- )- val MUX8 = ChipDef(- "MUX8", "MUX8",- listOf("a", "b", "c", "d", "e", "f", "g", "h", "sel0", "sel1", "sel2"),- listOf("out"), 24, "MUX8 RAM read", ChipCategory.ROUTING,- eval = { inp ->- val sel = (if (inp[10]) 4 else 0) + (if (inp[9]) 2 else 0) + (if (inp[8]) 1 else 0)- listOf(inp[sel])- }- )- val DMUX8 = ChipDef(- "DMUX8", "DMUX8", listOf("in", "sel0", "sel1", "sel2"),- listOf("a", "b", "c", "d", "e", "f", "g", "h"), 16,- "DMUX8 RAM write decode", ChipCategory.ROUTING,- eval = { inp ->- val inn = inp[0]- val sel = (if (inp[3]) 4 else 0) + (if (inp[2]) 2 else 0) + (if (inp[1]) 1 else 0)- List(8) { i -> i == sel && inn }- }- )-- val JOIN_8 = ChipDef(- "JOIN_8", "JOIN8 Exp 8b", (0..7).map { "b$it" }, listOf("OUT[8]"), 0,- "EXPANDER: 8 bits->BUS8[8] thick blue", ChipCategory.BUS,- inputWidths = List(8) { 1 }, outputWidths = listOf(8),- eval = { inp -> inp.take(8) }- )- val SPLIT_8 = ChipDef(- "SPLIT_8", "SPLIT8 Cont 8b", listOf("IN[8]"), (0..7).map { "b$it" }, 0,- "CONTRACTOR: BUS8[8]->8 bits", ChipCategory.BUS,- inputWidths = listOf(8), outputWidths = List(8) { 1 },- eval = { inp -> inp.take(8) }- )- val JOIN_4 = ChipDef(- "JOIN_4", "JOIN4 Exp 4b", (0..3).map { "b$it" }, listOf("OUT[4]"), 0,- "EXPANDER: 4 bits->BUS4[4] orange", ChipCategory.BUS,- inputWidths = List(4) { 1 }, outputWidths = listOf(4),- eval = { inp -> inp.take(4) }- )- val SPLIT_4 = ChipDef(- "SPLIT_4", "SPLIT4 Cont 4b", listOf("IN[4]"), (0..3).map { "b$it" }, 0,- "CONTRACTOR: BUS4[4]->bits", ChipCategory.BUS,- inputWidths = listOf(4), outputWidths = List(4) { 1 },- eval = { inp -> inp.take(4) }- )-- val MUX_B8 = ChipDef(- "MUX_B8", "MUX B8 [8]", listOf("A[8]", "B[8]", "sel"), listOf("OUT[8]"), 32,- "Bus MUX A[8],B[8],sel->OUT[8] CPU addr mux", ChipCategory.BUS,- inputWidths = listOf(8, 8, 1), outputWidths = listOf(8),- eval = { inp ->- val a = inp.slice(0..7)- val b = inp.slice(8..15)- val sel = inp[16]- if (sel) b else a- }- )- val DMUX_B8 = ChipDef(- "DMUX_B8", "DMUX B8", listOf("IN[8]", "sel"), listOf("A[8]", "B[8]"), 24,- "Bus DMUX IN[8],sel->A/B[8]", ChipCategory.BUS,- inputWidths = listOf(8, 1), outputWidths = listOf(8, 8),- eval = { inp ->- val inn = inp.slice(0..7)- val sel = inp[8]- if (sel) List(8) { false } + inn else inn + List(8) { false }- }- )- val MUX4_B8 = ChipDef(- "MUX4_B8", "MUX4 B8", listOf("A[8]", "B[8]", "C[8]", "D[8]", "sel0", "sel1"),- listOf("OUT[8]"), 96, "4-way BUS8 mux RAM read", ChipCategory.BUS,- inputWidths = listOf(8, 8, 8, 8, 1, 1), outputWidths = listOf(8),- eval = { inp ->- val sel = (if (inp[33]) 2 else 0) + (if (inp[32]) 1 else 0)- inp.slice(sel * 8 until sel * 8 + 8)- }- )- val MUX8_B8 = ChipDef(- "MUX8_B8", "MUX8 B8",- listOf("A[8]", "B[8]", "C[8]", "D[8]", "E[8]", "F[8]", "G[8]", "H[8]", "sel0", "sel1", "sel2"),- listOf("OUT[8]"), 192, "8-way BUS8", ChipCategory.BUS,- inputWidths = listOf(8, 8, 8, 8, 8, 8, 8, 8, 1, 1, 1), outputWidths = listOf(8),- eval = { inp ->- val sel = (if (inp[66]) 4 else 0) + (if (inp[65]) 2 else 0) + (if (inp[64]) 1 else 0)- inp.slice(sel * 8 until sel * 8 + 8)- }- )- val DMUX8_B = ChipDef(- "DMUX8_B", "DMUX8 B", listOf("IN[8]", "sel0", "sel1", "sel2"), List(8) { "O$it[8]" }, 128,- "Bus DMUX8 IN[8]->8 BUS8", ChipCategory.BUS,- inputWidths = listOf(8, 1, 1, 1), outputWidths = List(8) { 8 },- eval = { inp ->- val inn = inp.slice(0..7)- val sel = (if (inp[10]) 4 else 0) + (if (inp[9]) 2 else 0) + (if (inp[8]) 1 else 0)- val out = MutableList(64) { false }- for (k in 0..7) out[sel * 8 + k] = inn[k]- out- }- )-- val HALF_ADDER = ChipDef(- "HALF_ADDER", "HalfAdder", listOf("a", "b"), listOf("sum", "carry"), 6,- "sum=a^b carry=a&b", ChipCategory.ARITH,- eval = { inp -> listOf(inp[0] xor inp[1], inp[0] && inp[1]) }- )- val FULL_ADDER = ChipDef(- "FULL_ADDER", "FullAdder", listOf("a", "b", "cin"), listOf("sum", "cout"), 14,- "Full adder", ChipCategory.ARITH,- eval = { inp ->- val a = inp[0]- val b = inp[1]- val cin = inp[2]- listOf(a xor b xor cin, (a && b) || (b && cin) || (a && cin))- }- )- val ADDER_4 = ChipDef(- "ADDER_4", "Adder4 bit",- listOf("a0", "a1", "a2", "a3", "b0", "b1", "b2", "b3"),- listOf("s0", "s1", "s2", "s3", "cout"), 56,- "4b adder bit tedious", ChipCategory.ARITH,- eval = { inp ->- val a = bitsToInt(inp.slice(0..3))- val b = bitsToInt(inp.slice(4..7))- val s = a + b- intToBits(s, 4) + listOf(s >= 16)- }- )- val ADDER_8 = ChipDef(- "ADDER_8", "Adder8 bit",- (0..7).map { "a$it" } + (0..7).map { "b$it" },- (0..7).map { "s$it" } + listOf("cout"), 112,- "8b adder bit legacy", ChipCategory.ARITH,- eval = { inp ->- val a = bitsToInt(inp.slice(0..7))- val b = bitsToInt(inp.slice(8..15))- val s = a + b- intToBits(s, 8) + listOf(s >= 256)- }- )- val ADDER_4B = ChipDef(- "ADDER_4B", "Adder4 B [4]", listOf("A[4]", "B[4]"), listOf("S[4]", "cout"), 56,- "A[4]+B[4]->S[4] bus orange", ChipCategory.ARITH,- inputWidths = listOf(4, 4), outputWidths = listOf(4, 1),- eval = { inp ->- val a = bitsToInt(inp.slice(0..3))- val b = bitsToInt(inp.slice(4..7))- val s = a + b- intToBits(s, 4) + listOf(s >= 16)- }- )- val ADDER_8B = ChipDef(- "ADDER_8B", "Adder8 B [8]", listOf("A[8]", "B[8]"), listOf("S[8]", "cout"), 112,- "A[8]+B[8]->S[8] bus blue", ChipCategory.ARITH,- inputWidths = listOf(8, 8), outputWidths = listOf(8, 1),- eval = { inp ->- val a = bitsToInt(inp.slice(0..7))- val b = bitsToInt(inp.slice(8..15))- val s = a + b- intToBits(s, 8) + listOf(s >= 256)- }- )- val INC_8 = ChipDef(- "INC_8", "INC8 B [8]", listOf("A[8]"), listOf("S[8]", "cout"), 40,- "INC bus PC=PC+1 need", ChipCategory.ARITH,- inputWidths = listOf(8), outputWidths = listOf(8, 1),- eval = { inp ->- val a = bitsToInt(inp.take(8))- val s = a + 1- intToBits(s, 8) + listOf(s >= 256)- }- )- val SUB_8 = ChipDef(- "SUB_8", "SUB8 B [8]", listOf("A[8]", "B[8]"), listOf("S[8]", "borrow"), 120,- "Subtractor bus for ALU", ChipCategory.ARITH,- inputWidths = listOf(8, 8), outputWidths = listOf(8, 1),- eval = { inp ->- val a = bitsToInt(inp.slice(0..7))- val b = bitsToInt(inp.slice(8..15))- val d = a - b- intToBits(d and 0xFF, 8) + listOf(d < 0)- }- )-- val SR_LATCH = ChipDef(- "SR_LATCH", "SRLatch", listOf("S", "R"), listOf("Q", "nQ"), 4,- "SR latch cross NOR first memory hold", ChipCategory.MEMORY,- eval = { inp ->- val s = inp[0]- val r = inp[1]- when {- r && !s -> listOf(false, true)- s && !r -> listOf(true, false)- else -> listOf(false, false)- }- }- )- val DFF = ChipDef(- "DFF", "DFF", listOf("d", "clk"), listOf("q"), 6,- "DFF edge", ChipCategory.MEMORY,- eval = { inp -> listOf(inp[0]) }- )- val BIT = ChipDef(- "BIT", "Bit", listOf("in", "load"), listOf("out"), 12,- "1-bit reg MUX+DFF", ChipCategory.MEMORY,- eval = { inp -> listOf(inp[0]) }- )- val REG_8 = ChipDef(- "REG_8", "Reg8 bit", (0..7).map { "in$it" } + listOf("load"), (0..7).map { "out$it" }, 96,- "Reg8 bit legacy", ChipCategory.MEMORY,- eval = { inp -> inp.slice(0..7) }- )- val REG_8B = ChipDef(- "REG_8B", "Reg8 B [8]", listOf("IN[8]", "load"), listOf("OUT[8]"), 96,- "Bus reg IN[8],load->OUT[8] – accumulator A", ChipCategory.MEMORY,- inputWidths = listOf(8, 1), outputWidths = listOf(8),- eval = { inp -> inp.slice(0..7) }- )- val RAM_8 = ChipDef(- "RAM_8", "RAM8 bit",- (0..7).map { "in$it" } + listOf("load") + (0..2).map { "a$it" },- (0..7).map { "out$it" }, 400, "RAM8 bit", ChipCategory.MEMORY,- eval = { inp -> inp.slice(0..7) }- )- val RAM_8B = ChipDef(- "RAM_8B", "RAM8 B [8]", listOf("IN[8]", "load", "ADDR[3]"), listOf("OUT[8]"), 400,- "RAM8 bus small prog mem", ChipCategory.MEMORY,- inputWidths = listOf(8, 1, 3), outputWidths = listOf(8),- eval = { inp -> inp.slice(0..7) }- )- val RAM_64 = ChipDef(- "RAM_64", "RAM64 bit",- (0..7).map { "in$it" } + listOf("load") + (0..5).map { "a$it" },- (0..7).map { "out$it" }, 3200, "RAM64 bit", ChipCategory.MEMORY,- eval = { inp -> inp.slice(0..7) }- )- val RAM_64B = ChipDef(- "RAM_64B", "RAM64 B [8]", listOf("IN[8]", "load", "ADDR[6]"), listOf("OUT[8]"), 3200,- "RAM64 bus data for programs", ChipCategory.MEMORY,- inputWidths = listOf(8, 1, 6), outputWidths = listOf(8),- eval = { inp -> inp.slice(0..7) }- )- val PC_8 = ChipDef(- "PC_8", "PC Bus [8]", listOf("IN[8]", "inc", "load", "reset"), listOf("OUT[8]"), 120,- "PC bus reset=0 load=IN inc=PC+1 – instruction pointer", ChipCategory.MEMORY,- inputWidths = listOf(8, 1, 1, 1), outputWidths = listOf(8),- eval = { inp -> inp.slice(0..7) }- )- val RAM_256 = ChipDef(- "RAM_256", "RAM256 bit",- (0..7).map { "in$it" } + listOf("load") + (0..7).map { "a$it" },- (0..7).map { "out$it" }, 12000, "RAM256 bit", ChipCategory.MEMORY,- eval = { inp -> inp.slice(0..7) }- )- val RAM_256B = ChipDef(- "RAM_256B", "RAM256 Main [8]", listOf("IN[8]", "load", "ADDR[8]"), listOf("OUT[8]"), 12000,- "Main mem 256×8 BUS von Neumann prog+data share RAM", ChipCategory.MEMORY,- inputWidths = listOf(8, 1, 8), outputWidths = listOf(8),- eval = { inp -> inp.slice(0..7) }- )-- val ALU_8 = ChipDef(- "ALU_8", "ALU Bus", listOf("A[8]", "B[8]", "OP[3]"),- listOf("OUT[8]", "zero", "carry", "neg"), 300, "ALU bus", ChipCategory.CPU,- inputWidths = listOf(8, 8, 3), outputWidths = listOf(8, 1, 1, 1),- eval = { inp -> alu8Eval(inp) }- )- val CPU = ChipDef(- "CPU", "CPU Bus [4][8]", listOf("OPCODE[4]", "ADDR[8]", "DATA[8]", "reset"),- listOf("OUT[8]", "writeM", "ADDR_M[8]", "PC[8]"), 2000,- "CPU fetch-decode-execute FROM RAM", ChipCategory.CPU,- inputWidths = listOf(4, 8, 8, 1), outputWidths = listOf(8, 1, 8, 8),- eval = { _ -> List(25) { false } }- )- val CPU_8 = ChipDef(- "CPU_8", "CPU compat", CPU.inputs, CPU.outputs, CPU.nandCost, CPU.description, ChipCategory.CPU,- inputWidths = CPU.inputWidths, outputWidths = CPU.outputWidths, eval = CPU.eval- )- val COMPUTER = ChipDef(- "COMPUTER", "Computer RAM [8]", listOf("reset"), listOf("OUT[8]"), 15000,- "Final von Neumann", ChipCategory.CPU,- inputWidths = listOf(1), outputWidths = listOf(8),- eval = { _ -> intToBits(8, 8) }- )-- val all: Map<String, ChipDef> = listOf(- NAND, NOT, AND, OR, XOR, NOR, XNOR,- MUX, DMUX, MUX4, DMUX4, MUX8, DMUX8,- JOIN_8, SPLIT_8, JOIN_4, SPLIT_4, MUX_B8, DMUX_B8, MUX4_B8, MUX8_B8, DMUX8_B,- HALF_ADDER, FULL_ADDER, ADDER_4, ADDER_8, ADDER_4B, ADDER_8B, INC_8, SUB_8,- SR_LATCH, DFF, BIT, REG_8, REG_8B, RAM_8, RAM_8B, RAM_64, RAM_64B, PC_8, RAM_256, RAM_256B,- ALU_8, CPU, CPU_8, COMPUTER- ).associateBy { it.id }-- // Legacy ids from old saves / level text (no underscores, EXPANDER/CONTRACTOR names).- private val legacyAliases: Map<String, String> = mapOf(- "JOIN8" to "JOIN_8",- "SPLIT8" to "SPLIT_8",- "JOIN4" to "JOIN_4",- "SPLIT4" to "SPLIT_4",- "EXPANDER_8" to "JOIN_8",- "CONTRACTOR_8" to "SPLIT_8",- "EXPANDER_4" to "JOIN_4",- "CONTRACTOR_4" to "SPLIT_4",- "MUX_B" to "MUX_B8"- )-- fun get(id: String): ChipDef {- val canonical = legacyAliases[id] ?: id- return all[canonical]- ?: error("Unknown chip $id – use JOIN_8 expander or SPLIT_8 contractor")- }-- // 8-bit ALU spec constants: byte mask/modulus, sign bit, and opcode values.- private const val BYTE_MASK = 0xFF- private const val BYTE_MODULUS = 256- private const val SIGN_BIT_MASK = 0x80- private const val BYTE_WIDTH = 8- private const val OP_OR = 3- private const val OP_XOR = 4- private const val OP_NOT = 5- private const val OP_INC = 6-- private fun alu8Eval(inp: List<Boolean>): List<Boolean> {- val a = bitsToInt(inp.slice(0..7))- val b = bitsToInt(inp.slice(8..15))- val op = (if (inp[18]) 4 else 0) + (if (inp[17]) 2 else 0) + (if (inp[16]) 1 else 0)- val (res, c) = when (op) {- 0 -> {- val s = a + b- (s and BYTE_MASK) to (s >= BYTE_MODULUS)- }- 1 -> {- val d = a - b- (d and BYTE_MASK) to (d < 0)- }- 2 -> (a and b) to false- OP_OR -> (a or b) to false- OP_XOR -> (a xor b) to false- OP_NOT -> (a.inv() and BYTE_MASK) to false- OP_INC -> {- val s = a + 1- (s and BYTE_MASK) to (s >= BYTE_MODULUS)- }- else -> {- val d = a - 1- (d and BYTE_MASK) to (d < 0)- }- }- return intToBits(res, BYTE_WIDTH) + listOf(res == 0, c, (res and SIGN_BIT_MASK) != 0)- }-- fun bitsToInt(bits: List<Boolean>): Int {- var v = 0- bits.forEachIndexed { i, b -> if (b) v = v or (1 shl i) }- return v- }- fun intToBits(value: Int, width: Int): List<Boolean> = 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.ktdeleted file mode 100644index 8343fc802f..0000000000--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt+++ /dev/null@@ -1,236 +0,0 @@-package com.vayunmathur.games.logicgate.data--/**- * Bus-aware circuit: Wire.busWidth 1=thin bit, 4=orange nibble bus, 8=blue byte bus.- * JOIN_8 = Expander bits->BUS8 (0 cost, less tedious), SPLIT_8 = Contractor BUS8->bits.- * Level I/O terminals also have widths: ADDER_8B uses A[8], B[8] not 16 thin wires.- */--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, val busWidth: Int = 1)-data class OutputMapping(val outputIndex: Int, val from: WireEnd)-data class IoPos(val x: Float, val y: Float)--data class Circuit(- val gates: List<PlacedChip> = emptyList(),- val wires: List<Wire> = emptyList(),- val outputMappings: List<OutputMapping> = emptyList(),- val inputPositions: Map<Int, IoPos> = emptyMap(),- val outputPositions: Map<Int, IoPos> = emptyMap()-) { 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 {- internal 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()- }-- fun evaluate(level: LevelDef, circuit: Circuit): EvalResult {- if (isMemoryLevel(level) || containsSequentialGate(circuit)) {- return evaluateIterativeFull(level, circuit)- }- val bits = level.totalInputBits- val quick = if (bits == 0) emptyList() else List(bits) { false }- val qc = evalCombo(level, circuit, quick)- if (qc is ComboEval.Err) return EvalResult.Error(qc.msg)- if (qc is ComboEval.Cycle) {- return evaluateIterativeFull(level, circuit)- }- val res = mutableListOf<List<Boolean>>()- for (c in CircuitSampling.comboIndices(bits)) {- val flat = CircuitSampling.decodeCombo(c, bits)- when (val r = evalCombo(level, circuit, flat)) {- is ComboEval.Ok -> res.add(r.outputs)- is ComboEval.Err -> return EvalResult.Error("Row ${formatCombo(flat)}: ${r.msg}")- is ComboEval.Cycle -> return evaluateIterativeFull(level, circuit)- }- }- return EvalResult.Success(res)- }-- private fun evaluateIterativeFull(level: LevelDef, circuit: Circuit): EvalResult {- val bits = level.totalInputBits- val res = mutableListOf<List<Boolean>>()- for (c in CircuitSampling.comboIndices(bits)) {- val flat = CircuitSampling.decodeCombo(c, bits)- when (val r = evalComboIterative(level, circuit, flat)) {- is ComboEval.Ok -> res.add(r.outputs)- is ComboEval.Err -> return EvalResult.Error("Row ${formatCombo(flat)}: ${r.msg}")- is ComboEval.Cycle -> return EvalResult.Cycle(r.ids)- }- }- return EvalResult.Success(res)- }-- fun evaluateFullCorrectness(level: LevelDef, circuit: Circuit): Pair<Boolean, List<Int>> {- // SR latch structural pass – 2 NOR cross-coupled = first memory, feedback cycle required- if (level.id == "SR_LATCH" && isSrLatchStructureValid(circuit)) return true to emptyList()- val target = ComboShared.chipOrNull(level.targetChipId) ?: return false to emptyList()- val inBits = level.totalInputBits- val outBits = level.totalOutputBits- val vectors: List<List<Boolean>> = CircuitSampling.vectors(inBits)- val expected = vectors.map { target.eval(it).take(outBits) }- val actual = mutableListOf<List<Boolean>>()- for (vec in vectors) {- when (val r = evalComboWithMemoryFallback(level, circuit, vec)) {- is ComboEval.Ok -> actual.add(r.outputs)- else -> return false to listOf(0)- }- }- return (collectFailing(level, vectors, expected, actual).isEmpty()) to- collectFailing(level, vectors, expected, actual)- }-- private fun collectFailing(- level: LevelDef,- vectors: List<List<Boolean>>,- expected: List<List<Boolean>>,- actual: List<List<Boolean>>,- ): List<Int> {- val failing = mutableListOf<Int>()- for (i in expected.indices) {- collectOneFailure(level, vectors, expected, actual, i)?.let { failing.add(it) }- }- return failing- }-- private fun collectOneFailure(- level: LevelDef,- vectors: List<List<Boolean>>,- expected: List<List<Boolean>>,- actual: List<List<Boolean>>,- i: Int,- ): Int? {- if (i >= actual.size) return i- if (isHoldRow(level, vectors[i])) return null- if (expected[i] != actual[i]) return i- return null- }-- private fun isHoldRow(level: LevelDef, inp: List<Boolean>): Boolean {- if (level.id != "SR_LATCH") return false- val s = inp.getOrElse(0) { false }- val r = inp.getOrElse(1) { false }- return !s && !r- }-- fun isCorrect(level: LevelDef, circuit: Circuit): Pair<Boolean, List<Int>> = evaluateFullCorrectness(level, circuit)-- private fun isMemoryLevel(level: LevelDef): Boolean = level.chapter == ChapterId.MEMORY-- private fun containsSequentialGate(circuit: Circuit): Boolean {- return circuit.gates.any { ComboShared.chipOrNull(it.chipId)?.isSequential == true }- }-- private fun isSrLatchStructureValid(circuit: Circuit): Boolean {- val norGates = circuit.gates.filter { it.chipId == "NOR" }- if (norGates.size < 2) return false- val ids = norGates.map { it.instanceId }.toSet()- val crossWires = circuit.wires.filter {- it.from.instanceId in ids && it.to.instanceId in ids && it.from.instanceId != it.to.instanceId- }- if (crossWires.size < 2) return false- val fromTo = crossWires.map { it.from.instanceId to it.to.instanceId }.toSet()- val hasBothDirections = norGates.any { a ->- norGates.any { b ->- a.instanceId != b.instanceId &&- (a.instanceId to b.instanceId) in fromTo &&- (b.instanceId to a.instanceId) in fromTo- }- }- if (!hasBothDirections) return false- val inputWires = circuit.wires.filter {- it.from.instanceId.startsWith("__IN_") && it.to.instanceId in ids- }- if (inputWires.size < 2) return false- if (circuit.outputMappings.size < 2) return false- return true- }-- private fun evalComboWithMemoryFallback(level: LevelDef, circuit: Circuit, flatInputs: List<Boolean>): ComboEval {- val r = evalCombo(level, circuit, flatInputs)- return if (r is ComboEval.Cycle && (isMemoryLevel(level) || containsSequentialGate(circuit))) {- evalComboIterative(level, circuit, flatInputs)- } else r- }-- private fun evalComboIterative(- level: LevelDef,- circuit: Circuit,- flatInputs: List<Boolean>,- ): ComboEval = ComboIterative.eval(level, circuit, flatInputs)-- private fun evalCombo(level: LevelDef, circuit: Circuit, flatInputs: List<Boolean>): ComboEval {- val computed = mutableMapOf<String, List<Boolean>>()- ComboIterative.seedInputs(level, flatInputs, computed)- val graph = ComboOrdered.buildGraph(circuit)- val order = topoSort(circuit.gates.map { it.instanceId }, graph.deps)- ?: return ComboEval.Cycle(circuit.gates.map { it.instanceId })- return ComboOrdered.eval(level, circuit, order, graph, computed)- }-- 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- }-- // Shared sampling util — same sequence used by evaluator and TruthTableView.- // Previously TruthTableView used a different seed/pattern vs the evaluator,- // so failingRows indices mismatched the display.- fun generateSampleVectors(- totalInputBits: Int,- limit: Int = CircuitSampling.SAMPLE_LIMIT,- ): List<List<Boolean>> {- return CircuitSampling.vectors(totalInputBits, limit)- }-- fun generateTruthTable(- target: ChipDef,- inputBits: Int,- outputBits: Int,- limit: Int = CircuitSampling.SAMPLE_LIMIT,- ): List<List<Boolean>> {- val exhaustive = CircuitSampling.EXHAUSTIVE_BITS- val total = if (inputBits <= exhaustive) {- 1 shl inputBits- } else {- minOf(limit, 1 shl minOf(inputBits, CircuitSampling.HIGH_BIT_COUNT))- }- return if (inputBits <= exhaustive) {- (0 until total).map { c ->- val inp = List(inputBits) { i -> ((c shr i) and 1) == 1 }- target.eval(inp).take(outputBits)- }- } else {- val vecs = generateSampleVectors(inputBits, minOf(limit, total))- vecs.map { inp -> target.eval(inp).take(outputBits) }- }- }-- fun formatCombo(bits: List<Boolean>): String = bits.joinToString("") { if (it) "1" else "0" }-}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitSampling.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitSampling.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitSampling.ktdeleted file mode 100644index 4d8164e1b0..0000000000--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitSampling.kt+++ /dev/null@@ -1,69 +0,0 @@-package com.vayunmathur.games.logicgate.data--/**- * Shared input-vector sampling for the evaluator.- *- * Exhaustive up to [EXHAUSTIVE_BITS] inputs; beyond that a seeded random- * sample (plus all-off / all-on / alternating anchors) capped at- * [SAMPLE_LIMIT]. The seed is fixed so the evaluator, the truth-table view- * and the correctness check all agree on row indices.- */-internal object CircuitSampling {- const val EXHAUSTIVE_BITS = 10- const val SAMPLE_LIMIT = 256- const val SAMPLE_SEED = 1234L- const val HIGH_BIT_COUNT = 20- const val MAX_SETTLE_ITERS = 30-- /** Bit, nibble and byte bus widths used across evaluator hints. */- const val BIT = 1- const val BUS_4 = 4- const val BUS_8 = 8-- /** All combos to try for [bits] inputs: exhaustive or seeded sample. */- fun combos(bits: Int): List<List<Boolean>> = vectors(bits, SAMPLE_LIMIT)-- fun vectors(totalInputBits: Int, limit: Int = SAMPLE_LIMIT): List<List<Boolean>> {- if (totalInputBits <= EXHAUSTIVE_BITS) {- return (0 until (1 shl totalInputBits)).map { c -> decode(c, totalInputBits) }.take(limit)- }- val rnd = java.util.Random(SAMPLE_SEED)- val vs = mutableListOf<List<Boolean>>()- vs.add(List(totalInputBits) { false })- vs.add(List(totalInputBits) { true })- vs.add(List(totalInputBits) { it % 2 == 0 })- while (vs.size < limit) vs.add(List(totalInputBits) { rnd.nextBoolean() })- return vs- }-- /** Combo index list used by the row loop (int form, decoded per row). */- fun comboIndices(bits: Int): List<Int> {- if (bits <= EXHAUSTIVE_BITS) return (0 until (1 shl bits)).toList()- val rnd = java.util.Random(SAMPLE_SEED)- val set = LinkedHashSet<Int>()- set.add(0)- set.add((1 shl minOf(bits, HIGH_BIT_COUNT)) - 1)- while (set.size < SAMPLE_LIMIT) {- var v = 0- for (b in 0 until minOf(bits, HIGH_BIT_COUNT)) {- if (rnd.nextBoolean()) v = v or (1 shl b)- }- set.add(v)- }- return set.toList()- }-- fun decodeCombo(c: Int, bits: Int): List<Boolean> {- if (bits == 0) return emptyList()- return List(bits) { i ->- if (i < HIGH_BIT_COUNT) {- ((c shr i) and 1) == 1- } else {- java.util.Random(c.toLong() + i).nextBoolean()- }- }- }-- private fun decode(c: Int, bits: Int): List<Boolean> =- List(bits) { i -> ((c shr i) and 1) == 1 }-}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.ktnew file mode 100644index 0000000000..49c3bc03ef--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt@@ -0,0 +1,115 @@+package com.vayunmathur.games.logicgate.data++import android.content.Context+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.Gate+import com.vayunmathur.games.logicgate.domain.model.LevelInput+import com.vayunmathur.games.logicgate.domain.model.LevelOutput+import com.vayunmathur.games.logicgate.domain.model.Node+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.PinSide+import com.vayunmathur.games.logicgate.domain.model.Point+import com.vayunmathur.games.logicgate.domain.model.Wire+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.serialization.SerializationException+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/** Saved node. [kind] is `gate`, `in` or `out`. */+@Serializable+data class NodeDto(+ val id: Int,+ val kind: String,+ val chip: String? = null,+ val index: Int = 0,+ val x: Float,+ val y: Float,+)++/** Saved pin reference. */+@Serializable+data class PinDto(val node: Int, val out: Boolean, val index: Int)++/** Saved wire. */+@Serializable+data class WireDto(val from: PinDto, val to: PinDto)++/** Saved circuit draft. */+@Serializable+data class CircuitDto(val nodes: List<NodeDto>, val wires: List<WireDto>, val nextId: Int)++/**+ * Per-level circuit drafts, as one JSON map in the shared DataStore. Saves are debounced on the+ * store's own scope rather than the ViewModel's, so the last edit still lands after the screen+ * closes.+ */+class CircuitStore(context: Context, dispatcher: CoroutineDispatcher) {+ private val ds = DataStoreUtils.getInstance(context)+ private val scope = CoroutineScope(SupervisorJob() + dispatcher)+ private val json = Json { ignoreUnknownKeys = true }+ private var pending: Job? = null++ suspend fun load(levelId: String): Circuit? = decode(ds.getStringAwait(KEY))[levelId]?.toDomain()++ fun save(levelId: String, circuit: Circuit) {+ pending?.cancel()+ pending = scope.launch {+ delay(SAVE_DEBOUNCE_MS)+ val dto = circuit.toDto()+ ds.updateString(KEY) { old -> json.encodeToString(decode(old) + (levelId to dto)) }+ }+ }++ private fun decode(raw: String?): Map<String, CircuitDto> {+ if (raw.isNullOrEmpty()) return emptyMap()+ return try {+ json.decodeFromString<Map<String, CircuitDto>>(raw)+ } catch (ignored: SerializationException) {+ emptyMap()+ }+ }++ private companion object {+ const val KEY = "logicgate2_circuits"+ const val SAVE_DEBOUNCE_MS = 400L+ }+}++private fun PinRef.toDto() = PinDto(node.raw, side == PinSide.OUT, index)++private fun PinDto.toDomain() = PinRef(NodeId(node), if (out) PinSide.OUT else PinSide.IN, index)++private fun Node.toDto(): NodeDto = when (this) {+ is Gate -> NodeDto(id.raw, "gate", chip = chipId, x = pos.x, y = pos.y)+ is LevelInput -> NodeDto(id.raw, "in", index = index, x = pos.x, y = pos.y)+ is LevelOutput -> NodeDto(id.raw, "out", index = index, x = pos.x, y = pos.y)+}++private fun NodeDto.toDomain(): Node? {+ val p = Point(x, y)+ return when (kind) {+ "gate" -> chip?.let { Gate(NodeId(id), it, p) }+ "in" -> LevelInput(NodeId(id), index, p)+ "out" -> LevelOutput(NodeId(id), index, p)+ else -> null+ }+}++internal fun Circuit.toDto() = CircuitDto(+ nodes = nodes.map { it.toDto() },+ wires = wires.map { WireDto(it.from.toDto(), it.to.toDto()) },+ nextId = nextId,+)++internal fun CircuitDto.toDomain() = Circuit(+ nodes = nodes.mapNotNull { it.toDomain() },+ wires = wires.map { Wire(it.from.toDomain(), it.to.toDomain()) },+ nextId = nextId,+)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComboEvaluators.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComboEvaluators.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComboEvaluators.ktdeleted file mode 100644index a6ed6dcc6b..0000000000--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComboEvaluators.kt+++ /dev/null@@ -1,370 +0,0 @@-package com.vayunmathur.games.logicgate.data--import com.vayunmathur.games.logicgate.data.CircuitEvaluator.ComboEval-import com.vayunmathur.library.log.Log--/**- * Combo-evaluation strategies for [CircuitEvaluator].- *- * Split out: TooManyFunctions cap (25/class). Same module and package, so- * internal access is unchanged; behavior identical.- *- * - [ComboShared]: wire-slice resolution and output reading used by both strategies.- * - [ComboIterative]: fixed-point settling for sequential/feedback circuits.- * - [ComboOrdered]: single topological pass for combinational circuits.- */-internal object ComboShared {- private const val TAG = "ComboShared"-- internal fun chipOrNull(chipId: String): ChipDef? {- // Unknown chip ids come from stale saves; callers treat null as Unevaluated.- @Suppress("TooGenericExceptionCaught")- fun lookup(): ChipDef? {- return try {- ChipLibrary.get(chipId)- } catch (e: Exception) {- Log.debug(TAG, "unknown chip $chipId", e)- null- }- }- return lookup()- }-- internal fun sliceOrBlank(src: List<Boolean>, off: Int, width: Int): List<Boolean> {- if (off + width <= src.size) return src.slice(off until off + width)- return List(width) { k -> src.getOrElse(off + k) { false } }- }-- internal fun padOutputs(outVals: List<Boolean>, totalBits: Int): List<Boolean> {- if (outVals.size < totalBits) return outVals + List(totalBits - outVals.size) { false }- return outVals.take(totalBits)- }-- internal fun sourceDef(circuit: Circuit, wire: Wire): ChipDef? {- if (wire.from.instanceId.startsWith("__IN_")) return null- val placed = circuit.gates.find { it.instanceId == wire.from.instanceId } ?: return null- return chipOrNull(placed.chipId)- }-- internal fun sourceDefFor(from: WireEnd, circuit: Circuit): ChipDef? {- if (from.instanceId.startsWith("__IN_")) return null- val placed = circuit.gates.find { it.instanceId == from.instanceId } ?: return null- return chipOrNull(placed.chipId)- }-- internal fun readOutputs(- level: LevelDef,- circuit: Circuit,- computed: Map<String, List<Boolean>>,- ): ComboEval {- val outMap = circuit.outputMappings.associateBy { it.outputIndex }- val flatOut = mutableListOf<Boolean>()- for (oi in 0 until level.outputs.size) {- val slice = readOneOutput(level, circuit, computed, outMap, oi)- ?: return readOutputError(level, outMap, oi)- flatOut.addAll(slice)- }- return ComboEval.Ok(flatOut)- }-- private fun readOneOutput(- level: LevelDef,- circuit: Circuit,- computed: Map<String, List<Boolean>>,- outMap: Map<Int, OutputMapping>,- oi: Int,- ): List<Boolean>? {- val map = outMap[oi] ?: return null- val srcVals = computed[map.from.instanceId] ?: return null- val expectedW = level.outputWidth(oi)- val srcDef = sourceDefFor(map.from, circuit)- val srcOff = srcDef?.outputPinBitOffset(map.from.pinIndex) ?: 0- return sliceOrBlank(srcVals, srcOff, expectedW)- }-- private fun readOutputError(- level: LevelDef,- outMap: Map<Int, OutputMapping>,- oi: Int,- ): ComboEval {- val map = outMap[oi]- if (map == null) {- return ComboEval.Err(- "Output ${level.outputs[oi]} not connected – " +- "drag from gate output dot to output terminal pill",- )- }- return ComboEval.Err("Output ${level.outputs[oi]} source not computed")- }-}--internal object ComboIterative {- private const val TAG = "ComboIterative"- internal fun eval(level: LevelDef, circuit: Circuit, flatInputs: List<Boolean>): ComboEval {- val computed = mutableMapOf<String, List<Boolean>>()- seedInputs(level, flatInputs, computed)- seedGatesBlank(circuit, computed)- val incoming = buildIncoming(circuit)- settleGates(circuit, computed, incoming)- return ComboShared.readOutputs(level, circuit, computed)- }-- internal fun seedInputs(- level: LevelDef,- flatInputs: List<Boolean>,- computed: MutableMap<String, List<Boolean>>,- ) {- for (idx in level.inputs.indices) {- val off = level.inputBitOffset(idx)- val w = level.inputWidth(idx)- computed["__IN_$idx"] = ComboShared.sliceOrBlank(flatInputs, off, w)- }- }-- private fun seedGatesBlank(circuit: Circuit, computed: MutableMap<String, List<Boolean>>) {- for (g in circuit.gates) {- val def = ComboShared.chipOrNull(g.chipId) ?: continue- computed[g.instanceId] = List(def.totalOutputBits) { false }- }- }-- private fun buildIncoming(circuit: Circuit): Map<String, MutableMap<Int, Wire>> {- val incoming = mutableMapOf<String, MutableMap<Int, Wire>>()- circuit.gates.forEach { g -> incoming[g.instanceId] = mutableMapOf() }- for (w in circuit.wires) {- val dst = w.to.instanceId- if (dst.startsWith("__OUT_")) continue- incoming[dst]?.put(w.to.pinIndex, w)- }- return incoming- }-- private fun settleGates(- circuit: Circuit,- computed: MutableMap<String, List<Boolean>>,- incoming: Map<String, MutableMap<Int, Wire>>,- ) {- var changed: Boolean- var iters = 0- do {- changed = false- iters++- for (placed in circuit.gates) {- if (settleOneGate(circuit, placed, computed, incoming)) changed = true- }- } while (changed && iters < CircuitSampling.MAX_SETTLE_ITERS)- }-- private fun settleOneGate(- circuit: Circuit,- placed: PlacedChip,- computed: MutableMap<String, List<Boolean>>,- incoming: Map<String, MutableMap<Int, Wire>>,- ): Boolean {- val def = ComboShared.chipOrNull(placed.chipId) ?: return false- val flatIn = MutableList(def.totalInputBits) { false }- if (!gatherGateInputs(circuit, placed, def, computed, incoming, flatIn)) return false- // A throwing chip eval is a skipped update here; the fixed-point loop- // converges around it and readOutputs reports what never settled.- @Suppress("TooGenericExceptionCaught")- fun evalLenient(): List<Boolean>? {- return try {- def.eval(flatIn)- } catch (e: Exception) {- Log.debug(TAG, "chip ${def.id} eval failed; skipping update", e)- null- }- }- val outVals = evalLenient() ?: return false- val padded = ComboShared.padOutputs(outVals, def.totalOutputBits)- if (computed[placed.instanceId] == padded) return false- computed[placed.instanceId] = padded- return true- }-- private fun gatherGateInputs(- circuit: Circuit,- placed: PlacedChip,- def: ChipDef,- computed: Map<String, List<Boolean>>,- incoming: Map<String, MutableMap<Int, Wire>>,- flatIn: MutableList<Boolean>,- ): Boolean {- for (pin in 0 until def.inputCount) {- if (!gatherOnePin(circuit, placed, def, computed, incoming, flatIn, pin)) return false- }- return true- }-- private fun gatherOnePin(- circuit: Circuit,- placed: PlacedChip,- def: ChipDef,- computed: Map<String, List<Boolean>>,- incoming: Map<String, MutableMap<Int, Wire>>,- flatIn: MutableList<Boolean>,- pin: Int,- ): Boolean {- val wire = incoming[placed.instanceId]?.get(pin) ?: return false- val srcVals = computed[wire.from.instanceId] ?: return false- val slice = resolveSourceSlice(circuit, wire, srcVals)- val dstOff = def.inputPinBitOffset(pin)- for (k in slice.indices) {- if (dstOff + k < flatIn.size) flatIn[dstOff + k] = slice[k]- }- return true- }-- private fun resolveSourceSlice(- circuit: Circuit,- wire: Wire,- srcVals: List<Boolean>,- ): List<Boolean> {- val srcDef = ComboShared.sourceDef(circuit, wire)- val srcOff = srcDef?.outputPinBitOffset(wire.from.pinIndex) ?: 0- return ComboShared.sliceOrBlank(srcVals, srcOff, wire.busWidth)- }-}--internal object ComboOrdered {- internal class ComboGraph(- val deps: Map<String, Set<String>>,- val incoming: Map<String, Map<Int, Wire>>,- )-- internal fun eval(- level: LevelDef,- circuit: Circuit,- order: List<String>,- graph: ComboGraph,- computed: MutableMap<String, List<Boolean>>,- ): ComboEval {- for (gid in order) {- val step = evalOrderedGate(level, circuit, computed, graph.incoming, gid) ?: continue- if (step is ComboEval.Err || step is ComboEval.Cycle) return step- }- return ComboShared.readOutputs(level, circuit, computed)- }-- internal fun buildGraph(circuit: Circuit): ComboGraph {- val deps = mutableMapOf<String, MutableSet<String>>()- val incoming = mutableMapOf<String, MutableMap<Int, Wire>>()- circuit.gates.forEach { g ->- deps[g.instanceId] = mutableSetOf()- incoming[g.instanceId] = mutableMapOf()- }- for (w in circuit.wires) {- val dst = w.to.instanceId- if (dst.startsWith("__OUT_")) continue- if (incoming.containsKey(dst)) {- incoming[dst]!![w.to.pinIndex] = w- if (!w.from.instanceId.startsWith("__IN_")) deps[dst]?.add(w.from.instanceId)- }- }- return ComboGraph(deps, incoming)- }-- /**- * Evaluates one gate in topological order. Returns null to advance,- * or a terminal [ComboEval] to stop the whole combo.- */- private fun evalOrderedGate(- level: LevelDef,- circuit: Circuit,- computed: MutableMap<String, List<Boolean>>,- incoming: Map<String, Map<Int, Wire>>,- gid: String,- ): ComboEval? {- val placed = circuit.gates.find { it.instanceId == gid } ?: return null- val def = ChipLibrary.get(placed.chipId)- val flatIn = MutableList(def.totalInputBits) { false }- for (pin in 0 until def.inputCount) {- val err = gatherComboPin(level, circuit, computed, incoming, def, flatIn, gid, pin)- if (err != null) return err- }- // Chip eval lambdas are arbitrary code; any failure is an error row, not a crash.- @Suppress("TooGenericExceptionCaught")- fun evalLenient(): ComboEval? {- return try {- computed[gid] = ComboShared.padOutputs(def.eval(flatIn), def.totalOutputBits)- null- } catch (e: Exception) {- ComboEval.Err("Eval ${def.id}: ${e.message}")- }- }- return evalLenient()- }-- private fun gatherComboPin(- level: LevelDef,- circuit: Circuit,- computed: Map<String, List<Boolean>>,- incoming: Map<String, Map<Int, Wire>>,- def: ChipDef,- flatIn: MutableList<Boolean>,- gid: String,- pin: Int,- ): ComboEval.Err? {- val wire = incoming[gid]?.get(pin) ?: return pinError(def, pin, "unconnected")- val need = def.inputPinWidth(pin)- if (wire.busWidth != need) return ComboEval.Err(widthHint(def, pin, need, wire.busWidth))- val srcVals = computed[wire.from.instanceId]- ?: return ComboEval.Err("Source ${wire.from.instanceId} not computed (cycle?)")- checkSourceWidth(level, circuit, wire)?.let { return it }- val srcDef = ComboShared.sourceDef(circuit, wire)- val srcOff = srcDef?.outputPinBitOffset(wire.from.pinIndex) ?: 0- val slice = ComboShared.sliceOrBlank(srcVals, srcOff, wire.busWidth)- copySlice(flatIn, def.inputPinBitOffset(pin), slice)- return null- }-- private fun pinError(def: ChipDef, pin: Int, reason: String): ComboEval.Err {- val label = def.inputs.getOrElse(pin) { "in$pin" }- return ComboEval.Err(- "Gate ${def.displayName}[$label] $reason – " +- "${def.inputs.size} pins need wires",- )- }-- private fun widthHint(def: ChipDef, pin: Int, need: Int, got: Int): String {- val hint = when {- need == CircuitSampling.BUS_8 && got == CircuitSampling.BIT ->- "JOIN_8 expander (8 bits → BUS8[8] thick blue)"- need == CircuitSampling.BIT && got == CircuitSampling.BUS_8 ->- "SPLIT_8 contractor (BUS8 → bits)"- need == CircuitSampling.BUS_4 && got == CircuitSampling.BIT ->- "JOIN_4 (4 bits → BUS4[4] orange)"- need == CircuitSampling.BIT && got == CircuitSampling.BUS_4 ->- "SPLIT_4 (BUS4 → bits)"- else -> "JOIN/SPLIT expander/contractor to convert"- }- return "Width mismatch ${def.displayName}.${def.inputs[pin]}: " +- "need ${need}b got ${got}b. Use $hint."- }-- private fun checkSourceWidth(- level: LevelDef,- circuit: Circuit,- wire: Wire,- ): ComboEval.Err? {- val srcDef = ComboShared.sourceDef(circuit, wire)- val srcW = srcDef?.outputPinWidth(wire.from.pinIndex) ?: inputSourceWidth(level, wire)- if (srcW == wire.busWidth) return null- return ComboEval.Err(- "Src width mismatch ${wire.from.instanceId}[${wire.from.pinIndex}] " +- "is ${srcW}b vs wire ${wire.busWidth}b",- )- }-- private fun inputSourceWidth(level: LevelDef, wire: Wire): Int {- val ti = wire.from.instanceId.removePrefix("__IN_").toIntOrNull() ?: -1- if (ti >= 0) return level.inputWidth(ti)- return CircuitSampling.BIT- }-- private fun copySlice(flatIn: MutableList<Boolean>, dstOff: Int, slice: List<Boolean>) {- for (k in slice.indices) {- if (dstOff + k < flatIn.size) flatIn[dstOff + k] = slice[k]- }- }-}
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.ktdeleted file mode 100644index 3a0ab2b55e..0000000000--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt+++ /dev/null@@ -1,442 +0,0 @@-package com.vayunmathur.games.logicgate.data--/**- * NAND -> Computer (von Neumann stored-program) progression – 36 levels.- * FOUNDATION 6, ROUTING+BUS 12, ARITH 6, MEMORY 8, CPU 4 = 36 total.- * Goal: computer runs programs FROM RAM (same 256x8 holds program bytes + data).- */--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,- val inputs: List<String>,- val inputWidths: List<Int> = inputs.map { 1 },- val outputs: List<String>,- val outputWidths: List<Int> = outputs.map { 1 },- val targetChipId: String,- val allowedChipIds: List<String>,- val flavor: String = "",- val unlocksChipId: String? = null,- val prereqs: List<String> = emptyList()-) {- val totalInputBits: Int get() = inputWidths.sum()- val totalOutputBits: Int get() = outputWidths.sum()- fun inputWidth(i: Int): Int = inputWidths.getOrElse(i) { 1 }- fun outputWidth(i: Int): Int = outputWidths.getOrElse(i) { 1 }- fun inputBitOffset(i: Int): Int = inputWidths.take(i).sum()- fun outputBitOffset(i: Int): Int = outputWidths.take(i).sum()-}--object Levels {- val all: List<LevelDef> = listOf(- // FOUNDATION 6- LevelDef(- "NOT", "NOT", ChapterId.FOUNDATION,- "Build NOT from NAND only", "NAND(in,in)=NOT",- listOf("in"), outputs = listOf("out"), targetChipId = "NOT",- allowedChipIds = listOf("NAND"),- flavor = "Everything starts with NAND", unlocksChipId = "NOT"- ),- LevelDef(- "AND", "AND", ChapterId.FOUNDATION,- "Build AND: a AND b", "NOT(NAND(a,b))",- listOf("a", "b"), outputs = listOf("out"), targetChipId = "AND",- allowedChipIds = listOf("NAND", "NOT"),- unlocksChipId = "AND", prereqs = listOf("NOT")- ),- LevelDef(- "OR", "OR", ChapterId.FOUNDATION,- "Build OR: a OR b", "NAND(NOT a, NOT b)",- listOf("a", "b"), outputs = listOf("out"), targetChipId = "OR",- allowedChipIds = listOf("NAND", "NOT", "AND"),- flavor = "De Morgan", unlocksChipId = "OR", prereqs = listOf("AND")- ),- LevelDef(- "XOR", "XOR", ChapterId.FOUNDATION,- "XOR a^b – adder brick", "(a&!b)|(!a&b)",- listOf("a", "b"), outputs = listOf("out"), targetChipId = "XOR",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR"),- flavor = "Key to addition", unlocksChipId = "XOR", prereqs = listOf("OR")- ),- LevelDef(- "NOR", "NOR", ChapterId.FOUNDATION,- "NOR !(a|b) – cross for SR latch", "OR+NOT",- listOf("a", "b"), outputs = listOf("out"), targetChipId = "NOR",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR"),- flavor = "NOR->SR latch first memory", unlocksChipId = "NOR", prereqs = listOf("XOR")- ),- LevelDef(- "XNOR", "XNOR", ChapterId.FOUNDATION,- "XNOR equality", "NOT XOR",- listOf("a", "b"), outputs = listOf("out"), targetChipId = "XNOR",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "NOR"),- unlocksChipId = "XNOR", prereqs = listOf("XOR")- ),-- // ROUTING BIT – address decode for RAM- LevelDef(- "MUX", "MUX", ChapterId.ROUTING,- "MUX bit sel?b:a steering – CPU control decoder", "(a&!sel)|(b&sel)",- listOf("a", "b", "sel"), outputs = listOf("out"), targetChipId = "MUX",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR"),- flavor = "Select like CPU", unlocksChipId = "MUX", prereqs = listOf("NOR", "XNOR")- ),- LevelDef(- "DMUX", "DMUX", ChapterId.ROUTING,- "DMUX bit in,sel->a,b route – enables RAM", "a=in&!sel b=in&sel",- listOf("in", "sel"), outputs = listOf("a", "b"), targetChipId = "DMUX",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX"),- unlocksChipId = "DMUX", prereqs = listOf("MUX")- ),- LevelDef(- "MUX4", "MUX4", ChapterId.ROUTING,- "MUX4 2-bit select 00:a 01:b 10:c 11:d", "3 MUXes",- listOf("a", "b", "c", "d", "sel0", "sel1"), outputs = listOf("out"), targetChipId = "MUX4",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "DMUX"),- unlocksChipId = "MUX4", prereqs = listOf("MUX")- ),- LevelDef(- "DMUX4", "DMUX4", ChapterId.ROUTING,- "DMUX4 – 1 address -> 4 cells – RAM write decode core", "DMUX tree",- listOf("in", "sel0", "sel1"), outputs = listOf("a", "b", "c", "d"), targetChipId = "DMUX4",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "DMUX", "MUX4"),- flavor = "Addr->cell for RAM", unlocksChipId = "DMUX4", prereqs = listOf("DMUX", "MUX4")- ),- LevelDef(- "MUX8", "MUX8", ChapterId.ROUTING,- "MUX8 tree – RAM read bit from 8 sources", "2xMUX4+MUX",- listOf("a", "b", "c", "d", "e", "f", "g", "h", "sel0", "sel1", "sel2"),- outputs = listOf("out"), targetChipId = "MUX8",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "DMUX", "MUX4", "DMUX4"),- unlocksChipId = "MUX8", prereqs = listOf("DMUX4")- ),- LevelDef(- "DMUX8", "DMUX8", ChapterId.ROUTING,- "DMUX8 write-enable tree – selects one reg to write for bit RAM", "DMUX4+ branches",- listOf("in", "sel0", "sel1", "sel2"),- outputs = listOf("a", "b", "c", "d", "e", "f", "g", "h"), targetChipId = "DMUX8",- allowedChipIds = listOf(- "NAND", "NOT", "AND", "OR", "XOR", "MUX", "DMUX", "MUX4", "DMUX4", "MUX8"- ),- flavor = "Write decode", unlocksChipId = "DMUX8", prereqs = listOf("MUX8")- ),-- // BUS expanders (JOIN bits->bus thick) / contractors (SPLIT bus->bits)- LevelDef(- id = "JOIN_8", displayName = "JOIN8 Exp 8b", chapter = ChapterId.ROUTING,- description = "JOIN8 Expander: 8 bits -> BUS8[8] thick blue byte bus – one wire instead of 8 thin",- hint = "OUT[0]=b0 .. OUT[7]=b7 concat",- inputs = (0..7).map { "b$it" }, inputWidths = List(8) { 1 },- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "JOIN_8",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "DMUX"),- flavor = "Bits->Bus expander cuts 8 wires to 1",- unlocksChipId = "JOIN_8", prereqs = listOf("DMUX8")- ),- LevelDef(- id = "SPLIT_8", displayName = "SPLIT8 Cont 8b", chapter = ChapterId.ROUTING,- description = "SPLIT8 Contractor: BUS8[8] thick blue -> 8 bits – split for bit logic",- hint = "b0=IN[0]..b7=IN[7]",- inputs = listOf("IN"), inputWidths = listOf(8),- outputs = (0..7).map { "b$it" }, outputWidths = List(8) { 1 },- targetChipId = "SPLIT_8",- allowedChipIds = listOf("NAND", "JOIN_8"),- flavor = "Bus->bits contractor", unlocksChipId = "SPLIT_8", prereqs = listOf("JOIN_8")- ),- LevelDef(- id = "JOIN_4", displayName = "JOIN4 Exp 4b", chapter = ChapterId.ROUTING,- description = "JOIN4 Expander: 4 bits->BUS4[4] orange opcode nibble bus",- hint = "concat nibble",- inputs = (0..3).map { "b$it" }, inputWidths = List(4) { 1 },- outputs = listOf("OUT"), outputWidths = listOf(4),- targetChipId = "JOIN_4",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "JOIN_8", "SPLIT_8"),- flavor = "4-bit bus for opcode decode", unlocksChipId = "JOIN_4", prereqs = listOf("JOIN_8")- ),- LevelDef(- id = "SPLIT_4", displayName = "SPLIT4 Cont 4b", chapter = ChapterId.ROUTING,- description = "SPLIT4 Contractor: BUS4[4] orange -> 4 bits",- hint = "split nibble",- inputs = listOf("IN"), inputWidths = listOf(4),- outputs = (0..3).map { "b$it" }, outputWidths = List(4) { 1 },- targetChipId = "SPLIT_4",- allowedChipIds = listOf("NAND", "JOIN_4", "JOIN_8", "SPLIT_8"),- unlocksChipId = "SPLIT_4", prereqs = listOf("JOIN_4")- ),- LevelDef(- id = "MUX_B8", displayName = "MUX B8 [8]", chapter = ChapterId.ROUTING,- description = "MUX_B8 bus: A[8],B[8],sel->OUT[8] byte-wide – CPU addr mux PC vs data",- hint = "Byte MUX via bit MUXes",- inputs = listOf("A", "B", "sel"), inputWidths = listOf(8, 8, 1),- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "MUX_B8",- allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU" && it != "COMPUTER" }.toList(),- flavor = "Byte bus MUX – address mux for program-from-RAM",- unlocksChipId = "MUX_B8", prereqs = listOf("SPLIT_4")- ),- LevelDef(- id = "MUX4_B8", displayName = "MUX4 B8 [8]", chapter = ChapterId.ROUTING,- description = "MUX4_B8 bus: 4xBUS8 -> BUS8 – RAM64 read stage",- hint = "2xMUX_B8+MUX_B8",- inputs = listOf("A", "B", "C", "D", "sel0", "sel1"),- inputWidths = listOf(8, 8, 8, 8, 1, 1),- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "MUX4_B8",- allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU" && it != "COMPUTER" }.toList(),- unlocksChipId = "MUX4_B8", prereqs = listOf("MUX_B8")- ),-- // ARITH – bus versions reduce tedium- LevelDef(- "HALF_ADDER", "HalfAdd", ChapterId.ARITH,- "Half adder sum=a^b carry=a&b", "XOR+AND",- listOf("a", "b"), outputs = listOf("sum", "carry"), targetChipId = "HALF_ADDER",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "JOIN_8", "SPLIT_8"),- flavor = "1-bit addition", unlocksChipId = "HALF_ADDER", prereqs = listOf("MUX4_B8")- ),- LevelDef(- "FULL_ADDER", "FullAdd", ChapterId.ARITH,- "Full adder with carry", "2 half+OR",- listOf("a", "b", "cin"), outputs = listOf("sum", "cout"), targetChipId = "FULL_ADDER",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "HALF_ADDER"),- unlocksChipId = "FULL_ADDER", prereqs = listOf("HALF_ADDER")- ),- LevelDef(- id = "ADDER_4B", displayName = "Adder4 B [4]", chapter = ChapterId.ARITH,- description = "Adder4 bus A[4]+B[4]->S[4],cout – orange [4] wire",- hint = "Chain FullAdders, use JOIN_4/SPLIT_4",- inputs = listOf("A", "B"), inputWidths = listOf(4, 4),- outputs = listOf("S", "cout"), outputWidths = listOf(4, 1),- targetChipId = "ADDER_4B",- allowedChipIds = listOf(- "NAND", "NOT", "AND", "OR", "XOR", "HALF_ADDER", "FULL_ADDER", "JOIN_4", "SPLIT_4"- ),- unlocksChipId = "ADDER_4B", prereqs = listOf("FULL_ADDER")- ),- LevelDef(- id = "ADDER_8B", displayName = "Adder8 B [8]", chapter = ChapterId.ARITH,- description = "Adder8 bus A[8]+B[8]->S[8],cout – data path of CPU – thick blue [8]",- hint = "2xAdder4B bus or 8xFA, JOIN_8 expander",- inputs = listOf("A", "B"), inputWidths = listOf(8, 8),- outputs = listOf("S", "cout"), outputWidths = listOf(8, 1),- targetChipId = "ADDER_8B",- allowedChipIds = listOf(- "NAND", "NOT", "AND", "OR", "XOR", "HALF_ADDER", "FULL_ADDER",- "ADDER_4B", "JOIN_8", "SPLIT_8"- ),- flavor = "Bus data path", unlocksChipId = "ADDER_8B",- prereqs = listOf("FULL_ADDER", "ADDER_4B")- ),- LevelDef(- id = "INC_8", displayName = "INC8 Bus [8]", chapter = ChapterId.ARITH,- description = "INC8 Bus: A[8]->S[8] +1 – needed for PC=PC+1",- hint = "A+1",- inputs = listOf("A"), inputWidths = listOf(8),- outputs = listOf("S", "cout"), outputWidths = listOf(8, 1),- targetChipId = "INC_8",- allowedChipIds = listOf(- "NAND", "NOT", "AND", "OR", "XOR", "HALF_ADDER", "FULL_ADDER", "ADDER_8B"- ),- flavor = "PC increments via INC_8", unlocksChipId = "INC_8", prereqs = listOf("ADDER_8B")- ),- LevelDef(- id = "SUB_8", displayName = "SUB8 B [8]", chapter = ChapterId.ARITH,- description = "SUB8 bus A[8]-B[8]->S[8],borrow – ALU sub op",- hint = "A+~B+1",- inputs = listOf("A", "B"), inputWidths = listOf(8, 8),- outputs = listOf("S", "borrow"), outputWidths = listOf(8, 1),- targetChipId = "SUB_8",- allowedChipIds = listOf(- "NAND", "NOT", "AND", "OR", "XOR", "ADDER_8B", "INC_8", "JOIN_8", "SPLIT_8"- ),- unlocksChipId = "SUB_8", prereqs = listOf("INC_8")- ),-- // MEMORY – toward program-from-RAM computer- LevelDef(- "SR_LATCH", "SR Latch", ChapterId.MEMORY,- "SR latch NOR cross-coupled – first memory hold via feedback – S=1 sets, R=1 resets",- "2 NOR cross",- listOf("S", "R"), outputs = listOf("Q", "nQ"), targetChipId = "SR_LATCH",- allowedChipIds = listOf("NAND", "NOR", "NOT", "AND", "OR"),- flavor = "Time enters – bit remembers via feedback",- unlocksChipId = "SR_LATCH", prereqs = listOf("SUB_8")- ),- LevelDef(- "DFF", "DFF", ChapterId.MEMORY,- "D Flip-Flop edge-triggered – on clk rise Q=D", "Master-slave",- listOf("d", "clk"), outputs = listOf("q"), targetChipId = "DFF",- allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "SR_LATCH"),- flavor = "Clocked remember D", unlocksChipId = "DFF", prereqs = listOf("SR_LATCH")- ),- LevelDef(- "BIT", "Bit", ChapterId.MEMORY,- "1-bit register with load – if load=1 store in", "MUX+DFF",- listOf("in", "load"), outputs = listOf("out"), targetChipId = "BIT",- allowedChipIds = ChipLibrary.all.keys.filter {- it != "CPU" && it != "COMPUTER" && it != "RAM_256B"- }.toList(),- unlocksChipId = "BIT", prereqs = listOf("DFF")- ),- LevelDef(- id = "REG_8B", displayName = "Reg8 B [8]", chapter = ChapterId.MEMORY,- description = "Reg8 bus IN[8],load->OUT[8] – accumulator A – thick blue [8]",- hint = "8xBIT common load – JOIN_8 makes one bus",- inputs = listOf("IN", "load"), inputWidths = listOf(8, 1),- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "REG_8B",- allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU" && it != "COMPUTER" }.toList(),- unlocksChipId = "REG_8B", prereqs = listOf("BIT")- ),- LevelDef(- id = "RAM_8B", displayName = "RAM8 B [8]", chapter = ChapterId.MEMORY,- description = "RAM8 bus 8x8: IN[8],load,ADDR[3]->OUT[8] – DMUX8_B+ MUX8_B8 – small program mem",- hint = "DMUX8_B + MUX8_B8 bus",- inputs = listOf("IN", "load", "ADDR"), inputWidths = listOf(8, 1, 3),- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "RAM_8B",- allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU" && it != "COMPUTER" }.toList(),- unlocksChipId = "RAM_8B", prereqs = listOf("REG_8B")- ),- LevelDef(- id = "RAM_64B", displayName = "RAM64 B [8]", chapter = ChapterId.MEMORY,- description = "RAM64 bus 64x8 data – 6-bit address",- hint = "high bits via MUX",- inputs = listOf("IN", "load", "ADDR"), inputWidths = listOf(8, 1, 6),- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "RAM_64B",- allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU" && it != "COMPUTER" }.toList(),- unlocksChipId = "RAM_64", prereqs = listOf("RAM_8B")- ),- LevelDef(- id = "PC_8", displayName = "PC Bus [8]", chapter = ChapterId.MEMORY,- description = "Program Counter bus: IN[8],inc,load,reset->OUT[8] – instruction pointer",- hint = "REG_8B+INC_8+MUX_B8",- inputs = listOf("IN", "inc", "load", "reset"), inputWidths = listOf(8, 1, 1, 1),- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "PC_8",- allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU" && it != "COMPUTER" }.toList(),- flavor = "Where next instruction? PC needed",- unlocksChipId = "PC_8", prereqs = listOf("REG_8B")- ),- LevelDef(- id = "RAM_256B", displayName = "RAM256 Main [8]", chapter = ChapterId.MEMORY,- description = "RAM256 unified main memory 256x8 von Neumann – program+data share SAME RAM",- hint = "4xRAM64B hierarchy, thick bus",- inputs = listOf("IN", "load", "ADDR"), inputWidths = listOf(8, 1, 8),- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "RAM_256B",- allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU" && it != "COMPUTER" }.toList(),- flavor = "Main memory – programs live here too",- unlocksChipId = "RAM_256B", prereqs = listOf("RAM_64B", "PC_8")- ),-- // CPU – fetch/decode/execute FROM RAM- LevelDef(- id = "ALU_8", displayName = "ALU Bus [8]", chapter = ChapterId.CPU,- description = "ALU bus 8-bit: A[8],B[8],OP[3]->OUT[8],zero,carry,neg – " +- "OP 000ADD 001SUB 010AND 011OR 100XOR 101NOT 110INC 111DEC",- hint = "Byte ALU – bus cuts tedium from 16 thin to 2 thick",- inputs = listOf("A", "B", "OP"), inputWidths = listOf(8, 8, 3),- outputs = listOf("OUT", "zero", "carry", "neg"), outputWidths = listOf(8, 1, 1, 1),- targetChipId = "ALU_8",- allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU" && it != "COMPUTER" }.toList(),- flavor = "Calculator of CPU – ALU with flags",- unlocksChipId = "ALU_8", prereqs = listOf("RAM_256B", "SUB_8")- ),- LevelDef(- id = "CPU", displayName = "CPU Bus [4][8]", chapter = ChapterId.CPU,- description = "CPU bus accumulator fetch-decode-execute FROM RAM: " +- "Inputs OPCODE[4] orange bus via SPLIT_4 decode, ADDR[8] blue bus, " +- "DATA[8] blue from RAM main memory reset->OUT[8],writeM,ADDR_M[8],PC[8]. " +- "ISA: LDA addr A=RAM[addr], STA RAM[addr]=A, ADD, SUB, JMP, JZ (needs zero flag), LDI, HLT. " +- "Needs PC_8 inc via INC_8, ALU_8, REG_8B A register, DMUX8 opcode->control, " +- "MUX_B8 bus address mux PC vs ADDR_M because RAM shared program+data.",- hint = "PC_8+ALU_8+REG_8B+MUX_B8",- inputs = listOf("OPCODE", "ADDR", "DATA", "reset"), inputWidths = listOf(4, 8, 8, 1),- outputs = listOf("OUT", "writeM", "ADDR_M", "PC"), outputWidths = listOf(8, 1, 8, 8),- targetChipId = "CPU",- allowedChipIds = ChipLibrary.all.keys.toList(),- flavor = "Fetch-decode-execute – program code FROM RAM",- unlocksChipId = "CPU", prereqs = listOf("ALU_8")- ),- LevelDef(- id = "CPU_8", displayName = "CPU compat", chapter = ChapterId.CPU,- description = "CPU compat alias for old saves",- hint = "Same as CPU bus",- inputs = listOf("OPCODE", "ADDR", "DATA", "reset"), inputWidths = listOf(4, 8, 8, 1),- outputs = listOf("OUT", "writeM", "ADDR_M", "PC"), outputWidths = listOf(8, 1, 8, 8),- targetChipId = "CPU_8",- allowedChipIds = ChipLibrary.all.keys.toList(),- unlocksChipId = "CPU_8", prereqs = listOf("CPU")- ),- LevelDef(- id = "COMPUTER", displayName = "Computer RAM [8]", chapter = ChapterId.CPU,- description = "Final stored-program Computer: CPU+RAM_256B Main Memory unified + " +- "MUX_B8 address mux + JOIN/SPLIT bus [4][8]. von Neumann: RAM holds both " +- "instruction bytes (OPCODE[4] orange + ADDR[8] blue) and data bytes same space. " +- "Ref program mem[16]=5,17=3 prog @0 LDA16 ADD17 STA18 HLT -> RAM[18]=8 -> OUT[8]=8. " +- "Must wire CPU.PC[8] blue->MUX_B8 A[8] for fetch, CPU.ADDR_M[8]->MUX_B8 B[8] for data, " +- "MUX.OUT[8]->RAM ADDR[8] bus, RAM.OUT[8]->CPU.DATA[8] bus and via SPLIT_4 contractor->OPCODE[4] " +- "orange for decode, CPU.OUT[8]->RAM.IN[8] bus. Need bus converters.",- hint = "Von Neumann: PC[8]->MUX_B8 A, ADDR_M->B, MUX->RAM ADDR, RAM OUT[8]->CPU DATA + SPLIT_4 opcode",- inputs = listOf("reset"), inputWidths = listOf(1),- outputs = listOf("OUT"), outputWidths = listOf(8),- targetChipId = "COMPUTER",- allowedChipIds = ChipLibrary.all.keys.toList(),- flavor = "NAND->Computer running program FROM RAM (von Neumann) 1/4/8-bit buses",- unlocksChipId = "COMPUTER", prereqs = listOf("CPU_8")- )- )-- val chapters: List<Chapter> = listOf(- Chapter(- ChapterId.FOUNDATION, "Foundation", "NAND->XNOR basics",- all.filter { it.chapter == ChapterId.FOUNDATION }.map { it.id }- ),- Chapter(- ChapterId.ROUTING, "Routing + Bus",- "Muxes + JOIN/SPLIT expander/contractor bus [4][8] – less tedious – address decode",- all.filter { it.chapter == ChapterId.ROUTING }.map { it.id }- ),- Chapter(- ChapterId.ARITH, "Arithmetic Bus",- "Bus adders orange [4] blue [8] + INC_8 PC+1 + SUB_8 ALU",- all.filter { it.chapter == ChapterId.ARITH }.map { it.id }- ),- Chapter(- ChapterId.MEMORY, "Memory -> Main",- "Latch->DFF->REG_B bus->RAM hierarchy bus->PC->RAM256B unified prog+data",- all.filter { it.chapter == ChapterId.MEMORY }.map { it.id }- ),- Chapter(- ChapterId.CPU, "CPU -> Computer RAM",- "ALU bus -> CPU bus fetch from RAM -> COMPUTER stored-program",- 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 – use JOIN_8 expander or SPLIT_8 contractor")-- val timelineRows: List<List<String>> = listOf(- listOf("NOT"), listOf("AND"), listOf("OR"), listOf("XOR"), listOf("NOR", "XNOR"),- listOf("MUX"), listOf("DMUX", "MUX4"), listOf("DMUX4"), listOf("MUX8"), listOf("DMUX8"),- listOf("JOIN_8", "JOIN_4"), listOf("SPLIT_8", "SPLIT_4"), listOf("MUX_B8", "MUX4_B8"),- listOf("HALF_ADDER"), listOf("FULL_ADDER", "ADDER_4B"), listOf("ADDER_8B"),- listOf("INC_8"), listOf("SUB_8"),- listOf("SR_LATCH"), listOf("DFF"), listOf("BIT"), listOf("REG_8B"),- listOf("RAM_8B", "PC_8"), listOf("RAM_64B"), listOf("RAM_256B"),- listOf("ALU_8"), listOf("CPU"), listOf("CPU_8"), listOf("COMPUTER")- )-- fun availableLevels(completed: Set<String>): Set<String> =- 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/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.ktdeleted file mode 100644index b59179dc41..0000000000--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressRepository.kt+++ /dev/null@@ -1,45 +0,0 @@-package com.vayunmathur.games.logicgate.data--import android.content.Context-import android.content.SharedPreferences-import androidx.core.content.edit--class LogicProgressRepository(context: Context) {- private val prefs: SharedPreferences = context.getSharedPreferences("logicgate_stats", Context.MODE_PRIVATE)-- fun getCompletedLevelIds(): Set<String> {- return prefs.getStringSet(KEY_COMPLETED, emptySet())?.toSet() ?: emptySet()- }-- fun isLevelComplete(id: String): Boolean = id in getCompletedLevelIds()-- fun markCompleted(id: String) {- val current = getCompletedLevelIds()- if (id !in current) {- prefs.edit { putStringSet(KEY_COMPLETED, (current + id).toMutableSet()) }- }- }-- fun unlockedChipIds(): Set<String> {- val completed = getCompletedLevelIds()- val chips = mutableSetOf("NAND")- for (lvlId in completed) {- Levels.byId[lvlId]?.unlocksChipId?.let { chips.add(it) }- }- return chips- }-- fun totalCompleted(): Int = getCompletedLevelIds().size-- fun incCircuitsChecked() { prefs.edit { putInt("circuits_checked", prefs.getInt("circuits_checked", 0) + 1) } }- fun getCircuitsChecked(): Int = prefs.getInt("circuits_checked", 0)-- // For achievements compatibility- fun getLevelStats(): Map<String, DummyStat> = getCompletedLevelIds().associateWith { DummyStat() }-- data class DummyStat(val bestScore: Int = 0)-- companion object {- private const val KEY_COMPLETED = "completed_levels"- }-}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.ktnew file mode 100644index 0000000000..c8ecacd437--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.kt@@ -0,0 +1,27 @@+package com.vayunmathur.games.logicgate.data++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.LevelStatsRepository++/**+ * Which levels are solved and at what best NAND cost (lower wins), plus which level briefs the+ * player has already seen. A level is complete exactly when it has a best cost.+ */+class ProgressStore(context: Context) {+ private val stats = LevelStatsRepository(context, PREFS_NAME)+ private val ds = DataStoreUtils.getInstance(context)++ fun bestCosts(): Map<String, Int> = stats.getLevelStats().mapValues { it.value.bestScore }++ fun record(levelId: String, cost: Int) = stats.updateBestScore(levelId, cost)++ /** Marks the brief for [levelId] seen; true when this is the first visit. */+ suspend fun markBriefSeen(levelId: String): Boolean = ds.addStringToSetIfAbsent(BRIEFS_KEY, levelId)++ /** Storage names. */+ companion object {+ const val PREFS_NAME = "logicgate2_stats"+ private const val BRIEFS_KEY = "logicgate2_briefs_seen"+ }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/Achievements.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/Achievements.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/Achievements.ktdeleted file mode 100644index ea915209bd..0000000000--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/Achievements.kt+++ /dev/null@@ -1,30 +0,0 @@-package com.vayunmathur.games.logicgate.platform--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 completedIds = repo.getLevelStats().keys- if (completedIds.isNotEmpty()) onAchievementUnlocked("first_gate")- 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/platform/AppBackupAgent.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.ktindex ee2b019667..e22053d7a9 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.kt@@ -1,14 +1,15 @@ package com.vayunmathur.games.logicgate.platform +import com.vayunmathur.games.logicgate.data.ProgressStore import com.vayunmathur.library.util.BaseBackupAgent +/**+ * Backs up the stats prefs and the shared DataStore file, which holds the circuit drafts+ * (`logicgate2_circuits` is a key inside it, not a file of its own).+ */ class AppBackupAgent : BaseBackupAgent() { override val prefNames: List<String>- get() = listOf("logicgate_stats")- // datastore_default is the actual file from DataStoreUtils.getInstance- // (datastore_default.preferences_pb)- // logicgate_circuits_v1 is a *key* inside that file, not a separate datastore file —- // listing bogus names causes backup/restore crash+ get() = listOf(ProgressStore.PREFS_NAME) override val datastoreNames: List<String> get() = listOf("datastore_default") }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicAchievements.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicAchievements.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicAchievements.ktnew file mode 100644index 0000000000..c9a5f21287--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicAchievements.kt@@ -0,0 +1,40 @@+package com.vayunmathur.games.logicgate.platform++import android.content.Context+import com.vayunmathur.games.logicgate.data.ProgressStore+import com.vayunmathur.games.logicgate.domain.levels.Chapter+import com.vayunmathur.games.logicgate.domain.levels.LevelRegistry+import com.vayunmathur.games.logicgate.domain.sim.Scoring+import com.vayunmathur.library.util.AchievementsManager++/** Achievements derived entirely from the stored best costs, so re-checking is always safe. */+class LogicAchievements(+ context: Context,+ json: String,+ private val progress: ProgressStore,+) : AchievementsManager(context, json) {++ override fun checkExistingAchievements() {+ val best = progress.bestCosts()+ if (best.isEmpty()) return+ onAchievementUnlocked("lg2_first_circuit")+ for ((chapter, id) in chapterAchievements) {+ onProgressUpdated(id, LevelRegistry.chapter(chapter).count { it.id in best })+ }+ if ("computer" in best) onAchievementUnlocked("lg2_computer")+ val threeStars = LevelRegistry.levels.count { level ->+ best[level.id]?.let { Scoring.stars(solved = true, cost = it, par = level.par) } == MAX_STARS+ }+ onProgressUpdated("lg2_three_stars_10", threeStars)+ }++ private companion object {+ const val MAX_STARS = 3+ val chapterAchievements = mapOf(+ Chapter.BASICS to "lg2_basics",+ Chapter.ROUTING to "lg2_routing",+ Chapter.ARITHMETIC to "lg2_arith",+ Chapter.MEMORY to "lg2_memory",+ )+ }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicEngine.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicEngine.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicEngine.ktdeleted file mode 100644index 23d7c4e43c..0000000000--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicEngine.kt+++ /dev/null@@ -1,320 +0,0 @@-package com.vayunmathur.games.logicgate.platform--import com.vayunmathur.games.logicgate.data.Circuit-import com.vayunmathur.games.logicgate.data.LevelDef-import kotlinx.coroutines.delay-import kotlinx.coroutines.launch-import kotlinx.coroutines.sync.withLock--/**- * Internal engine behind [LogicViewModel].- *- * Split out: TooManyFunctions cap (25/class). Same module and package, so- * internal access is unchanged; behavior identical. The ViewModel keeps the- * [LogicActions] overrides (thin, delegating here), the UI-observed state,- * and the two members the UI touches directly- * ([LogicViewModel.dismissAchievement], `achievementsManager`).- */-internal class LogicEngine internal constructor(internal val vm: LogicViewModel) {- // ------------------------------------------------------------------- // History- // -------------------------------------------------------------------- internal fun pushHistory(c: Circuit) {- val lvl = vm.uiStateValue.currentLevelId ?: return- val stack = vm.undoStacks.getOrPut(lvl) { mutableListOf() }- // Alchemist-style dedup: avoid filling undo stack with micro-moves (<1f jitter)- val prev = stack.lastOrNull()- if (prev != null && circuitsAreSameIgnoringJitter(prev, c)) return- stack.add(c)- if (stack.size > vm.maxHistory) stack.removeAt(0)- vm.redoStacks[lvl]?.clear()- vm.updateUiState { it.copy(canUndo = stack.isNotEmpty(), canRedo = false) }- }-- internal fun circuitsAreSameIgnoringJitter(a: Circuit, b: Circuit, thresh: Float = 1f): Boolean {- if (!sameTopology(a, b)) return false- if (!sameGates(a, b, thresh)) return false- if (a.wires != b.wires) return false- if (a.outputMappings != b.outputMappings) return false- if (!samePositions(a.inputPositions, b.inputPositions, thresh)) return false- return samePositions(a.outputPositions, b.outputPositions, thresh)- }-- private fun sameTopology(a: Circuit, b: Circuit): Boolean {- return a.gates.size == b.gates.size &&- a.wires.size == b.wires.size &&- a.outputMappings.size == b.outputMappings.size- }-- private fun sameGates(a: Circuit, b: Circuit, thresh: Float): Boolean {- for (i in a.gates.indices) {- val ga = a.gates[i]- val gb = b.gates[i]- if (ga.instanceId != gb.instanceId || ga.chipId != gb.chipId) return false- if (!withinJitter(ga.x, gb.x, thresh) || !withinJitter(ga.y, gb.y, thresh)) return false- }- return true- }-- private fun samePositions(- a: Map<Int, com.vayunmathur.games.logicgate.data.IoPos>,- b: Map<Int, com.vayunmathur.games.logicgate.data.IoPos>,- thresh: Float,- ): Boolean {- if (a.size != b.size) return false- for ((k, v) in a) {- val vb = b[k] ?: return false- if (!withinJitter(v.x, vb.x, thresh) || !withinJitter(v.y, vb.y, thresh)) return false- }- return true- }-- private fun withinJitter(a: Float, b: Float, thresh: Float): Boolean =- kotlin.math.abs(a - b) <= thresh-- // ------------------------------------------------------------------- // Persistence- // -------------------------------------------------------------------- internal suspend fun loadAllCircuits() {- val raw = vm.dataStore.getString(LogicViewModel.KEY_CIRCUITS) ?: return- try {- val parsed = vm.jsonLenient.decodeFromString<AllSavedCircuits>(raw)- parsed.map.forEach { (lvlId, pc) -> vm.allCircuits[lvlId] = pc.toCircuit() }- } catch (_: Exception) {- try {- val parsedOld = kotlinx.serialization.json.Json.decodeFromString<AllSavedCircuits>(raw)- parsedOld.map.forEach { (lvlId, pc) -> vm.allCircuits[lvlId] = pc.toCircuit() }- } catch (_: Exception) { }- }- }-- internal fun saveAllCircuitsNow() {- vm.vmScope.launch(kotlinx.coroutines.Dispatchers.IO) {- vm.persistMutex.withLock {- val toSave = AllSavedCircuits(vm.allCircuits.mapValues { it.value.toPersisted() })- val json = vm.jsonLenient.encodeToString(toSave)- vm.dataStore.setString(LogicViewModel.KEY_CIRCUITS, json)- }- }- }-- internal fun schedulePersist(delayMs: Long = 400L) {- vm.persistJob?.cancel()- vm.persistJob = vm.vmScope.launch(kotlinx.coroutines.Dispatchers.IO) {- kotlinx.coroutines.delay(delayMs)- vm.persistMutex.withLock {- val toSave = AllSavedCircuits(vm.allCircuits.mapValues { it.value.toPersisted() })- val json = vm.jsonLenient.encodeToString(toSave)- vm.dataStore.setString(LogicViewModel.KEY_CIRCUITS, json)- }- }- }-- // ------------------------------------------------------------------- // Placement- // -------------------------------------------------------------------- internal fun defaultGateX(cnt: Int): Float =- LogicViewModel.PLACEMENT_BASE_X + (cnt % LogicViewModel.PLACEMENT_COLS) * LogicViewModel.PLACEMENT_DX-- internal fun defaultGateY(cnt: Int): Float =- LogicViewModel.PLACEMENT_BASE_Y + (cnt / LogicViewModel.PLACEMENT_COLS) * LogicViewModel.PLACEMENT_DY-- internal fun clampCanvasX(x: Float): Float =- x.coerceIn(LogicViewModel.CANVAS_MIN, LogicViewModel.CANVAS_MAX_X)-- internal fun clampCanvasY(y: Float): Float =- y.coerceIn(LogicViewModel.CANVAS_MIN, LogicViewModel.CANVAS_MAX_X)-- // ------------------------------------------------------------------- // Wiring- // -------------------------------------------------------------------- internal fun loadAchievementsJson(): String {- return try {- vm.appContext.assets.open(LogicViewModel.ACHIEVEMENTS_ASSET).bufferedReader().use { it.readText() }- } catch (_: Exception) {- LogicViewModel.EMPTY_ACHIEVEMENTS_JSON- }- }- // ------------------------------------------------------------------- // Wiring (see LogicWiring)- // -------------------------------------------------------------------- internal val wiring by lazy { LogicWiring(vm) }-- // ------------------------------------------------------------------- // Evaluation- // -------------------------------------------------------------------- internal fun evaluateCurrent() {- val state = vm.uiStateValue- val lvlId = state.currentLevelId ?: return- val level = currentLevel(lvlId) ?: return- val circuit = state.circuit- if (level.id == "COMPUTER") {- evaluateComputerBranch(level, circuit)- return- }- val evalResult = com.vayunmathur.games.logicgate.data.CircuitEvaluator.evaluate(level, circuit)- val (fullyCorrect, failing) = com.vayunmathur.games.logicgate.data.CircuitEvaluator.isCorrect(level, circuit)- when (evalResult) {- is com.vayunmathur.games.logicgate.data.EvalResult.Error ->- vm.updateUiState { it.copy(evalStatus = EvalStatus.Error(evalResult.message)) }- is com.vayunmathur.games.logicgate.data.EvalResult.Cycle ->- vm.updateUiState { it.copy(evalStatus = EvalStatus.Cycle(evalResult.ids)) }- is com.vayunmathur.games.logicgate.data.EvalResult.Success -> {- val total = if (level.totalInputBits <=- com.vayunmathur.games.logicgate.data.CircuitSampling.EXHAUSTIVE_BITS- ) {- 1 shl level.totalInputBits- } else {- evalResult.rows.size- }- val passing = total - failing.size- vm.updateUiState {- it.copy(evalStatus = EvalStatus.Ok(passing, total, fullyCorrect, failing))- }- if (fullyCorrect) onLevelWon(level)- }- }- }-- private fun currentLevel(lvlId: String): LevelDef? {- return try {- com.vayunmathur.games.logicgate.data.Levels.get(lvlId)- } catch (_: Exception) {- null- }- }-- private fun evaluateComputerBranch(level: LevelDef, circuit: Circuit) {- val msg = evaluateComputerLevel(circuit)- if (msg == null) {- val evalResult =- com.vayunmathur.games.logicgate.data.CircuitEvaluator.evaluate(level, circuit)- when (evalResult) {- is com.vayunmathur.games.logicgate.data.EvalResult.Success -> {- vm.updateUiState {- it.copy(- evalStatus = EvalStatus.Ok(- passingRows = evalResult.rows.size,- totalRows = evalResult.rows.size,- isFullyCorrect = true,- failingRows = emptyList(),- ),- )- }- onLevelWon(level)- }- is com.vayunmathur.games.logicgate.data.EvalResult.Error ->- vm.updateUiState { it.copy(evalStatus = EvalStatus.Error(evalResult.message)) }- is com.vayunmathur.games.logicgate.data.EvalResult.Cycle -> {- vm.updateUiState {- it.copy(- evalStatus = EvalStatus.Ok(- passingRows = 1,- totalRows = 1,- isFullyCorrect = true,- failingRows = emptyList(),- ),- )- }- onLevelWon(level)- }- }- } else {- vm.updateUiState { it.copy(evalStatus = EvalStatus.Error(msg)) }- }- }-- private fun evaluateComputerLevel(circuit: Circuit): String? {- val ids = circuit.gates.map { it.chipId }.toSet()- return listOfNotNull(- missingCpuMessage(ids),- missingRamMessage(ids),- missingWiresMessage(circuit),- missingBusMessage(circuit),- missingMuxMessage(ids),- missingSplitMessage(ids),- missingOutputMessage(circuit),- ).firstOrNull()- }-- private fun missingCpuMessage(ids: Set<String>): String? {- if (ids.contains("CPU") || ids.contains("CPU_8")) return null- return "Add CPU bus chip – it does fetch-decode-execute from RAM. " +- "It needs OPCODE[4] orange bus via SPLIT_4 and ADDR[8] blue bus."- }-- private fun missingRamMessage(ids: Set<String>): String? {- if (ids.contains("RAM_256B") || ids.contains("RAM_256")) return null- return "Add RAM_256B Main Memory [8] – unified 256x8 where program lives " +- "alongside data (von Neumann)."- }-- private fun missingWiresMessage(circuit: Circuit): String? {- if (circuit.wires.size >= LogicViewModel.MIN_CPU_RAM_WIRES) return null- return "Wire CPU <-> RAM with BUS wires: CPU.PC[8] blue thick -> MUX_B8 A[8] " +- "(fetch phase), CPU.ADDR_M[8] blue -> MUX_B8 B[8] (data phase). " +- "MUX_B8 OUT[8] blue -> RAM ADDR[8]. Use bus [8] wires."- }-- private fun missingBusMessage(circuit: Circuit): String? {- val hasBusWire = circuit.wires.any {- it.busWidth == com.vayunmathur.games.logicgate.data.CircuitSampling.BUS_8- }- if (hasBusWire) return null- return "Use 8-bit BUS wires [8] thick blue – they cut tedium from 8 thin green " +- "wires to 1 thick. Use JOIN_8 expander to build bus."- }-- private fun missingMuxMessage(ids: Set<String>): String? {- if (ids.contains("MUX_B8") || ids.contains("MUX4_B8") || ids.contains("MUX8_B8")) return null- return "Add MUX_B8 bus address MUX – it chooses PC[8] for fetch vs ADDR_M[8] " +- "for data – key for shared RAM program-from-RAM."- }-- private fun missingSplitMessage(ids: Set<String>): String? {- if (ids.contains("SPLIT_4") || ids.contains("JOIN_4")) return null- return "Add SPLIT_4 contractor for opcode decode – " +- "CPU needs OPCODE[4] orange bus via SPLIT_4 from RAM data."- }-- private fun missingOutputMessage(circuit: Circuit): String? {- if (circuit.outputMappings.isNotEmpty()) return null- return "Connect final OUT[8] bus – drag from RAM or CPU output bus dot to output terminal."- }-- private fun onLevelWon(level: LevelDef) {- vm.vmScope.launch {- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {- vm.progressRepo.markCompleted(level.id)- }- vm.completedIdsMutable.value = vm.progressRepo.getCompletedLevelIds()- vm.unlockedChipsMutable.value = vm.progressRepo.unlockedChipIds()- vm.progressRepo.incCircuitsChecked()- vm.achievementsManager.onAchievementUnlocked("first_gate")- val allCompleted = vm.completedIdsMutable.value- vm.achievementsManager.onProgressUpdated("all_levels", vm.progressRepo.totalCompleted())- com.vayunmathur.games.logicgate.data.Levels.chapters.forEach { ch ->- val cnt = allCompleted.count {- com.vayunmathur.games.logicgate.data.Levels.byId[it]?.chapter == ch.id- }- vm.achievementsManager.onProgressUpdated(chapterAchievementKey(ch.id), cnt)- }- }- }-- private fun chapterAchievementKey(- id: com.vayunmathur.games.logicgate.data.ChapterId,- ): String = when (id) {- com.vayunmathur.games.logicgate.data.ChapterId.FOUNDATION -> "foundation_complete"- com.vayunmathur.games.logicgate.data.ChapterId.ROUTING -> "routing_complete"- com.vayunmathur.games.logicgate.data.ChapterId.ARITH -> "arith_complete"- com.vayunmathur.games.logicgate.data.ChapterId.MEMORY -> "memory_complete"- com.vayunmathur.games.logicgate.data.ChapterId.CPU -> "cpu_complete"- }-}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.ktindex d2132b8d79..b3dd68f676 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.kt@@ -1,47 +1,87 @@ package com.vayunmathur.games.logicgate.platform -import androidx.compose.ui.geometry.Offset-import com.vayunmathur.games.logicgate.data.WireEnd--/**- * Everything the circuit editor asks [LogicViewModel] to do.- *- * The editor takes this interface plus a [UiState] value rather than the ViewModel itself,- * so it can be rendered by a `@Preview` — which is what the store listing images are- * generated from. Every method has a no-op default, so [Noop] is the whole implementation a- * preview needs.- *- * The names match [LogicViewModel]'s existing methods exactly, so the ViewModel implements- * this directly rather than through an adapter. Navigation is deliberately not here: it- * belongs to the caller, not the ViewModel, and the screen takes it as plain lambdas.+import com.vayunmathur.games.logicgate.domain.levels.Chapter+import com.vayunmathur.games.logicgate.domain.levels.LevelDef+import com.vayunmathur.games.logicgate.domain.model.ChipSpec+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.Point+import com.vayunmathur.games.logicgate.domain.model.Wire+import com.vayunmathur.games.logicgate.domain.sim.Probe+import com.vayunmathur.games.logicgate.domain.sim.VerifyResult++/*+ * The UI contract between LogicViewModel and the screens: plain state plus an actions interface,+ * so every screen renders from a @Preview with LogicActions.Noop. */-interface LogicActions {- fun selectLevel(levelId: String) {} - /** Returns the new gate's instance id; the editor ignores it, so the default is empty. */- fun addGateAt(chipId: String, x: Float?, y: Float?): String = ""+/** One level card on the map. */+data class LevelCard(+ val id: String,+ val number: Int,+ val title: String,+ val chapter: Chapter,+ val unlocked: Boolean,+ val stars: Int,+ val bestCost: Int?,+ val par: Int,+) {+ val completed: Boolean get() = bestCost != null+}++/** The level map. */+data class ProgressionUiState(val levels: List<LevelCard> = emptyList()) {+ val solved: Int get() = levels.count { it.completed }+}++/** What is selected on the canvas. */+sealed interface Selection {+ /** A gate. */+ data class OfNode(val id: NodeId) : Selection - fun removeGate(instanceId: String) {}- fun clearCircuit() {}- fun selectGate(id: String?) {}+ /** A wire. */+ data class OfWire(val wire: Wire) : Selection+}++/** Everything the editor draws for one level. */+data class GameUiState(+ val level: LevelDef,+ val circuit: Circuit,+ val chips: List<ChipSpec>,+ val manualInputs: List<Int>,+ val selection: Selection? = null,+ val verify: VerifyResult? = null,+ val probeCase: Int? = null,+ val live: Probe = Probe(emptyMap(), emptySet()),+ val canUndo: Boolean = false,+ val canRedo: Boolean = false,+ val won: Boolean = false,+ val stars: Int = 0,+ val cost: Int = 0,+ val bestCost: Int? = null,+ val showBrief: Boolean = false,+ /** Bumped when the canvas should frame the whole circuit, e.g. on opening a level. */+ val fitToken: Int = 0,+ val nextLevelId: String? = null,+)++/** Editor callbacks. Every method has a no-op default so a preview needs only [Noop]. */+interface LogicActions {+ fun placeChip(chipId: String, at: Point) {}+ fun moveNode(id: NodeId, to: Point) {}+ fun connect(a: PinRef, b: PinRef) {}+ fun select(selection: Selection?) {}+ fun deleteSelection() {}+ fun deleteNode(id: NodeId) {} fun undo() {} fun redo() {}+ fun setInput(index: Int, value: Int) {}+ fun probe(caseIndex: Int?) {}+ fun showBrief(show: Boolean) {}+ fun dismissWin() {} - /** In-drag position updates; the `…Finished` variants are what push undo history. */- fun onGateMoved(instanceId: String, x: Float, y: Float) {}- fun onGateMoveFinished(instanceId: String, x: Float, y: Float) {}- fun onInputMoved(idx: Int, x: Float, y: Float) {}- fun onInputMoveFinished(idx: Int, x: Float, y: Float) {}- fun onOutputMoved(idx: Int, x: Float, y: Float) {}- fun onOutputMoveFinished(idx: Int, x: Float, y: Float) {}-- fun startWiring(from: WireEnd) {}- fun cancelWiring() {}- fun updateGhostLine(end: Offset?) {}- fun createWire(from: WireEnd, to: WireEnd) {}- fun removeWire(wireId: String) {}- fun removeOutputMapping(outIdx: Int) {}-+ /** Ready-made instances. */ companion object { val Noop: LogicActions = object : LogicActions {} }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.ktindex 6b6208f684..3bc94f3004 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.kt@@ -1,401 +1,282 @@-@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)- package com.vayunmathur.games.logicgate.platform -import kotlin.uuid.Uuid import android.app.Application-import android.content.Context-import androidx.compose.ui.geometry.Offset import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope-import com.vayunmathur.games.logicgate.data.ChapterId-import com.vayunmathur.games.logicgate.data.ChipLibrary-import com.vayunmathur.games.logicgate.data.Circuit-import com.vayunmathur.games.logicgate.data.CircuitSampling-import com.vayunmathur.games.logicgate.data.IoPos-import com.vayunmathur.games.logicgate.data.LevelDef-import com.vayunmathur.games.logicgate.data.Levels-import com.vayunmathur.games.logicgate.data.LogicProgressRepository-import com.vayunmathur.games.logicgate.data.OutputMapping-import com.vayunmathur.games.logicgate.data.PlacedChip-import com.vayunmathur.games.logicgate.data.Wire-import com.vayunmathur.games.logicgate.data.WireEnd-import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.games.logicgate.data.CircuitStore+import com.vayunmathur.games.logicgate.data.ProgressStore+import com.vayunmathur.games.logicgate.domain.levels.LevelDef+import com.vayunmathur.games.logicgate.domain.levels.LevelRegistry+import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.Point+import com.vayunmathur.games.logicgate.domain.sim.Probe+import com.vayunmathur.games.logicgate.domain.sim.Scoring+import com.vayunmathur.games.logicgate.domain.sim.Verifier+import com.vayunmathur.games.logicgate.domain.sim.VerifyResult+import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch-import kotlinx.coroutines.sync.Mutex-import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json--// Persisted format v2 with busWidth + lenient json-@Serializable-data class PersistedWire(- val id: String,- val fromInstance: String,- val fromPin: Int,- val toInstance: String,- val toPin: Int,- val busWidth: Int = 1,-)-@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 PersistedIoPos(val x: Float, val y: Float)-@Serializable-data class PersistedCircuit(- val gates: List<PersistedGate>,- val wires: List<PersistedWire>,- val outputs: List<PersistedOutputMap>,- val inputPos: Map<Int, PersistedIoPos> = emptyMap(),- val outputPos: Map<Int, PersistedIoPos> = emptyMap()-)-@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 dragGhostLineEnd: Offset? = null,- val showTruthTable: Boolean = true,- val draggedChipGhost: DraggedChipGhost? = null,- val canUndo: Boolean = false,- val canRedo: Boolean = false-)--data class DraggedChipGhost(val chipId: String, val offset: Offset)--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), LogicActions {- internal val progressRepo = LogicProgressRepository(application)- internal val dataStore = DataStoreUtils.getInstance(application)- internal val appContext: Context = application.applicationContext- private val ctx: Context get() = getApplication()-- val achievementsManager: LogicAchievementsManager = run {- val json = engine.loadAchievementsJson()- LogicAchievementsManager(ctx, json, progressRepo)- }-- /** Engine owning history, persistence and evaluation (TooManyFunctions cap). */- internal val engine by lazy { LogicEngine(this) }-- private val _completedIds = MutableStateFlow(progressRepo.getCompletedLevelIds())- val completedIds: StateFlow<Set<String>> = _completedIds.asStateFlow()- internal val completedIdsMutable: MutableStateFlow<Set<String>> get() = _completedIds-- private val _unlockedChips = MutableStateFlow(progressRepo.unlockedChipIds())- val unlockedChips: StateFlow<Set<String>> = _unlockedChips.asStateFlow()- internal val unlockedChipsMutable: MutableStateFlow<Set<String>> get
Diff truncated.