From 273aed7680209db37ba4ea48d3ac95c7ccf6c432 Mon Sep 17 00:00:00 2001 From: Jakub Duras Date: Sun, 15 Nov 2026 01:39:13 +0100 Subject: [PATCH 1/2] Show connected visual progression through all 41 course steps --- cypress/e2e/journey.cy.ts | 199 ++++++++ docs/visual-learning-journey.md | 74 +++ src/lib/course/Chapter.svelte | 2 + src/lib/course/Path.svelte | 15 +- src/lib/game/Game.svelte | 8 +- src/lib/game/Landing.svelte | 4 +- src/lib/game/MissionWorkbench.svelte | 9 + src/lib/game/NandDiscovery.svelte | 6 + src/lib/game/SignalIntro.svelte | 16 + src/lib/journey/ConnectedScene.svelte | 182 ++++++++ src/lib/journey/Journey.svelte | 511 +++++++++++++++++++++ src/lib/journey/Runtime.svelte | 276 +++++++++++ src/lib/journey/Scene.svelte | 611 ++++++++++++++++++++++++ src/lib/journey/advancedDiagrams.ts | 637 ++++++++++++++++++++++++++ src/lib/journey/basicDiagrams.ts | 215 +++++++++ src/lib/journey/data.ts | 139 ++++++ src/lib/journey/journey.test.ts | 160 +++++++ src/lib/journey/progress.ts | 49 ++ src/lib/journey/runtime.ts | 59 +++ src/lib/journey/schematicTypes.ts | 29 ++ src/lib/journey/schematics.test.ts | 63 +++ src/lib/journey/system.ts | 30 ++ src/lib/journey/treatments.ts | 311 +++++++++++++ src/routes/+page.svelte | 2 +- 24 files changed, 3603 insertions(+), 4 deletions(-) create mode 100644 cypress/e2e/journey.cy.ts create mode 100644 docs/visual-learning-journey.md create mode 100644 src/lib/journey/ConnectedScene.svelte create mode 100644 src/lib/journey/Journey.svelte create mode 100644 src/lib/journey/Runtime.svelte create mode 100644 src/lib/journey/Scene.svelte create mode 100644 src/lib/journey/advancedDiagrams.ts create mode 100644 src/lib/journey/basicDiagrams.ts create mode 100644 src/lib/journey/data.ts create mode 100644 src/lib/journey/journey.test.ts create mode 100644 src/lib/journey/progress.ts create mode 100644 src/lib/journey/runtime.ts create mode 100644 src/lib/journey/schematicTypes.ts create mode 100644 src/lib/journey/schematics.test.ts create mode 100644 src/lib/journey/system.ts create mode 100644 src/lib/journey/treatments.ts diff --git a/cypress/e2e/journey.cy.ts b/cypress/e2e/journey.cy.ts new file mode 100644 index 0000000..f499e76 --- /dev/null +++ b/cypress/e2e/journey.cy.ts @@ -0,0 +1,199 @@ +import { treatments } from '../../src/lib/journey/treatments'; +const journeySteps = Object.entries(treatments).map(([id, values]) => ({ + id, + diagram: values[0], + prior: values[2], + change: values[3], + next: values[4], +})); +import { checkAccessibility, expectNoPageOverflow } from '../support/checks'; + +const scene = () => cy.get('.learning-journey'); +const pick = (id: string) => + cy.findByRole('combobox', { name: 'Explore a visual learning step' }).select(id); + +describe('A growing computer at every learning step', () => { + it('maps every step and captures each distinct visual family without granting completion', () => { + cy.visit('/learn/path'); + cy.get('.course-page').should('have.attr', 'data-ready', 'true'); + const captured = new Set(); + for (const step of journeySteps) { + pick(step.id); + scene() + .should('have.attr', 'data-journey-step', step.id) + .and('have.attr', 'data-journey-view', 'inside'); + scene() + .should('contain.text', step.change) + .and('contain.text', step.prior) + .and('contain.text', step.next); + if ( + !captured.has(step.diagram) || + [ + 'missions/not', + 'missions/and', + 'missions/or', + 'missions/xor', + 'arithmetic/fulladder', + 'arithmetic/add16', + 'arithmetic/inc16', + 'memory/register', + 'memory/ram16k', + ].includes(step.id) + ) { + captured.add(step.diagram); + cy.get('.scene-stage').should('not.have.class', 'revealing'); + scene().screenshot( + `journey-desktop-${captured.has(step.diagram) && ['missions/not', 'missions/and', 'missions/or', 'missions/xor', 'arithmetic/fulladder', 'arithmetic/add16', 'arithmetic/inc16', 'memory/register', 'memory/ram16k'].includes(step.id) ? step.id.replace('/', '-') : step.diagram}`, + ); + } + } + cy.window().then((win) => { + expect(win.localStorage.getItem('chipsandcode.progress.v1')).to.equal(null); + expect(win.localStorage.getItem('chipsandcode.part-one.progress.v1')).to.equal(null); + }); + cy.injectAxe(); + checkAccessibility(); + expectNoPageOverflow(); + }); + + it('keeps the active draft while inspecting another layer, then reveals verified composition', () => { + cy.visit('/learn/path/buses'); + cy.get('.course-page').should('have.attr', 'data-ready', 'true'); + cy.findByRole('combobox', { name: 'Construction view' }).select('code'); + const source = `CHIP Not16 { IN in[16]; OUT out[16]; PARTS:\n${Array.from({ length: 16 }, (_, i) => `Not(in=in[${i}],out=out[${i}]);`).join('\n')}\n}`; + cy.findByRole('textbox', { name: 'HDL source' }) + .clear() + .type(source, { parseSpecialCharSequences: false, delay: 0 }); + scene().should('contain.text', 'Not × 16'); + pick('architecture/cpu'); + scene().should('have.attr', 'data-journey-status', 'Not verified here'); + cy.window().then((win) => + win.dispatchEvent( + new win.CustomEvent('chipsandcode:learning-choices-changed', { + detail: { version: 1, topics: { architecture: { skipped: true } } }, + }), + ), + ); + scene().should('have.attr', 'data-journey-status', 'Bypassed · not verified here'); + cy.window().then((win) => + win.dispatchEvent( + new win.CustomEvent('chipsandcode:learning-choices-changed', { + detail: { version: 1, topics: {} }, + }), + ), + ); + scene().should('have.attr', 'data-journey-status', 'Not verified here'); + cy.findByRole('button', { name: 'Return to Not16' }).focus().type('{enter}'); + scene().should('have.attr', 'data-journey-step', 'buses/not16'); + cy.findByRole('textbox', { name: 'HDL source' }).should('have.value', source); + cy.findByRole('button', { name: 'Check my work' }).click(); + scene() + .should('have.attr', 'data-journey-status', 'Verified') + .and('have.attr', 'data-journey-view', 'system'); + cy.get('.scene-stage').should('not.have.class', 'revealing'); + scene() + .find('[data-system-module="Logic"]') + .should('have.attr', 'data-evidence-count', '1') + .and('contain', 'Not16'); + scene().find('[data-system-module="ALU"]').should('have.attr', 'data-evidence-count', '0'); + scene().screenshot('journey-verified-zoom-out'); + cy.findByRole('button', { name: 'Inside this piece' }).click(); + scene().should('have.attr', 'data-journey-view', 'inside'); + cy.reload(); + cy.get('.course-page').should('have.attr', 'data-task', 'and16'); + pick('buses/not16'); + scene().should('have.attr', 'data-journey-status', 'Verified'); + }); + + it('makes every introductory observation visible in the journey', () => { + cy.visit('/learn'); + cy.get('.computer-game').should('have.attr', 'data-ready', 'true'); + scene().should('have.attr', 'data-journey-step', 'intro/signal'); + cy.findByRole('switch', { name: 'Signal' }).click(); + scene().should('contain.text', 'out = 1'); + cy.findByRole('switch', { name: 'Signal' }).click(); + scene().should('have.attr', 'data-journey-status', 'Explored'); + cy.findByRole('button', { name: 'Continue' }).click(); + scene().should('have.attr', 'data-journey-step', 'intro/not'); + cy.findByRole('switch', { name: 'NOT input' }).click().click(); + cy.findByRole('button', { name: 'Continue' }).click(); + scene().should('have.attr', 'data-journey-step', 'intro/and'); + cy.findByRole('switch', { name: 'AND input a' }).click(); + cy.findByRole('switch', { name: 'AND input b' }).click(); + scene().should('contain.text', 'out = 1'); + cy.findByRole('switch', { name: 'AND input a' }).click(); + cy.findByRole('switch', { name: 'AND input b' }).click(); + cy.findByRole('button', { name: 'Continue' }).click(); + scene().should('have.attr', 'data-journey-step', 'missions/nand'); + }); + + it('executes keyboard reads and screen writes, and loads a learner draft honestly', () => { + cy.visit('/learn/path/machine-language'); + cy.get('.course-page').should('have.attr', 'data-ready', 'true'); + cy.contains('summary', 'Steps in this layer').click(); + cy.findByRole('button', { name: 'Connect a key to the screen' }).click(); + cy.get('[data-runtime-pixels]').should('contain', '0 / 8,192'); + cy.findByRole('button', { name: 'Press A key' }).click(); + cy.get('[data-runtime-pixels]').should('contain', '0 / 8,192'); + cy.findByRole('button', { name: 'Run program' }).click(); + cy.get('[data-runtime-pixels]').should('contain', '8,192 / 8,192'); + cy.get('.execution-evidence').should('contain', '65 at instruction'); + cy.get('.scene-stage').should('not.have.class', 'revealing'); + scene().screenshot('journey-keyboard-program-pixels'); + cy.findByRole('button', { name: 'Release A key' }).click(); + cy.get('.execution-evidence').should('not.contain', '65 at instruction'); + cy.get('[data-runtime-pixels]').should('contain', '8,192 / 8,192'); + cy.findByRole('button', { name: 'Run program' }).click(); + cy.get('[data-runtime-pixels]').should('contain', '0 / 8,192'); + cy.findByRole('textbox', { name: 'Assembly source' }).clear().type('@1\nD=A', { delay: 0 }); + cy.findByRole('button', { name: 'Load my Fill draft' }).click(); + cy.findByRole('button', { name: 'Run program' }).click(); + scene() + .should('contain', 'Your Fill draft · loaded snapshot') + .and('contain', 'No keyboard read observed') + .and('contain', 'No screen write observed'); + cy.findByRole('textbox', { name: 'Assembly source' }).should('have.value', '@1\nD=A'); + }); + + it('keeps diagrams, explanations and controls usable at 320 pixels with reduced motion', () => { + cy.viewport(320, 760); + cy.visit('/learn/path', { + onBeforeLoad(win) { + const original = win.matchMedia.bind(win); + win.matchMedia = (query: string) => { + const result = original(query); + if (query === '(prefers-reduced-motion: reduce)') + Object.defineProperty(result, 'matches', { value: true }); + return result; + }; + }, + }); + for (const id of [ + 'buses/not16', + 'missions/not', + 'arithmetic/fulladder', + 'memory/bit', + 'arithmetic/alu', + 'memory/ram16k', + 'architecture/cpu', + 'architecture/computer', + 'assembler/assembler', + ]) { + pick(id); + cy.get('.scene-stage') + .should('have.attr', 'data-motion', 'reduced') + .and('not.have.class', 'revealing'); + cy.findByRole('button', { name: 'Replay reveal' }).should('not.exist'); + expectNoPageOverflow(); + cy.get('.scene-stage').should('not.have.class', 'revealing'); + scene().screenshot(`journey-mobile-reduced-${id.replace('/', '-')}`); + } + cy.findByRole('button', { name: /Zoom out/ }) + .focus() + .type('{enter}'); + scene().should('have.attr', 'data-journey-view', 'system'); + cy.injectAxe(); + checkAccessibility(); + expectNoPageOverflow(); + }); +}); diff --git a/docs/visual-learning-journey.md b/docs/visual-learning-journey.md new file mode 100644 index 0000000..fdb0067 --- /dev/null +++ b/docs/visual-learning-journey.md @@ -0,0 +1,74 @@ +# The visual learning journey + +## Model and interaction (chosen before implementation) + +The course uses two linked SVG views: **Inside this piece** explains each task's composition or behavior; **Place in the computer** preserves that piece's label while revealing its role. The journey sits in the main learning flow above construction. Its topic browser can inspect any earlier or later step without unmounting the active editor. Returning to the challenge restores the active scene; no inspection awards progress. + +The outside view is a recognizable computer frame with supplied keyboard and display. It receives all evidence, fills the corresponding branches as work is verified, shows reusable pieces by name inside their parent modules, and leaves unverified parts dashed. A completed piece retains its label as it shrinks into the larger context. The hardware model branches. Logic supplies word operations and arithmetic; routing plus clocked state supplies memory. The branches meet at the CPU and memory interface. Instruction ROM, mapped data memory, the supplied keyboard, and supplied screen form the connected computer. Assembly is a representation translated into ROM words, never a physically larger shell surrounding hardware. DFF, NAND, ROM32K, Screen, and Keyboard are labeled supplied where relevant. + +Every introduction concept, gate mission, and Project 1–6 task has explicit journey metadata in `src/lib/journey/data.ts`. Distinct layouts show parallel lanes, reduction/routing trees, carry propagation, state feedback, memory banks, instruction fields, and the connected machine. Explicit connected graph models cover gate composition, half/full adders, ALU preprocessing and selection, bank decoding and read multiplexing, CPU control/data paths, PC priority, loops, and assembler passes. Arrows carry data or control; no generic dangling component stubs stand in for these relationships. Desktop and mobile use separately arranged graphs with legible labels. The coverage table below is generated from that metadata and tested against the real curriculum. This avoids a milestone list silently missing small steps. + +### State and triggers + +- A new task selects its own composition, context, and next capability. Within a layer the structure changes (for example four to eight routes or one to sixteen stored bits). +- A verified task reveals the wider system with the same component identity. Verification is derived only from existing course/mission completion data; opening an advanced lesson never awards previous work. +- Introduction stages report observed behavior separately from built circuits. NAND is characterized, not fabricated. +- The scene accepts actual part names from the active draft and live pin values when available. The internal teaching diagram is explicitly a conceptual composition, not a claim to reproduce every valid learner circuit. +- Revisit controls affect only the scene. A separate explicit lesson link navigates; drafts retain the existing save behavior. Page reload uses the existing task/progress selection. A saved completion is identified as previously verified; editing still requires a fresh check. +- A short reveal runs on task or verification change. Replay and skip are available. Reduced motion presents the exact same final diagram, explanatory text, and controls without motion. No timeout, animation, or browsing controls progression. + +### Runtime payoff + +A small runtime panel reuses `HackMachine`, the assembler, and the existing `Screen` component. The supplied example reads KBD, selects a fill value, and writes screen memory by executing instructions. The learner can load their Fill source into the same panel. The display is always drawn from actual screen words. Read and write trace facts explain the causal path: keyboard → CPU/program → screen memory → pixels. The assembler view exposes the same source → machine word → executed machine relationship. + +### Alternatives + +A 3D engine would add navigation and accessibility cost without explaining logical relationships better. A literal matryoshka zoom would misrepresent the arithmetic/memory branches and software. A small breadcrumb would miss the requested central experience. SVG and native HTML reuse the site's restrained typography, violet signals, dark surfaces, and responsive controls; text equivalents carry the same information. + +## Coverage + +The complete level-by-level table is appended with the implementation and kept alongside the executable metadata. No guided VM or Jack curriculum is added; existing tools remain the continuation after assembler. + +| Step | Reused / supplied pieces | Relationship to prior work | Visible progression | Enables next | +| ------------------------------ | ---------------------------------------------- | ----------------------------------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------- | +| `intro/signal` | 0, 1 | One wire can carry either value. | signal: A changing signal becomes a readable bit. | A gate can transform that value. | +| `intro/not` | signal | A signal carries 0 or 1. | gate: NOT gives the opposite value at its output. | Combine more than one input. | +| `intro/and` | signal a, signal b | NOT transforms one input. | gate: AND asks whether both inputs are 1. | NAND combines AND with inversion. | +| `missions/nand` | AND behavior, NOT behavior | You have observed AND and NOT. | gate: The supplied NAND produces the opposite of AND. | Reuse NAND to construct every gate in this layer. | +| `missions/not` | Nand | NAND accepts two input pins. | gate: One signal feeding both pins becomes an inverter. | Invert a NAND result to build AND. | +| `missions/and` | Nand, Not | You can invert a value. | gate: Combining gates restores the AND behavior. | Compose more complex conditions. | +| `missions/or` | Not, Nand | Inversion changes the question a circuit asks. | gate: Either input can now produce a high output. | Combine conditions to detect a difference. | +| `missions/xor` | Or, And, Not | OR includes the case where both inputs are high. | gate: XOR isolates the cases where inputs differ. | The sum bit of a half adder uses this behavior. | +| `missions/mux` | Not, And, Or | Gates can enable and combine paths. | select: One selector chooses between two data inputs. | Use the same choice across a 16-bit word. | +| `missions/dmux` | Not, And | A selector can enable one path. | distribute: One input is routed to either of two outputs. | Route a write signal to one memory location. | +| `buses/not16` | Not | One NOT flips one bit. | parallel: Sixteen independent lanes invert a word. | Apply logic to whole words. | +| `buses/and16` | And | A word is sixteen related wires. | parallel: Matching positions combine, with no carry. | The ALU will offer a bitwise AND operation. | +| `buses/or16` | Or | Bitwise logic keeps positions separate. | parallel: Each lane merges the corresponding input bits. | Compose word-level logic with the same gates. | +| `buses/mux16` | Mux | A Mux chooses one data bit. | parallel: One selector controls sixteen choices together. | Choose complete operands and results. | +| `buses/or8way` | Or | OR merges two conditions. | reduce: An OR tree reduces eight bits to one answer. | Detect whether any result bit is set. | +| `buses/mux4way16` | Mux16 | Mux16 chooses between two words. | select: Two selector bits choose one of four words. | Build larger selectors from smaller ones. | +| `buses/mux8way16` | Mux4Way16, Mux16 | Four-way selection is reusable. | select: A final choice combines two four-word groups. | Select a word read from a memory bank. | +| `buses/dmux4way` | DMux | DMux distributes one enable signal. | distribute: Two decisions choose one of four destinations. | Use address bits to direct a write. | +| `buses/dmux8way` | DMux, DMux4Way | A routing tree can be composed. | distribute: Three selector bits open one of eight paths. | Enable exactly one of eight registers. | +| `arithmetic/halfadder` | Xor, And | XOR detects difference; AND detects two ones. | adder: Two outputs represent a two-bit sum: carry and sum. | Add an incoming carry from another column. | +| `arithmetic/fulladder` | HalfAdder, HalfAdder, Or | A half adder adds two bits. | adder: A third input carries work from the previous column. | Chain columns to add whole words. | +| `arithmetic/add16` | FullAdder | Each full adder accepts and produces a carry. | adder: Carry flows from bit 0 toward bit 15. | Word addition becomes one reusable component. | +| `arithmetic/inc16` | Add16, constant 1 | Add16 adds whole words. | adder: A fixed second operand advances a value by one. | Advance a program counter. | +| `arithmetic/alu` | Mux16, Not16, And16, Add16, Or8Way | Word logic, arithmetic, and selection are available. | alu: Control bits choose a calculation; flags describe its result. | The CPU uses this result to store values and decide jumps. | +| `memory/bit` | Mux, DFF · supplied | A Mux chooses a new value or feedback. | state: The clock separates the stored value from its next value. | Place sixteen memories side by side. | +| `memory/register` | Bit | One Bit retains state when load is low. | parallel: Sixteen bits share load and clock to remember a word. | Address a collection of stored words. | +| `memory/ram8` | Register, DMux8Way, Mux8Way16 | Registers store words; routing selects paths. | bank: Three address bits select one of eight words. | Group banks to expand memory. | +| `memory/ram64` | RAM8 | RAM8 is now a reusable bank. | bank: The address selects a bank and a word inside it. | Repeat the hierarchy for 512 words. | +| `memory/ram512` | RAM64 | A bank exposes the same read/write interface. | bank: Nine address bits reach 512 words through two decisions. | Reuse the interface at a larger capacity. | +| `memory/ram4k` | RAM512 | Smaller banks keep the structure manageable. | bank: Twelve address bits reach 4,096 stored words. | Build the RAM region of the computer. | +| `memory/ram16k` | RAM4K | Four 4K banks can share one interface. | bank: Fourteen address bits reach 16,384 words. | Combine RAM with memory-mapped devices. | +| `memory/pc` | Register, Inc16, Mux16 | Registers remember; an incrementer advances. | counter: Priority selects reset, load, increment, or hold. | The PC will select the next instruction from ROM. | +| `machine-language/instruction` | A instruction, C instruction | The machine needs values and control signals. | instruction: Sixteen bits specify an address or a computation. | Sequence instructions into a program. | +| `machine-language/mult` | Add, Store, Jump | Instructions can calculate, store, and branch. | loop: A loop reuses addition to perform multiplication. | Use a program to respond to an input device. | +| `machine-language/fill` | Keyboard · supplied, CPU, Screen · supplied | Programs read and write addressed memory. | devices: The CPU reads a key and writes screen words; pixels follow. | Build the memory interface that connects these devices. | +| `architecture/memory` | RAM16K, Screen · supplied, Keyboard · supplied | RAM stores words and routing decodes addresses. | address: One address space selects RAM, screen, or keyboard. | Connect the CPU through this single memory interface. | +| `architecture/cpu` | ARegister, DRegister, ALU, PC | Arithmetic and state are two branches of the machine. | cpu: Instruction bits coordinate registers, calculation, and jumps. | Connect this processor to program ROM and data memory. | +| `architecture/computer` | ROM32K · supplied, CPU, Memory | The CPU has separate instruction and data paths. | computer: The PC reads ROM; CPU memory pins reach RAM and devices. | Translate readable programs into its instruction words. | +| `assembler/encode` | assembly, encoding table, ROM words | The CPU executes bits with fixed meanings. | encode: Readable operations become the same 16-bit instructions. | Replace numeric addresses with useful names. | +| `assembler/symbols` | labels → ROM, variables → RAM, symbol table | Instructions and data each have addresses. | symbols: Two passes resolve names without allocating ROM for labels. | Combine symbol resolution with instruction encoding. | +| `assembler/assembler` | clean source, resolve symbols, encode words | You can resolve names and encode instructions. | translator: Your translator turns a whole program into machine words. | Run those words on the computer; keep exploring in Tools. | diff --git a/src/lib/course/Chapter.svelte b/src/lib/course/Chapter.svelte index 2e4c492..e38a01e 100644 --- a/src/lib/course/Chapter.svelte +++ b/src/lib/course/Chapter.svelte @@ -18,6 +18,7 @@ import TopicNavigator from '#lib/learning/adaptive/TopicNavigator.svelte'; import TopicCoach from '#lib/learning/adaptive/TopicCoach.svelte'; import { learningStorage } from '#lib/learning/adaptive/storage.js'; + import Journey from '#lib/journey/Journey.svelte'; import './course.css'; export let chapter: CourseChapter; let taskIndex = 0; @@ -246,6 +247,7 @@ +

{task.explanation}

{#if task.kind === 'symbols'}
 {
@@ -33,12 +34,24 @@
   

FROM SIGNALS TO ASSEMBLY

Build it up.

-

Each layer uses the one beneath it. One working piece at a time.

+

+ Logic becomes calculation and memory. Bring them together, then give your computer a program. +

+ !completed.includes(taskKey(next!, task))) ?? next.tasks[0], + ) + : 'assembler/assembler'} + {completed} + overview + />
    {#each courseChapters as chapter (chapter.id)} {@const count = chapter.tasks.filter((task) => diff --git a/src/lib/game/Game.svelte b/src/lib/game/Game.svelte index c96b07c..41f774e 100644 --- a/src/lib/game/Game.svelte +++ b/src/lib/game/Game.svelte @@ -3,6 +3,7 @@ import { afterNavigate, goto, replaceState } from '$app/navigation'; import { page } from '$app/state'; import SignalIntro from './SignalIntro.svelte'; + import Journey from '#lib/journey/Journey.svelte'; import MissionWorkbench from './MissionWorkbench.svelte'; import FieldGuide from './FieldGuide.svelte'; import { missions, getMission, type MissionId } from './missions'; @@ -229,6 +230,11 @@ ? 'Its output is 0 only when both inputs are 1.' : lastMission.goal}

    + `missions/${id}`)} + verified + /> Break down the magic of computers. -

    By building your own.

    +

    + Learn how computers work from first principles—by building your own. +

    + + + +
    + {#key `${inspected.id}:${outside}:${replay}`}{/key} +
    + {outside + ? 'Functional relationships · not physical scale' + : 'Conceptual composition · valid designs can differ'} + {#if !reducedMotion}{/if} +
    +
    + {#if inspected.inputs.length || inspected.outputs.length}

    + Interface + {inspected.inputs.join(' · ') || 'program / reset'} → {inspected.outputs.join(' · ') || + 'internal memory + devices'} +

    {/if} + {#if inspected.id === currentId && Object.keys(live).length}

    + Live signals + {Object.entries(live) + .map(([pin, value]) => `${pin} = ${Number(value)}`) + .join(' · ')} +

    {/if} + {#if done && !verified && inspected.id === currentId}

    + Previously verified. Check the current draft again to verify any edits. +

    {/if} +
    +

    BUILDS ON{inspected.prior}

    +

    MAKES POSSIBLE{inspected.next}

    +
    + {#if inspected.id === currentId && parts.length} +

    + Your current design + {countedParts.join(' · ')}. {verified + ? 'This draft passed its checks.' + : 'Shown from your draft; check it to verify the connections.'} +

    + {/if} + {#if inspected.supplied}

    + {inspected.id === 'missions/nand' + ? 'NAND is a supplied primitive. You characterize its behavior before building with it.' + : 'This gate is supplied for observation here. You will construct its behavior in the gate missions.'} +

    {/if} + +
    + + {#if inspected.id !== currentId}{/if} + {#if overview || inspected.id !== currentId}Open this lesson →{/if} +
    + {#if ['machine-language/fill', 'architecture/computer', 'assembler/assembler'].includes(inspected.id)} + + {/if} + + + diff --git a/src/lib/journey/Runtime.svelte b/src/lib/journey/Runtime.svelte new file mode 100644 index 0000000..141d279 --- /dev/null +++ b/src/lib/journey/Runtime.svelte @@ -0,0 +1,276 @@ + + +
    +
    + WATCH THE MACHINE DO THE WORK +

    A key becomes pixels.

    +

    Reference computer · supplied Screen and Keyboard

    +

    + The keyboard changes a memory value. Only the running program can turn it into a screen write. +

    +
    + + +
    +

    + {origin} · KBD = {pressed ? 65 : 0}
    CPU cycles: {program.machine.cycles.toLocaleString( + 'en-US', + )} +

    + {#if draftChanged}

    + Your draft has changed. Reload it to run the latest version. +

    {/if} +
    + {#if allowStudent}{/if} + +
    +
    +
    + +

    + {darkWords.toLocaleString('en-US')} / 8,192 screen words contain dark pixels. +

    +
    +
    + {#if evidence} +
      +
    1. + Keyboard{pressed ? '65 (A)' : '0 (released)'} at address 24576 +
    2. +
    3. + CPU read{evidence.read + ? `${evidence.read.inM} at instruction ${evidence.read.before.pc}` + : 'No keyboard read observed in this run'} +
    4. +
    5. + Memory write{evidence.write + ? `${evidence.write.outM} → address ${evidence.write.addressM}` + : 'No screen write observed in this run'} +
    6. +
    7. PixelsDrawn from the actual 8,192 screen words
    8. +
    + {#if evidence.read}

    + Executed word: {binary16(evidence.read.instruction)} · PC {evidence.read.before.pc} +

    {/if} + {#if program.machine.halted}

    + The program reached the end of its loaded instructions. +

    {/if} + {:else}

    + Change the key, then run. The display stays unchanged until instructions execute. +

    {/if} +
    + {#if error}{/if} +
    + Inspect the supplied program and encoded instructions +

    + This example demonstrates the runtime. Loading it does not change your answer or completion. +

    +
    +
    {journeyFillExample}
    +
    {loadJourneyProgram().assembly.binary}
    +
    +
    +
    + + diff --git a/src/lib/journey/Scene.svelte b/src/lib/journey/Scene.svelte new file mode 100644 index 0000000..214eea0 --- /dev/null +++ b/src/lib/journey/Scene.svelte @@ -0,0 +1,611 @@ + + +{#if detailed} + +{:else} + + {step.label} — {outside ? 'Place in the computer' : 'Conceptual composition'} + {step.prior} + {step.change} + {step.next} Screen and Keyboard are supplied devices. Connections show functional relationships, + not physical scale. + {#if connected} + + COMPUTER + + + {#each systemEdges as path (path)}{/each} + {#each modules as item (item.label)} + {@const earned = progress[item.label]?.count ?? 0} + {@const total = progress[item.label]?.total ?? 0} + {@const focused = item.label === activeModule} + {@const keepPiece = + focused && + !software && + step.id !== 'architecture/computer' && + step.label !== item.label && + step.label.length < 19} + {@const device = item.label === 'Screen' || item.label === 'Keyboard'} + 0} + class:unbuilt={!earned && !device} + data-system-module={item.label} + data-evidence-count={earned} + > + + {#if keepPiece} + {item.label} · reusable piece + + {step.label} + {:else if device} + {#if item.label === 'Screen'} + + + {:else} + {#each Array.from({ length: 12 }, (_, i) => i) as i (i)}{/each} + {/if} + {item.label}{small ? '' : ' · supplied'} + {:else} + {item.label} + {earned + ? progress[item.label].pieces.slice(small ? -1 : -2).join(' · ') + : small + ? ({ + ROM: 'program words', + CPU: 'A · D · PC', + Logic: 'gates / words', + ALU: 'inside CPU', + Memory: 'RAM / devices', + }[item.label] ?? item.sub) + : item.sub} + {/if} + {#if total}{earned + ? small + ? `${earned}/${total} steps` + : `${earned}/${total} steps explored / verified` + : small + ? 'not verified' + : 'not verified here'}{/if} + {#if device && small}supplied{/if} + + {/each} + {#if !small}Arithmetic + state meet here.The program directs reads and writes.{/if} + {small + ? software + ? 'Source → words → ROM → execution' + : 'Dashed = not verified here.' + : software + ? 'Source → encoded words → ROM → execution' + : 'Your verified pieces accumulate here. Dashed outlines are not verified.'} + {:else} + + {step.label} + {#if step.diagram === 'signal'} + + + + {Number(live.in ?? 0)} + {Number(live.out ?? 0)} + one wire · two possible values + A value, carried from input to output. + {:else if gridCount} + {step.diagram === 'parallel' + ? small + ? '16 independent bit lanes' + : 'Same operation · independent bit positions' + : `${step.count?.toLocaleString('en-US')} words · select bank + word`} + {#each Array.from({ length: gridCount }, (_, i) => i) as i (i)} + {@const x = 40 + (i % columns) * cellWidth} + {@const y = 105 + Math.floor(i / columns) * (small ? 58 : 67)} + + + + {step.parts[0]} + {step.diagram === 'parallel' ? `bit ${i}` : `bank ${i}`} + {/each} + {step.diagram === 'bank' + ? 'load routes down · selected data returns' + : step.id === 'memory/register' + ? 'shared load + clock · one stored word' + : step.id === 'buses/mux16' + ? 'one shared selector · sixteen data paths' + : 'No carry between these lanes.'} + {:else if ['select', 'distribute', 'reduce'].includes(step.diagram)} + {@const reverse = step.diagram === 'distribute'} + {@const count = step.count ?? 8} + {@const leafX = reverse ? width - 65 : 65} + {@const rootX = reverse ? 65 : width - 65} + {@const top = 100} + {@const span = height - 160} + {#each Array.from({ length: count }, (_, i) => i) as i (i)} + {@const y = top + (i * span) / (count - 1)} + + + {i.toString(2).padStart(Math.log2(count), '0')} + {/each} + + {step.diagram === 'reduce' ? 'OR tree' : 'routing'} + {step.diagram === 'reduce' ? 'any high?' : `${Math.log2(count)} select bits`} + + {reverse ? 'in' : 'out'} + {reverse + ? 'one input → selected destination' + : step.diagram === 'reduce' + ? 'many input bits → one answer' + : 'selected input → one output'} + {:else if step.diagram === 'instruction' || step.diagram === 'encode'} + {step.diagram === 'instruction' + ? 'Source: @21; D=A' + : 'Source: @7; D=A; @3; D=D+A'} + + {#each ['111', '0 110000', '010', '000'] as word, i (i)} + {@const x = small ? 20 + (i % 2) * 140 : 85 + i * 155} + {@const y = small ? 160 + Math.floor(i / 2) * 75 : 155} + + {word} + {['C instruction', 'computation', 'destination', 'jump'][i]} + {/each} + D=A becomes 1110110000010000 + {:else if step.diagram === 'adder' && step.count === 16} + {#each ['bit 0', 'bit 1', '…', 'bit 15'] as bit, i (i)} + {@const x = small ? 55 : 65 + i * 175} + {@const y = small ? 85 + i * 78 : 125} + + {bit} + FullAdder + {#if i < 3}{/if} + {/each} + Carry moves toward the higher bit. + {:else if step.diagram === 'address'} + {#each [['0–16383', 'RAM16K', 'read / write'], ['16384–24575', 'Screen · supplied', 'read / write → pixels'], ['24576', 'Keyboard · supplied', 'read only']] as region, i (i)} + {@const y = small ? 105 + i * 90 : 95 + i * 64} + + {region[0]} + {region[1]} + {region[2]} + {/each} + Address decode selects one region. + {:else if step.diagram === 'cpu'} + {#each ['A register', 'D register', 'ALU', 'PC + jump control'] as part, i (i)} + {@const x = small ? 65 : 95 + (i % 2) * 320} + {@const y = small ? 90 + i * 68 : 95 + Math.floor(i / 2) * 110} + + {part} + {#if i < 3}{/if} + {/each} + Instruction → calculation · destinations · next PC + {:else if step.diagram === 'state'} + + + Mux → DFF + choose → capture + load + clock + feedback keeps the stored value + DFF is supplied · state changes at the edge + {:else} + {#each parts as part, i (i)} + {@const cols = small ? 1 : Math.min(3, parts.length)} + {@const w = small ? 230 : 185} + {@const x = small ? 65 : (width - cols * w - (cols - 1) * 22) / 2 + (i % cols) * (w + 22)} + {@const y = 100 + Math.floor(i / cols) * (small ? 63 : 85)} + + {part} + {#if i < parts.length - 1}{/if} + {/each} + {software + ? 'A representation of work the machine executes.' + : step.diagram === 'counter' + ? 'reset → load → increment → hold' + : step.diagram === 'alu' + ? 'control bits → chosen result + zero / negative flags' + : 'Reusable parts, connected by signals.'} + {software + ? 'Software runs on the computer; it is not an outer hardware layer.' + : `${step.inputs.join(', ')} → ${step.outputs.join(', ')}`} + {/if} + {/if} + +{/if} + + diff --git a/src/lib/journey/advancedDiagrams.ts b/src/lib/journey/advancedDiagrams.ts new file mode 100644 index 0000000..f476389 --- /dev/null +++ b/src/lib/journey/advancedDiagrams.ts @@ -0,0 +1,637 @@ +import type { JourneyStep } from './data'; +import type { ConnectedDiagram, DiagramNode, DiagramEdge } from './schematicTypes'; + +const node = ( + id: string, + label: string, + x: number, + y: number, + w = 130, + detail?: string, + kind: DiagramNode['kind'] = 'chip', +): DiagramNode => ({ id, label, x, y, w, h: 60, detail, kind }); +const edge = ( + from: string, + to: string, + extra: Omit = {}, +): DiagramEdge => ({ from, to, ...extra }); + +function alu(small: boolean): ConnectedDiagram { + if (small) + return { + width: 300, + height: 760, + nodes: [ + node('x', 'Prepare x', 20, 100, 120, 'zx: zero; nx: NOT'), + node('y', 'Prepare y', 160, 100, 120, 'zy: zero; ny: NOT'), + node('and', 'And16', 20, 265, 120, 'bitwise x AND y'), + node('add', 'Add16', 160, 265, 120, 'word sum x + y'), + node('select', 'Mux16', 90, 410, 120, 'f: AND or sum'), + node('out', 'out[16]', 90, 535, 120, 'no: keep / NOT', 'output'), + node('flags', 'zr / ng', 90, 660, 120, 'zero / sign bit'), + ], + edges: [ + edge('x', 'and'), + edge('x', 'add', { fromOffset: 25, toOffset: -25 }), + edge('y', 'and', { fromOffset: -25, toOffset: 25 }), + edge('y', 'add'), + edge('and', 'select', { toOffset: -25 }), + edge('add', 'select', { toOffset: 25 }), + edge('select', 'out'), + edge('out', 'flags'), + ], + notes: [{ text: 'Both operations receive prepared x, y.', x: 150, y: 220 }], + }; + return { + width: 780, + height: 540, + nodes: [ + node('x', 'Prepare x', 30, 120, 150, 'zx: zero; nx: invert'), + node('y', 'Prepare y', 30, 330, 150, 'zy: zero; ny: invert'), + node('and', 'And16', 270, 120, 135, 'x AND y'), + node('add', 'Add16', 270, 330, 135, 'x + y'), + node('select', 'Mux16', 465, 225, 130, 'f: choose operation'), + node('out', 'out[16]', 625, 225, 130, 'no: keep / invert', 'output'), + node('flags', 'zr / ng', 625, 390, 130, 'zero / sign bit'), + ], + edges: [ + edge('x', 'and'), + edge('y', 'add'), + edge('x', 'add', { + fromSide: 'right', + toSide: 'left', + via: [ + [220, 150], + [220, 360], + ], + toOffset: -15, + }), + edge('y', 'and', { + fromSide: 'right', + toSide: 'left', + via: [ + [240, 360], + [240, 150], + ], + toOffset: 15, + }), + edge('and', 'select', { + fromSide: 'right', + toSide: 'left', + via: [ + [435, 150], + [435, 240], + ], + toOffset: -15, + }), + edge('add', 'select', { + fromSide: 'right', + toSide: 'left', + via: [ + [445, 360], + [445, 270], + ], + toOffset: 15, + }), + edge('select', 'out'), + edge('out', 'flags'), + ], + notes: [ + { + text: 'The six control bits prepare operands, choose a result, and optionally invert it.', + x: 390, + y: 495, + }, + ], + }; +} + +function bank(step: JourneyStep, small: boolean): ConnectedDiagram { + const words = step.count ?? 8; + const banks = words === 16384 ? 4 : 8; + const child = step.parts[0]; + const detail = `${words / banks} ${words / banks === 1 ? 'word' : 'words'} · ${child}`; + const addressNote = + words === 8 ? '3 address bits choose a register.' : `High bits choose 1 of ${banks} banks.`; + if (small) + return { + width: 300, + height: 780, + nodes: [ + node('address', 'address', 15, 100, 125, `${Math.log2(words)} bits`, 'input'), + node('write', 'in + load', 160, 100, 125, 'shared write data', 'input'), + node('decode', 'Write select', 15, 245, 125, `1 of ${banks} enables`, 'control'), + node('first', 'Bank 0', 15, 390, 125, detail), + node('last', `Bank ${banks - 1}`, 160, 390, 125, detail), + node('mux', 'Read Mux', 90, 530, 125, 'address selects'), + node('out', 'out[16]', 90, 650, 125, 'selected word', 'output'), + ], + edges: [ + edge('address', 'decode'), + edge('decode', 'first', { toOffset: -25 }), + edge('decode', 'last', { toOffset: -25, fromOffset: 25 }), + edge('write', 'first', { + fromSide: 'bottom', + toSide: 'right', + via: [ + [225, 200], + [150, 200], + [150, 420], + ], + }), + edge('write', 'last'), + edge('address', 'mux', { + fromSide: 'top', + toSide: 'right', + via: [ + [77.5, 80], + [292, 80], + [292, 560], + ], + label: 'read address', + labelAt: [235, 70], + }), + edge('first', 'mux', { toOffset: -25 }), + edge('last', 'mux', { toOffset: 25 }), + edge('mux', 'out'), + ], + notes: [ + { text: addressNote, x: 150, y: 725 }, + { + text: + words === 8 + ? 'Only the selected register is written.' + : 'Low bits address a word inside a bank.', + x: 150, + y: 745, + }, + ], + }; + return { + width: 780, + height: 560, + nodes: [ + node('address', 'address', 25, 105, 130, `${Math.log2(words)} bits`, 'input'), + node('decode', 'Write select', 205, 105, 140, `1 of ${banks} enables`, 'control'), + node('write', 'in + load', 25, 325, 130, 'shared write data', 'input'), + node('first', 'Bank 0', 400, 190, 140, detail), + node('last', `Bank ${banks - 1}`, 400, 365, 140, detail), + node('mux', 'Read Mux', 605, 275, 140, 'address selects'), + node('out', 'out[16]', 605, 420, 140, 'selected word', 'output'), + ], + edges: [ + edge('address', 'decode'), + edge('address', 'mux', { + fromSide: 'top', + toSide: 'right', + via: [ + [90, 80], + [755, 80], + [755, 305], + ], + label: 'read address', + labelAt: [625, 70], + }), + edge('decode', 'first', { fromSide: 'right', toSide: 'top', via: [[470, 135]] }), + edge('decode', 'last', { + fromSide: 'right', + toSide: 'left', + via: [ + [370, 135], + [370, 380], + ], + toOffset: -15, + }), + edge('write', 'first', { + fromSide: 'right', + toSide: 'left', + via: [ + [350, 355], + [350, 235], + ], + toOffset: 15, + }), + edge('write', 'last', { + fromSide: 'right', + toSide: 'left', + via: [ + [330, 355], + [330, 410], + ], + toOffset: 15, + }), + edge('first', 'mux', { + fromSide: 'right', + toSide: 'left', + via: [ + [570, 220], + [570, 290], + ], + toOffset: -15, + }), + edge('last', 'mux', { + fromSide: 'right', + toSide: 'left', + via: [ + [585, 395], + [585, 320], + ], + toOffset: 15, + }), + edge('mux', 'out'), + ], + notes: [ + { + text: `First and last banks shown; the same read/write interface repeats across all ${banks}.`, + x: 390, + y: 500, + }, + { + text: `${addressNote} ${words === 8 ? 'Each register stores one word.' : 'Low bits choose the word inside that bank.'}`, + x: 390, + y: 520, + }, + ], + }; +} + +function cpu(small: boolean): ConnectedDiagram { + if (small) + return { + width: 300, + height: 975, + nodes: [ + node('instruction', 'instruction', 90, 100, 120, 'from ROM', 'input'), + node('decode', 'Decode', 90, 220, 120, 'comp·dest·jump', 'control'), + node('operands', 'A, D and M', 90, 345, 120, 'D and chosen A/M'), + node('alu', 'ALU', 90, 470, 120, 'result + zr / ng'), + node('dest', 'Destinations', 90, 595, 120, 'A / D / memory'), + node('pc', 'PC + jump', 90, 765, 120, 'reset / flags / A'), + node('rom', 'pc → ROM', 90, 885, 120, 'next instruction', 'output'), + ], + edges: [ + edge('instruction', 'decode'), + edge('decode', 'alu', { + fromSide: 'right', + toSide: 'right', + via: [ + [250, 250], + [250, 485], + ], + toOffset: -15, + }), + edge('decode', 'dest', { + fromSide: 'right', + toSide: 'right', + via: [ + [275, 250], + [275, 625], + ], + }), + edge('operands', 'alu'), + edge('alu', 'dest'), + edge('dest', 'operands', { + fromSide: 'left', + toSide: 'left', + via: [ + [50, 625], + [50, 375], + ], + }), + edge('operands', 'pc', { + fromSide: 'left', + toSide: 'left', + via: [ + [25, 375], + [25, 795], + ], + }), + edge('alu', 'pc', { + fromSide: 'right', + toSide: 'right', + via: [ + [235, 515], + [235, 795], + ], + fromOffset: 15, + }), + edge('decode', 'pc', { + fromSide: 'right', + toSide: 'right', + via: [ + [290, 265], + [290, 810], + ], + fromOffset: 15, + toOffset: 15, + }), + edge('pc', 'rom'), + ], + notes: [ + { text: 'A/D update at the clock edge.', x: 150, y: 700 }, + { text: 'Memory and jumps use the old A.', x: 150, y: 720 }, + ], + }; + return { + width: 780, + height: 660, + nodes: [ + node('instruction', 'instruction', 25, 100, 140, 'from ROM', 'input'), + node('decode', 'Decode', 235, 100, 160, 'comp·dest·jump', 'control'), + node('operands', 'A, D and M', 235, 300, 160, 'D and selected A/M'), + node('alu', 'ALU', 460, 300, 130, 'result + zr / ng'), + node('dest', 'Destinations', 625, 300, 130, 'A / D / memory'), + node('pc', 'PC + jump', 460, 490, 130, 'reset / flags / A'), + node('rom', 'pc → ROM', 625, 490, 130, 'next instruction', 'output'), + ], + edges: [ + edge('instruction', 'decode'), + edge('operands', 'alu'), + edge('alu', 'dest'), + edge('decode', 'alu', { + fromSide: 'right', + toSide: 'top', + via: [[525, 130]], + label: 'comp', + labelAt: [460, 115], + }), + edge('decode', 'dest', { + fromSide: 'top', + toSide: 'top', + via: [ + [315, 75], + [690, 75], + ], + label: 'dest', + labelAt: [650, 65], + }), + edge('dest', 'operands', { + fromSide: 'bottom', + toSide: 'bottom', + via: [ + [690, 420], + [315, 420], + ], + label: 'register feedback', + labelAt: [470, 410], + }), + edge('operands', 'pc', { + fromSide: 'left', + toSide: 'left', + via: [ + [200, 330], + [200, 520], + ], + label: 'old A: target', + labelAt: [320, 510], + }), + edge('alu', 'pc', { label: 'zr / ng', labelAt: [560, 455] }), + edge('decode', 'pc', { + fromSide: 'left', + toSide: 'bottom', + via: [ + [180, 130], + [180, 590], + [525, 590], + ], + label: 'jump bits', + labelAt: [340, 580], + }), + edge('pc', 'rom'), + ], + notes: [ + { + text: 'Instruction control selects operands, destinations and jumps. Memory addresses use the old A.', + x: 390, + y: 630, + }, + ], + }; +} + +function translation(symbols: boolean, small: boolean): ConnectedDiagram { + const output = symbols ? 'Addresses' : '16-bit words'; + if (small) + return { + width: 300, + height: 720, + nodes: [ + node('source', 'Clean source', 90, 100, 120, 'without comments', 'input'), + node('first', 'Pass 1', 90, 225, 120, 'labels → ROM'), + node('table', 'Symbols', 15, 360, 115, 'built-in + new'), + node('second', 'Pass 2', 165, 480, 120, symbols ? 'variables → RAM' : 'resolve + encode'), + node('out', output, 165, 605, 120, symbols ? 'ready to encode' : 'ready for ROM', 'output'), + ], + edges: [ + edge('source', 'first'), + edge('first', 'table', { fromSide: 'left', toSide: 'top', via: [[72.5, 255]] }), + edge('first', 'second', { fromSide: 'right', toSide: 'top', via: [[225, 255]] }), + edge('table', 'second', { fromSide: 'bottom', toSide: 'left', via: [[72.5, 510]] }), + edge('second', 'out'), + ], + notes: [{ text: 'Labels do not occupy ROM words.', x: 150, y: 690 }], + }; + return { + width: 780, + height: 470, + nodes: [ + node('source', 'Clean source', 25, 120, 145, 'without comments', 'input'), + node('first', 'Pass 1', 220, 120, 145, 'labels → ROM'), + node('table', 'Symbol table', 220, 300, 145, 'built-in + new'), + node('second', 'Pass 2', 420, 120, 145, symbols ? 'variables → RAM' : 'resolve + encode'), + node('out', output, 620, 120, 135, symbols ? 'ready to encode' : 'ready for ROM', 'output'), + ], + edges: [ + edge('source', 'first'), + edge('first', 'second', { label: 'instructions' }), + edge('first', 'table', { label: 'ROM labels', labelAt: [335, 245] }), + edge('table', 'second', { + fromSide: 'right', + toSide: 'bottom', + via: [[492.5, 330]], + label: 'name → address', + labelAt: [500, 280], + }), + edge('second', 'out'), + ], + notes: [ + { + text: 'Labels name ROM positions without taking space. New variables receive RAM addresses from 16.', + x: 390, + y: 420, + }, + ], + }; +} + +function loop(small: boolean): ConnectedDiagram { + if (small) + return { + width: 300, + height: 820, + nodes: [ + node('start', 'Initialize', 90, 100, 120, 'R2=0; count=R1'), + node('test', 'count = 0?', 90, 240, 120, 'conditional jump', 'control'), + node('add', 'R2 += R0', 90, 380, 120, 'one more addition'), + node('dec', 'count − 1', 90, 520, 120, 'then test again'), + node('done', 'Result in R2', 90, 685, 120, 'stable final loop', 'output'), + ], + edges: [ + edge('start', 'test'), + edge('test', 'add', { label: 'no', labelAt: [175, 345] }), + edge('add', 'dec'), + edge('dec', 'test', { + fromSide: 'left', + toSide: 'left', + via: [ + [35, 550], + [35, 270], + ], + }), + edge('test', 'done', { + fromSide: 'right', + toSide: 'right', + via: [ + [265, 270], + [265, 715], + ], + label: 'yes', + labelAt: [265, 640], + }), + ], + notes: [{ text: 'Multiply by repeating addition.', x: 150, y: 785 }], + }; + return { + width: 780, + height: 490, + nodes: [ + node('start', 'Initialize', 25, 110, 155, 'R2=0; count=R1'), + node('test', 'count = 0?', 300, 110, 155, 'conditional jump', 'control'), + node('done', 'Result in R2', 600, 110, 155, 'stable final loop', 'output'), + node('add', 'R2 += R0', 300, 310, 155, 'one more addition'), + node('dec', 'count − 1', 25, 310, 155, 'then test again'), + ], + edges: [ + edge('start', 'test'), + edge('test', 'done', { label: 'yes' }), + edge('test', 'add', { label: 'no', labelAt: [405, 245] }), + edge('add', 'dec'), + edge('dec', 'test', { + fromSide: 'bottom', + toSide: 'right', + via: [ + [102.5, 425], + [520, 425], + [520, 140], + ], + }), + ], + notes: [ + { + text: 'The program repeats an ALU operation; the hardware does not need a multiply instruction.', + x: 390, + y: 460, + }, + ], + }; +} + +function counter(small: boolean): ConnectedDiagram { + if (small) + return { + width: 300, + height: 890, + nodes: [ + node('reset', 'reset?', 20, 100, 115, 'first choice', 'control'), + node('zero', '0', 165, 100, 115, 'reset value', 'input'), + node('load', 'load?', 20, 240, 115, 'otherwise', 'control'), + node('in', 'in[16]', 165, 240, 115, 'in value', 'input'), + node('inc', 'inc?', 20, 380, 115, 'otherwise', 'control'), + node('plus', 'Inc16(PC)', 165, 380, 115, 'current PC + 1'), + node('hold', 'Hold PC', 20, 520, 115, 'otherwise'), + node('register', 'Register', 165, 665, 115, 'clocked value'), + node('out', 'out[16]', 165, 785, 115, 'stored PC', 'output'), + ], + edges: [ + edge('reset', 'zero', { label: 'yes' }), + edge('reset', 'load', { label: 'no', labelAt: [95, 205] }), + edge('load', 'in', { label: 'yes' }), + edge('load', 'inc', { label: 'no', labelAt: [95, 345] }), + edge('inc', 'plus', { label: 'yes' }), + edge('inc', 'hold', { label: 'no', labelAt: [95, 485] }), + edge('zero', 'register', { + fromSide: 'right', + toSide: 'right', + via: [ + [292, 130], + [292, 695], + ], + }), + edge('in', 'register', { + fromSide: 'right', + toSide: 'right', + via: [ + [292, 270], + [292, 695], + ], + }), + edge('plus', 'register'), + edge('hold', 'register', { fromSide: 'bottom', toSide: 'left', via: [[77.5, 695]] }), + edge('register', 'out'), + ], + }; + return { + width: 780, + height: 620, + nodes: [ + node('reset', 'reset?', 30, 110, 140, 'first choice', 'control'), + node('load', 'load?', 220, 110, 140, 'otherwise', 'control'), + node('inc', 'inc?', 410, 110, 140, 'otherwise', 'control'), + node('hold', 'Hold PC', 600, 110, 140, 'otherwise'), + node('zero', '0', 30, 295, 140, 'reset value', 'input'), + node('in', 'in[16]', 220, 295, 140, 'in value', 'input'), + node('plus', 'Inc16(PC)', 410, 295, 140, 'current PC + 1'), + node('register', 'Register', 315, 480, 150, 'clocked value'), + node('out', 'out[16]', 600, 480, 140, 'stored PC', 'output'), + ], + edges: [ + edge('reset', 'load', { label: 'no' }), + edge('load', 'inc', { label: 'no' }), + edge('inc', 'hold', { label: 'no' }), + edge('reset', 'zero', { label: 'yes', labelAt: [125, 240] }), + edge('load', 'in', { label: 'yes', labelAt: [315, 240] }), + edge('inc', 'plus', { label: 'yes', labelAt: [505, 240] }), + edge('zero', 'register', { toOffset: -50 }), + edge('in', 'register', { toOffset: -20 }), + edge('plus', 'register', { toOffset: 20 }), + edge('hold', 'register', { + fromSide: 'bottom', + toSide: 'top', + via: [ + [670, 420], + [440, 420], + ], + toOffset: 50, + }), + edge('register', 'out'), + ], + notes: [ + { + text: 'Only the first matching choice supplies the value captured at the next clock edge.', + x: 390, + y: 585, + }, + ], + }; +} + +export function advancedDiagram(step: JourneyStep, small: boolean): ConnectedDiagram | null { + if (step.diagram === 'alu') return alu(small); + if (step.diagram === 'bank') return bank(step, small); + if (step.diagram === 'cpu') return cpu(small); + if (step.diagram === 'counter') return counter(small); + if (step.diagram === 'translator' || step.diagram === 'symbols') + return translation(step.diagram === 'symbols', small); + if (step.diagram === 'loop') return loop(small); + return null; +} diff --git a/src/lib/journey/basicDiagrams.ts b/src/lib/journey/basicDiagrams.ts new file mode 100644 index 0000000..0adc604 --- /dev/null +++ b/src/lib/journey/basicDiagrams.ts @@ -0,0 +1,215 @@ +import type { JourneyStep } from './data'; +import type { ConnectedDiagram, DiagramNode, DiagramEdge } from './schematicTypes'; + +export function basicDiagram(step: JourneyStep, small: boolean): ConnectedDiagram | null { + const width = small ? 300 : 780; + const w = small ? 120 : 160; + const left = small ? 15 : 95, + right = small ? 165 : 525, + center = (width - w) / 2; + const node = ( + id: string, + label: string, + x: number, + y: number, + detail?: string, + kind: DiagramNode['kind'] = 'chip', + ): DiagramNode => ({ id, label, x, y, w, h: 55, detail, kind }); + const edge = (from: string, to: string, label?: string): DiagramEdge => ({ from, to, label }); + const graph = (nodes: DiagramNode[], edges: DiagramEdge[], height = 485): ConnectedDiagram => ({ + width, + height, + nodes, + edges, + }); + if (step.diagram === 'gate') { + if (step.id === 'missions/not') { + return graph( + [ + node('in', 'in', center, 90, 'one input signal', 'input'), + node('nand', 'Nand', center, 220, 'a and b tied'), + node('out', 'out', center, 355, 'opposite signal', 'output'), + ], + [ + { + from: 'in', + to: 'nand', + fromSide: 'bottom', + toSide: 'top', + toOffset: -30, + via: [ + [width / 2, 180], + [width / 2 - 30, 180], + ], + label: 'a', + labelAt: [width / 2 - 42, 203], + }, + { + from: 'in', + to: 'nand', + fromSide: 'bottom', + toSide: 'top', + toOffset: 30, + via: [ + [width / 2, 180], + [width / 2 + 30, 180], + ], + label: 'b', + labelAt: [width / 2 + 42, 203], + }, + edge('nand', 'out'), + ], + 445, + ); + } + if (step.id === 'missions/and') + return graph( + [ + node('inputs', 'a, b', center, 85, 'two input bits', 'input'), + node('nand', 'Nand', center, 185, 'combine + invert'), + node('not', 'Not', center, 285, 'invert again'), + node('out', 'out', center, 385, 'both inputs high', 'output'), + ], + [edge('inputs', 'nand'), edge('nand', 'not'), edge('not', 'out')], + ); + if (step.id === 'missions/or') + return graph( + [ + node('a', 'a', left, 85, undefined, 'input'), + node('b', 'b', right, 85, undefined, 'input'), + node('notA', 'Not', left, 185, 'invert a'), + node('notB', 'Not', right, 185, 'invert b'), + node('nand', 'Nand', center, 290, 'combine inversions'), + node('out', 'out', center, 395, 'either input high', 'output'), + ], + [ + edge('a', 'notA'), + edge('b', 'notB'), + edge('notA', 'nand'), + edge('notB', 'nand'), + edge('nand', 'out'), + ], + 495, + ); + if (step.id === 'missions/xor') + return graph( + [ + node('inputs', 'a, b', center, 85, 'two input bits', 'input'), + node('or', 'Or', left, 185, 'at least one high'), + node('and', 'And', right, 185, 'both high'), + node('not', 'Not', right, 285, 'not both high'), + node('both', 'And', center, 390, 'combine conditions'), + node('out', 'out', center, 490, 'inputs differ', 'output'), + ], + [ + edge('inputs', 'or'), + edge('inputs', 'and'), + edge('and', 'not'), + { + from: 'or', + to: 'both', + fromSide: 'bottom', + toSide: 'left', + via: [[left + w / 2, 417]], + label: 'either high', + labelAt: [left + w / 2, 365], + }, + edge('not', 'both'), + edge('both', 'out'), + ], + 590, + ); + const two = step.id === 'intro/and' || step.id === 'missions/nand'; + return graph( + [ + node( + 'inputs', + two ? 'a, b' : 'in', + center, + 95, + two ? 'two input bits' : 'one input signal', + 'input', + ), + node( + 'gate', + step.label, + center, + 215, + step.supplied ? 'supplied behavior' : 'transform a signal', + step.supplied ? 'supplied' : 'chip', + ), + node( + 'out', + 'out', + center, + 335, + step.id === 'intro/and' + ? '1 when both are 1' + : step.id === 'missions/nand' + ? '0 only for two 1s' + : 'opposite signal', + 'output', + ), + ], + [edge('inputs', 'gate'), edge('gate', 'out')], + 440, + ); + } + if (step.id === 'arithmetic/halfadder') + return graph( + [ + node('inputs', 'a, b', center, 85, 'two input bits', 'input'), + node('xor', 'Xor', left, 200, 'inputs differ'), + node('and', 'And', right, 200, 'both inputs high'), + node('sum', 'sum', left, 330, 'low result bit', 'output'), + node('carry', 'carry', right, 330, 'high result bit', 'output'), + ], + [edge('inputs', 'xor'), edge('inputs', 'and'), edge('xor', 'sum'), edge('and', 'carry')], + 435, + ); + if (step.id === 'arithmetic/fulladder') + return graph( + [ + node('ab', 'a, b', left, 85, 'input bits', 'input'), + node('c', 'c', right, 85, 'carry from bit below', 'input'), + node('first', 'HalfAdder', left, 195, 'a + b'), + node('second', 'HalfAdder', right, 195, 'partial sum + c'), + node('or', 'Or', center, 320, 'combine carries'), + node('carry', 'carry', left, 435, 'to the next column', 'output'), + node('sum', 'sum', right, 435, 'this column’s bit', 'output'), + ], + [ + edge('ab', 'first'), + edge('c', 'second'), + { from: 'first', to: 'second', label: 'sum', labelAt: [width / 2, 180] }, + { from: 'first', to: 'or', label: 'carry 1', labelAt: [left + w / 2, 285] }, + { from: 'second', to: 'or', label: 'carry 2', labelAt: [right + w / 2, 285] }, + edge('or', 'carry'), + { + from: 'second', + to: 'sum', + fromSide: 'right', + toSide: 'right', + via: [ + [width - 12, 222], + [width - 12, 462], + ], + label: 'sum', + labelAt: [right + w / 2, 405], + }, + ], + 540, + ); + if (step.id === 'arithmetic/inc16') + return graph( + [ + node('in', 'in[16]', left, 90, 'input word', 'input'), + node('one', '1', right, 90, 'constant word', 'input'), + node('add', 'Add16', center, 220, 'add the operands'), + node('out', 'out[16]', center, 350, '(in + 1) mod 65536', 'output'), + ], + [edge('in', 'add'), edge('one', 'add'), edge('add', 'out')], + 450, + ); + return null; +} diff --git a/src/lib/journey/data.ts b/src/lib/journey/data.ts new file mode 100644 index 0000000..dc46229 --- /dev/null +++ b/src/lib/journey/data.ts @@ -0,0 +1,139 @@ +import { courseChapters, taskKey } from '#lib/course/data.js'; +import { missions } from '#lib/game/missions.js'; +import { treatments } from './treatments'; +export { treatments } from './treatments'; + +export type Layer = + | 'signals' + | 'gates' + | 'buses' + | 'arithmetic' + | 'memory' + | 'machine-language' + | 'architecture' + | 'assembler'; +export type Diagram = + | 'signal' + | 'gate' + | 'parallel' + | 'reduce' + | 'select' + | 'distribute' + | 'adder' + | 'alu' + | 'state' + | 'bank' + | 'counter' + | 'instruction' + | 'loop' + | 'devices' + | 'address' + | 'cpu' + | 'computer' + | 'encode' + | 'symbols' + | 'translator'; +export interface JourneyStep { + id: string; + layer: Layer; + label: string; + diagram: Diagram; + parts: string[]; + prior: string; + change: string; + next: string; + inputs: string[]; + outputs: string[]; + href: string; + supplied?: boolean; + count?: number; +} +export const layers: { id: Layer; label: string; role: string }[] = [ + { id: 'signals', label: 'Signals', role: 'Represent a value' }, + { id: 'gates', label: 'Logic', role: 'Transform and route bits' }, + { id: 'buses', label: 'Words', role: 'Work with many bits' }, + { id: 'arithmetic', label: 'Arithmetic', role: 'Calculate a result' }, + { id: 'memory', label: 'State', role: 'Keep a value over time' }, + { id: 'machine-language', label: 'Instructions', role: 'Control the machine' }, + { id: 'architecture', label: 'Computer', role: 'Connect the whole system' }, + { id: 'assembler', label: 'Assembler', role: 'Translate names into bits' }, +]; +const intro = ['signal', 'not', 'and'].map((id): JourneyStep => ({ + id: `intro/${id}`, + layer: 'signals', + label: id === 'signal' ? 'Signal' : id.toUpperCase(), + diagram: treatments[`intro/${id}`][0], + parts: treatments[`intro/${id}`][1], + prior: treatments[`intro/${id}`][2], + change: treatments[`intro/${id}`][3], + next: treatments[`intro/${id}`][4], + inputs: id === 'and' ? ['a', 'b'] : ['in'], + outputs: ['out'], + href: '/learn?topic=signals', + supplied: id !== 'signal', +})); +export const journeySteps: JourneyStep[] = [ + ...intro, + ...missions.map((mission): JourneyStep => { + const [diagram, parts, prior, change, next, count] = treatments[`missions/${mission.id}`]; + return { + id: `missions/${mission.id}`, + layer: 'gates', + label: mission.chip, + diagram, + parts, + prior, + change, + next, + count, + inputs: mission.inputs, + outputs: mission.outputs, + href: `/learn?mission=${mission.id}`, + supplied: mission.id === 'nand', + }; + }), + ...courseChapters.flatMap((chapter) => + chapter.tasks.map((task): JourneyStep => { + const id = taskKey(chapter, task); + const [diagram, parts, prior, change, next, count] = treatments[id]; + const pins = (values: Record = {}) => + Object.entries(values).map(([name, width]) => (width === 1 ? name : `${name}[${width}]`)); + return { + id, + layer: chapter.id, + label: task.chip ?? task.title, + diagram, + parts, + prior, + change, + next, + count, + inputs: pins(task.inputs), + outputs: pins(task.outputs), + href: `/learn/path/${chapter.id}?task=${task.id}`, + }; + }), + ), +]; +export const getJourneyStep = (id: string) => + journeySteps.find((step) => step.id === id) ?? journeySteps[0]; +export function journeyStatus( + step: JourneyStep, + activeId: string, + completed: readonly string[], + bypassed: readonly string[] = [], +): string { + if (completed.includes(step.id)) + return step.id.startsWith('intro/') || step.supplied ? 'Explored' : 'Verified'; + if (step.id === activeId) return 'Current challenge'; + const topic = step.id === 'missions/mux' || step.id === 'missions/dmux' ? 'routing' : step.layer; + return bypassed.includes(topic) ? 'Bypassed · not verified here' : 'Not verified here'; +} +export function draftParts(source: string): string[] { + const body = + source + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\/\/[^\n]*/g, '') + .split(/PARTS\s*:/i)[1] ?? ''; + return [...body.matchAll(/\b([A-Za-z][A-Za-z0-9_]*)\s*\(/g)].map((match) => match[1]); +} diff --git a/src/lib/journey/journey.test.ts b/src/lib/journey/journey.test.ts new file mode 100644 index 0000000..c0ab231 --- /dev/null +++ b/src/lib/journey/journey.test.ts @@ -0,0 +1,160 @@ +import { describe, expect, it } from 'vitest'; +import { readJourneyEvidence } from './progress'; +import { systemEvidence } from './system'; +import { courseChapters, taskKey } from '#lib/course/data.js'; +import { missions } from '#lib/game/missions.js'; +import { + draftParts, + getJourneyStep, + journeyStatus, + journeySteps, + layers, + treatments, +} from './data'; +import { loadJourneyProgram, runJourneyProgram } from './runtime'; + +describe('visual journey curriculum contract', () => { + it('covers every intro concept, mission and task with an explicit teaching treatment', () => { + const curriculum = [ + 'intro/signal', + 'intro/not', + 'intro/and', + ...missions.map((mission) => `missions/${mission.id}`), + ...courseChapters.flatMap((chapter) => chapter.tasks.map((task) => taskKey(chapter, task))), + ]; + expect(journeySteps.map((step) => step.id)).toEqual(curriculum); + expect(Object.keys(treatments).sort()).toEqual([...curriculum].sort()); + expect(new Set(curriculum).size).toBe(41); + for (const step of journeySteps) { + expect(step.prior.length).toBeGreaterThan(15); + expect(step.change.length).toBeGreaterThan(15); + expect(step.next.length).toBeGreaterThan(15); + expect(step.parts.length).toBeGreaterThan(0); + expect(layers.some((layer) => layer.id === step.layer)).toBe(true); + expect(step.href).toMatch(/^\/learn/); + } + }); + it('never turns navigation, skipping, or supplied devices into built credit', () => { + const alu = getJourneyStep('arithmetic/alu'); + expect(journeyStatus(alu, alu.id, [])).toBe('Current challenge'); + expect(journeyStatus(alu, 'architecture/computer', [])).toBe('Not verified here'); + expect(journeyStatus(alu, 'architecture/computer', [], ['arithmetic'])).toBe( + 'Bypassed · not verified here', + ); + expect(journeyStatus(alu, 'architecture/computer', [alu.id])).toBe('Verified'); + for (const id of ['intro/signal', 'intro/not', 'missions/nand']) + expect(journeyStatus(getJourneyStep(id), id, [id])).toBe('Explored'); + for (const id of ['missions/mux', 'missions/dmux']) + expect(journeyStatus(getJourneyStep(id), 'intro/signal', [], ['routing'])).toBe( + 'Bypassed · not verified here', + ); + expect(getJourneyStep('missing')).toBe(journeySteps[0]); + }); + it('keeps software as translation and correctly labels supplied devices', () => { + expect(getJourneyStep('architecture/memory').parts).toContain('Screen · supplied'); + expect(getJourneyStep('architecture/memory').parts).toContain('Keyboard · supplied'); + expect(getJourneyStep('memory/bit').parts).toContain('DFF · supplied'); + expect(getJourneyStep('assembler/assembler').diagram).toBe('translator'); + expect(getJourneyStep('architecture/cpu').parts).toContain('ALU'); + expect(getJourneyStep('memory/pc').parts).toContain('Inc16'); + }); + it('retains real repeated draft components while ignoring commented examples', () => { + expect( + draftParts( + 'CHIP Not16 { PARTS: Not(in=in[0],out=out[0]); // Or(a=a);\n /* And(a=a); */ Not(in=in[1],out=out[1]); }', + ), + ).toEqual(['Not', 'Not']); + expect(draftParts('CHIP Incomplete {')).toEqual([]); + }); +}); + +describe('keyboard → program → memory → pixels', () => { + it('changes pixels only through executed writes and responds to repeated key changes', () => { + const { machine, assembly } = loadJourneyProgram(); + expect(assembly.binary.split('\n')[0]).toHaveLength(16); + machine.setKeyboard(65); + expect(machine.screen.every((word) => word === 0)).toBe(true); + for (const key of [65, 0, 65, 0]) { + const evidence = runJourneyProgram(machine, key); + expect(evidence.read?.inM).toBe(key); + expect(evidence.write?.addressM).toBeGreaterThanOrEqual(16384); + expect(evidence.write?.addressM).toBeLessThan(24576); + expect(machine.screen.every((word) => word === (key ? 65535 : 0))).toBe(true); + expect(evidence.executed).toBe(250000); + } + }); + it('reports student programs honestly when they halt or do not read or write devices', () => { + const { machine } = loadJourneyProgram('@1\nD=A'); + const evidence = runJourneyProgram(machine, 0); + expect(evidence).toEqual({ read: null, write: null, executed: 2 }); + expect(machine.halted).toBe(true); + expect(runJourneyProgram(machine, 0, 0).executed).toBe(0); + expect(() => loadJourneyProgram('THIS IS NOT ASSEMBLY')).toThrow(); + }); +}); + +describe('journey evidence migration and isolation', () => { + it('retains legacy evidence and isolates corrupt optional stores', () => { + const values: Record = { + 'chipsandcode.signal-isles.progress.v1': '["nand","not"]', + 'chipsandcode.part-one.progress.v1': '["buses/not16",null]', + 'chipsandcode.signal-intro.v1': 'complete', + 'chipsandcode.learning-choices.v1': 'broken JSON', + }; + const storage = { getItem: (key: string) => values[key] ?? null }; + expect(readJourneyEvidence(storage)).toEqual({ + completed: [ + 'buses/not16', + 'missions/nand', + 'missions/not', + 'intro/signal', + 'intro/not', + 'intro/and', + ], + bypassed: [], + }); + values['chipsandcode.progress.v1'] = '[]'; + values['chipsandcode.learning-choices.v1'] = + '{"topics":{"memory":{"skipped":true},"gates":{"skipped":false}}}'; + expect(readJourneyEvidence(storage).completed).not.toContain('missions/nand'); + expect(readJourneyEvidence(storage).bypassed).toEqual(['memory']); + values['chipsandcode.part-one.progress.v1'] = 'null'; + values['chipsandcode.learning-choices.v1'] = '{"arithmetic":{"skipped":true}}'; + expect(readJourneyEvidence(storage).bypassed).toEqual(['arithmetic']); + values['chipsandcode.progress.v1'] = '["nand"]'; + delete values['chipsandcode.signal-intro.v1']; + expect(readJourneyEvidence(storage).completed).toContain('intro/signal'); + values['chipsandcode.signal-intro.v1'] = 'not-observed'; + expect(readJourneyEvidence(storage).completed).not.toContain('intro/signal'); + }); + it('uses no completion when storage is unavailable or has the wrong shape', () => { + expect( + readJourneyEvidence({ + getItem() { + throw new Error('blocked'); + }, + }), + ).toEqual({ completed: [], bypassed: [] }); + expect(readJourneyEvidence({ getItem: () => '7' })).toEqual({ completed: [], bypassed: [] }); + }); +}); + +describe('the accumulating machine', () => { + it('grows the correct parallel branch without crediting unbuilt components', () => { + const fresh = systemEvidence([]); + expect(Object.values(fresh).every((group) => group.count === 0)).toBe(true); + const built = systemEvidence([ + 'missions/not', + 'buses/not16', + 'arithmetic/halfadder', + 'memory/bit', + 'memory/pc', + ]); + expect(built.Logic.pieces).toEqual(['Not', 'Not16']); + expect(built.ALU.count).toBe(1); + expect(built.Memory.pieces).toEqual(['Bit']); + expect(built.CPU.pieces).toEqual(['PC']); + expect(built.ROM.count).toBe(0); + expect(built.Screen).toBeUndefined(); + }); +}); diff --git a/src/lib/journey/progress.ts b/src/lib/journey/progress.ts new file mode 100644 index 0000000..168b778 --- /dev/null +++ b/src/lib/journey/progress.ts @@ -0,0 +1,49 @@ +/** Read legacy evidence defensively. One corrupt optional store must not hide another. */ +export function readJourneyEvidence(storage: Pick): { + completed: string[]; + bypassed: string[]; +} { + const raw = (key: string): string | null => { + try { + return storage.getItem(key); + } catch { + return null; + } + }; + const json = (value: string | null): unknown => { + try { + return JSON.parse(value ?? 'null'); + } catch { + return null; + } + }; + const ids = (value: unknown): string[] => + Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : []; + const gates = ids( + json(raw('chipsandcode.progress.v1') ?? raw('chipsandcode.signal-isles.progress.v1')), + ); + const intro = raw('chipsandcode.signal-intro.v1'); + // Preserve legacy intro evidence, while an explicit direct-entry marker defeats inference. + const introComplete = intro === 'complete' || (intro === null && gates.includes('nand')); + const completed = [ + ...ids(json(raw('chipsandcode.part-one.progress.v1'))), + ...gates.map((id) => `missions/${id}`), + ...(introComplete ? ['intro/signal', 'intro/not', 'intro/and'] : []), + ]; + const choices = json(raw('chipsandcode.learning-choices.v1')); + const bypassed = journeyBypassed(choices); + return { completed: [...new Set(completed)], bypassed }; +} + +export function journeyBypassed(choices: unknown): string[] { + const topics = + choices && typeof choices === 'object' && 'topics' in choices ? choices.topics : choices; + return topics && typeof topics === 'object' && !Array.isArray(topics) + ? Object.entries(topics) + .filter( + ([, value]) => + value && typeof value === 'object' && 'skipped' in value && value.skipped === true, + ) + .map(([id]) => id) + : []; +} diff --git a/src/lib/journey/runtime.ts b/src/lib/journey/runtime.ts new file mode 100644 index 0000000..64238f5 --- /dev/null +++ b/src/lib/journey/runtime.ts @@ -0,0 +1,59 @@ +import { assemble, createMachine, type HackMachine, type StepTrace } from '#lib/computer/hack.js'; + +/** Supplied example; never installed as the learner's answer or awarded completion. */ +export const journeyFillExample = `// Supplied demonstration: the CPU repeatedly reads KBD and writes SCREEN. +(LOOP) +@KBD +D=M +@WHITE +D;JEQ +@color +M=-1 +@START +0;JMP +(WHITE) +@color +M=0 +(START) +@SCREEN +D=A +@pointer +M=D +(PAINT) +@color +D=M +@pointer +A=M +M=D +@pointer +M=M+1 +D=M +@KBD +D=D-A +@PAINT +D;JLT +@LOOP +0;JMP`; +export function loadJourneyProgram(source = journeyFillExample) { + const assembly = assemble(source); + return { assembly, machine: createMachine(assembly.words) }; +} +export interface RunEvidence { + read: StepTrace | null; + write: StepTrace | null; + executed: number; +} +/** Bounded work for one deliberate interaction; keyboard never writes screen memory directly. */ +export function runJourneyProgram(machine: HackMachine, key: number, budget = 250000): RunEvidence { + machine.setKeyboard(key); + let read: StepTrace | null = null, + write: StepTrace | null = null, + executed = 0; + for (; executed < budget && !machine.halted; executed++) { + const trace = machine.step(); + if (!trace) break; + if (trace.addressM === 24576 && (trace.instruction & 0x9000) === 0x9000) read = trace; + if (trace.writeM && trace.addressM >= 16384 && trace.addressM < 24576) write = trace; + } + return { read, write, executed }; +} diff --git a/src/lib/journey/schematicTypes.ts b/src/lib/journey/schematicTypes.ts new file mode 100644 index 0000000..546a7d2 --- /dev/null +++ b/src/lib/journey/schematicTypes.ts @@ -0,0 +1,29 @@ +export type Side = 'left' | 'right' | 'top' | 'bottom'; +export interface DiagramNode { + id: string; + label: string; + detail?: string; + x: number; + y: number; + w: number; + h: number; + kind?: 'input' | 'output' | 'chip' | 'supplied' | 'control'; +} +export interface DiagramEdge { + from: string; + to: string; + label?: string; + fromSide?: Side; + toSide?: Side; + fromOffset?: number; + toOffset?: number; + via?: [number, number][]; + labelAt?: [number, number]; +} +export interface ConnectedDiagram { + width: number; + height: number; + nodes: DiagramNode[]; + edges: DiagramEdge[]; + notes?: { text: string; x: number; y: number }[]; +} diff --git a/src/lib/journey/schematics.test.ts b/src/lib/journey/schematics.test.ts new file mode 100644 index 0000000..9d72da4 --- /dev/null +++ b/src/lib/journey/schematics.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { journeySteps, getJourneyStep } from './data'; +import { basicDiagram } from './basicDiagrams'; +import { advancedDiagram } from './advancedDiagrams'; + +describe('connected educational schematics', () => { + it('keeps every visible part connected in desktop and mobile compositions', () => { + for (const small of [false, true]) + for (const step of journeySteps) { + const diagram = basicDiagram(step, small) ?? advancedDiagram(step, small); + if (!diagram) continue; + const ids = new Set(diagram.nodes.map((node) => node.id)); + expect(ids.size).toBe(diagram.nodes.length); + for (const node of diagram.nodes) { + expect( + diagram.edges.some((edge) => edge.from === node.id || edge.to === node.id), + `${step.id}: connected ${node.id}`, + ).toBe(true); + expect(node.x).toBeGreaterThanOrEqual(0); + expect(node.y).toBeGreaterThanOrEqual(75); + expect(node.x + node.w).toBeLessThanOrEqual(diagram.width); + expect(node.y + node.h).toBeLessThan(diagram.height); + } + for (const edge of diagram.edges) { + expect(ids.has(edge.from)).toBe(true); + expect(ids.has(edge.to)).toBe(true); + for (const [x, y] of edge.via ?? []) { + expect(x).toBeGreaterThanOrEqual(0); + expect(x).toBeLessThanOrEqual(diagram.width); + expect(y).toBeGreaterThanOrEqual(0); + expect(y).toBeLessThanOrEqual(diagram.height); + } + } + } + }); + it('shows sum and carry as separate consequences of the input bits', () => { + const half = basicDiagram(getJourneyStep('arithmetic/halfadder'), false)!; + expect(half.edges).toEqual( + expect.arrayContaining([ + expect.objectContaining({ from: 'inputs', to: 'xor' }), + expect.objectContaining({ from: 'inputs', to: 'and' }), + expect.objectContaining({ from: 'xor', to: 'sum' }), + expect.objectContaining({ from: 'and', to: 'carry' }), + ]), + ); + const full = basicDiagram(getJourneyStep('arithmetic/fulladder'), true)!; + expect(full.edges).toEqual( + expect.arrayContaining([ + expect.objectContaining({ from: 'first', to: 'second', label: 'sum' }), + expect.objectContaining({ from: 'first', to: 'or' }), + expect.objectContaining({ from: 'second', to: 'or' }), + expect.objectContaining({ from: 'or', to: 'carry' }), + ]), + ); + }); + it('keeps supplied NAND as a primitive and shows fan-out when building NOT', () => { + const nand = basicDiagram(getJourneyStep('missions/nand'), true)!; + expect(nand.nodes.find((node) => node.id === 'gate')?.kind).toBe('supplied'); + const not = basicDiagram(getJourneyStep('missions/not'), false)!; + const wires = not.edges.filter((edge) => edge.from === 'in' && edge.to === 'nand'); + expect(wires.map((edge) => edge.toOffset)).toEqual([-30, 30]); + }); +}); diff --git a/src/lib/journey/system.ts b/src/lib/journey/system.ts new file mode 100644 index 0000000..3df9e41 --- /dev/null +++ b/src/lib/journey/system.ts @@ -0,0 +1,30 @@ +import { journeySteps } from './data'; +/** Learning branches, not a fabricated single chain of physical containment. */ +export function systemEvidence(completed: readonly string[]) { + const groups: Record = { + Logic: journeySteps + .filter((step) => ['signals', 'gates', 'buses'].includes(step.layer)) + .map((step) => step.id), + ALU: journeySteps.filter((step) => step.layer === 'arithmetic').map((step) => step.id), + Memory: journeySteps + .filter((step) => step.layer === 'memory' && step.id !== 'memory/pc') + .map((step) => step.id) + .concat('architecture/memory'), + CPU: ['memory/pc', 'architecture/cpu'], + ROM: journeySteps + .filter((step) => ['machine-language', 'assembler'].includes(step.layer)) + .map((step) => step.id), + }; + return Object.fromEntries( + Object.entries(groups).map(([name, ids]) => [ + name, + { + count: ids.filter((id) => completed.includes(id)).length, + total: ids.length, + pieces: journeySteps + .filter((step) => ids.includes(step.id) && completed.includes(step.id)) + .map((step) => step.label), + }, + ]), + ); +} diff --git a/src/lib/journey/treatments.ts b/src/lib/journey/treatments.ts new file mode 100644 index 0000000..262f209 --- /dev/null +++ b/src/lib/journey/treatments.ts @@ -0,0 +1,311 @@ +import type { Diagram } from './data'; + +type Treatment = [Diagram, string[], string, string, string, number?]; +// Every task is explicit: changing the curriculum must also change this teaching map. +export const treatments: Record = { + 'intro/signal': [ + 'signal', + ['0', '1'], + 'One wire can carry either value.', + 'A changing signal becomes a readable bit.', + 'A gate can transform that value.', + ], + 'intro/not': [ + 'gate', + ['signal'], + 'A signal carries 0 or 1.', + 'NOT gives the opposite value at its output.', + 'Combine more than one input.', + ], + 'intro/and': [ + 'gate', + ['signal a', 'signal b'], + 'NOT transforms one input.', + 'AND asks whether both inputs are 1.', + 'NAND combines AND with inversion.', + ], + 'missions/nand': [ + 'gate', + ['AND behavior', 'NOT behavior'], + 'You have observed AND and NOT.', + 'The supplied NAND produces the opposite of AND.', + 'Reuse NAND to construct every gate in this layer.', + ], + 'missions/not': [ + 'gate', + ['Nand'], + 'NAND accepts two input pins.', + 'One signal feeding both pins becomes an inverter.', + 'Invert a NAND result to build AND.', + ], + 'missions/and': [ + 'gate', + ['Nand', 'Not'], + 'You can invert a value.', + 'Combining gates restores the AND behavior.', + 'Compose more complex conditions.', + ], + 'missions/or': [ + 'gate', + ['Not', 'Nand'], + 'Inversion changes the question a circuit asks.', + 'Either input can now produce a high output.', + 'Combine conditions to detect a difference.', + ], + 'missions/xor': [ + 'gate', + ['Or', 'And', 'Not'], + 'OR includes the case where both inputs are high.', + 'XOR isolates the cases where inputs differ.', + 'The sum bit of a half adder uses this behavior.', + ], + 'missions/mux': [ + 'select', + ['Not', 'And', 'Or'], + 'Gates can enable and combine paths.', + 'One selector chooses between two data inputs.', + 'Use the same choice across a 16-bit word.', + 2, + ], + 'missions/dmux': [ + 'distribute', + ['Not', 'And'], + 'A selector can enable one path.', + 'One input is routed to either of two outputs.', + 'Route a write signal to one memory location.', + 2, + ], + 'buses/not16': [ + 'parallel', + ['Not'], + 'One NOT flips one bit.', + 'Sixteen independent lanes invert a word.', + 'Apply logic to whole words.', + 16, + ], + 'buses/and16': [ + 'parallel', + ['And'], + 'A word is sixteen related wires.', + 'Matching positions combine, with no carry.', + 'The ALU will offer a bitwise AND operation.', + 16, + ], + 'buses/or16': [ + 'parallel', + ['Or'], + 'Bitwise logic keeps positions separate.', + 'Each lane merges the corresponding input bits.', + 'Compose word-level logic with the same gates.', + 16, + ], + 'buses/mux16': [ + 'parallel', + ['Mux'], + 'A Mux chooses one data bit.', + 'One selector controls sixteen choices together.', + 'Choose complete operands and results.', + 16, + ], + 'buses/or8way': [ + 'reduce', + ['Or'], + 'OR merges two conditions.', + 'An OR tree reduces eight bits to one answer.', + 'Detect whether any result bit is set.', + 8, + ], + 'buses/mux4way16': [ + 'select', + ['Mux16'], + 'Mux16 chooses between two words.', + 'Two selector bits choose one of four words.', + 'Build larger selectors from smaller ones.', + 4, + ], + 'buses/mux8way16': [ + 'select', + ['Mux4Way16', 'Mux16'], + 'Four-way selection is reusable.', + 'A final choice combines two four-word groups.', + 'Select a word read from a memory bank.', + 8, + ], + 'buses/dmux4way': [ + 'distribute', + ['DMux'], + 'DMux distributes one enable signal.', + 'Two decisions choose one of four destinations.', + 'Use address bits to direct a write.', + 4, + ], + 'buses/dmux8way': [ + 'distribute', + ['DMux', 'DMux4Way'], + 'A routing tree can be composed.', + 'Three selector bits open one of eight paths.', + 'Enable exactly one of eight registers.', + 8, + ], + 'arithmetic/halfadder': [ + 'adder', + ['Xor', 'And'], + 'XOR detects difference; AND detects two ones.', + 'Two outputs represent a two-bit sum: carry and sum.', + 'Add an incoming carry from another column.', + ], + 'arithmetic/fulladder': [ + 'adder', + ['HalfAdder', 'HalfAdder', 'Or'], + 'A half adder adds two bits.', + 'A third input carries work from the previous column.', + 'Chain columns to add whole words.', + ], + 'arithmetic/add16': [ + 'adder', + ['FullAdder'], + 'Each full adder accepts and produces a carry.', + 'Carry flows from bit 0 toward bit 15.', + 'Word addition becomes one reusable component.', + 16, + ], + 'arithmetic/inc16': [ + 'adder', + ['Add16', 'constant 1'], + 'Add16 adds whole words.', + 'A fixed second operand advances a value by one.', + 'Advance a program counter.', + ], + 'arithmetic/alu': [ + 'alu', + ['Mux16', 'Not16', 'And16', 'Add16', 'Or8Way'], + 'Word logic, arithmetic, and selection are available.', + 'Control bits choose a calculation; flags describe its result.', + 'The CPU uses this result to store values and decide jumps.', + ], + 'memory/bit': [ + 'state', + ['Mux', 'DFF · supplied'], + 'A Mux chooses a new value or feedback.', + 'The clock separates the stored value from its next value.', + 'Place sixteen memories side by side.', + ], + 'memory/register': [ + 'parallel', + ['Bit'], + 'One Bit retains state when load is low.', + 'Sixteen bits share load and clock to remember a word.', + 'Address a collection of stored words.', + 16, + ], + 'memory/ram8': [ + 'bank', + ['Register', 'DMux8Way', 'Mux8Way16'], + 'Registers store words; routing selects paths.', + 'Three address bits select one of eight words.', + 'Group banks to expand memory.', + 8, + ], + 'memory/ram64': [ + 'bank', + ['RAM8'], + 'RAM8 is now a reusable bank.', + 'The address selects a bank and a word inside it.', + 'Repeat the hierarchy for 512 words.', + 64, + ], + 'memory/ram512': [ + 'bank', + ['RAM64'], + 'A bank exposes the same read/write interface.', + 'Nine address bits reach 512 words through two decisions.', + 'Reuse the interface at a larger capacity.', + 512, + ], + 'memory/ram4k': [ + 'bank', + ['RAM512'], + 'Smaller banks keep the structure manageable.', + 'Twelve address bits reach 4,096 stored words.', + 'Build the RAM region of the computer.', + 4096, + ], + 'memory/ram16k': [ + 'bank', + ['RAM4K'], + 'Four 4K banks can share one interface.', + 'Fourteen address bits reach 16,384 words.', + 'Combine RAM with memory-mapped devices.', + 16384, + ], + 'memory/pc': [ + 'counter', + ['Register', 'Inc16', 'Mux16'], + 'Registers remember; an incrementer advances.', + 'Priority selects reset, load, increment, or hold.', + 'The PC will select the next instruction from ROM.', + ], + 'machine-language/instruction': [ + 'instruction', + ['A instruction', 'C instruction'], + 'The machine needs values and control signals.', + 'Sixteen bits specify an address or a computation.', + 'Sequence instructions into a program.', + ], + 'machine-language/mult': [ + 'loop', + ['Add', 'Store', 'Jump'], + 'Instructions can calculate, store, and branch.', + 'A loop reuses addition to perform multiplication.', + 'Use a program to respond to an input device.', + ], + 'machine-language/fill': [ + 'devices', + ['Keyboard · supplied', 'CPU', 'Screen · supplied'], + 'Programs read and write addressed memory.', + 'The CPU reads a key and writes screen words; pixels follow.', + 'Build the memory interface that connects these devices.', + ], + 'architecture/memory': [ + 'address', + ['RAM16K', 'Screen · supplied', 'Keyboard · supplied'], + 'RAM stores words and routing decodes addresses.', + 'One address space selects RAM, screen, or keyboard.', + 'Connect the CPU through this single memory interface.', + ], + 'architecture/cpu': [ + 'cpu', + ['ARegister', 'DRegister', 'ALU', 'PC'], + 'Arithmetic and state are two branches of the machine.', + 'Instruction bits coordinate registers, calculation, and jumps.', + 'Connect this processor to program ROM and data memory.', + ], + 'architecture/computer': [ + 'computer', + ['ROM32K · supplied', 'CPU', 'Memory'], + 'The CPU has separate instruction and data paths.', + 'The PC reads ROM; CPU memory pins reach RAM and devices.', + 'Translate readable programs into its instruction words.', + ], + 'assembler/encode': [ + 'encode', + ['assembly', 'encoding table', 'ROM words'], + 'The CPU executes bits with fixed meanings.', + 'Readable operations become the same 16-bit instructions.', + 'Replace numeric addresses with useful names.', + ], + 'assembler/symbols': [ + 'symbols', + ['labels → ROM', 'variables → RAM', 'symbol table'], + 'Instructions and data each have addresses.', + 'Two passes resolve names without allocating ROM for labels.', + 'Combine symbol resolution with instruction encoding.', + ], + 'assembler/assembler': [ + 'translator', + ['clean source', 'resolve symbols', 'encode words'], + 'You can resolve names and encode instructions.', + 'Your translator turns a whole program into machine words.', + 'Run those words on the computer; keep exploring in Tools.', + ], +}; diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 4733164..84d6048 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -27,7 +27,7 @@ Break down the magic of computers — Chips and Code
    From 7741de32c15ebf371cb5ab0f24fa6d5adaa0fe92 Mon Sep 17 00:00:00 2001 From: Jakub Duras Date: Sun, 15 Nov 2026 01:47:50 +0100 Subject: [PATCH 2/2] Clarify instruction and memory paths and improve mobile diagram labels --- cypress/e2e/journey.cy.ts | 4 ++++ src/lib/journey/ConnectedScene.svelte | 3 +++ src/lib/journey/Scene.svelte | 13 +++++++++---- src/lib/journey/advancedDiagrams.ts | 14 ++++++++------ src/lib/journey/basicDiagrams.ts | 8 ++++---- 5 files changed, 28 insertions(+), 14 deletions(-) diff --git a/cypress/e2e/journey.cy.ts b/cypress/e2e/journey.cy.ts index f499e76..b1f7cc7 100644 --- a/cypress/e2e/journey.cy.ts +++ b/cypress/e2e/journey.cy.ts @@ -180,6 +180,7 @@ describe('A growing computer at every learning step', () => { 'assembler/assembler', ]) { pick(id); + cy.findByRole('button', { name: 'Inside this piece' }).click(); cy.get('.scene-stage') .should('have.attr', 'data-motion', 'reduced') .and('not.have.class', 'revealing'); @@ -192,6 +193,9 @@ describe('A growing computer at every learning step', () => { .focus() .type('{enter}'); scene().should('have.attr', 'data-journey-view', 'system'); + pick('buses/not16'); + cy.findByRole('button', { name: /Zoom out/ }).click(); + scene().screenshot('journey-mobile-reduced-system-not16'); cy.injectAxe(); checkAccessibility(); expectNoPageOverflow(); diff --git a/src/lib/journey/ConnectedScene.svelte b/src/lib/journey/ConnectedScene.svelte index 9ccfd7b..637d8bf 100644 --- a/src/lib/journey/ConnectedScene.svelte +++ b/src/lib/journey/ConnectedScene.svelte @@ -151,6 +151,9 @@ .wire-label { font-size: 11px; fill: #d0c1f2; + } + .wire-label, + .diagram-note { paint-order: stroke; stroke: #0d111c; stroke-width: 5px; diff --git a/src/lib/journey/Scene.svelte b/src/lib/journey/Scene.svelte index 214eea0..eb74d95 100644 --- a/src/lib/journey/Scene.svelte +++ b/src/lib/journey/Scene.svelte @@ -153,7 +153,7 @@ {#if keepPiece} {item.label} · reusable piece{item.label} · {small ? 'chip' : 'reusable piece'} @@ -269,9 +269,12 @@ {#each Array.from({ length: gridCount }, (_, i) => i) as i (i)} {@const x = 40 + (i % columns) * cellWidth} {@const y = 105 + Math.floor(i / columns) * (small ? 58 : 67)} - + - + {step.parts[0]} {step.diagram === 'parallel' ? `bit ${i}` : `bank ${i}`}feedback keeps the stored value DFF is supplied · state changes at the edge{small + ? 'supplied DFF · capture at edge' + : 'DFF is supplied · state changes at the edge'} {:else} {#each parts as part, i (i)} diff --git a/src/lib/journey/advancedDiagrams.ts b/src/lib/journey/advancedDiagrams.ts index f476389..43d3cfb 100644 --- a/src/lib/journey/advancedDiagrams.ts +++ b/src/lib/journey/advancedDiagrams.ts @@ -50,7 +50,7 @@ function alu(small: boolean): ConnectedDiagram { node('y', 'Prepare y', 30, 330, 150, 'zy: zero; ny: invert'), node('and', 'And16', 270, 120, 135, 'x AND y'), node('add', 'Add16', 270, 330, 135, 'x + y'), - node('select', 'Mux16', 465, 225, 130, 'f: choose operation'), + node('select', 'Mux16', 465, 225, 130, 'f: AND or sum'), node('out', 'out[16]', 625, 225, 130, 'no: keep / invert', 'output'), node('flags', 'zr / ng', 625, 390, 130, 'zero / sign bit'), ], @@ -118,8 +118,8 @@ function bank(step: JourneyStep, small: boolean): ConnectedDiagram { width: 300, height: 780, nodes: [ - node('address', 'address', 15, 100, 125, `${Math.log2(words)} bits`, 'input'), - node('write', 'in + load', 160, 100, 125, 'shared write data', 'input'), + node('address', 'addr + load', 15, 100, 125, `${Math.log2(words)} address bits`, 'input'), + node('write', 'in[16]', 160, 100, 125, 'shared write data', 'input'), node('decode', 'Write select', 15, 245, 125, `1 of ${banks} enables`, 'control'), node('first', 'Bank 0', 15, 390, 125, detail), node('last', `Bank ${banks - 1}`, 160, 390, 125, detail), @@ -171,9 +171,9 @@ function bank(step: JourneyStep, small: boolean): ConnectedDiagram { width: 780, height: 560, nodes: [ - node('address', 'address', 25, 105, 130, `${Math.log2(words)} bits`, 'input'), + node('address', 'addr + load', 25, 105, 130, `${Math.log2(words)} address bits`, 'input'), node('decode', 'Write select', 205, 105, 140, `1 of ${banks} enables`, 'control'), - node('write', 'in + load', 25, 325, 130, 'shared write data', 'input'), + node('write', 'in[16]', 25, 325, 130, 'shared write data', 'input'), node('first', 'Bank 0', 400, 190, 140, detail), node('last', `Bank ${banks - 1}`, 400, 365, 140, detail), node('mux', 'Read Mux', 605, 275, 140, 'address selects'), @@ -288,6 +288,7 @@ function cpu(small: boolean): ConnectedDiagram { [275, 625], ], }), + edge('decode', 'operands', { label: 'A immediate' }), edge('operands', 'alu'), edge('alu', 'dest'), edge('dest', 'operands', { @@ -346,6 +347,7 @@ function cpu(small: boolean): ConnectedDiagram { ], edges: [ edge('instruction', 'decode'), + edge('decode', 'operands', { label: 'A immediate' }), edge('operands', 'alu'), edge('alu', 'dest'), edge('decode', 'alu', { @@ -443,7 +445,7 @@ function translation(symbols: boolean, small: boolean): ConnectedDiagram { ], edges: [ edge('source', 'first'), - edge('first', 'second', { label: 'instructions' }), + edge('first', 'second', { label: 'instructions', labelAt: [392.5, 105] }), edge('first', 'table', { label: 'ROM labels', labelAt: [335, 245] }), edge('table', 'second', { fromSide: 'right', diff --git a/src/lib/journey/basicDiagrams.ts b/src/lib/journey/basicDiagrams.ts index 0adc604..11b1cd0 100644 --- a/src/lib/journey/basicDiagrams.ts +++ b/src/lib/journey/basicDiagrams.ts @@ -171,12 +171,12 @@ export function basicDiagram(step: JourneyStep, small: boolean): ConnectedDiagra return graph( [ node('ab', 'a, b', left, 85, 'input bits', 'input'), - node('c', 'c', right, 85, 'carry from bit below', 'input'), + node('c', 'c', right, 85, 'incoming carry', 'input'), node('first', 'HalfAdder', left, 195, 'a + b'), node('second', 'HalfAdder', right, 195, 'partial sum + c'), node('or', 'Or', center, 320, 'combine carries'), - node('carry', 'carry', left, 435, 'to the next column', 'output'), - node('sum', 'sum', right, 435, 'this column’s bit', 'output'), + node('carry', 'carry', left, 435, 'next column', 'output'), + node('sum', 'sum', right, 435, 'this result bit', 'output'), ], [ edge('ab', 'first'), @@ -206,7 +206,7 @@ export function basicDiagram(step: JourneyStep, small: boolean): ConnectedDiagra node('in', 'in[16]', left, 90, 'input word', 'input'), node('one', '1', right, 90, 'constant word', 'input'), node('add', 'Add16', center, 220, 'add the operands'), - node('out', 'out[16]', center, 350, '(in + 1) mod 65536', 'output'), + node('out', 'out[16]', center, 350, 'wraps at 65536', 'output'), ], [edge('in', 'add'), edge('one', 'add'), edge('add', 'out')], 450,