diff --git a/src/i18n/en.ts b/src/i18n/en.ts index c35da6a..0b2f91a 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -6,7 +6,7 @@ const listOf = (names: readonly string[]) => names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`; -const digits = (count: number) => (count === 1 ? "1 digit" : `${count} digits`); +const bitCount = (count: number) => (count === 1 ? "1 bit" : `${count} bits`); const themOf = (names: readonly string[]) => names.length === 1 ? "it" : "them"; @@ -36,7 +36,7 @@ const stageTexts: Record = { }, "half-adder": { title: "Adding one digit", - goal: "From here on, think of ON as 1 and OFF as 0, and the tables write them that way too. Then A + B is 0, 1 or 2. Binary writes numbers with only 0 and 1: just as 9 + 1 carries over and becomes 10 in everyday numbers, 1 + 1 carries over and becomes 10 in binary. So 0, 1 and 2 are 00, 01 and 10 in two digits. Output the left digit (the twos digit) to C and the right digit (the ones digit) to S. C is called the carry and S the sum, and this circuit is called a half adder.", + goal: "From here on, think of ON as 1 and OFF as 0, and the tables write them that way too. Then A + B is 0, 1 or 2. Binary writes numbers with only 0 and 1: just as 9 + 1 carries over and becomes 10 in everyday numbers, 1 + 1 carries over and becomes 10 in binary. So 0, 1 and 2 are 00, 01 and 10 in two digits. A digit of a binary number is called a bit. Output the left digit (the twos digit) to C and the right digit (the ones digit) to S. C is called the carry and S the sum, and this circuit is called a half adder.", steps: [], }, "full-adder": { @@ -59,11 +59,22 @@ const stageTexts: Record = { goal: "After pressing the play button, a number with an arrow button on each side appears at the bottom. The number is called the time step, and the right arrow goes to the next one. The circuit runs one time step at a time. Make Count go up by 1 at each time step, and go back to 0000 after 1111. 0000 to 1111 are 0 to F in hexadecimal.", steps: [ "Place a FlipFlop. A FlipFlop outputs what it received at the time step before, and 0 at the first time step. Connect its output to Count and to the 7seg at the top right.", - "Place a Const. A Const always outputs the value written in it. Change 00000000 in its box to 0001 and press Apply (four digits, to match the B it connects to).", + 'Place a Const. A Const always outputs the value written in it. Change 00000000 in its box to 0001 and press Apply (four bits, to match the B it connects to). The "4 bits" below the box is the number of bits of the value.', 'Place "Adding four digits". Connect the output of the FlipFlop to its A, the Const to its B, and its S to the input of the FlipFlop. Then the number the FlipFlop outputs plus 1 comes out of the FlipFlop at the next time step. C is not used.', 'Press the play button and go through the time steps with the right arrow. Press "Auto" to go on by itself, one time step a second. The circuit works when the Display at the top right shows 0 to F in turn.', ], }, + "decimal-digit": { + title: "One decimal digit", + goal: "Writing numbers with 0 to 9, carrying over after 9 as everyday numbers do, is called decimal. Make Count go up by 1 only at the time steps when Up is ON, and go back to 0000 after 1001. 1001 is 9, 8 plus 1. At a time step when Count is 1001 and Up is ON, make Carry turn ON: it tells the digit above to go up. Check turns Up ON for time steps 1 to 9, OFF for 10 and 11, and ON again from 12.", + steps: [ + 'The Const, Broadcast and And on the left send 0001 to B of "Adding four digits" when Up is ON, and 0000 when it is OFF. A Broadcast spreads a one-bit value over several bits: 1111 for ON, 0000 for OFF. An And given values of several bits makes each bit 1 only where both are 1.', + "Make Carry. From 0000 to 1001, only 1001 has 1 in both the eights and the ones digit. Join the top pin (eights) and the bottom pin (ones) on the right of the Decompose at the bottom with an And, join its output and Up with another And, and connect that to Carry.", + "Place a Broadcast and click the pin on its right. The box that appears is the bit width, the number of bits of the output. Change its 1 to 4 and press Apply, and the output has four bits. Do this before connecting it.", + "Go back to 0000 when Carry is ON. S is not connected to the FlipFlop yet. Connect the output of the And that goes to Carry to a Not as well to turn it over, spread it to four bits with that Broadcast, join it and S with an And, and connect the And to the input of the FlipFlop.", + "While playing, click Up to switch it ON and OFF, and go through the time steps with the right arrow. The circuit works when the number on the Display goes up only while Up is ON, and goes back to 0 after 9.", + ], + }, }; export const en = { @@ -83,13 +94,12 @@ export const en = { XOR: "ON when exactly one input is ON", TRUE: "Always ON", FALSE: "Always OFF", - DECOMPOSE: - "Splits a number of several digits, from the highest digit down", - AGGREGATE: - "Joins values into one number, the upper pins as the higher digits", + DECOMPOSE: "Splits a value of several bits, from the highest digit down", + AGGREGATE: "Joins values into one, the upper pins as the higher digits", FLIPFLOP: "Outputs what it received at the time step before (0 at the first time step)", CONST: "Always outputs the value written in it", + BROADCAST: "Repeats a one-bit value over several bits", }, about: (name: string) => `About ${name}`, ofStage: "Available parts", @@ -186,7 +196,7 @@ export const en = { missingPin: (pinType: "input" | "output", pinName: string) => `There is no ${pinType} pin named ${pinName}. "Reset this stage" brings back how the stage started.`, wrongBitWidth: (pinName: string, expected: number, actual: number) => - `${pinName} should have ${digits(expected)}, but it has ${digits(actual)}. Check what it is connected to.`, + `${pinName} should have ${bitCount(expected)}, but it has ${bitCount(actual)}. Check what it is connected to.`, wrongOutput: ( inputs: readonly { name: string; value: string }[], pinName: string, diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index c02fc73..a657f16 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -21,10 +21,11 @@ export const ja: Messages = { XOR: "片方だけが ON のとき ON", TRUE: "いつも ON", FALSE: "いつも OFF", - DECOMPOSE: "何桁もある数を、上の桁から順に分ける", - AGGREGATE: "上のピンを大きい桁として、1つの数にまとめる", + DECOMPOSE: "何ビットもある値を、上の桁から順に分ける", + AGGREGATE: "上のピンを上の桁として、値を1つにまとめる", FLIPFLOP: "1つ前のステップで受け取った値を出す(最初のステップでは 0)", CONST: "中に書いた値をいつも出す", + BROADCAST: "1ビットの値を、同じ値が並んだ何ビットもの値に広げる", }, about: (name) => `${name} について`, ofStage: "使える部品", @@ -120,7 +121,7 @@ export const ja: Messages = { missingPin: (pinType, pinName) => `${pinName} という名前の${pinType === "input" ? "入力" : "出力"}ピンが見つかりません。「この課題をやり直す」で最初の状態に戻せます。`, wrongBitWidth: (pinName, expected, actual) => - `${pinName} は ${expected}桁のはずですが、${actual}桁になっています。つないだ先を確かめてください。`, + `${pinName} は ${expected}ビットのはずですが、${actual}ビットになっています。つないだ先を確かめてください。`, wrongOutput: (inputs, pinName, expected, actual) => `${inputs.map(({ name, value }) => `${name} が ${value}`).join("、")} のとき、${pinName} は ${expected} になるはずが、${actual === null ? "値がありませんでした" : `${actual} でした`}。`, wrongOutputAtStep: (stepNumber, inputs, pinName, expected, actual) => @@ -160,7 +161,7 @@ export const ja: Messages = { }, "half-adder": { title: "1桁の足し算", - goal: "ここからは ON を 1、OFF を 0 と考え、表もそう書きます。すると、A+B は 0、1、2 のどれかです。2進数では、0 と 1 だけで数を書きます。ふだんの数で 9+1 が繰り上がって 10 になるように、2進数では 1+1 が繰り上がって 10 になります。そのため、0、1、2 は2桁で 00、01、10 です。左の桁(2の位)を C に、右の桁(1の位)を S に出しましょう。C を「桁上がり」、S を「和」といい、この回路を「半加算器」といいます。", + goal: "ここからは ON を 1、OFF を 0 と考え、表もそう書きます。すると、A+B は 0、1、2 のどれかです。2進数では、0 と 1 だけで数を書きます。ふだんの数で 9+1 が繰り上がって 10 になるように、2進数では 1+1 が繰り上がって 10 になります。そのため、0、1、2 は2桁で 00、01、10 です。2進数の1桁を「ビット」といいます。左の桁(2の位)を C に、右の桁(1の位)を S に出しましょう。C を「桁上がり」、S を「和」といい、この回路を「半加算器」といいます。", steps: [], }, "full-adder": { @@ -183,11 +184,22 @@ export const ja: Messages = { goal: "再生ボタンを押すと、下に数字と、その左右に矢印のボタンが出ます。この数字を「ステップ」といい、右の矢印を押すと次のステップに進みます。回路はステップごとに動きます。Count が 1 ステップごとに 1 ずつ増え、1111 の次は 0000 に戻るようにしましょう。0000 から 1111 は、16進数の 0 から F です。", steps: [ "FlipFlop を置きます。FlipFlop は、1つ前のステップで受け取った値を出します。最初のステップでは 0 を出します。FlipFlop の出力を、Count と、右上の 7seg につなぎます。", - "Const を置きます。Const は、中に書いた値をいつも出します。欄の 00000000 を 0001 に書きかえて、「適用」を押します(つなぐ先の B に合わせて、4桁で書きます)。", + "Const を置きます。Const は、中に書いた値をいつも出します。欄の 00000000 を 0001 に書きかえて、「適用」を押します(つなぐ先の B に合わせて、4ビットで書きます)。欄の下の「4 ビット」は、書いた値のビット数です。", "「4桁の足し算」を置き、FlipFlop の出力を A に、Const を B に、S を FlipFlop の入力につなぎます。こうすると、FlipFlop が出している数に 1 を足した数が、次のステップで FlipFlop から出てきます。C は使いません。", "再生ボタンを押し、右の矢印でステップを進めます。「自動」を押すと、1秒に1ステップずつひとりでに進みます。右上の Display に 0 から F が順に出れば、うまく動いています。", ], }, + "decimal-digit": { + title: "10進の1桁", + goal: "ふだんの数のように、0 から 9 までを使い、9 の次で桁が上がる書き方を10進数といいます。Up が ON のステップだけ Count が 1 増え、1001 の次は 0000 に戻るようにしましょう。1001 は、8 と 1 を足した 9 です。Count が 1001 で Up が ON のステップでは、Carry が ON になるようにします。Carry は、上の桁に桁上がりを知らせる合図です。「確かめる」を押すと、Up を 1〜9 ステップ目は ON、10・11 ステップ目は OFF、12 ステップ目からはまた ON にして調べます。", + steps: [ + "左の Const・Broadcast・And は、Up が ON のときは 0001 を、OFF のときは 0000 を「4桁の足し算」の B に送っています。Broadcast は、1ビットの値を、同じ値が並んだ何ビットもの値に広げます(ON なら 1111、OFF なら 0000)。And に何ビットもの値をつなぐと、ビットごとに、両方が 1 のビットだけ 1 になります。", + "Carry を作ります。0000 から 1001 のうち、8の位と1の位がどちらも 1 なのは 1001 だけです。一番下の Decompose の右側の、一番上(8の位)と一番下(1の位)のピンを And でまとめ、その出力と Up をもう1つの And でまとめて、Carry につなぎます。", + "Broadcast を置き、右側のピンをクリックします。出てきた欄はビット幅、つまり出力のビット数です。1 を 4 に書きかえて「適用」を押すと、出力が4ビットになります。線をつなぐ前にしておきます。", + "Carry が ON のときに 0000 に戻す部分を作ります。S はまだ FlipFlop につながっていません。Carry につないだ And の出力を Not にもつないで反対にし、その Broadcast で4ビットに広げ、S と And でまとめて、FlipFlop の入力につなぎます。", + "再生中は、Up をクリックして ON と OFF を切り替えながら、右の矢印でステップを進めます。Up が ON のときだけ Display の数が進み、9 の次に 0 に戻れば、うまく動いています。", + ], + }, }, }, componentProperties: { diff --git a/src/i18n/messages.test.ts b/src/i18n/messages.test.ts index 562e9e3..058d914 100644 --- a/src/i18n/messages.test.ts +++ b/src/i18n/messages.test.ts @@ -160,15 +160,15 @@ describe("the message on a wrong output at a step", () => { }); describe("the message on a pin of the wrong width", () => { - it("counts digits in both languages", () => { + it("counts bits in both languages", () => { expect(messagesByLanguage.en.tutorial.wrongBitWidth("A", 4, 1)).toBe( - "A should have 4 digits, but it has 1 digit. Check what it is connected to.", + "A should have 4 bits, but it has 1 bit. Check what it is connected to.", ); expect(messagesByLanguage.en.tutorial.wrongBitWidth("C", 1, 4)).toBe( - "C should have 1 digit, but it has 4 digits. Check what it is connected to.", + "C should have 1 bit, but it has 4 bits. Check what it is connected to.", ); expect(messagesByLanguage.ja.tutorial.wrongBitWidth("A", 4, 1)).toBe( - "A は 4桁のはずですが、1桁になっています。つないだ先を確かめてください。", + "A は 4ビットのはずですが、1ビットになっています。つないだ先を確かめてください。", ); }); }); diff --git a/src/pages/edit/Editor/renderer/Connection/index.tsx b/src/pages/edit/Editor/renderer/Connection/index.tsx index 094150d..0574ad6 100644 --- a/src/pages/edit/Editor/renderer/Connection/index.tsx +++ b/src/pages/edit/Editor/renderer/Connection/index.tsx @@ -1,7 +1,5 @@ import nullthrows from "nullthrows"; import { useState } from "react"; -import type { Vector2 } from "../../../../../common/vector2"; -import type { CCComponentPinType } from "../../../../../store/componentPin"; import type { CCConnectionId } from "../../../../../store/connection"; import { useStore } from "../../../../../store/react"; import { @@ -12,12 +10,13 @@ import { theme } from "../../../../../style"; import { useComponentEditorStore } from "../../store"; import { stringifySimulationValue } from "../../store/slices/core/index"; import { getCCComponentEditorRendererNodeGeometry } from "../Node/geometry"; +import { + type CCComponentEditorRendererConnectionEndpoint, + connectionPathData, +} from "./path"; import styles from "./style.module.css"; -export type CCComponentEditorRendererConnectionEndpoint = { - direction: CCComponentPinType; - position: Vector2; -}; +export type { CCComponentEditorRendererConnectionEndpoint }; export type CCComponentEditorRendererConnectionCoreProps = { from: CCComponentEditorRendererConnectionEndpoint; @@ -29,13 +28,8 @@ export type CCComponentEditorRendererConnectionCoreProps = { onMouseLeave?: React.MouseEventHandler; }; -const straightGap = 10; const HIT_AREA_STROKE_WIDTH = 12; const VALUE_LABEL_SIZE = { x: 200, y: 24 }; -const polarity: Record = { - input: -1, - output: 1, -}; export function CCComponentEditorRendererConnectionCore({ from, to, @@ -46,19 +40,7 @@ export function CCComponentEditorRendererConnectionCore({ }: CCComponentEditorRendererConnectionCoreProps) { const componentEditorState = useComponentEditorStore()(); - const d = [ - `M ${from.position.x} ${from.position.y}`, - `h ${straightGap * polarity[from.direction]}`, - `C ${[ - from.position.x + 4 * straightGap * polarity[from.direction], - from.position.y, - to.position.x + 4 * straightGap * polarity[to.direction], - to.position.y, - to.position.x + straightGap * polarity[to.direction], - to.position.y, - ].join(" ")}`, - `h ${straightGap * polarity[from.direction]}`, - ].join(" "); + const d = connectionPathData(from, to); return ( <> diff --git a/src/pages/edit/Editor/renderer/Connection/path.test.ts b/src/pages/edit/Editor/renderer/Connection/path.test.ts new file mode 100644 index 0000000..6476341 --- /dev/null +++ b/src/pages/edit/Editor/renderer/Connection/path.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { connectionPathData, pointsOnConnection } from "./path"; + +const from = { direction: "output" as const, position: { x: 0, y: 0 } }; +const to = { direction: "input" as const, position: { x: 100, y: 50 } }; + +describe("connectionPathData", () => { + it("runs straight out of the output, bends, and runs straight into the input", () => { + expect(connectionPathData(from, to)).toBe( + "M 0 0 L 10 0 C 40 0 60 50 90 50 L 100 50", + ); + }); +}); + +describe("pointsOnConnection", () => { + it("follows the curve from where it bends out to where it bends in", () => { + const points = pointsOnConnection(from, to, 4); + + expect(points[0]).toEqual({ x: 10, y: 0 }); + expect(points[2]).toEqual({ x: 50, y: 25 }); + expect(points[4]).toEqual({ x: 90, y: 50 }); + }); +}); diff --git a/src/pages/edit/Editor/renderer/Connection/path.ts b/src/pages/edit/Editor/renderer/Connection/path.ts new file mode 100644 index 0000000..ff9a5f7 --- /dev/null +++ b/src/pages/edit/Editor/renderer/Connection/path.ts @@ -0,0 +1,61 @@ +import type { Vector2 } from "../../../../../common/vector2"; +import type { CCComponentPinType } from "../../../../../store/componentPin"; + +export type CCComponentEditorRendererConnectionEndpoint = { + direction: CCComponentPinType; + position: Vector2; +}; + +/** How far a wire runs straight out of a pin before it bends */ +export const connectionStraightGap = 10; +const polarity: Record = { + input: -1, + output: 1, +}; + +/** A wire leaves `from` straight, bends along a cubic curve and enters `to` straight */ +export function connectionCurve( + from: CCComponentEditorRendererConnectionEndpoint, + to: CCComponentEditorRendererConnectionEndpoint, +): [Vector2, Vector2, Vector2, Vector2] { + const fromSide = connectionStraightGap * polarity[from.direction]; + const toSide = connectionStraightGap * polarity[to.direction]; + return [ + { x: from.position.x + fromSide, y: from.position.y }, + { x: from.position.x + 4 * fromSide, y: from.position.y }, + { x: to.position.x + 4 * toSide, y: to.position.y }, + { x: to.position.x + toSide, y: to.position.y }, + ]; +} + +export function connectionPathData( + from: CCComponentEditorRendererConnectionEndpoint, + to: CCComponentEditorRendererConnectionEndpoint, +): string { + const [start, control1, control2, end] = connectionCurve(from, to); + return [ + `M ${from.position.x} ${from.position.y}`, + `L ${start.x} ${start.y}`, + `C ${control1.x} ${control1.y} ${control2.x} ${control2.y} ${end.x} ${end.y}`, + `L ${to.position.x} ${to.position.y}`, + ].join(" "); +} + +/** Points along the curve of a wire, from `from` to `to` */ +export function pointsOnConnection( + from: CCComponentEditorRendererConnectionEndpoint, + to: CCComponentEditorRendererConnectionEndpoint, + count: number, +): Vector2[] { + const [p0, p1, p2, p3] = connectionCurve(from, to); + return Array.from({ length: count + 1 }, (_, index) => { + const t = index / count; + const u = 1 - t; + const at = (key: "x" | "y") => + u ** 3 * p0[key] + + 3 * u ** 2 * t * p1[key] + + 3 * u * t ** 2 * p2[key] + + t ** 3 * p3[key]; + return { x: at("x"), y: at("y") }; + }); +} diff --git a/src/pages/edit/Editor/renderer/Node/components/Default/geometry.ts b/src/pages/edit/Editor/renderer/Node/components/Default/geometry.ts index 4c40bed..55c27fd 100644 --- a/src/pages/edit/Editor/renderer/Node/components/Default/geometry.ts +++ b/src/pages/edit/Editor/renderer/Node/components/Default/geometry.ts @@ -5,6 +5,17 @@ import type { CCComponentEditorRendererNodeLayoutSource, } from "../../types"; +/** The name of a node is written above its top left corner */ +export const CC_COMPONENT_EDITOR_RENDERER_NODE_TITLE = { + baselineY: -5, + fontSize: 12, +}; + +/** How far above a node its name reaches */ +export const nodeTitleHeight = + CC_COMPONENT_EDITOR_RENDERER_NODE_TITLE.fontSize - + CC_COMPONENT_EDITOR_RENDERER_NODE_TITLE.baselineY; + const width = 100; const gapY = 20; const paddingY = 15; diff --git a/src/pages/edit/Editor/renderer/Node/components/Default/index.tsx b/src/pages/edit/Editor/renderer/Node/components/Default/index.tsx index 2729fbb..79f3605 100644 --- a/src/pages/edit/Editor/renderer/Node/components/Default/index.tsx +++ b/src/pages/edit/Editor/renderer/Node/components/Default/index.tsx @@ -2,10 +2,9 @@ import type { Ref } from "react"; import styles from "../../style.module.css"; import type { CCComponentEditorRendererNodeRendererProps } from "../../types"; -export const CC_COMPONENT_EDITOR_RENDERER_NODE_TITLE = { - baselineY: -5, - fontSize: 12, -}; +import { CC_COMPONENT_EDITOR_RENDERER_NODE_TITLE } from "./geometry"; + +export { CC_COMPONENT_EDITOR_RENDERER_NODE_TITLE }; export function CCComponentEditorRendererNodeDefaultRenderer({ title, diff --git a/src/tutorial/circuit.ts b/src/tutorial/circuit.ts index 5e012c1..f3c29c0 100644 --- a/src/tutorial/circuit.ts +++ b/src/tutorial/circuit.ts @@ -41,6 +41,10 @@ export class StageCircuit { return node; } + setBitWidth(node: CCNode, componentPin: CCComponentPin, bitWidth: number) { + this.split(node, componentPin, [bitWidth]); + } + split(node: CCNode, componentPin: CCComponentPin, widths: readonly number[]) { const [first, ...rest] = widths; const existing = this.store.nodePins.getManyByNodeIdAndComponentPinId( diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts index eb88894..42d5920 100644 --- a/src/tutorial/stages.test.ts +++ b/src/tutorial/stages.test.ts @@ -1,5 +1,11 @@ import nullthrows from "nullthrows"; import { describe, expect, it } from "vitest"; +import { + connectionStraightGap, + pointsOnConnection, +} from "../pages/edit/Editor/renderer/Connection/path"; +import { nodeTitleHeight } from "../pages/edit/Editor/renderer/Node/components/Default/geometry"; +import { getCCComponentEditorRendererNodeGeometry } from "../pages/edit/Editor/renderer/Node/geometry"; import type { CCComponentId } from "../store/component"; import { and, @@ -11,6 +17,8 @@ import { seven_segment, xor, } from "../store/intrinsics/definitions"; +import type { CCNodeId } from "../store/node"; +import type { CCNodePinId } from "../store/nodePin"; import { createTestStore, registerTestComponent, @@ -85,6 +93,100 @@ describe("tutorialStages", () => { ); }); +describe("the layout of every stage", () => { + it.each(tutorialStages.map((s) => [s.id, s] as const))( + "%s places no node or its name over another, also once solved", + (_, laidOut) => { + const store = createTestStore(); + setUpTutorialStage(store, laidOut, titleOf)(); + const rects = store.nodes + .getManyByParentComponentId(laidOut.componentId) + .map((node) => { + const { position, size } = getCCComponentEditorRendererNodeGeometry( + store, + node.id, + ).rect; + return { + name: nullthrows(store.components.get(node.componentId)).name, + position: { x: position.x, y: position.y - nodeTitleHeight }, + size: { x: size.x, y: size.y + nodeTitleHeight }, + }; + }); + const overlaps = rects.flatMap((a, i) => + rects + .slice(i + 1) + .filter( + (b) => + a.position.x < b.position.x + b.size.x && + b.position.x < a.position.x + a.size.x && + a.position.y < b.position.y + b.size.y && + b.position.y < a.position.y + a.size.y, + ) + .map((b) => `${a.name} and ${b.name}`), + ); + + expect(overlaps).toEqual([]); + }, + ); +}); + +describe("the wires every stage starts with", () => { + // Below the straight part of a wire, which starts that far from its own node + const clearance = connectionStraightGap - 4; + + it.each(tutorialStages.map((s) => [s.id, s] as const))( + "%s runs no wire over a node or its name", + (_, laidOut) => { + const store = createTestStore(); + setUpTutorialStage(store, laidOut, titleOf); + const nodes = store.nodes.getManyByParentComponentId(laidOut.componentId); + const nameOf = (nodeId: CCNodeId) => + nullthrows( + store.components.get(nullthrows(store.nodes.get(nodeId)).componentId), + ).name; + const endpointOf = (nodePinId: CCNodePinId) => { + const nodePin = nullthrows(store.nodePins.get(nodePinId)); + return { + nodeId: nodePin.nodeId, + direction: nullthrows(store.componentPins.get(nodePin.componentPinId)) + .type, + position: nullthrows( + getCCComponentEditorRendererNodeGeometry( + store, + nodePin.nodeId, + ).nodePinPositionById.get(nodePinId), + ), + }; + }; + const crossings = store.connections + .getManyByParentComponentId(laidOut.componentId) + .flatMap((connection) => { + const from = endpointOf(connection.from); + const to = endpointOf(connection.to); + const points = pointsOnConnection(from, to, 100); + return nodes + .filter((node) => { + const { position, size } = + getCCComponentEditorRendererNodeGeometry(store, node.id).rect; + return points.some( + (point) => + point.x > position.x - clearance && + point.x < position.x + size.x + clearance && + point.y > position.y - nodeTitleHeight - clearance && + point.y < position.y + size.y + clearance, + ); + }) + .map( + (node) => + `${nameOf(from.nodeId)} to ${nameOf(to.nodeId)} over ${nameOf(node.id)}`, + ); + }); + + expect(crossings).toEqual([]); + }, + ); +}); + describe("setUpTutorialStage", () => { it("hands over the parts of earlier stages, built and named after them", () => { const store = createTestStore(); @@ -120,6 +222,32 @@ describe("the counter stage", () => { }); }); +describe("the decimal digit stage", () => { + it("shows Count held at 1001 while Up is OFF, and the carry back to 0000", () => { + const decimal = nullthrows(findTutorialStage("decimal-digit")); + const table = nullthrows(goalTableOf(decimal.check)); + const digitsOf = (values: boolean[][]) => + values.map((value) => value.map(Number).join("")); + + expect(table.inputs).toEqual(["Up"]); + expect(table.outputs).toEqual(["Count", "Carry"]); + expect( + table.rows.map(({ stepNumber, inputs, outputs }) => [ + stepNumber, + ...digitsOf(inputs), + ...digitsOf(outputs), + ]), + ).toEqual([ + [1, "1", "0000", "0"], + [2, "1", "0001", "0"], + [10, "0", "1001", "0"], + [11, "0", "1001", "0"], + [12, "1", "1001", "1"], + [13, "1", "0000", "0"], + ]); + }); +}); + describe("setUpTutorialStage with decorations", () => { it("places the display only for the player, not inside the part handed over", () => { const fourBit = nullthrows(findTutorialStage("four-bit-adder")); diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index 1b49ab1..645ff50 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -2,6 +2,7 @@ import nullthrows from "nullthrows"; import type { BitNotation } from "../common/bitLabel"; import { bitsOf, numberOf } from "../common/bits"; import type { Rect } from "../common/rect"; +import type { Vector2 } from "../common/vector2"; import type CCStore from "../store"; import { type CCComponent, @@ -12,6 +13,7 @@ import type { CCComponentPin } from "../store/componentPin"; import { aggregate, and, + broadcast, const_, decompose, display, @@ -42,6 +44,7 @@ export const tutorialStageIds = [ "full-adder", "four-bit-adder", "counter", + "decimal-digit", ] as const; export type TutorialStageId = (typeof tutorialStageIds)[number]; export type StageTitleOf = (id: TutorialStageId) => string; @@ -260,12 +263,15 @@ const fullAdderStage = defineStage("full-adder", { const digitCount = 4; -/** A 7seg showing a number on a Display at the top right; returns the 7seg's input */ -function placeNumeral(circuit: StageCircuit): CCNodePinId { - const digit = circuit.place(seven_segment.component.id, { x: 290, y: -250 }); +/** A 7seg at `position` showing a number on a Display right of it; returns the 7seg's input */ +function placeNumeral( + circuit: StageCircuit, + position: Vector2 = { x: 290, y: -250 }, +): CCNodePinId { + const digit = circuit.place(seven_segment.component.id, position); const screen = circuit.place( display.component.id, - { x: 430, y: -250 }, + { x: position.x + 140, y: position.y }, { resolution: { x: 4, y: 7 }, pixelOrder: "row-major" }, ); circuit.connect( @@ -406,6 +412,127 @@ const counterStage = defineStage("counter", { }, }); +const decimalDigitCount = 10; + +/** Count goes up while Up is ON and back to 0 after 9; Carry is ON when it goes back */ +const decimalDigitStage = defineStage("decimal-digit", { + parts: [flipflop, const_, broadcast, and, not, decompose].map( + (part) => part.component.id, + ), + givenParts: ["four-bit-adder"], + tableNotation: "digits", + pinDistance: 560, + check: sequentialCheck( + { inputs: oneBitInputs("Up"), outputs: ["Count", "Carry"] }, + { + initialState: 0, + step: (count, { Up }) => { + const isUp = isOn(Up); + const carries = isUp && count === decimalDigitCount - 1; + return { + outputs: { Count: bitsOf(count, digitCount), Carry: bit(carries) }, + next: carries ? 0 : isUp ? count + 1 : count, + }; + }, + }, + // Up is OFF while Count stays at 9, so a Carry that ignores Up is caught + Array.from({ length: 24 }, (_, index) => ({ + Up: bit(index + 1 < 10 || index + 1 > 11), + })), + [1, 2, 10, 11, 12, 13], + ), + layOut(circuit, { decorate }) { + // Every wire placed here runs left to right, so that none crosses a node + const memory = circuit.place(flipflop.component.id, { x: -150, y: -150 }); + const adder = circuit.place(fourBitAdderStage.componentId, { + x: 100, + y: 0, + }); + const one = circuit.place( + const_.component.id, + { x: -400, y: -300 }, + { mode: "binary", data: bitsOf(1, digitCount) }, + ); + const spreadUp = circuit.place(broadcast.component.id, { x: -400, y: 120 }); + const step = circuit.place(and.component.id, { x: -150, y: 120 }); + const digits = circuit.place(decompose.component.id, { x: 0, y: 250 }); + circuit.setBitWidth(spreadUp, broadcast.outputPin.Out, digitCount); + circuit.split( + digits, + decompose.outputPin.Out, + new Array(digitCount).fill(1), + ); + const count = circuit.pinOf(memory, flipflop.outputPin.Out); + circuit.connect(count, circuit.pin("Count")); + circuit.connect(count, circuit.pinOf(adder, "A")); + circuit.connect(count, circuit.pinOf(digits, decompose.inputPin.In)); + circuit.connect( + circuit.pin("Up"), + circuit.pinOf(spreadUp, broadcast.inputPin.In), + ); + circuit.connect( + circuit.pinOf(one, const_.outputPin.Out), + circuit.pinOf(step, and.inputPin.A), + ); + circuit.connect( + circuit.pinOf(spreadUp, broadcast.outputPin.Out), + circuit.pinOf(step, and.inputPin.B), + ); + circuit.connect( + circuit.pinOf(step, and.outputPin.Out), + circuit.pinOf(adder, "B"), + ); + if (decorate) { + circuit.connect(count, placeNumeral(circuit, { x: 380, y: -330 })); + } + return () => { + const nineAt = circuit.place(and.component.id, { x: 180, y: 290 }); + const carries = circuit.place(and.component.id, { x: 330, y: 200 }); + const stays = circuit.place(not.component.id, { x: 380, y: 40 }); + const spreadStays = circuit.place(broadcast.component.id, { + x: 380, + y: -30, + }); + const kept = circuit.place(and.component.id, { x: -320, y: -120 }); + circuit.setBitWidth(spreadStays, broadcast.outputPin.Out, digitCount); + const digit = (index: number) => + circuit.pinOf(digits, decompose.outputPin.Out, index); + circuit.connect(digit(0), circuit.pinOf(nineAt, and.inputPin.A)); + circuit.connect( + digit(digitCount - 1), + circuit.pinOf(nineAt, and.inputPin.B), + ); + circuit.connect( + circuit.pinOf(nineAt, and.outputPin.Out), + circuit.pinOf(carries, and.inputPin.A), + ); + circuit.connect( + circuit.pin("Up"), + circuit.pinOf(carries, and.inputPin.B), + ); + const carry = circuit.pinOf(carries, and.outputPin.Out); + circuit.connect(carry, circuit.pin("Carry")); + circuit.connect(carry, circuit.pinOf(stays, not.inputPin.In)); + circuit.connect( + circuit.pinOf(stays, not.outputPin.Out), + circuit.pinOf(spreadStays, broadcast.inputPin.In), + ); + circuit.connect( + circuit.pinOf(adder, "S"), + circuit.pinOf(kept, and.inputPin.A), + ); + circuit.connect( + circuit.pinOf(spreadStays, broadcast.outputPin.Out), + circuit.pinOf(kept, and.inputPin.B), + ); + circuit.connect( + circuit.pinOf(kept, and.outputPin.Out), + circuit.pinOf(memory, flipflop.inputPin.In), + ); + }; + }, +}); + export const tutorialStages: readonly TutorialStage[] = [ andStage, aOnlyStage, @@ -414,6 +541,7 @@ export const tutorialStages: readonly TutorialStage[] = [ fullAdderStage, fourBitAdderStage, counterStage, + decimalDigitStage, ]; /** Between the columns of input and output pins, also for a stage without inputs */