Modern Apps git

← Modern-Apps.git

logicgate: real simulator, chip catalog and 28 verified levels

Commit
a1131ba87f187b4c6092f37dc569f95ae463efa9
Author
Vayun Mathur <[email protected]>
When
2026-11-01 18:25 UTC (1 month ago)
Parents
856df43
Adds a pure-Kotlin domain layer for Logic Gate that actually simulates
circuits, replacing the old black-box ChipDef.eval model where memory
chips passed inputs straight through, the CPU returned zeros, the
"computer" returned a constant 8 and the SR latch passed on a
structural check. Nothing in the app uses it yet; the next commit
rebuilds the UI on top of it.

Model (domain/model):
- Circuit is immutable: nodes are Gate, LevelInput or LevelOutput (the
  level's own pins are real nodes now, not fake __IN_n ids), and wires
  always run output pin -> input pin. Edits enforce one wire per input
  and matching bus widths; sanitized() repairs stale saves.
- Pins are typed 1/4/8-bit; signals are Int bit masks.
- Chips.kt is the catalog: NAND, HIGH/LOW, the basic gates, MUX/DMUX/
  DEC2, SPLIT/JOIN (8<->8x1, 4<->4x1) and NIB SPLIT/JOIN (8<->2x4), a
  bitwise bus pack, adders/INC4/SUB8/ZERO8/ALU8, DFF/BIT/REG8/PC4/RAM4,
  a dual-port RAM16, DECODER and CPU. A solved level's chip runs
  natively, so later levels stay cheap to simulate.
- Isa.kt fixes an 8-bit ISA (op[4]|operand[4]: LDA STA ADD SUB LDI JMP
  JZ HLT) executing one instruction per tick via the dual-port RAM.

Simulation (domain/sim):
- One tick of an implicit clock = settle, then latch. Acyclic logic
  runs once in topological order (Tarjan SCCs); feedback loops iterate
  in order (Gauss-Seidel) from the previous tick's values, which is
  what lets a cross-coupled latch hold. A loop still changing after 64
  passes is reported as oscillating. State-only chips break loops.
- Verifier: combinational levels are exhaustive up to 10 input bits,
  otherwise edge values crossed plus 200 seeded random vectors;
  sequential levels replay scripted ticks from reset; the CPU level is
  run against a harness RAM model and the computer level loads three
  programs (2 + 3, a JZ countdown, 3 x 4) into the player's RAM16.
- Scoring: cost is the sum of chip NAND costs; 1-3 stars against par.

Levels (domain/levels): 28 levels in five chapters with briefs, hints
and plain-language row titles ("1 OR 1 = 1", "q=1, then hold") used
in place of row numbers. Reward levels derive their pins, tests and
par from the chip they unlock, so they cannot drift apart.

Verified with ./gradlew :games:logicgate:testDevUnitTest: every
level's reference circuit passes its own tests and its cost equals the
level's par; a wrong XOR fails on 1 XOR 1; the SR latch holds; NAND
and inverter rings oscillate; register, PC and RAM traces match; and
the computer level's programs end with acc 5, 0 and 12, halted.

Diff

games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.ktnew file mode 100644index 0000000000..c34b2236d5--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.kt@@ -0,0 +1,78 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.Chips++internal val arithmeticLevels: List<LevelDef> = listOf(+    chipLevel(+        Chapter.ARITHMETIC, "half_adder", Chips.HALF,+        LevelText(+            "Half adder",+            "Add two bits. s is the sum bit and c the carry.",+            "s is XOR and c is AND — and the NAND(a, b) inside an XOR is already NOT c.",+        ),+        title = RowTitles.half,+    ),+    chipLevel(+        Chapter.ARITHMETIC, "full_adder", Chips.FULL,+        LevelText(+            "Full adder",+            "Add three bits: a, b and a carry in.",+            "Two half adders and an OR work. Nine NANDs is the record.",+        ),+        title = RowTitles.full,+    ),+    chipLevel(+        Chapter.ARITHMETIC, "add4", Chips.ADD4,+        LevelText(+            "4-bit adder",+            "Add two 4-bit numbers and a carry in.",+            "Chain four full adders, each carry out feeding the next carry in.",+        ),+        title = RowTitles.add,+    ),+    chipLevel(+        Chapter.ARITHMETIC, "add8", Chips.ADD8,+        LevelText(+            "8-bit adder",+            "Add two bytes and a carry in.",+            "Two ADD4s, one per nibble.",+        ),+        title = RowTitles.add,+    ),+    chipLevel(+        Chapter.ARITHMETIC, "inc4", Chips.INC4,+        LevelText(+            "Incrementer",+            "Output a + 1, wrapping 15 round to 0.",+            "Bit 0 always flips. Every other bit is a half adder fed by the carry from below.",+        ),+        title = RowTitles.inc,+    ),+    chipLevel(+        Chapter.ARITHMETIC, "sub8", Chips.SUB8,+        LevelText(+            "Subtractor",+            "Output a − b, wrapping below zero.",+            "In two's complement −b is NOT b + 1. Feed the + 1 in as the carry.",+        ),+        title = RowTitles.sub,+    ),+    chipLevel(+        Chapter.ARITHMETIC, "zero8", Chips.ZERO8,+        LevelText(+            "Zero test",+            "Output 1 when every bit of a is 0.",+            "OR all eight bits together, then invert.",+        ),+        title = RowTitles.zero,+    ),+    chipLevel(+        Chapter.ARITHMETIC, "alu8", Chips.ALU8,+        LevelText(+            "ALU",+            "op1 op0 picks the operation: 00 add, 01 subtract, 10 AND, 11 pass b. z is 1 when o is 0.",+            "Subtracting is adding NOT b with carry 1: XOR b with op0 to invert it on demand.",+        ),+        title = RowTitles.alu,+    ),+)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.ktnew file mode 100644index 0000000000..7691361386--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.kt@@ -0,0 +1,60 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.Chips++internal val basicsLevels: List<LevelDef> = listOf(+    chipLevel(+        Chapter.BASICS, "not", Chips.NOT,+        LevelText(+            "NOT",+            "Everything here is built from NAND. Make o the opposite of a.",+            "A NAND with both inputs tied to the same wire inverts it.",+        ),+        title = RowTitles.not,+    ),+    chipLevel(+        Chapter.BASICS, "and", Chips.AND,+        LevelText(+            "AND",+            "Output 1 only when a and b are both 1.",+            "NAND is NOT-AND. Undo the NOT.",+        ),+        title = RowTitles.infix("AND"),+    ),+    chipLevel(+        Chapter.BASICS, "or", Chips.OR,+        LevelText(+            "OR",+            "Output 1 when either input is 1.",+            "De Morgan: a OR b is NAND(NOT a, NOT b).",+        ),+        title = RowTitles.infix("OR"),+    ),+    chipLevel(+        Chapter.BASICS, "nor", Chips.NOR,+        LevelText(+            "NOR",+            "Output 1 only when both inputs are 0.",+            "Invert an OR.",+        ),+        title = RowTitles.infix("NOR"),+    ),+    chipLevel(+        Chapter.BASICS, "xor", Chips.XOR,+        LevelText(+            "XOR",+            "Output 1 when the inputs differ.",+            "Four NANDs: NAND(a, b) goes into two more NANDs, one with a and one with b; NAND their outputs.",+        ),+        title = RowTitles.infix("XOR"),+    ),+    chipLevel(+        Chapter.BASICS, "xnor", Chips.XNOR,+        LevelText(+            "XNOR",+            "Output 1 when the inputs match.",+            "Invert an XOR.",+        ),+        title = RowTitles.infix("XNOR"),+    ),+)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.ktnew file mode 100644index 0000000000..3bf3e518d6--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.kt@@ -0,0 +1,31 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.sim.TestSpec++/** A level whose pins, tests and par all come from the chip it rewards, so they cannot drift apart. */+internal fun chipLevel(+    chapter: Chapter,+    id: String,+    chipId: String,+    text: LevelText,+    title: RowTitle? = null,+    unlocks: List<String> = listOf(chipId),+    tests: TestSpec = TestGen.fromChip(chipId, checkNotNull(title) { "$id needs row titles" }),+): LevelDef {+    val spec = TestGen.chip(chipId)+    return LevelDef(+        id = id,+        chapter = chapter,+        title = text.title,+        brief = text.brief,+        hint = text.hint,+        inputs = spec.inputs,+        outputs = spec.outputs,+        tests = tests,+        par = spec.nandCost,+        unlocks = unlocks,+    )+}++/** The words of a level. */+internal data class LevelText(val title: String, val brief: String, val hint: String)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.ktnew file mode 100644index 0000000000..51572296f9--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.kt@@ -0,0 +1,85 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Isa+import com.vayunmathur.games.logicgate.domain.model.Isa.encode+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.games.logicgate.domain.sim.Case+import com.vayunmathur.games.logicgate.domain.sim.ProgramTest+import com.vayunmathur.games.logicgate.domain.sim.TestSpec++private fun program(name: String, maxTicks: Int, expectAcc: Int, vararg cells: Pair<Int, Int>): ProgramTest {+    val ram = MutableList(16) { 0 }+    for ((addr, value) in cells) ram[addr] = value+    return ProgramTest(name, ram, maxTicks, expectAcc)+}++/** Add two numbers, count down to zero with JZ, and multiply 3 × 4 by repeated addition. */+internal val cpuPrograms: List<ProgramTest> = listOf(+    program(+        "2 + 3 = 5", 16, 5,+        0 to encode(Isa.LDA, 14), 1 to encode(Isa.ADD, 15), 2 to encode(Isa.HLT),+        14 to 2, 15 to 3,+    ),+    program(+        "count 5 down to 0", 64, 0,+        0 to encode(Isa.LDI, 5), 1 to encode(Isa.SUB, 15), 2 to encode(Isa.JZ, 4), 3 to encode(Isa.JMP, 1),+        4 to encode(Isa.HLT),+        15 to 1,+    ),+    program(+        "3 × 4 = 12", 128, 12,+        0 to encode(Isa.LDA, 13), 1 to encode(Isa.ADD, 14), 2 to encode(Isa.STA, 13),+        3 to encode(Isa.LDA, 12), 4 to encode(Isa.SUB, 15), 5 to encode(Isa.STA, 12),+        6 to encode(Isa.JZ, 8), 7 to encode(Isa.JMP, 0), 8 to encode(Isa.LDA, 13), 9 to encode(Isa.HLT),+        12 to 4, 13 to 0, 14 to 3, 15 to 1,+    ),+)++private val decoderTests = TestSpec.Comb(+    (0..7).flatMap { op ->+        (0..1).map { z ->+            val lines = Isa.decode(op, z)+            val aluCare = lines[2] == 1+            val expected = lines.mapIndexed { i, v -> if (i < 2 && !aluCare) null else v }+            Case(listOf(op, z), expected, RowTitles.decoder(listOf(op, z), expected))+        }+    },+)++internal val cpuLevels: List<LevelDef> = listOf(+    chipLevel(+        Chapter.CPU, "decoder", Chips.DECODER,+        LevelText(+            "Instruction decoder",+            "Opcodes: 0 LDA · 1 STA · 2 ADD · 3 SUB · 4 LDI · 5 JMP · 6 JZ · 7 HLT. Drive the ALU op " ++                "(LDA and LDI pass b), load acc for LDA/ADD/SUB/LDI, write memory for STA, use the immediate " ++                "for LDI, jump for JMP (and JZ when z is 1), halt for HLT. op's top bit is unused.",+            "Split op, decode its low three bits into eight lines, then OR together the lines each control needs.",+        ),+        tests = decoderTests,+    ),+    chipLevel(+        Chapter.CPU, "cpu", Chips.CPU,+        LevelText(+            "CPU",+            "Each tick, instr is the byte at pc and data is the byte at addr. Run the instruction: update acc " ++                "and pc, and to store put acc on dout and raise we. Tested by running real programs.",+            "operand → addr and PC4 v · ALU(acc, data or operand) → REG8 acc · ZERO8(acc) → decoder z · " ++                "NOT halt → PC4 en.",+        ),+        tests = TestSpec.Programs(cpuPrograms, harness = true),+    ),+    LevelDef(+        id = "computer",+        chapter = Chapter.CPU,+        title = "Computer",+        brief = "Wire your CPU to a RAM16. Three programs get loaded into the RAM: add two numbers, count down, " ++            "and multiply 3 × 4.",+        hint = "pc → iaddr, addr → daddr, dout → din, we → we; instr and dout go back into the CPU.",+        inputs = emptyList(),+        outputs = listOf(Pin("acc", 8), Pin("halt")),+        tests = TestSpec.Programs(cpuPrograms, harness = false),+        par = TestGen.chip(Chips.CPU).nandCost + TestGen.chip(Chips.RAM16).nandCost,+    ),+)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelDef.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelDef.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelDef.ktnew file mode 100644index 0000000000..09eba5dc25--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelDef.kt@@ -0,0 +1,29 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.LevelIo+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.games.logicgate.domain.sim.TestSpec++/** The five chapters, in play order. */+enum class Chapter { BASICS, ROUTING, ARITHMETIC, MEMORY, CPU }++/**+ * One puzzle. [gifts] are chips handed over for this level onwards without being earned;+ * [unlocks] are chips earned by solving it. [par] is the NAND cost of the reference solution.+ */+data class LevelDef(+    val id: String,+    val chapter: Chapter,+    val title: String,+    val brief: String,+    val hint: String,+    val inputs: List<Pin>,+    val outputs: List<Pin>,+    val tests: TestSpec,+    val par: Int,+    val gifts: List<String> = emptyList(),+    val unlocks: List<String> = emptyList(),+) {+    val io: LevelIo get() = LevelIo(inputs, outputs)+    val isSequential: Boolean get() = tests !is TestSpec.Comb+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.ktnew file mode 100644index 0000000000..90800eb1c1--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt@@ -0,0 +1,43 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.Chips++/** The ordered level list and the rules for what is open and what is in the chip tray. */+object LevelRegistry {+    val levels: List<LevelDef> = basicsLevels + routingLevels + arithmeticLevels + memoryLevels + cpuLevels++    private val byId = levels.associateBy { it.id }++    operator fun get(id: String): LevelDef? = byId[id]++    fun indexOf(id: String): Int = levels.indexOfFirst { it.id == id }++    fun next(id: String): LevelDef? = levels.getOrNull(indexOf(id) + 1)++    fun chapter(chapter: Chapter): List<LevelDef> = levels.filter { it.chapter == chapter }++    /**+     * The first level is always open. Otherwise a level opens once the previous level of its+     * chapter is solved; a chapter's first level needs the previous chapter's last level.+     */+    fun isUnlocked(id: String, completed: Set<String>): Boolean {+        val i = indexOf(id)+        return i == 0 || (i > 0 && levels[i - 1].id in completed)+    }++    /**+     * Chips on offer in level [id], newest first: what this and earlier levels gift, everything+     * earned before it, then NAND and the constants.+     */+    fun allowedChips(id: String): List<String> {+        val idx = indexOf(id)+        if (idx < 0) return Chips.base+        val chips = LinkedHashSet<String>()+        for (i in idx downTo 0) {+            if (i < idx) chips += levels[i].unlocks+            chips += levels[i].gifts+        }+        chips += Chips.base+        return chips.toList()+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.ktnew file mode 100644index 0000000000..6c9c871e86--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.kt@@ -0,0 +1,124 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.games.logicgate.domain.sim.Case+import com.vayunmathur.games.logicgate.domain.sim.TestSpec++private fun ticks(title: RowTitle, vararg rows: Pair<List<Int>, List<Int?>>) =+    TestSpec.Seq(rows.map { (i, o) -> Case(i, o, title(i, o)) })++internal val memoryLevels: List<LevelDef> = listOf(+    LevelDef(+        id = "sr_latch",+        chapter = Chapter.MEMORY,+        title = "SR latch",+        brief = "Memory from feedback. s sets q to 1, r resets it to 0, and with both low q holds. nq is always NOT q.",+        hint = "Two NORs, each one's output wired into the other's input.",+        inputs = listOf(Pin("s"), Pin("r")),+        outputs = listOf(Pin("q"), Pin("nq")),+        tests = ticks(+            RowTitles.srLatch,+            listOf(1, 0) to listOf(1, 0),+            listOf(0, 0) to listOf(1, 0),+            listOf(0, 1) to listOf(0, 1),+            listOf(0, 0) to listOf(0, 1),+            listOf(1, 0) to listOf(1, 0),+            listOf(0, 0) to listOf(1, 0),+            listOf(0, 1) to listOf(0, 1),+            listOf(0, 0) to listOf(0, 1),+        ),+        par = 4,+    ),+    LevelDef(+        id = "d_latch",+        chapter = Chapter.MEMORY,+        title = "D latch",+        brief = "While en is 1, q follows d. When en drops to 0, q holds its last value.",+        hint = "Build an SR latch and drive its set and reset from d and en.",+        inputs = listOf(Pin("d"), Pin("en")),+        outputs = listOf(Pin("q")),+        tests = ticks(+            RowTitles.dLatch,+            listOf(1, 1) to listOf(1),+            listOf(0, 0) to listOf(1),+            listOf(0, 1) to listOf(0),+            listOf(1, 0) to listOf(0),+            listOf(1, 1) to listOf(1),+            listOf(0, 0) to listOf(1),+            listOf(1, 0) to listOf(1),+            listOf(0, 1) to listOf(0),+            listOf(0, 0) to listOf(0),+        ),+        par = 4,+        unlocks = listOf(Chips.DFF, Chips.DFF4, Chips.DFF8),+    ),+    chipLevel(+        Chapter.MEMORY, "bit", Chips.BIT,+        LevelText(+            "1-bit register",+            "A DFF stores its input on every tick. Build one that only stores when load is 1; q shows the stored bit.",+            "Feed the DFF from a MUX choosing between d and the DFF's own output.",+        ),+        tests = TestGen.seqFromChip(+            Chips.BIT,+            RowTitles.bit,+            listOf(+                listOf(1, 1), listOf(0, 0), listOf(0, 0), listOf(0, 1), listOf(1, 0),+                listOf(1, 0), listOf(1, 1), listOf(0, 0), listOf(0, 1), listOf(1, 1),+            ),+        ),+    ),+    chipLevel(+        Chapter.MEMORY, "reg8", Chips.REG8,+        LevelText(+            "8-bit register",+            "The same, a byte wide.",+            "A MUX8b in front of a DFF8.",+        ),+        tests = TestGen.seqFromChip(+            Chips.REG8,+            RowTitles.reg8,+            listOf(+                listOf(0x5A, 1), listOf(0, 0), listOf(0xFF, 0), listOf(0xFF, 1), listOf(0x12, 0),+                listOf(0x80, 1), listOf(0, 0), listOf(0x01, 1), listOf(0, 0),+            ),+        ),+    ),+    chipLevel(+        Chapter.MEMORY, "pc4", Chips.PC4,+        LevelText(+            "Program counter",+            "Each tick: if load is 1, jump to v; otherwise if en is 1, count up by one (15 wraps to 0); " ++                "otherwise hold.",+            "An INC4 and two MUX4bs in front of a DFF4.",+        ),+        tests = TestGen.seqFromChip(+            Chips.PC4,+            RowTitles.pc4,+            listOf(+                listOf(1, 0, 0), listOf(1, 0, 0), listOf(0, 0, 0), listOf(1, 0, 0), listOf(0, 1, 9),+                listOf(1, 0, 0), listOf(1, 0, 0), listOf(1, 1, 15), listOf(1, 0, 0), listOf(1, 0, 0),+                listOf(0, 0, 3), listOf(0, 1, 4), listOf(0, 0, 0),+            ),+        ),+    ),+    chipLevel(+        Chapter.MEMORY, "ram4", Chips.RAM4,+        LevelText(+            "RAM",+            "Four bytes. dout always shows the byte at address a1 a0; when we is 1, that byte becomes din on the tick.",+            "A DEC2 picks which REG8 loads; MUX8bs pick which one is read.",+        ),+        unlocks = listOf(Chips.RAM4, Chips.RAM16),+        tests = TestGen.seqFromChip(+            Chips.RAM4,+            RowTitles.ram4,+            listOf(+                listOf(0, 0, 0x11, 1), listOf(0, 1, 0x22, 1), listOf(0, 0, 0, 0), listOf(0, 1, 0, 0),+                listOf(1, 0, 0x33, 0), listOf(1, 0, 0, 0), listOf(1, 1, 0x44, 1), listOf(1, 1, 0, 0),+                listOf(0, 0, 0x99, 0), listOf(1, 0, 0x55, 1), listOf(1, 0, 0, 0), listOf(0, 1, 0, 0),+            ),+        ),+    ),+)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.ktnew file mode 100644index 0000000000..10878d9057--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.kt@@ -0,0 +1,64 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Pin++/** Splitters and joiners arrive with the first bus level and stay for the rest of the game. */+internal val busGifts = listOf(Chips.NIB_SPLIT, Chips.NIB_JOIN, Chips.SPLIT8, Chips.JOIN8, Chips.SPLIT4, Chips.JOIN4)++/** The bus-wide gates handed over for solving the bus MUX. */+internal val bitwisePack = listOf(Chips.NOT8, Chips.AND8, Chips.OR8, Chips.XOR8, Chips.MUX8B, Chips.MUX4B)++internal val routingLevels: List<LevelDef> = listOf(+    chipLevel(+        Chapter.ROUTING, "mux", Chips.MUX,+        LevelText(+            "MUX",+            "A selector: o is a when s is 0, and b when s is 1.",+            "AND a with NOT s and b with s, then OR the two. In NANDs it is just four gates.",+        ),+        title = RowTitles.mux,+    ),+    chipLevel(+        Chapter.ROUTING, "dmux", Chips.DMUX,+        LevelText(+            "DMUX",+            "Send in to a when s is 0, or to b when s is 1. The other output stays 0.",+            "a = in AND NOT s, b = in AND s.",+        ),+        title = RowTitles.dmux,+    ),+    chipLevel(+        Chapter.ROUTING, "dec2", Chips.DEC2,+        LevelText(+            "Decoder",+            "Light exactly one of y0–y3: the one numbered by s1 s0 (s1 is the high bit).",+            "Each output is an AND of s1 or NOT s1 with s0 or NOT s0.",+        ),+        title = RowTitles.dec2,+    ),+    LevelDef(+        id = "nibble_swap",+        chapter = Chapter.ROUTING,+        title = "Nibble swap",+        brief = "Thick wires are buses carrying 4 or 8 bits at once. Swap the low and high halves of x.",+        hint = "NIB SPLIT gives the two halves; cross them into a NIB JOIN.",+        inputs = listOf(Pin("x", 8)),+        outputs = listOf(Pin("y", 8)),+        tests = TestGen.comb(listOf(Pin("x", 8)), seed = 10, RowTitles.nibbleSwap) {+            listOf(((it[0] shl 4) or (it[0] shr 4)) and 0xFF)+        },+        par = 0,+        gifts = busGifts,+    ),+    chipLevel(+        Chapter.ROUTING, "bus_mux", Chips.MUX8B,+        LevelText(+            "Bus MUX",+            "Choose between two whole bytes. The one tedious bus level: solve it and every bus-wide gate is yours.",+            "Split both buses, use eight MUXes, and join the results.",+        ),+        title = RowTitles.busMux,+        unlocks = bitwisePack,+    ),+)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.ktnew file mode 100644index 0000000000..5603c94def--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.kt@@ -0,0 +1,99 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.Isa+import com.vayunmathur.games.logicgate.domain.model.formatValue++/** Builds a test row's title from its inputs and expected outputs. */+typealias RowTitle = (inputs: List<Int>, expected: List<Int?>) -> String++/**+ * Plain-language row titles, written as the behaviour the row checks: `1 OR 1 = 1`,+ * `200 + 100 = 44, carry 1`, `q=1, hold`. Arithmetic reads in decimal; other buses in hex.+ */+internal object RowTitles {+    private fun hex8(v: Int?) = v?.let { formatValue(it, 8) } ?: "?"+    private fun carry(c: Int?) = if (c == 1) ", carry 1" else ""++    fun infix(op: String): RowTitle = { i, e -> "${i[0]} $op ${i[1]} = ${e[0]}" }++    val not: RowTitle = { i, e -> "NOT ${i[0]} = ${e[0]}" }++    val mux: RowTitle = { i, e -> "a=${i[0]} b=${i[1]}, s=${i[2]} picks ${if (i[2] == 1) "b" else "a"} = ${e[0]}" }++    val dmux: RowTitle = { i, e -> "send ${i[0]} to ${if (i[1] == 1) "b" else "a"} → a=${e[0]} b=${e[1]}" }++    val dec2: RowTitle = { i, _ -> "select ${i[0] * 2 + i[1]} → y${i[0] * 2 + i[1]} = 1" }++    val nibbleSwap: RowTitle = { i, e -> "swap ${hex8(i[0])} → ${hex8(e[0])}" }++    val busMux: RowTitle = { i, e -> "s=${i[2]} picks ${if (i[2] == 1) "b" else "a"} = ${hex8(e[0])}" }++    val half: RowTitle = { i, e -> "${i[0]} + ${i[1]} = ${e[0]}${carry(e[1])}" }++    val full: RowTitle = { i, e -> "${i[0]} + ${i[1]} + ${i[2]} = ${e[0]}${carry(e[1])}" }++    val add: RowTitle = { i, e ->+        val cin = if (i[2] == 1) " + 1" else ""+        "${i[0]} + ${i[1]}$cin = ${e[0]}${carry(e[1])}"+    }++    val inc: RowTitle = { i, e -> "${i[0]} + 1 = ${e[0]}" }++    val sub: RowTitle = { i, e -> "${i[0]} − ${i[1]} = ${e[0]}" }++    val zero: RowTitle = { i, e -> "${i[0]} is zero? ${if (e[0] == 1) "yes" else "no"}" }++    val alu: RowTitle = { i, e ->+        val body = when (i[2] * 2 + i[3]) {+            0 -> "${i[0]} + ${i[1]}"+            1 -> "${i[0]} − ${i[1]}"+            2 -> "${i[0]} AND ${i[1]}"+            else -> "pass ${i[1]}"+        }+        "$body = ${e[0]}${if (e[1] == 1) ", zero" else ""}"+    }++    private val opNames = listOf("LDA", "STA", "ADD", "SUB", "LDI", "JMP", "JZ", "HLT")+    private val aluNames = listOf("add", "subtract", "AND", "pass b")+    private val lineNames = listOf("load acc", "write memory", "use immediate", "jump", "halt")++    val decoder: RowTitle = { i, e ->+        val op = i[0] and 7+        val name = opNames[op] + if (op == Isa.JZ) " with z=${i[1]}" else ""+        val aluOp = e[0]?.let { hi -> e[1]?.let { lo -> hi * 2 + lo } }+        val alu = listOfNotNull(aluOp?.let { "ALU ${aluNames[it]}" })+        val lines = lineNames.filterIndexed { k, _ -> e[k + 2] == 1 }+        val active = (alu + lines).ifEmpty { listOf("nothing") }+        "$name → ${active.joinToString()}"+    }++    val srLatch: RowTitle = { i, e ->+        val action = when {+            i[0] == 1 -> "set"+            i[1] == 1 -> "reset"+            else -> "hold"+        }+        "$action → q=${e[0]}"+    }++    val dLatch: RowTitle = { i, e -> if (i[1] == 1) "en=1, d=${i[0]} → q=${e[0]}" else "en=0, hold → q=${e[0]}" }++    val bit: RowTitle = { i, e -> "q=${e[0]}, then ${if (i[1] == 1) "store ${i[0]}" else "hold"}" }++    val reg8: RowTitle = { i, e -> "q=${hex8(e[0])}, then ${if (i[1] == 1) "store ${hex8(i[0])}" else "hold"}" }++    val pc4: RowTitle = { i, e ->+        val next = when {+            i[1] == 1 -> "jump to ${i[2]}"+            i[0] == 1 -> "count"+            else -> "hold"+        }+        "pc=${e[0]}, then $next"+    }++    val ram4: RowTitle = { i, e ->+        val addr = i[0] * 2 + i[1]+        val write = if (i[3] == 1) ", then write ${hex8(i[2])}" else ""+        "read [$addr] = ${hex8(e[0])}$write"+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.ktnew file mode 100644index 0000000000..834b0694f9--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.kt@@ -0,0 +1,71 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.Behavior+import com.vayunmathur.games.logicgate.domain.model.ChipSpec+import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.games.logicgate.domain.sim.Case+import com.vayunmathur.games.logicgate.domain.sim.TestSpec+import kotlin.random.Random++/** Builds test tables from a reference function or a native chip. */+internal object TestGen {+    private const val EXHAUSTIVE_BITS = 10+    private const val RANDOM_CASES = 200++    fun chip(id: String): ChipSpec = requireNotNull(Chips[id]) { "unknown chip $id" }++    /**+     * Exhaustive when the inputs total at most [EXHAUSTIVE_BITS] bits; otherwise edge values for+     * every input (0, 1, 0x7F, 0x80, max) crossed together, plus seeded random vectors.+     */+    fun comb(inputs: List<Pin>, seed: Int, title: RowTitle, f: (IntArray) -> List<Int?>): TestSpec.Comb {+        val vectors = if (inputs.sumOf { it.width } <= EXHAUSTIVE_BITS) exhaustive(inputs) else sampled(inputs, seed)+        return TestSpec.Comb(+            vectors.map { v ->+                val expected = f(v.toIntArray())+                Case(v, expected, title(v, expected))+            },+        )+    }++    fun fromChip(id: String, title: RowTitle): TestSpec.Comb {+        val spec = chip(id)+        val eval = (spec.behavior as Behavior.Comb).eval+        return comb(spec.inputs, id.hashCode(), title) { eval(it).toList() }+    }++    /** Expected outputs come from running the native chip over [ticks]. */+    fun seqFromChip(id: String, title: RowTitle, ticks: List<List<Int>>): TestSpec.Seq {+        val seq = chip(id).behavior as Behavior.Seq+        var state = seq.init+        return TestSpec.Seq(+            ticks.map { t ->+                val ins = t.toIntArray()+                val out = seq.outputs(state, ins).toList()+                state = seq.next(state, ins)+                Case(t, out, title(t, out))+            },+        )+    }++    private fun exhaustive(inputs: List<Pin>): List<List<Int>> {+        val total = 1 shl inputs.sumOf { it.width }+        return (0 until total).map { code ->+            var rest = code+            inputs.asReversed().map { p ->+                val v = rest and p.mask+                rest = rest shr p.width+                v+            }.asReversed()+        }+    }++    private fun sampled(inputs: List<Pin>, seed: Int): List<List<Int>> {+        val edges = inputs.map { p -> listOf(0, 1, 0x7F, 0x80, p.mask).map { it and p.mask }.distinct() }+        val crossed = edges.fold(listOf(emptyList<Int>())) { acc, vals -> acc.flatMap { pre -> vals.map { pre + it } } }+        val rng = Random(seed)+        val random = List(RANDOM_CASES) { inputs.map { p -> rng.nextInt(p.mask + 1) } }+        return (crossed + random).distinct()+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.ktnew file mode 100644index 0000000000..d91c9a0f2f--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt@@ -0,0 +1,36 @@+package com.vayunmathur.games.logicgate.domain.model++/** A named pin carrying a [width]-bit signal (1, 4 or 8). Signals are bit masks in an `Int`. */+data class Pin(val name: String, val width: Int = 1) {+    val mask: Int get() = (1 shl width) - 1+}++/** How a chip turns input signals into output signals. */+sealed interface Behavior {+    /** Outputs are a pure function of inputs. */+    class Comb(val eval: (IntArray) -> IntArray) : Behavior++    /**+     * Clocked state. [outputs] reads the current state (and, when [readsInputs], the inputs too —+     * an asynchronous memory read); [next] runs once per tick on the clock edge.+     */+    class Seq(+        val init: IntArray,+        val outputs: (state: IntArray, inputs: IntArray) -> IntArray,+        val next: (state: IntArray, inputs: IntArray) -> IntArray,+        val readsInputs: Boolean = false,+    ) : Behavior+}++/** A placeable chip: its pins, what it costs in NAND gates, and its trusted native behaviour. */+data class ChipSpec(+    val id: String,+    val label: String,+    val inputs: List<Pin>,+    val outputs: List<Pin>,+    val nandCost: Int,+    val behavior: Behavior,+) {+    /** True when outputs depend only on stored state, so this chip breaks combinational loops. */+    val isStateOnly: Boolean get() = behavior is Behavior.Seq && !behavior.readsInputs+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.ktnew file mode 100644index 0000000000..957002db2d--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt@@ -0,0 +1,238 @@+package com.vayunmathur.games.logicgate.domain.model++/**+ * Every chip in the game. A level's reward chip runs here natively — trusted, fast, and never+ * expanded into the player's own build — which is what keeps the CPU levels cheap to simulate.+ */+object Chips {+    const val NAND = "NAND"+    const val HIGH = "HIGH"+    const val LOW = "LOW"+    const val NOT = "NOT"+    const val AND = "AND"+    const val OR = "OR"+    const val NOR = "NOR"+    const val XOR = "XOR"+    const val XNOR = "XNOR"+    const val MUX = "MUX"+    const val DMUX = "DMUX"+    const val DEC2 = "DEC2"+    const val SPLIT8 = "SPLIT8"+    const val JOIN8 = "JOIN8"+    const val SPLIT4 = "SPLIT4"+    const val JOIN4 = "JOIN4"+    const val NIB_SPLIT = "NIB_SPLIT"+    const val NIB_JOIN = "NIB_JOIN"+    const val NOT8 = "NOT8"+    const val AND8 = "AND8"+    const val OR8 = "OR8"+    const val XOR8 = "XOR8"+    const val MUX8B = "MUX8b"+    const val MUX4B = "MUX4b"+    const val HALF = "HALF"+    const val FULL = "FULL"+    const val ADD4 = "ADD4"+    const val ADD8 = "ADD8"+    const val INC4 = "INC4"+    const val SUB8 = "SUB8"+    const val ZERO8 = "ZERO8"+    const val ALU8 = "ALU8"+    const val DFF = "DFF"+    const val DFF4 = "DFF4"+    const val DFF8 = "DFF8"+    const val BIT = "BIT"+    const val REG8 = "REG8"+    const val PC4 = "PC4"+    const val RAM4 = "RAM4"+    const val RAM16 = "RAM16"+    const val DECODER = "DECODER"+    const val CPU = "CPU"++    /** Chips every level offers. */+    val base: List<String> = listOf(NAND, HIGH, LOW)++    private fun p(name: String, width: Int = 1) = Pin(name, width)+    private fun bits(prefix: String, n: Int) = (0 until n).map { p("$prefix$it") }++    private fun comb(+        id: String,+        inputs: List<Pin>,+        outputs: List<Pin>,+        cost: Int,+        label: String = id,+        f: (IntArray) -> IntArray,+    ) = ChipSpec(id, label, inputs, outputs, cost, Behavior.Comb(f))++    private fun gate2(id: String, cost: Int, f: (Int, Int) -> Int) =+        comb(id, listOf(p("a"), p("b")), listOf(p("o")), cost) { intArrayOf(f(it[0], it[1]) and 1) }++    private fun split(id: String, n: Int, label: String) =+        comb(id, listOf(p("x", n)), bits("b", n), 0, label) { v -> IntArray(n) { (v[0] shr it) and 1 } }++    private fun join(id: String, n: Int, label: String) =+        comb(id, bits("b", n), listOf(p("x", n)), 0, label) { v ->+            intArrayOf(v.foldIndexed(0) { i, acc, b -> acc or ((b and 1) shl i) })+        }++    private fun bitwise8(id: String, cost: Int, f: (Int, Int) -> Int) =+        comb(id, listOf(p("a", 8), p("b", 8)), listOf(p("o", 8)), cost) { intArrayOf(f(it[0], it[1]) and 0xFF) }++    private val logic = listOf(+        gate2(NAND, 1) { a, b -> (a and b) xor 1 },+        comb(HIGH, emptyList(), listOf(p("o")), 0) { intArrayOf(1) },+        comb(LOW, emptyList(), listOf(p("o")), 0) { intArrayOf(0) },+        comb(NOT, listOf(p("a")), listOf(p("o")), 1) { intArrayOf(it[0] xor 1) },+        gate2(AND, 2) { a, b -> a and b },+        gate2(OR, 3) { a, b -> a or b },+        gate2(NOR, 4) { a, b -> (a or b) xor 1 },+        gate2(XOR, 4) { a, b -> a xor b },+        gate2(XNOR, 5) { a, b -> a xor b xor 1 },+    )++    private val routing = listOf(+        comb(MUX, listOf(p("a"), p("b"), p("s")), listOf(p("o")), 4) {+            intArrayOf(if (it[2] == 1) it[1] else it[0])+        },+        comb(DMUX, listOf(p("in"), p("s")), listOf(p("a"), p("b")), 5) {+            intArrayOf(it[0] and (it[1] xor 1), it[0] and it[1])+        },+        comb(DEC2, listOf(p("s1"), p("s0")), bits("y", 4), 10) { v ->+            val sel = v[0] * 2 + v[1]+            IntArray(4) { if (it == sel) 1 else 0 }+        },+        split(SPLIT8, 8, "SPLIT 8"),+        join(JOIN8, 8, "JOIN 8"),+        split(SPLIT4, 4, "SPLIT 4"),+        join(JOIN4, 4, "JOIN 4"),+        comb(NIB_SPLIT, listOf(p("x", 8)), listOf(p("lo", 4), p("hi", 4)), 0, "NIB SPLIT") {+            intArrayOf(it[0] and 0xF, it[0] shr 4)+        },+        comb(NIB_JOIN, listOf(p("lo", 4), p("hi", 4)), listOf(p("x", 8)), 0, "NIB JOIN") {+            intArrayOf(it[0] or (it[1] shl 4))+        },+        comb(NOT8, listOf(p("a", 8)), listOf(p("o", 8)), 8) { intArrayOf(it[0].inv() and 0xFF) },+        bitwise8(AND8, 16) { a, b -> a and b },+        bitwise8(OR8, 24) { a, b -> a or b },+        bitwise8(XOR8, 32) { a, b -> a xor b },+        comb(MUX8B, listOf(p("a", 8), p("b", 8), p("s")), listOf(p("o", 8)), 32) {+            intArrayOf(if (it[2] == 1) it[1] else it[0])+        },+        comb(MUX4B, listOf(p("a", 4), p("b", 4), p("s")), listOf(p("o", 4)), 16) {+            intArrayOf(if (it[2] == 1) it[1] else it[0])+        },+    )++    private val arithmetic = listOf(+        comb(HALF, listOf(p("a"), p("b")), listOf(p("s"), p("c")), 5) {+            intArrayOf(it[0] xor it[1], it[0] and it[1])+        },+        comb(FULL, listOf(p("a"), p("b"), p("cin")), listOf(p("s"), p("cout")), 9) {+            val t = it[0] + it[1] + it[2]+            intArrayOf(t and 1, t shr 1)+        },+        comb(ADD4, listOf(p("a", 4), p("b", 4), p("cin")), listOf(p("s", 4), p("cout")), 36) {+            val t = it[0] + it[1] + it[2]+            intArrayOf(t and 0xF, t shr 4)+        },+        comb(ADD8, listOf(p("a", 8), p("b", 8), p("cin")), listOf(p("s", 8), p("cout")), 72) {+            val t = it[0] + it[1] + it[2]+            intArrayOf(t and 0xFF, t shr 8)+        },+        comb(INC4, listOf(p("a", 4)), listOf(p("o", 4)), 16) { intArrayOf((it[0] + 1) and 0xF) },+        comb(SUB8, listOf(p("a", 8), p("b", 8)), listOf(p("d", 8)), 80) { intArrayOf((it[0] - it[1]) and 0xFF) },+        comb(ZERO8, listOf(p("a", 8)), listOf(p("z")), 22) { intArrayOf(if (it[0] == 0) 1 else 0) },+        comb(ALU8, listOf(p("a", 8), p("b", 8), p("op1"), p("op0")), listOf(p("o", 8), p("z")), 206) {+            val r = alu(it[0], it[1], it[2] * 2 + it[3])+            intArrayOf(r, if (r == 0) 1 else 0)+        },+    )++    private fun register(id: String, width: Int, cost: Int, withLoad: Boolean): ChipSpec {+        val ins = if (withLoad) listOf(p("d", width), p("load")) else listOf(p("d", width))+        return ChipSpec(+            id, id, ins, listOf(p("q", width)), cost,+            Behavior.Seq(+                init = IntArray(1),+                outputs = { s, _ -> intArrayOf(s[0]) },+                next = { s, i -> intArrayOf(if (!withLoad || i[1] == 1) i[0] else s[0]) },+            ),+        )+    }++    private val memory = listOf(+        register(DFF, 1, 8, withLoad = false),+        register(DFF4, 4, 32, withLoad = false),+        register(DFF8, 8, 64, withLoad = false),+        register(BIT, 1, 12, withLoad = true),+        register(REG8, 8, 96, withLoad = true),+        ChipSpec(+            PC4, PC4, listOf(p("en"), p("load"), p("v", 4)), listOf(p("pc", 4)), 80,+            Behavior.Seq(+                init = IntArray(1),+                outputs = { s, _ -> intArrayOf(s[0]) },+                next = { s, i -> intArrayOf(pcNext(s[0], i[0], i[1], i[2])) },+            ),+        ),+        ChipSpec(+            RAM4, RAM4, listOf(p("a1"), p("a0"), p("din", 8), p("we")), listOf(p("dout", 8)), 498,+            Behavior.Seq(+                init = IntArray(4),+                outputs = { s, i -> intArrayOf(s[i[0] * 2 + i[1]]) },+                next = { s, i -> s.copyOf().also { if (i[3] == 1) it[i[0] * 2 + i[1]] = i[2] } },+                readsInputs = true,+            ),+        ),+        ChipSpec(+            RAM16, RAM16, listOf(p("iaddr", 4), p("daddr", 4), p("din", 8), p("we")),+            listOf(p("instr", 8), p("dout", 8)), 2560,+            Behavior.Seq(+                init = IntArray(16),+                outputs = { s, i -> intArrayOf(s[i[0]], s[i[1]]) },+                next = { s, i -> s.copyOf().also { if (i[3] == 1) it[i[1]] = i[2] } },+                readsInputs = true,+            ),+        ),+    )++    private val cpu = listOf(+        comb(DECODER, listOf(p("op", 4), p("z")), Isa.decoderOutputs, 44) { Isa.decode(it[0], it[1]) },+        ChipSpec(+            CPU, CPU, listOf(p("instr", 8), p("data", 8)), Isa.cpuOutputs, 481,+            Behavior.Seq(+                init = IntArray(2),+                outputs = { s, i -> Isa.cpuOut(s[0], s[1], i[0]) },+                next = { s, i -> Isa.cpuNext(s[0], s[1], i[0], i[1]) },+                readsInputs = true,+            ),+        ),+    )++    val all: List<ChipSpec> = logic + routing + arithmetic + memory + cpu++    private val byId: Map<String, ChipSpec> = all.associateBy { it.id }++    operator fun get(id: String): ChipSpec? = byId[id]++    /** Pin lookup for a board with the level pins [io]. */+    fun lookup(io: LevelIo): PinLookup = PinLookup { node ->+        when (node) {+            is Gate -> byId[node.chipId]?.let { NodePins(it.inputs, it.outputs) }+            is LevelInput -> io.inputs.getOrNull(node.index)?.let { NodePins(emptyList(), listOf(it)) }+            is LevelOutput -> io.outputs.getOrNull(node.index)?.let { NodePins(listOf(it), emptyList()) }+        }+    }++    /** `00` ADD · `01` SUB · `10` AND · `11` PASS B, all 8-bit wrapping. */+    fun alu(a: Int, b: Int, op: Int): Int = when (op) {+        0 -> a + b+        1 -> a - b+        2 -> a and b+        else -> b+    } and 0xFF++    fun pcNext(pc: Int, en: Int, load: Int, v: Int): Int = when {+        load == 1 -> v+        en == 1 -> (pc + 1) and 0xF+        else -> pc+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.ktnew file mode 100644index 0000000000..55f81c0a52--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.kt@@ -0,0 +1,174 @@+package com.vayunmathur.games.logicgate.domain.model++/** Stable identity of a node within one circuit. */+@JvmInline+value class NodeId(val raw: Int)++/** Which edge of a node a pin sits on. */+enum class PinSide { IN, OUT }++/** One pin of one node. */+data class PinRef(val node: NodeId, val side: PinSide, val index: Int)++/** A position in world units. */+data class Point(val x: Float, val y: Float)++/** Something on the board: a chip, or one of the level's own inputs/outputs. */+sealed interface Node {+    val id: NodeId+    val pos: Point+    fun moved(to: Point): Node+}++/** A placed chip. */+data class Gate(override val id: NodeId, val chipId: String, override val pos: Point) : Node {+    override fun moved(to: Point) = copy(pos = to)+}++/** The level's input [index], drawn as a source on the left of the board. */+data class LevelInput(override val id: NodeId, val index: Int, override val pos: Point) : Node {+    override fun moved(to: Point) = copy(pos = to)+}++/** The level's output [index], drawn as a sink on the right of the board. */+data class LevelOutput(override val id: NodeId, val index: Int, override val pos: Point) : Node {+    override fun moved(to: Point) = copy(pos = to)+}++/** A connection from an output pin to an input pin. */+data class Wire(val from: PinRef, val to: PinRef)++/** The pins a node exposes. */+data class NodePins(val inputs: List<Pin>, val outputs: List<Pin>) {+    fun pin(side: PinSide, index: Int): Pin? =+        (if (side == PinSide.IN) inputs else outputs).getOrNull(index)+}++/** The pin layout of a level's board. */+data class LevelIo(val inputs: List<Pin>, val outputs: List<Pin>)++/** Resolves the pins of a node; null when the node's chip is unknown. */+fun interface PinLookup {+    fun pins(node: Node): NodePins?+}++/** Outcome of asking whether two pins may be wired together. */+sealed interface ConnectCheck {+    /** Allowed; [wire] is the normalised output-to-input connection. */+    data class Ok(val wire: Wire) : ConnectCheck++    /** Both ends are inputs, or both are outputs. */+    data class SameSide(val side: PinSide) : ConnectCheck++    /** The pins carry different bus widths. */+    data class WidthMismatch(val fromWidth: Int, val toWidth: Int) : ConnectCheck++    /** One end does not exist. */+    data object MissingPin : ConnectCheck+}++/** An immutable circuit. Every edit returns a new value, which is what makes undo trivial. */+data class Circuit(+    val nodes: List<Node> = emptyList(),+    val wires: List<Wire> = emptyList(),+    val nextId: Int = 0,+) {+    fun node(id: NodeId): Node? = nodes.firstOrNull { it.id == id }++    fun addGate(chipId: String, pos: Point): Pair<Circuit, NodeId> {+        val id = NodeId(nextId)+        return copy(nodes = nodes + Gate(id, chipId, pos), nextId = nextId + 1) to id+    }++    fun moveNode(id: NodeId, pos: Point): Circuit =+        copy(nodes = nodes.map { if (it.id == id) it.moved(pos) else it })++    /** Removes a gate and every wire touching it. Level inputs/outputs cannot be removed. */+    fun removeNode(id: NodeId): Circuit {+        if (node(id) !is Gate) return this+        return copy(+            nodes = nodes.filterNot { it.id == id },+            wires = wires.filterNot { it.from.node == id || it.to.node == id },+        )+    }++    fun removeWire(wire: Wire): Circuit = copy(wires = wires - wire)++    fun wireInto(pin: PinRef): Wire? = wires.firstOrNull { it.to == pin }++    fun pin(ref: PinRef, lookup: PinLookup): Pin? =+        node(ref.node)?.let { lookup.pins(it) }?.pin(ref.side, ref.index)++    fun check(a: PinRef, b: PinRef, lookup: PinLookup): ConnectCheck {+        if (a.side == b.side) return ConnectCheck.SameSide(a.side)+        val (from, to) = if (a.side == PinSide.OUT) a to b else b to a+        val fromPin = pin(from, lookup) ?: return ConnectCheck.MissingPin+        val toPin = pin(to, lookup) ?: return ConnectCheck.MissingPin+        if (fromPin.width != toPin.width) return ConnectCheck.WidthMismatch(fromPin.width, toPin.width)+        return ConnectCheck.Ok(Wire(from, to))+    }++    /** Wires [a] to [b] in whichever direction is valid, replacing any wire already on the input. */+    fun connect(a: PinRef, b: PinRef, lookup: PinLookup): Circuit? {+        val ok = check(a, b, lookup) as? ConnectCheck.Ok ?: return null+        return copy(wires = wires.filterNot { it.to == ok.wire.to } + ok.wire)+    }++    /**+     * Drops anything a stale save could carry that the editor would never create: unknown chips,+     * wires to missing pins or of mismatched width, and second wires into one input. Also makes+     * sure every level input/output node exists.+     */+    fun sanitized(io: LevelIo, lookup: PinLookup): Circuit {+        val withIo = withLevelIo(io)+        val keptNodes = withIo.nodes.filter { lookup.pins(it) != null }+        val base = withIo.copy(nodes = keptNodes)+        val seenInputs = HashSet<PinRef>()+        val keptWires = base.wires.filter { w ->+            base.check(w.from, w.to, lookup) == ConnectCheck.Ok(w) && seenInputs.add(w.to)+        }+        val maxId = keptNodes.maxOfOrNull { it.id.raw } ?: -1+        return base.copy(wires = keptWires, nextId = maxOf(base.nextId, maxId + 1))+    }++    private fun withLevelIo(io: LevelIo): Circuit {+        val inIdx = nodes.filterIsInstance<LevelInput>().map { it.index }.toSet()+        val outIdx = nodes.filterIsInstance<LevelOutput>().map { it.index }.toSet()+        val fresh = forLevel(io)+        var next = nextId+        val missing = fresh.nodes.filter {+            (it is LevelInput && it.index !in inIdx) || (it is LevelOutput && it.index !in outIdx)+        }.map { n ->+            val id = NodeId(next++)+            when (n) {+                is LevelInput -> n.copy(id = id)+                is LevelOutput -> n.copy(id = id)+                is Gate -> n+            }+        }+        val pruned = nodes.filterNot {+            (it is LevelInput && it.index >= io.inputs.size) || (it is LevelOutput && it.index >= io.outputs.size)+        }+        return copy(nodes = pruned + missing, nextId = next)+    }++    /** Board layout defaults. */+    companion object {+        const val IO_SPACING = 96f+        const val OUTPUT_X = 400f++        /** An empty board with the level's inputs down the left and outputs down the right. */+        fun forLevel(io: LevelIo): Circuit {+            var id = 0+            val ins = io.inputs.indices.map { i ->+                LevelInput(NodeId(id++), i, Point(0f, column(i, io.inputs.size)))+            }+            val outs = io.outputs.indices.map { i ->+                LevelOutput(NodeId(id++), i, Point(OUTPUT_X, column(i, io.outputs.size)))+            }+            return Circuit(nodes = ins + outs, nextId = id)+        }++        private fun column(i: Int, n: Int) = (i - (n - 1) / 2f) * IO_SPACING+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.ktnew file mode 100644index 0000000000..77790e4660--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.kt@@ -0,0 +1,65 @@+package com.vayunmathur.games.logicgate.domain.model++/**+ * The fixed 8-bit instruction set. An instruction is `op[4] | operand[4]`; one instruction runs+ * per tick because the dual-port RAM fetches the instruction and reads the operand together.+ */+object Isa {+    const val LDA = 0+    const val STA = 1+    const val ADD = 2+    const val SUB = 3+    const val LDI = 4+    const val JMP = 5+    const val JZ = 6+    const val HLT = 7++    private const val ALU_ADD = 0+    private const val ALU_SUB = 1+    private const val ALU_PASS_B = 3++    val decoderOutputs: List<Pin> = listOf(+        Pin("aluOp1"), Pin("aluOp0"), Pin("accLoad"), Pin("memWrite"), Pin("useImm"), Pin("jump"), Pin("halt"),+    )++    val cpuOutputs: List<Pin> = listOf(+        Pin("pc", 4), Pin("addr", 4), Pin("dout", 8), Pin("we"), Pin("acc", 8), Pin("halt"),+    )++    fun encode(op: Int, operand: Int = 0): Int = (op shl 4) or (operand and 0xF)++    /** Control lines for [op] (the top bit is ignored) given the accumulator-zero flag [z]. */+    fun decode(op: Int, z: Int): IntArray {+        val o = op and 7+        val aluOp = when (o) {+            LDA, LDI -> ALU_PASS_B+            SUB -> ALU_SUB+            else -> ALU_ADD+        }+        return intArrayOf(+            aluOp shr 1,+            aluOp and 1,+            bit(o == LDA || o == ADD || o == SUB || o == LDI),+            bit(o == STA),+            bit(o == LDI),+            bit(o == JMP || (o == JZ && z == 1)),+            bit(o == HLT),+        )+    }++    fun cpuOut(pc: Int, acc: Int, instr: Int): IntArray {+        val o = (instr shr 4) and 7+        return intArrayOf(pc, instr and 0xF, acc, bit(o == STA), acc, bit(o == HLT))+    }++    /** Next `[pc, acc]` after executing [instr] with [data] read from its operand address. */+    fun cpuNext(pc: Int, acc: Int, instr: Int, data: Int): IntArray {+        val c = decode(instr shr 4, bit(acc == 0))+        val operand = instr and 0xF+        val b = if (c[4] == 1) operand else data+        val newAcc = if (c[2] == 1) Chips.alu(acc, b, c[0] * 2 + c[1]) else acc+        return intArrayOf(Chips.pcNext(pc, c[6] xor 1, c[5], operand), newAcc)+    }++    private fun bit(b: Boolean) = if (b) 1 else 0+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.ktnew file mode 100644index 0000000000..4626400bc0--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.kt@@ -0,0 +1,7 @@+package com.vayunmathur.games.logicgate.domain.model++/** Signal text: 1-bit as 0/1, buses as zero-padded upper-case hex (one digit per nibble). */+fun formatValue(value: Int, width: Int): String =+    if (width == 1) value.toString() else value.toString(HEX).uppercase().padStart((width + 3) / 4, '0')++private const val HEX = 16
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.ktnew file mode 100644index 0000000000..3260afa9c7--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.kt@@ -0,0 +1,58 @@+package com.vayunmathur.games.logicgate.domain.sim++/** Orders a dependency graph into strongly connected groups, sources first (Tarjan). */+internal object Scheduler {++    /**+     * Groups nodes `0 until n` (except [excluded]) so every group only depends on groups before+     * it. Each entry is `(members in index order, isCyclic)`.+     */+    fun groups(n: Int, edges: List<Pair<Int, Int>>, excluded: Set<Int>): List<Pair<IntArray, Boolean>> {+        val adj = Array(n) { mutableListOf<Int>() }+        val selfLoop = BooleanArray(n)+        for ((a, b) in edges) {+            if (a in excluded || b in excluded) continue+            if (a == b) selfLoop[a] = true else adj[a] += b+        }+        val tarjan = Tarjan(n, adj)+        for (v in 0 until n) if (v !in excluded && tarjan.index[v] < 0) tarjan.visit(v)+        return tarjan.sccs.asReversed().map { scc ->+            val sorted = scc.sorted().toIntArray()+            sorted to (sorted.size > 1 || selfLoop[sorted[0]])+        }+    }++    private class Tarjan(n: Int, val adj: Array<MutableList<Int>>) {+        val index = IntArray(n) { -1 }+        val low = IntArray(n)+        val onStack = BooleanArray(n)+        val stack = ArrayDeque<Int>()+        val sccs = mutableListOf<List<Int>>()+        var counter = 0++        fun visit(v: Int) {+            index[v] = counter+            low[v] = counter+            counter+++            stack.addLast(v)+            onStack[v] = true+            for (w in adj[v]) {+                if (index[w] < 0) {+                    visit(w)+                    low[v] = minOf(low[v], low[w])+                } else if (onStack[w]) {+                    low[v] = minOf(low[v], index[w])+                }+            }+            if (low[v] == index[v]) {+                val scc = mutableListOf<Int>()+                do {+                    val w = stack.removeLast()+                    onStack[w] = false+                    scc += w+                } while (w != v)+                sccs += scc+            }+        }+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.ktnew file mode 100644index 0000000000..6ab5e96252--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.kt@@ -0,0 +1,19 @@+package com.vayunmathur.games.logicgate.domain.sim++import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.Gate++/** Circuit cost and star rating. */+object Scoring {++    fun cost(circuit: Circuit, nandCost: (String) -> Int?): Int =+        circuit.nodes.sumOf { (it as? Gate)?.let { g -> nandCost(g.chipId) } ?: 0 }++    /** ★ solved, ★★ within 1.5× par, ★★★ at or under par; 0 when unsolved. */+    fun stars(solved: Boolean, cost: Int, par: Int): Int = when {+        !solved -> 0+        cost <= par -> 3+        cost * 2 <= par * 3 -> 2+        else -> 1+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.ktnew file mode 100644index 0000000000..1a8a874067--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt@@ -0,0 +1,209 @@+package com.vayunmathur.games.logicgate.domain.sim++import com.vayunmathur.games.logicgate.domain.model.Behavior+import com.vayunmathur.games.logicgate.domain.model.ChipSpec+import com.vayunmathur.games.logicgate.domain.model.Chips+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.LevelIo+import com.vayunmathur.games.logicgate.domain.model.LevelOutput+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.NodePins+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.PinSide++/**+ * Cycle-accurate simulator. One [step] is one tick of an implicit global clock:+ *+ * 1. [settle] combinational logic. Acyclic parts run once in topological order. Feedback loops+ *    iterate in-order (Gauss-Seidel) from the previous tick's values, which is what lets a+ *    cross-coupled latch pick a side and hold it; a loop still changing after [MAX_PASSES]+ *    passes is reported as oscillating.+ * 2. [clock] every sequential chip into its next state.+ *+ * State-only chips (registers) publish their outputs before anything else settles, so they break+ * every loop that runs through them. Unconnected inputs read 0.+ */+class Simulator(+    circuit: Circuit,+    io: LevelIo,+    catalog: (String) -> ChipSpec? = Chips::get,+) {+    private val nodes = circuit.nodes+    private val specs: Array<ChipSpec?> = Array(nodes.size) { (nodes[it] as? Gate)?.let { g -> catalog(g.chipId) } }+    private val inPins: Array<List<Pin>>+    private val outPins: Array<List<Pin>>+    private val outBase: IntArray+    private val values: IntArray+    private val inSrc: Array<IntArray>+    private val scratch: Array<IntArray>+    private val states: Array<IntArray?> = arrayOfNulls(nodes.size)+    private val levelInputs = IntArray(io.inputs.size)+    private val outputNodes = IntArray(io.outputs.size) { -1 }+    private val stateOnly: IntArray+    private val groups: List<IntArray>+    private val cyclic: BooleanArray++    init {+        val lookup = Chips.lookup(io)+        val empty = NodePins(emptyList(), emptyList())+        val pins = nodes.mapIndexed { i, n ->+            val spec = specs[i]+            if (n is Gate) NodePins(spec?.inputs.orEmpty(), spec?.outputs.orEmpty()) else lookup.pins(n) ?: empty+        }+        inPins = Array(nodes.size) { pins[it].inputs }+        outPins = Array(nodes.size) { pins[it].outputs }+        outBase = IntArray(nodes.size)+        var slot = 0+        for (i in nodes.indices) {+            outBase[i] = slot+            slot += outPins[i].size+        }+        values = IntArray(slot)+        val index = HashMap<NodeId, Int>()+        nodes.forEachIndexed { i, n -> index[n.id] = i }+        inSrc = Array(nodes.size) { IntArray(inPins[it].size) { -1 } }+        for (w in circuit.wires) {+            val src = index[w.from.node] ?: continue+            val dst = index[w.to.node] ?: continue+            if (w.from.index !in outPins[src].indices || w.to.index !in inPins[dst].indices) continue+            inSrc[dst][w.to.index] = outBase[src] + w.from.index+        }+        scratch = Array(nodes.size) { IntArray(inPins[it].size) }+        nodes.forEachIndexed { i, n ->+            if (n is LevelOutput && n.index in outputNodes.indices) outputNodes[n.index] = i+        }+        stateOnly = nodes.indices.filter { specs[it]?.isStateOnly == true }.toIntArray()+        val order = Scheduler.groups(nodes.size, edges(index, circuit), stateOnly.toSet())+        groups = order.map { it.first }+        cyclic = BooleanArray(order.size) { order[it].second }+        reset()+    }++    private fun edges(index: Map<NodeId, Int>, circuit: Circuit): List<Pair<Int, Int>> =+        circuit.wires.mapNotNull { w ->+            val a = index[w.from.node] ?: return@mapNotNull null+            val b = index[w.to.node] ?: return@mapNotNull null+            a to b+        }++    fun reset() {+        values.fill(0)+        for (i in nodes.indices) {+            states[i] = (specs[i]?.behavior as? Behavior.Seq)?.init?.copyOf()+        }+    }++    fun setInputs(inputs: IntArray) {+        for (i in levelInputs.indices) levelInputs[i] = inputs.getOrElse(i) { 0 }+    }++    /** Settles combinational logic; returns the nodes of any loop that never stabilised. */+    fun settle(): Set<NodeId> {+        for (i in stateOnly) evaluate(i)+        val oscillating = LinkedHashSet<NodeId>()+        for (g in groups.indices) {+            val group = groups[g]+            if (!cyclic[g]) {+                evaluate(group[0])+                continue+            }+            var pass = 0+            var changed = true+            while (changed && pass < MAX_PASSES) {+                changed = false+                for (i in group) if (evaluate(i)) changed = true+                pass+++            }+            if (changed) {+                for (i in group) if (evaluate(i)) oscillating += nodes[i].id+            }+        }+        return oscillating+    }++    /** Level output values from the last [settle]. */+    fun outputs(): IntArray = IntArray(outputNodes.size) { o ->+        val node = outputNodes[o]+        if (node < 0) 0 else read(node, 0)+    }++    /** Latches every sequential chip from the settled values. */+    fun clock() {+        for (i in nodes.indices) {+            val seq = specs[i]?.behavior as? Behavior.Seq ?: continue+            states[i] = seq.next(states[i] ?: seq.init, gather(i))+        }+    }++    /** One full tick: drive [inputs], settle, read outputs, then clock. */+    fun step(inputs: IntArray): Step {+        setInputs(inputs)+        val osc = settle()+        val out = outputs()+        clock()+        return Step(out, osc)+    }++    /** Overwrites the state of every [chipId] chip, e.g. to load a program into RAM. */+    fun preload(chipId: String, data: IntArray) {+        for (i in nodes.indices) {+            if (specs[i]?.id == chipId) states[i] = data.copyOf()+        }+    }++    fun stateOf(id: NodeId): IntArray? = nodes.indexOfFirst { it.id == id }.takeIf { it >= 0 }?.let { states[it] }++    /** Current value on every output pin, which is also the value of every wire leaving it. */+    fun pinValues(): Map<PinRef, Int> {+        val map = HashMap<PinRef, Int>(values.size)+        for (i in nodes.indices) {+            for (k in outPins[i].indices) map[PinRef(nodes[i].id, PinSide.OUT, k)] = values[outBase[i] + k]+        }+        return map+    }++    private fun read(node: Int, pin: Int): Int {+        val src = inSrc[node][pin]+        return if (src < 0) 0 else values[src] and inPins[node][pin].mask+    }++    private fun gather(i: Int): IntArray {+        val buf = scratch[i]+        for (k in buf.indices) buf[k] = read(i, k)+        return buf+    }++    private fun evaluate(i: Int): Boolean {+        val node = nodes[i]+        val out: IntArray = when (node) {+            is LevelInput -> intArrayOf(levelInputs.getOrElse(node.index) { 0 })+            is LevelOutput -> return false+            is Gate -> when (val b = specs[i]?.behavior ?: return false) {+                is Behavior.Comb -> b.eval(gather(i))+                is Behavior.Seq -> b.outputs(states[i] ?: b.init, gather(i))+            }+        }+        var changed = false+        val base = outBase[i]+        val pins = outPins[i]+        for (k in pins.indices) {+            val v = out.getOrElse(k) { 0 } and pins[k].mask+            if (values[base + k] != v) {+                values[base + k] = v+                changed = true+            }+        }+        return changed+    }++    /** Outputs of one tick, read after settling and before the clock edge. */+    class Step(val outputs: IntArray, val oscillating: Set<NodeId>)++    /** Simulator limits. */+    companion object {+        const val MAX_PASSES = 64+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.ktnew file mode 100644index 0000000000..544b529d35--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.kt@@ -0,0 +1,26 @@+package com.vayunmathur.games.logicgate.domain.sim++/**+ * One row of a test: the level inputs to drive, the outputs expected (null = don't care), and a+ * plain-language [title] such as `1 OR 1 = 1`.+ */+data class Case(val inputs: List<Int>, val expected: List<Int?>, val title: String)++/** A program run on the finished CPU: 16 bytes of RAM, a tick budget, and the answer in `acc`. */+data class ProgramTest(val name: String, val ram: List<Int>, val maxTicks: Int, val expectAcc: Int)++/** How a level is checked. */+sealed interface TestSpec {+    /** Each case is settled from reset on its own. */+    data class Comb(val cases: List<Case>) : TestSpec++    /** Ticks run in order on one simulator, from reset. */+    data class Seq(val ticks: List<Case>) : TestSpec++    /**+     * Each program runs from reset until `halt`. With [harness] the circuit is a CPU whose+     * `instr`/`data` inputs are fed from a RAM model driven by its `pc`/`addr`/`dout`/`we`+     * outputs; without it the circuit must contain its own RAM16, which gets the program.+     */+    data class Programs(val programs: List<ProgramTest>, val harness: Boolean) : TestSpec+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.ktnew file mode 100644index 0000000000..fec085c966--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt@@ -0,0 +1,177 @@+package com.vayunmathur.games.logicgate.domain.sim++import com.vayunmathur.games.logicgate.domain.model.ChipSpec+import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.Gate+import com.vayunmathur.games.logicgate.domain.model.LevelIo+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.PinRef++/** The outcome of one test row. [actual] is null when the row never ran. */+data class CaseResult(+    val title: String,+    val inputs: List<Int>,+    val expected: List<Int?>,+    val actual: List<Int>?,+    val ok: Boolean,+)++/** Why a level could not even be run. */+enum class VerifyProblem { NO_RAM }++/** Every row's outcome plus anything that stopped the circuit from settling. */+data class VerifyResult(+    val cases: List<CaseResult>,+    val oscillating: Set<NodeId> = emptySet(),+    val problem: VerifyProblem? = null,+) {+    val total: Int get() = cases.size+    val passed: Int get() = cases.count { it.ok }+    val solved: Boolean get() = total > 0 && passed == total+    val firstFailureIndex: Int? get() = cases.indexOfFirst { !it.ok }.takeIf { it >= 0 }+    val firstFailure: CaseResult? get() = firstFailureIndex?.let { cases[it] }+}++/** Live wire values for one moment of a run, for the canvas. */+data class Probe(val values: Map<PinRef, Int>, val oscillating: Set<NodeId>)++/** Runs a level's tests against a player's circuit. */+object Verifier {++    fun verify(+        io: LevelIo,+        tests: TestSpec,+        circuit: Circuit,+        catalog: (String) -> ChipSpec? = Chips::get,+    ): VerifyResult {+        val sim = Simulator(circuit, io, catalog)+        return when (tests) {+            is TestSpec.Comb -> verifyComb(sim, tests)+            is TestSpec.Seq -> verifySeq(sim, tests)+            is TestSpec.Programs -> verifyPrograms(sim, io, tests, circuit)+        }+    }++    /** Wire values with the level inputs held at [inputs], from reset. */+    fun manual(io: LevelIo, circuit: Circuit, inputs: List<Int>): Probe {+        val sim = Simulator(circuit, io)+        sim.setInputs(inputs.toIntArray())+        val osc = sim.settle()+        return Probe(sim.pinValues(), osc)+    }++    /** Wire values at test row [caseIndex], replaying earlier ticks for sequential levels. */+    fun probe(io: LevelIo, tests: TestSpec, circuit: Circuit, caseIndex: Int): Probe {+        val sim = Simulator(circuit, io)+        val osc: Set<NodeId> = when (tests) {+            is TestSpec.Comb -> {+                sim.setInputs(tests.cases[caseIndex].inputs.toIntArray())+                sim.settle()+            }+            is TestSpec.Seq -> {+                for (t in 0 until caseIndex) sim.step(tests.ticks[t].inputs.toIntArray())+                sim.setInputs(tests.ticks[caseIndex].inputs.toIntArray())+                sim.settle()+            }+            is TestSpec.Programs -> run(sim, io, tests.programs[caseIndex], tests.harness).oscillating+        }+        return Probe(sim.pinValues(), osc)+    }++    private fun matches(expected: List<Int?>, actual: IntArray): Boolean =+        expected.indices.all { k -> expected[k] == null || expected[k] == actual.getOrNull(k) }++    private fun verifyComb(sim: Simulator, tests: TestSpec.Comb): VerifyResult {+        val osc = LinkedHashSet<NodeId>()+        val results = tests.cases.map { c ->+            sim.reset()+            sim.setInputs(c.inputs.toIntArray())+            val o = sim.settle()+            osc += o+            val out = sim.outputs()+            CaseResult(c.title, c.inputs, c.expected, out.toList(), o.isEmpty() && matches(c.expected, out))+        }+        return VerifyResult(results, osc)+    }++    private fun verifySeq(sim: Simulator, tests: TestSpec.Seq): VerifyResult {+        val osc = LinkedHashSet<NodeId>()+        val results = tests.ticks.map { c ->+            val step = sim.step(c.inputs.toIntArray())+            osc += step.oscillating+            val ok = step.oscillating.isEmpty() && matches(c.expected, step.outputs)+            CaseResult(c.title, c.inputs, c.expected, step.outputs.toList(), ok)+        }+        return VerifyResult(results, osc)+    }++    private fun verifyPrograms(sim: Simulator, io: LevelIo, tests: TestSpec.Programs, circuit: Circuit): VerifyResult {+        val accIdx = io.outputs.indexOfFirst { it.name == "acc" }+        val haltIdx = io.outputs.indexOfFirst { it.name == "halt" }+        val noRam = !tests.harness && circuit.nodes.none { it is Gate && it.chipId == Chips.RAM16 }+        val osc = LinkedHashSet<NodeId>()+        val results = tests.programs.map { p ->+            val expected = io.outputs.indices.map { k ->+                when (k) {+                    accIdx -> p.expectAcc+                    haltIdx -> 1+                    else -> null+                }+            }+            if (noRam) return@map CaseResult(p.name, emptyList(), expected, null, false)+            val run = run(sim, io, p, tests.harness)+            osc += run.oscillating+            val ok = run.oscillating.isEmpty() && matches(expected, run.outputs)+            CaseResult(p.name, emptyList(), expected, run.outputs.toList(), ok)+        }+        return VerifyResult(results, osc, if (noRam) VerifyProblem.NO_RAM else null)+    }++    /** Runs [program] until halt or the tick budget, leaving [sim] settled on the last tick. */+    private fun run(sim: Simulator, io: LevelIo, program: ProgramTest, harness: Boolean): Simulator.Step {+        sim.reset()+        val haltIdx = io.outputs.indexOfFirst { it.name == "halt" }+        val ram = IntArray(RAM_SIZE) { program.ram.getOrElse(it) { 0 } }+        if (!harness) sim.preload(Chips.RAM16, ram)+        val bus = if (harness) Harness(io, ram) else null+        var last = Simulator.Step(IntArray(io.outputs.size), emptySet())+        for (t in 0 until program.maxTicks) {+            val osc = bus?.settle(sim) ?: sim.settle()+            last = Simulator.Step(sim.outputs(), osc)+            if (osc.isNotEmpty() || last.outputs.getOrNull(haltIdx) == 1) break+            bus?.write(last.outputs)+            sim.clock()+        }+        return last+    }++    /** The RAM model wired to a bare CPU's pins for the CPU level. */+    private class Harness(io: LevelIo, val ram: IntArray) {+        private val pc = io.outputs.indexOfFirst { it.name == "pc" }+        private val addr = io.outputs.indexOfFirst { it.name == "addr" }+        private val dout = io.outputs.indexOfFirst { it.name == "dout" }+        private val we = io.outputs.indexOfFirst { it.name == "we" }++        fun settle(sim: Simulator): Set<NodeId> {+            var inputs = intArrayOf(-1, -1)+            var osc: Set<NodeId> = emptySet()+            repeat(HARNESS_PASSES) {+                val out = sim.outputs()+                val next = intArrayOf(ram[out[pc] and 0xF], ram[out[addr] and 0xF])+                if (next.contentEquals(inputs)) return osc+                inputs = next+                sim.setInputs(inputs)+                osc = sim.settle()+            }+            return osc+        }++        fun write(outputs: IntArray) {+            if (outputs[we] == 1) ram[outputs[addr] and 0xF] = outputs[dout]+        }+    }++    private const val RAM_SIZE = 16+    private const val HARNESS_PASSES = 8+}
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/LevelSolutionsTest.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/LevelSolutionsTest.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/LevelSolutionsTest.ktnew file mode 100644index 0000000000..928056f3ee--- /dev/null+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/LevelSolutionsTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.games.logicgate.domain++import com.vayunmathur.games.logicgate.domain.levels.LevelRegistry+import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Gate+import com.vayunmathur.games.logicgate.domain.sim.Scoring+import com.vayunmathur.games.logicgate.domain.sim.Verifier+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class LevelSolutionsTest {++    @Test+    fun thereAreTwentyEightLevelsWithUniqueIds() {+        assertEquals(28, LevelRegistry.levels.size)+        assertEquals(28, LevelRegistry.levels.map { it.id }.toSet().size)+    }++    @Test+    fun everyLevelHasAReferenceSolution() {+        assertEquals(LevelRegistry.levels.map { it.id }.toSet(), ReferenceCircuits.levelIds)+    }++    @Test+    fun everyReferenceSolutionPassesItsOwnVerifier() {+        for (level in LevelRegistry.levels) {+            val result = Verifier.verify(level.io, level.tests, ReferenceCircuits.build(level.id))+            assertTrue(result.total > 0, "${level.id} has no tests")+            assertTrue(+                result.solved,+                "${level.id}: ${result.passed}/${result.total}, first failure ${result.firstFailure}, " ++                    "oscillating ${result.oscillating}",+            )+        }+    }++    @Test+    fun everyParIsTheCostOfTheReferenceSolution() {+        for (level in LevelRegistry.levels) {+            val cost = Scoring.cost(ReferenceCircuits.build(level.id)) { Chips[it]?.nandCost }+            assertEquals(level.par, cost, "par of ${level.id}")+        }+    }++    @Test+    fun referenceSolutionsOnlyUseChipsTheLevelOffers() {+        for (level in LevelRegistry.levels) {+            val allowed = LevelRegistry.allowedChips(level.id).toSet()+            val used = ReferenceCircuits.build(level.id).nodes.filterIsInstance<Gate>().map { it.chipId }.toSet()+            assertTrue(allowed.containsAll(used), "${level.id} uses ${used - allowed}")+        }+    }++    @Test+    fun everyOfferedChipWasEarnedOrGiftedEarlier() {+        val earned = mutableSetOf<String>()+        val gifted = mutableSetOf<String>()+        for (level in LevelRegistry.levels) {+            gifted += level.gifts+            for (chip in LevelRegistry.allowedChips(level.id)) {+                assertNotNull(Chips[chip], "unknown chip $chip")+                assertTrue(chip in Chips.base || chip in earned || chip in gifted, "$chip offered early in ${level.id}")+            }+            earned += level.unlocks+        }+    }++    @Test+    fun onlyTheFirstLevelStartsOpenAndEachSolveOpensTheNext() {+        val ids = LevelRegistry.levels.map { it.id }+        assertEquals(listOf("not"), ids.filter { LevelRegistry.isUnlocked(it, emptySet()) })+        assertTrue(LevelRegistry.isUnlocked("mux", setOf("xnor")))+        assertTrue(LevelRegistry.isUnlocked("half_adder", setOf("bus_mux")))+    }+}
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/ReferenceCircuits.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/ReferenceCircuits.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/ReferenceCircuits.ktnew file mode 100644index 0000000000..abd30f67ec--- /dev/null+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/ReferenceCircuits.kt@@ -0,0 +1,263 @@+package com.vayunmathur.games.logicgate.domain++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.LevelInput+import com.vayunmathur.games.logicgate.domain.model.LevelOutput+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++/** Builds circuits for tests: `g(chip, inputs...)` places a chip and wires its inputs in order. */+class Board(val level: LevelDef) {+    var circuit: Circuit = Circuit.forLevel(level.io)+        private set+    private val lookup = Chips.lookup(level.io)++    /** A placed chip. */+    inner class G(val id: NodeId) {+        fun out(i: Int = 0) = PinRef(id, PinSide.OUT, i)+        fun inp(i: Int) = PinRef(id, PinSide.IN, i)+    }++    fun input(i: Int): PinRef =+        PinRef(circuit.nodes.first { it is LevelInput && it.index == i }.id, PinSide.OUT, 0)++    fun output(i: Int): PinRef =+        PinRef(circuit.nodes.first { it is LevelOutput && it.index == i }.id, PinSide.IN, 0)++    fun wire(from: PinRef, to: PinRef) {+        circuit = requireNotNull(circuit.connect(from, to, lookup)) { "cannot wire $from -> $to in ${level.id}" }+    }++    fun g(chip: String, vararg ins: PinRef?): G {+        val (c, id) = circuit.addGate(chip, Point(120f + circuit.nodes.size * 8f, 0f))+        circuit = c+        val gate = G(id)+        ins.forEachIndexed { i, p -> if (p != null) wire(p, gate.inp(i)) }+        return gate+    }++    infix fun PinRef.into(to: PinRef) = wire(this, to)+}++/** A known-good solution for every level; each one's cost is that level's par. */+object ReferenceCircuits {++    fun build(levelId: String): Circuit {+        val level = requireNotNull(LevelRegistry[levelId])+        val board = Board(level)+        val recipe = requireNotNull(recipes[levelId]) { "no reference for $levelId" }+        board.recipe()+        return board.circuit+    }++    val levelIds: Set<String> get() = recipes.keys++    private val recipes: Map<String, Board.() -> Unit> = mapOf(+        "not" to { g(Chips.NAND, input(0), input(0)).out() into output(0) },+        "and" to { g(Chips.NOT, g(Chips.NAND, input(0), input(1)).out()).out() into output(0) },+        "or" to { g(Chips.NAND, g(Chips.NOT, input(0)).out(), g(Chips.NOT, input(1)).out()).out() into output(0) },+        "nor" to { g(Chips.NOT, g(Chips.OR, input(0), input(1)).out()).out() into output(0) },+        "xor" to { xorFromNands(input(0), input(1)) into output(0) },+        "xnor" to { g(Chips.NOT, g(Chips.XOR, input(0), input(1)).out()).out() into output(0) },+        "mux" to {+            val ns = g(Chips.NOT, input(2))+            g(Chips.NAND, g(Chips.NAND, input(0), ns.out()).out(), g(Chips.NAND, input(1), input(2)).out()).out() into+                output(0)+        },+        "dmux" to {+            val ns = g(Chips.NOT, input(1))+            g(Chips.AND, input(0), ns.out()).out() into output(0)+            g(Chips.AND, input(0), input(1)).out() into output(1)+        },+        "dec2" to {+            val n1 = g(Chips.NOT, input(0)).out()+            val n0 = g(Chips.NOT, input(1)).out()+            g(Chips.AND, n1, n0).out() into output(0)+            g(Chips.AND, n1, input(1)).out() into output(1)+            g(Chips.AND, input(0), n0).out() into output(2)+            g(Chips.AND, input(0), input(1)).out() into output(3)+        },+        "nibble_swap" to {+            val s = g(Chips.NIB_SPLIT, input(0))+            g(Chips.NIB_JOIN, s.out(1), s.out(0)).out() into output(0)+        },+        "bus_mux" to {+            val sa = g(Chips.SPLIT8, input(0))+            val sb = g(Chips.SPLIT8, input(1))+            val j = g(Chips.JOIN8)+            for (i in 0 until 8) g(Chips.MUX, sa.out(i), sb.out(i), input(2)).out() into j.inp(i)+            j.out() into output(0)+        },+        "half_adder" to {+            val n1 = g(Chips.NAND, input(0), input(1))+            val n2 = g(Chips.NAND, input(0), n1.out())+            val n3 = g(Chips.NAND, input(1), n1.out())+            g(Chips.NAND, n2.out(), n3.out()).out() into output(0)+            g(Chips.NOT, n1.out()).out() into output(1)+        },+        "full_adder" to {+            val n1 = g(Chips.NAND, input(0), input(1))+            val x = g(Chips.NAND, g(Chips.NAND, input(0), n1.out()).out(), g(Chips.NAND, input(1), n1.out()).out())+            val n5 = g(Chips.NAND, x.out(), input(2))+            g(Chips.NAND, g(Chips.NAND, x.out(), n5.out()).out(), g(Chips.NAND, input(2), n5.out()).out()).out() into+                output(0)+            g(Chips.NAND, n1.out(), n5.out()).out() into output(1)+        },+        "add4" to {+            val sa = g(Chips.SPLIT4, input(0))+            val sb = g(Chips.SPLIT4, input(1))+            val j = g(Chips.JOIN4)+            var carry = input(2)+            for (i in 0 until 4) {+                val f = g(Chips.FULL, sa.out(i), sb.out(i), carry)+                f.out(0) into j.inp(i)+                carry = f.out(1)+            }+            j.out() into output(0)+            carry into output(1)+        },+        "add8" to {+            val na = g(Chips.NIB_SPLIT, input(0))+            val nb = g(Chips.NIB_SPLIT, input(1))+            val lo = g(Chips.ADD4, na.out(0), nb.out(0), input(2))+            val hi = g(Chips.ADD4, na.out(1), nb.out(1), lo.out(1))+            g(Chips.NIB_JOIN, lo.out(0), hi.out(0)).out() into output(0)+            hi.out(1) into output(1)+        },+        "inc4" to {+            val s = g(Chips.SPLIT4, input(0))+            val j = g(Chips.JOIN4)+            g(Chips.NOT, s.out(0)).out() into j.inp(0)+            var carry = s.out(0)+            for (i in 1 until 4) {+                val h = g(Chips.HALF, s.out(i), carry)+                h.out(0) into j.inp(i)+                carry = h.out(1)+            }+            j.out() into output(0)+        },+        "sub8" to {+            g(Chips.ADD8, input(0), g(Chips.NOT8, input(1)).out(), g(Chips.HIGH).out()).out(0) into output(0)+        },+        "zero8" to {+            val s = g(Chips.SPLIT8, input(0))+            val pairs = (0 until 4).map { g(Chips.OR, s.out(2 * it), s.out(2 * it + 1)).out() }+            val any = g(+                Chips.OR,+                g(Chips.OR, pairs[0], pairs[1]).out(),+                g(Chips.OR, pairs[2], pairs[3]).out(),+            )+            g(Chips.NOT, any.out()).out() into output(0)+        },+        "alu8" to { alu() },+        "sr_latch" to {+            val q = g(Chips.NAND, g(Chips.NOT, input(0)).out())+            val nq = g(Chips.NAND, g(Chips.NOT, input(1)).out(), q.out())+            nq.out() into q.inp(1)+            q.out() into output(0)+            nq.out() into output(1)+        },+        "d_latch" to {+            val sp = g(Chips.NAND, input(0), input(1))+            val rp = g(Chips.NAND, sp.out(), input(1))+            val q = g(Chips.NAND, sp.out())+            val qb = g(Chips.NAND, rp.out(), q.out())+            qb.out() into q.inp(1)+            q.out() into output(0)+        },+        "bit" to { register(Chips.MUX, Chips.DFF) },+        "reg8" to { register(Chips.MUX8B, Chips.DFF8) },+        "pc4" to {+            val r = g(Chips.DFF4)+            val inc = g(Chips.INC4, r.out())+            val counted = g(Chips.MUX4B, r.out(), inc.out(), input(0))+            g(Chips.MUX4B, counted.out(), input(2), input(1)).out() into r.inp(0)+            r.out() into output(0)+        },+        "ram4" to {+            val dec = g(Chips.DEC2, input(0), input(1))+            val regs = (0 until 4).map { i -> g(Chips.REG8, input(2), g(Chips.AND, input(3), dec.out(i)).out()) }+            val m01 = g(Chips.MUX8B, regs[0].out(), regs[1].out(), input(1))+            val m23 = g(Chips.MUX8B, regs[2].out(), regs[3].out(), input(1))+            g(Chips.MUX8B, m01.out(), m23.out(), input(0)).out() into output(0)+        },+        "decoder" to { decoder() },+        "cpu" to { cpu() },+        "computer" to {+            val cpu = g(Chips.CPU)+            val ram = g(Chips.RAM16, cpu.out(0), cpu.out(1), cpu.out(2), cpu.out(3))+            ram.out(0) into cpu.inp(0)+            ram.out(1) into cpu.inp(1)+            cpu.out(4) into output(0)+            cpu.out(5) into output(1)+        },+    )++    private fun Board.xorFromNands(a: PinRef, b: PinRef): PinRef {+        val n1 = g(Chips.NAND, a, b)+        return g(Chips.NAND, g(Chips.NAND, a, n1.out()).out(), g(Chips.NAND, b, n1.out()).out()).out()+    }++    /** `q = DFF(MUX(q, d, load))`. */+    private fun Board.register(mux: String, dff: String) {+        val m = g(mux)+        val r = g(dff, m.out())+        r.out() into m.inp(0)+        input(0) into m.inp(1)+        input(1) into m.inp(2)+        r.out() into output(0)+    }++    private fun Board.alu() {+        val op1 = input(2)+        val op0 = input(3)+        val inv = g(Chips.JOIN8, op0, op0, op0, op0, op0, op0, op0, op0)+        val bx = g(Chips.XOR8, input(1), inv.out())+        val sum = g(Chips.ADD8, input(0), bx.out(), op0)+        val and = g(Chips.AND8, input(0), input(1))+        val logic = g(Chips.MUX8B, and.out(), input(1), op0)+        val o = g(Chips.MUX8B, sum.out(0), logic.out(), op1)+        o.out() into output(0)+        g(Chips.ZERO8, o.out()).out() into output(1)+    }++    private fun Board.decoder() {+        val s = g(Chips.SPLIT4, input(0))+        val (o0, o1, o2) = Triple(s.out(0), s.out(1), s.out(2))+        val dec = g(Chips.DEC2, o1, o0)+        val n2 = g(Chips.NOT, o2).out()+        val line = (0 until 8).map { k -> g(Chips.AND, dec.out(k and 3), if (k < 4) n2 else o2).out() }+        g(Chips.NOT, o1).out() into output(0)+        g(Chips.NAND, o1, g(Chips.NOT, o0).out()).out() into output(1)+        g(Chips.OR, g(Chips.OR, line[0], line[2]).out(), g(Chips.OR, line[3], line[4]).out()).out() into output(2)+        line[1] into output(3)+        line[4] into output(4)+        g(Chips.OR, line[5], g(Chips.AND, line[6], input(1)).out()).out() into output(5)+        line[7] into output(6)+    }++    private fun Board.cpu() {+        val instr = g(Chips.NIB_SPLIT, input(0))+        val operand = instr.out(0)+        val dec = g(Chips.DECODER, instr.out(1))+        val imm = g(Chips.NIB_JOIN, operand)+        val b = g(Chips.MUX8B, input(1), imm.out(), dec.out(4))+        val acc = g(Chips.REG8)+        val alu = g(Chips.ALU8, acc.out(), b.out(), dec.out(0), dec.out(1))+        alu.out(0) into acc.inp(0)+        dec.out(2) into acc.inp(1)+        g(Chips.ZERO8, acc.out()).out() into dec.inp(1)+        val pc = g(Chips.PC4, g(Chips.NOT, dec.out(6)).out(), dec.out(5), operand)+        pc.out() into output(0)+        operand into output(1)+        acc.out() into output(2)+        dec.out(3) into output(3)+        acc.out() into output(4)+        dec.out(6) into output(5)+    }+}
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/SimulatorTest.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/SimulatorTest.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/SimulatorTest.ktnew file mode 100644index 0000000000..60a6944b8e--- /dev/null+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/SimulatorTest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.games.logicgate.domain++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.LevelIo+import com.vayunmathur.games.logicgate.domain.model.Pin+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.sim.Simulator+import com.vayunmathur.games.logicgate.domain.sim.Verifier+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class SimulatorTest {++    private fun out(c: Circuit, gate: Int, i: Int = 0) = PinRef(c.nodes[gate].id, PinSide.OUT, i)+    private fun inp(c: Circuit, gate: Int, i: Int) = PinRef(c.nodes[gate].id, PinSide.IN, i)++    @Test+    fun srLatchHoldsAcrossTicks() {+        val level = requireNotNull(LevelRegistry["sr_latch"])+        val sim = Simulator(ReferenceCircuits.build("sr_latch"), level.io)+        assertContentEquals(intArrayOf(1, 0), sim.step(intArrayOf(1, 0)).outputs)+        repeat(5) { assertContentEquals(intArrayOf(1, 0), sim.step(intArrayOf(0, 0)).outputs) }+        assertContentEquals(intArrayOf(0, 1), sim.step(intArrayOf(0, 1)).outputs)+        repeat(5) { assertContentEquals(intArrayOf(0, 1), sim.step(intArrayOf(0, 0)).outputs) }+    }++    @Test+    fun aNandFeedingItselfOscillates() {+        val io = LevelIo(emptyList(), listOf(Pin("o")))+        var c = Circuit.forLevel(io)+        val (withGate, id) = c.addGate(Chips.NAND, Point(0f, 0f))+        val lookup = Chips.lookup(io)+        val self = PinRef(id, PinSide.OUT, 0)+        c = withGate.connect(self, PinRef(id, PinSide.IN, 0), lookup)!!+        c = c.connect(self, PinRef(id, PinSide.IN, 1), lookup)!!+        assertEquals(setOf(id), Simulator(c, io).settle())+    }++    @Test+    fun aThreeInverterRingOscillatesButATwoInverterRingSettles() {+        val io = LevelIo(emptyList(), emptyList())+        val lookup = Chips.lookup(io)+        fun ring(n: Int): Circuit {+            var c = Circuit.forLevel(io)+            repeat(n) { c = c.addGate(Chips.NOT, Point(0f, 0f)).first }+            for (i in 0 until n) c = c.connect(out(c, i), inp(c, (i + 1) % n, 0), lookup)!!+            return c+        }+        assertEquals(3, Simulator(ring(3), io).settle().size)+        assertTrue(Simulator(ring(2), io).settle().isEmpty())+    }++    @Test+    fun unconnectedInputsReadZero() {+        val io = LevelIo(emptyList(), listOf(Pin("o")))+        val (c0, _) = Circuit.forLevel(io).addGate(Chips.NAND, Point(0f, 0f))+        val c = c0.connect(out(c0, 1), inp(c0, 0, 0), Chips.lookup(io))!!+        val sim = Simulator(c, io)+        sim.settle()+        assertContentEquals(intArrayOf(1), sim.outputs())+    }++    @Test+    fun registerProgramCounterAndRamTracesMatchTheirSpecs() {+        for (id in listOf("bit", "reg8", "pc4", "ram4")) {+            val level = requireNotNull(LevelRegistry[id])+            val result = Verifier.verify(level.io, level.tests, ReferenceCircuits.build(id))+            assertTrue(result.solved, "$id failed at ${result.firstFailure}")+        }+        val pc = requireNotNull(LevelRegistry["pc4"])+        val sim = Simulator(ReferenceCircuits.build("pc4"), pc.io)+        val counted = (0 until 18).map { sim.step(intArrayOf(1, 0, 0)).outputs[0] }+        assertEquals((0 until 18).map { it % 16 }, counted)+    }++    @Test+    fun theComputerRunsAllThreeProgramsToTheRightAnswer() {+        val level = requireNotNull(LevelRegistry["computer"])+        val result = Verifier.verify(level.io, level.tests, ReferenceCircuits.build("computer"))+        assertEquals(listOf(listOf(5, 1), listOf(0, 1), listOf(12, 1)), result.cases.map { it.actual })+    }++    @Test+    fun aPlayerBuiltCpuRunsTheSameProgramsInTheComputer() {+        val cpuLevel = requireNotNull(LevelRegistry["cpu"])+        val result = Verifier.verify(cpuLevel.io, cpuLevel.tests, ReferenceCircuits.build("cpu"))+        assertEquals(listOf(5, 0, 12), result.cases.map { it.actual?.get(4) })+        assertTrue(result.cases.all { it.actual?.get(5) == 1 })+    }+}
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/VerifierTest.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/VerifierTest.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/VerifierTest.ktnew file mode 100644index 0000000000..2e9528c144--- /dev/null+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/VerifierTest.kt@@ -0,0 +1,167 @@+package com.vayunmathur.games.logicgate.domain++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.ConnectCheck+import com.vayunmathur.games.logicgate.domain.model.Gate+import com.vayunmathur.games.logicgate.domain.model.LevelInput+import com.vayunmathur.games.logicgate.domain.model.Point+import com.vayunmathur.games.logicgate.domain.model.Wire+import com.vayunmathur.games.logicgate.domain.sim.Scoring+import com.vayunmathur.games.logicgate.domain.sim.TestSpec+import com.vayunmathur.games.logicgate.domain.sim.Verifier+import com.vayunmathur.games.logicgate.domain.sim.VerifyProblem+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue++class VerifierTest {++    private fun level(id: String) = requireNotNull(LevelRegistry[id])++    @Test+    fun anOrSubmittedForXorFailsOnTheBothHighRow() {+        val xor = level("xor")+        val board = Board(xor)+        with(board) { g(Chips.OR, input(0), input(1)).out() into output(0) }+        val result = Verifier.verify(xor.io, xor.tests, board.circuit)+        assertEquals(3, result.passed)+        assertEquals(3, result.firstFailureIndex)+        val failure = requireNotNull(result.firstFailure)+        assertEquals(listOf(1, 1), failure.inputs)+        assertEquals(listOf<Int?>(0), failure.expected)+        assertEquals(listOf(1), failure.actual)+        assertEquals("1 XOR 1 = 0", failure.title)+    }++    @Test+    fun everyRowOfEveryLevelHasATitle() {+        for (l in LevelRegistry.levels) {+            val result = Verifier.verify(l.io, l.tests, Circuit.forLevel(l.io))+            assertTrue(result.cases.all { it.title.isNotBlank() }, "${l.id} has an untitled row")+        }+    }++    @Test+    fun rowTitlesReadAsTheBehaviourBeingChecked() {+        fun titles(id: String) = Verifier.verify(level(id).io, level(id).tests, Circuit.forLevel(level(id).io)).cases.map { it.title }+        assertTrue("1 OR 1 = 1" in titles("or"))+        assertTrue("NOT 0 = 1" in titles("not"))+        assertTrue("1 + 1 + 1 = 1, carry 1" in titles("full_adder"))+        assertEquals("set → q=1", titles("sr_latch").first())+        assertTrue("JZ with z=1 → jump" in titles("decoder"))+        assertEquals("2 + 3 = 5", titles("computer").first())+    }++    @Test+    fun anEmptyBoardFailsWithoutCrashing() {+        for (l in LevelRegistry.levels) {+            val result = Verifier.verify(l.io, l.tests, Circuit.forLevel(l.io))+            assertFalse(result.solved, "${l.id} solved by an empty board")+        }+    }++    @Test+    fun smallInputsAreTestedExhaustivelyAndWideOnesAreSampled() {+        assertEquals(512, (level("add4").tests as TestSpec.Comb).cases.size)+        assertEquals(256, (level("zero8").tests as TestSpec.Comb).cases.size)+        val add8 = (level("add8").tests as TestSpec.Comb).cases.size+        assertTrue(add8 in 200..400, "add8 has $add8 cases")+    }++    @Test+    fun aDelayedLatchFailsTheTransparentLatchLevel() {+        val dLatch = level("d_latch")+        val board = Board(dLatch)+        with(board) { g(Chips.DFF, input(0)).out() into output(0) }+        assertFalse(Verifier.verify(dLatch.io, dLatch.tests, board.circuit).solved)+    }++    @Test+    fun theNativeCpuChipPassesTheCpuLevelHarness() {+        val cpu = level("cpu")+        val board = Board(cpu)+        with(board) {+            val chip = g(Chips.CPU, input(0), input(1))+            for (i in 0 until 6) chip.out(i) into output(i)+        }+        assertTrue(Verifier.verify(cpu.io, cpu.tests, board.circuit).solved)+    }++    @Test+    fun theComputerLevelReportsAMissingRam() {+        val computer = level("computer")+        val board = Board(computer)+        with(board) { g(Chips.CPU) }+        val result = Verifier.verify(computer.io, computer.tests, board.circuit)+        assertEquals(VerifyProblem.NO_RAM, result.problem)+        assertEquals(0, result.passed)+    }++    @Test+    fun probingASequentialRowReplaysEarlierTicks() {+        val bit = level("bit")+        val circuit = ReferenceCircuits.build("bit")+        val output = circuit.nodes.first { it is Gate && it.chipId == Chips.DFF }.id+        val values = Verifier.probe(bit.io, bit.tests, circuit, caseIndex = 1).values+        assertEquals(1, values.entries.first { it.key.node == output }.value)+    }++    @Test+    fun starsFollowPar() {+        assertEquals(0, Scoring.stars(solved = false, cost = 1, par = 10))+        assertEquals(3, Scoring.stars(solved = true, cost = 10, par = 10))+        assertEquals(2, Scoring.stars(solved = true, cost = 15, par = 10))+        assertEquals(1, Scoring.stars(solved = true, cost = 16, par = 10))+        assertEquals(3, Scoring.stars(solved = true, cost = 0, par = 0))+    }+}++class CircuitTest {+    private val level = requireNotNull(LevelRegistry["add4"])+    private val lookup = Chips.lookup(level.io)++    @Test+    fun wiresAreNormalisedOutputToInputAndReplaceTheOldWireOnAnInput() {+        val board = Board(level)+        val add = board.g(Chips.ADD4)+        val a = board.input(0)+        var c = requireNotNull(board.circuit.connect(add.inp(0), a, lookup))+        assertEquals(listOf(Wire(a, add.inp(0))), c.wires)+        c = requireNotNull(c.connect(board.input(1), add.inp(0), lookup))+        assertEquals(listOf(Wire(board.input(1), add.inp(0))), c.wires)+    }++    @Test+    fun mismatchedWidthsAndSameSidePinsAreRejected() {+        val board = Board(level)+        val add = board.g(Chips.ADD4)+        val c = board.circuit+        assertIs<ConnectCheck.WidthMismatch>(c.check(board.input(2), add.inp(0), lookup))+        assertIs<ConnectCheck.SameSide>(c.check(add.inp(0), add.inp(1), lookup))+        assertNull(c.connect(board.input(0), add.inp(2), lookup))+    }++    @Test+    fun removingAGateDropsItsWiresButLevelPinsStay() {+        val board = Board(level)+        val add = board.g(Chips.ADD4, board.input(0))+        val c = board.circuit.removeNode(add.id)+        assertTrue(c.wires.isEmpty())+        val input = c.nodes.first { it is LevelInput }+        assertEquals(c, c.removeNode(input.id))+    }++    @Test+    fun sanitizingDropsUnknownChipsAndRestoresMissingLevelPins() {+        val (withJunk, _) = Circuit().addGate("NOPE", Point(0f, 0f))+        val clean = withJunk.sanitized(level.io, lookup)+        assertTrue(clean.nodes.none { it is Gate })+        assertEquals(level.inputs.size + level.outputs.size, clean.nodes.size)+        assertEquals(clean.nodes.map { it.id }.toSet().size, clean.nodes.size)+    }+}