From ef4b078eac02d07aed54c5e6def0363f6363094c Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 01:44:28 +0900 Subject: [PATCH 1/9] feat(tutorial): let a stage start with more than its pins, and check pin widths - A stage lays out what it starts with through layOut, which returns how to clear it from there. Decorations are only placed for the player, not inside a part handed over. StageCircuit can now set a node's config and split a pin. - A stage can place its pins further apart (pinDistance). - Check compares each stage pin's bit width with what the stage expects before simulating, and says "A should have 4 digits, but it has 1", instead of the simulation's internal error. - describeFailure moves out of the page into src/tutorial/failure.ts. Co-Authored-By: Claude Opus 5.5 --- src/i18n/en.ts | 2 ++ src/i18n/ja.ts | 2 ++ src/i18n/messages.test.ts | 11 +++++++ src/pages/tutorial/stage.tsx | 36 ++------------------- src/tutorial/check.test.ts | 62 +++++++++++++++++++++++++++++++++++- src/tutorial/check.ts | 42 ++++++++++++++++++++++++ src/tutorial/circuit.ts | 42 ++++++++++++++++++++---- src/tutorial/failure.ts | 41 ++++++++++++++++++++++++ src/tutorial/stages.test.ts | 12 ++++--- src/tutorial/stages.ts | 62 ++++++++++++++++++++++++++++-------- 10 files changed, 254 insertions(+), 58 deletions(-) create mode 100644 src/tutorial/failure.ts diff --git a/src/i18n/en.ts b/src/i18n/en.ts index ff6dd0c..c5d81cf 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -152,6 +152,8 @@ export const en = { backToStages: "Back to the stages", 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 ${expected} digits, but it has ${actual === 1 ? "1 digit" : `${actual} digits`}. 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 ab50e73..450d0d1 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -110,6 +110,8 @@ export const ja: Messages = { backToStages: "課題の一覧へ", missingPin: (pinType, pinName) => `${pinName} という名前の${pinType === "input" ? "入力" : "出力"}ピンが見つかりません。「この課題をやり直す」で最初の状態に戻せます。`, + wrongBitWidth: (pinName, expected, actual) => + `${pinName} は ${expected}けたのはずが、${actual}けたになっています。つないだ先を確かめてください。`, wrongOutput: (inputs, pinName, expected, actual) => `${inputs.map(({ name, value }) => `${name} が ${value}`).join("、")} のとき、${pinName} は ${expected} になるはずが、${actual === null ? "値がありませんでした" : `${actual} でした`}。`, simulationFailed: (detail) => diff --git a/src/i18n/messages.test.ts b/src/i18n/messages.test.ts index 2bf764c..a1b3301 100644 --- a/src/i18n/messages.test.ts +++ b/src/i18n/messages.test.ts @@ -132,6 +132,17 @@ describe("the message on a wrong output", () => { }); }); +describe("the message on a pin of the wrong width", () => { + it("counts digits 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.", + ); + expect(messagesByLanguage.ja.tutorial.wrongBitWidth("A", 4, 1)).toBe( + "A は 4けたのはずが、1けたになっています。つないだ先を確かめてください。", + ); + }); +}); + describe("English messages", () => { it("lists the inputs reset with their bit widths", () => { expect( diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx index c6ea692..4fb9171 100644 --- a/src/pages/tutorial/stage.tsx +++ b/src/pages/tutorial/stage.tsx @@ -16,7 +16,6 @@ import { useNavigate, useParams, } from "react-router"; -import { valueLabel } from "../../common/bitLabel"; import { BitNotationContext } from "../../components/bitNotation"; import { ConfirmDialog } from "../../components/ConfirmDialog"; import { @@ -24,10 +23,8 @@ import { PartDescriptionView, } from "../../components/PartDescription"; import { TruthTableView } from "../../components/TruthTableView"; -import { type Messages, useMessages } from "../../i18n"; -import type CCStore from "../../store"; +import { useMessages } from "../../i18n"; import { definitionByComponentId } from "../../store/intrinsics/definitions"; -import { SimulationNodeError } from "../../store/netlist"; import { StoreScope } from "../../store/react"; import { theme } from "../../style"; import { @@ -35,6 +32,7 @@ import { checkCombinational, truthTableOfCheck, } from "../../tutorial/check"; +import { describeFailure } from "../../tutorial/failure"; import { markStageCleared } from "../../tutorial/progress"; import { getTutorialStageStore, @@ -53,36 +51,6 @@ import CCComponentEditor from "../edit/Editor"; import type { OffersComponent } from "../edit/placement"; import SidePanel from "../edit/SidePanel"; -function describeFailure( - result: Exclude, - store: CCStore, - messages: Messages, -): string { - const texts = messages.tutorial; - switch (result.type) { - case "missingPin": - return texts.missingPin(result.pinType, result.pinName); - case "wrongOutput": - return texts.wrongOutput( - result.inputs.map(({ name, value }) => ({ - name, - value: valueLabel(value), - })), - result.pinName, - valueLabel(result.expected), - result.actual ? valueLabel(result.actual) : null, - ); - case "simulationFailed": - return texts.simulationFailed( - result.error instanceof SimulationNodeError - ? result.error.describe(store, messages.simulation) - : result.error instanceof Error - ? result.error.message - : String(result.error), - ); - } -} - function SectionHeading({ children }: { children: ReactNode }) { return ( { }); }); }); + +describe("checkCombinational on pins of several bits", () => { + const twoBitCheck: CombinationalCheck = { + inputs: [{ name: "A", bitWidth: 2 }], + outputs: ["Out"], + expected: (values) => ({ Out: [...nullthrows(values.A)] }), + }; + + it("tells an input left one bit wide", () => { + const store = createTestStore(); + const component = registerTestComponent(store, "Wide"); + registerTestInputNode(store, component.id, "A"); + registerTestOutputNode(store, component.id, "Out"); + + expect(checkCombinational(store, component.id, twoBitCheck)).toEqual({ + type: "wrongBitWidth", + pinName: "A", + expected: 2, + actual: 1, + }); + }); + + it("tells an output fixed to another width", () => { + const store = createTestStore(); + const component = registerTestComponent(store, "Wide"); + const a = registerTestInputNode(store, component.id, "A"); + const out = registerTestOutputNode(store, component.id, "Out"); + const split = registerTestNode(store, component.id, decompose.component.id); + splitTestNodePin(store, split, decompose.outputPin.Out, [1, 1]); + const joined = registerTestNode( + store, + component.id, + aggregate.component.id, + ); + splitTestNodePin(store, joined, aggregate.inputPin.In, [1, 1, 1]); + connectTestNodePins( + store, + component.id, + a.out, + testNodePin(store, split, decompose.inputPin.In), + ); + connectTestNodePins( + store, + component.id, + testNodePin(store, joined, aggregate.outputPin.Out), + out.in, + ); + + expect(checkCombinational(store, component.id, twoBitCheck)).toEqual({ + type: "wrongBitWidth", + pinName: "Out", + expected: 2, + actual: 3, + }); + }); +}); diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts index 291a767..6a96534 100644 --- a/src/tutorial/check.ts +++ b/src/tutorial/check.ts @@ -3,6 +3,7 @@ import type CCStore from "../store"; import type { CCComponentId } from "../store/component"; import type { CCComponentPinId } from "../store/componentPin"; import type { TruthTable } from "../store/intrinsics/truthTable"; +import { DEFAULT_SIMULATION_BIT_WIDTH } from "../store/netlist"; import type { CCNodePinId } from "../store/nodePin"; import simulateComponent, { type SimulationFrame, @@ -21,6 +22,12 @@ export type CombinationalCheck = { export type CheckResult = | { type: "passed" } | { type: "missingPin"; pinType: "input" | "output"; pinName: string } + | { + type: "wrongBitWidth"; + pinName: string; + expected: number; + actual: number; + } | { type: "simulationFailed"; error: unknown } | { type: "wrongOutput"; @@ -109,6 +116,41 @@ export function checkCombinational( outputNodePinIds.set(name, pin.implementation); } + // A pin whose width nothing fixes is simulated as one bit wide + const bitWidthOf = (nodePinId: CCNodePinId) => { + const status = store.nodePins.getNodePinBitWidthStatus(nodePinId); + return status.isFixed ? status.bitWidth : DEFAULT_SIMULATION_BIT_WIDTH; + }; + const someExpected = check.expected( + nullthrows(inputCombinations(check.inputs).next().value), + ); + const expectedBitWidths = [ + ...check.inputs.map(({ name, bitWidth }) => ({ + name, + bitWidth, + nodePinId: nullthrows( + store.componentPins.get(nullthrows(inputPinIds.get(name))) + ?.implementation, + ), + })), + ...check.outputs.map((name) => ({ + name, + bitWidth: expectedValueOf(someExpected, name).length, + nodePinId: nullthrows(outputNodePinIds.get(name)), + })), + ]; + for (const { name, bitWidth, nodePinId } of expectedBitWidths) { + const actual = bitWidthOf(nodePinId); + if (actual !== bitWidth) { + return { + type: "wrongBitWidth", + pinName: name, + expected: bitWidth, + actual, + }; + } + } + for (const inputs of inputCombinations(check.inputs)) { const inputValues = new Map(); for (const [name, pinId] of inputPinIds) { diff --git a/src/tutorial/circuit.ts b/src/tutorial/circuit.ts index 534e5b5..a84f12d 100644 --- a/src/tutorial/circuit.ts +++ b/src/tutorial/circuit.ts @@ -6,7 +6,7 @@ import type { CCComponentId } from "../store/component"; import type { CCComponentPin } from "../store/componentPin"; import { CCConnectionStore } from "../store/connection"; import { type CCNode, CCNodeStore } from "../store/node"; -import type { CCNodePinId } from "../store/nodePin"; +import { type CCNodePinId, CCNodePinStore } from "../store/nodePin"; /** Builds a circuit inside one component, as the editor would when drawn by hand */ export class StageCircuit { @@ -26,25 +26,55 @@ export class StageCircuit { ); } - place(componentId: CCComponentId, position: Vector2): CCNode { + place( + componentId: CCComponentId, + position: Vector2, + config?: CCNode["config"], + ): CCNode { const node = CCNodeStore.create({ parentComponentId: this.componentId, componentId, position, }); + if (config !== undefined) node.config = config; this.store.nodes.register(node); return node; } - /** By name only on a stage's component, as intrinsic pins are named for display */ - pinOf(node: CCNode, pin: CCComponentPin | string): CCNodePinId { + /** Splits a configurable pin of `node` into pins of the given bit widths */ + split(node: CCNode, componentPin: CCComponentPin, widths: readonly number[]) { + const [first, ...rest] = widths; + const [existing] = this.store.nodePins.getManyByNodeIdAndComponentPinId( + node.id, + componentPin.id, + ); + invariant(first !== undefined && existing, "Nothing to split"); + this.store.nodePins.update(existing.id, { manualBitWidth: first }); + for (const [index, manualBitWidth] of rest.entries()) { + this.store.nodePins.register( + CCNodePinStore.create({ + nodeId: node.id, + componentPinId: componentPin.id, + order: index + 1, + manualBitWidth, + }), + ); + } + } + + /** + * By name only on a stage's component, as intrinsic pins are named for display. + * `index` picks one of the pins a split pin became, from the top. + */ + pinOf(node: CCNode, pin: CCComponentPin | string, index = 0): CCNodePinId { const nodePin = this.store.nodePins .getManyByNodeId(node.id) - .find((nodePin) => + .filter((nodePin) => typeof pin === "string" ? this.store.componentPins.get(nodePin.componentPinId)?.name === pin : nodePin.componentPinId === pin.id, - ); + ) + .toSorted((a, b) => a.order - b.order)[index]; return nullthrows( nodePin, `The node has no pin ${typeof pin === "string" ? pin : pin.name}`, diff --git a/src/tutorial/failure.ts b/src/tutorial/failure.ts new file mode 100644 index 0000000..9da5d64 --- /dev/null +++ b/src/tutorial/failure.ts @@ -0,0 +1,41 @@ +import { valueLabel } from "../common/bitLabel"; +import type { Messages } from "../i18n"; +import type CCStore from "../store"; +import { SimulationNodeError } from "../store/netlist"; +import type { CheckResult } from "./check"; + +export function describeFailure( + result: Exclude, + store: CCStore, + messages: Messages, +): string { + const texts = messages.tutorial; + switch (result.type) { + case "missingPin": + return texts.missingPin(result.pinType, result.pinName); + case "wrongBitWidth": + return texts.wrongBitWidth( + result.pinName, + result.expected, + result.actual, + ); + case "wrongOutput": + return texts.wrongOutput( + result.inputs.map(({ name, value }) => ({ + name, + value: valueLabel(value), + })), + result.pinName, + valueLabel(result.expected), + result.actual ? valueLabel(result.actual) : null, + ); + case "simulationFailed": + return texts.simulationFailed( + result.error instanceof SimulationNodeError + ? result.error.describe(store, messages.simulation) + : result.error instanceof Error + ? result.error.message + : String(result.error), + ); + } +} diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts index aa77176..536a35f 100644 --- a/src/tutorial/stages.test.ts +++ b/src/tutorial/stages.test.ts @@ -14,7 +14,6 @@ import { registerTestNode, } from "../store/testUtils"; import { checkCombinational } from "./check"; -import { StageCircuit } from "./circuit"; import { findTutorialStage, isStagePart, @@ -55,16 +54,21 @@ describe("tutorialStages", () => { "%s is cleared by its solution, made of the parts it offers", (_, solved) => { const store = createTestStore(); - setUpTutorialStage(store, solved, titleOf); + const solve = setUpTutorialStage(store, solved, titleOf); + const laidOut = new Set( + store.nodes + .getManyByParentComponentId(solved.componentId) + .map((node) => node.id), + ); - solved.solve(new StageCircuit(store, solved.componentId)); + solve(); expect( checkCombinational(store, solved.componentId, solved.check), ).toEqual({ type: "passed" }); const placed = store.nodes .getManyByParentComponentId(solved.componentId) - .filter((node) => !isStagePinNode(store, solved, node.id)) + .filter((node) => !laidOut.has(node.id)) .map((node) => node.componentId); const offered = [ ...solved.parts, diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index 31e547f..01ed1a3 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -41,7 +41,13 @@ export type TutorialStage = { tableNotation: BitNotation; /** also the input and output pins the stage starts with */ check: CombinationalCheck; - solve(circuit: StageCircuit): void; + /** how far left and right of the middle the input and output pins sit */ + pinDistance: number; + /** + * Places what the stage starts with besides its pins, and returns how to clear it + * from there. Decorations, such as a display, are only placed for the player. + */ + layOut(circuit: StageCircuit, options: { decorate: boolean }): () => void; }; const gateParts = [and, or, not].map((gate) => gate.component.id); @@ -52,26 +58,45 @@ const isOn = (value: readonly boolean[] | undefined) => nullthrows(value?.[0]); const oneBitInputs = (...names: string[]) => names.map((name) => ({ name, bitWidth: 1 })); -type StageDefinition = Pick & - Partial>; +/** For a stage that starts with nothing but its pins */ +type Solving = { solve(circuit: StageCircuit): void }; + +type StageDefinition = Pick & + Partial> & + (Pick | Solving); function defineStage( id: TutorialStageId, definition: StageDefinition, ): TutorialStage { + const { + parts, + check, + givenParts = [], + tableNotation = "onOff", + pinDistance = 300, + } = definition; return { id, componentId: `tutorial-${id}` as CCComponentId, - givenParts: [], + parts, + check, + givenParts, + tableNotation, + pinDistance, allowsNewComponents: false, - tableNotation: "onOff", - ...definition, + layOut: + "layOut" in definition + ? definition.layOut + : (circuit) => () => definition.solve(circuit), }; } function twoSwitchesStage( id: TutorialStageId, - definition: Omit, + definition: Pick & + Partial> & + Solving, lampIsOn: (a: boolean, b: boolean) => boolean, ): TutorialStage { return defineStage(id, { @@ -332,9 +357,14 @@ function registerStageComponent( input.component.id, input.outputPin.Out, stage.check.inputs.map(({ name }) => name), - -300, + -stage.pinDistance, + ); + place( + output.component.id, + output.inputPin.In, + stage.check.outputs, + stage.pinDistance, ); - place(output.component.id, output.inputPin.In, stage.check.outputs, 300); } /** Skips the parts `store` already has, as a save from before may lack only some */ @@ -347,19 +377,25 @@ export function registerGivenParts( if (store.components.get(given.componentId)) continue; registerGivenParts(store, given, titleOf); registerStageComponent(store, given, titleOf(given.id)); - given.solve(new StageCircuit(store, given.componentId)); + given.layOut(new StageCircuit(store, given.componentId), { + decorate: false, + })(); } } /** - * Lay out the component of `stage`, with its input and output pins, and the components - * it hands over, in a mounted store + * Lay out the component of `stage`, with its pins and what else it starts with, and the + * components it hands over, in a mounted store + * @returns builds the stage's solution from there */ export function setUpTutorialStage( store: CCStore, stage: TutorialStage, titleOf: StageTitleOf, -): void { +): () => void { registerGivenParts(store, stage, titleOf); registerStageComponent(store, stage, titleOf(stage.id)); + return stage.layOut(new StageCircuit(store, stage.componentId), { + decorate: true, + }); } From 49b8a23b0eb867ea4c813e6b385e77b2f5e2b493 Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 01:45:59 +0900 Subject: [PATCH 2/9] feat(tutorial): show examples as the goal of a stage with pins of several bits A truth table's cells now hold values of any width, written in binary when they have several bits. goalTableOf replaces truthTableOfCheck: it lists every combination when each input is one bit, and otherwise the stage's examples. The bit helpers bitsOf and numberOf are shared by the value editor and tests. Co-Authored-By: Claude Opus 5.5 --- src/common/bits.ts | 13 +++++ src/components/TruthTableView.tsx | 18 ++++--- .../Editor/components/ValueEditor/value.ts | 21 ++------ src/pages/tutorial/stage.tsx | 24 ++++----- src/store/intrinsics/truthTable.test.ts | 22 ++++----- src/store/intrinsics/truthTable.ts | 7 +-- src/store/testUtils.ts | 13 ++--- src/tutorial/check.test.ts | 49 ++++++++----------- src/tutorial/check.ts | 33 +++++++------ src/tutorial/stages.ts | 13 ++++- 10 files changed, 109 insertions(+), 104 deletions(-) create mode 100644 src/common/bits.ts diff --git a/src/common/bits.ts b/src/common/bits.ts new file mode 100644 index 0000000..ad3a300 --- /dev/null +++ b/src/common/bits.ts @@ -0,0 +1,13 @@ +import type { SimulationValue } from "../store/simulation"; + +/** `value` in `width` bits, the most significant first, as in `SimulationValue` */ +export function bitsOf(value: number, width: number): SimulationValue { + return Array.from( + { length: width }, + (_, i) => ((value >> (width - 1 - i)) & 1) === 1, + ); +} + +export function numberOf(bits: SimulationValue): number { + return bits.reduce((value, bit) => value * 2 + (bit ? 1 : 0), 0); +} diff --git a/src/components/TruthTableView.tsx b/src/components/TruthTableView.tsx index 7cd6869..222ae9c 100644 --- a/src/components/TruthTableView.tsx +++ b/src/components/TruthTableView.tsx @@ -2,14 +2,19 @@ import { Box, type Theme } from "@mui/material"; import { useContext } from "react"; import { bitDigit, bitLabel } from "../common/bitLabel"; import type { TruthTable } from "../store/intrinsics/truthTable"; +import type { SimulationValue } from "../store/simulation"; import { theme } from "../style"; import { BitNotationContext } from "./bitNotation"; const divider = (muiTheme: Theme) => `1px solid ${muiTheme.palette.divider}`; export function TruthTableView({ table }: { table: TruthTable }) { - const labelOf = + const bitLabelOf = useContext(BitNotationContext) === "digits" ? bitDigit : bitLabel; + const labelOf = (value: SimulationValue) => + value.length === 1 && value[0] !== undefined + ? bitLabelOf(value[0]) + : value.map(bitDigit).join(""); const columns = [ ...table.inputs.map((name) => ({ key: `in-${name}`, name })), ...table.outputs.map((name) => ({ key: `out-${name}`, name })), @@ -43,17 +48,18 @@ export function TruthTableView({ table }: { table: TruthTable }) { {table.rows.map((row) => ( - + {[...row.inputs, ...row.outputs].map((value, i) => ( {labelOf(value)} diff --git a/src/pages/edit/Editor/components/ValueEditor/value.ts b/src/pages/edit/Editor/components/ValueEditor/value.ts index 6c3351d..575a92e 100644 --- a/src/pages/edit/Editor/components/ValueEditor/value.ts +++ b/src/pages/edit/Editor/components/ValueEditor/value.ts @@ -1,5 +1,6 @@ import { chunk } from "es-toolkit"; import invariant from "tiny-invariant"; +import { bitsOf, numberOf } from "../../../../../common/bits"; import type { Messages } from "../../../../../i18n/messages"; import type { CCIntrinsicComponentConstSpecConfigViewMode as Mode } from "../../../../../store/intrinsics/types"; import type { SimulationValue } from "../../../../../store/simulation"; @@ -7,18 +8,6 @@ import type { SimulationValue } from "../../../../../store/simulation"; const bitsPerHexDigit = 4; const bitsPerByte = 8; -/** Bits are ordered from the most significant one, as in `SimulationValue`. */ -function toBits(value: number, bitCount: number): boolean[] { - return Array.from( - { length: bitCount }, - (_, i) => ((value >> (bitCount - 1 - i)) & 1) === 1, - ); -} - -function fromBits(bits: boolean[]): number { - return bits.reduce((value, bit) => value * 2 + (bit ? 1 : 0), 0); -} - /** Pads the head with zeros so that the length becomes a multiple of `unit`. */ function padBits(bits: SimulationValue, unit: number): boolean[] { const padding = (unit - (bits.length % unit)) % unit; @@ -34,12 +23,12 @@ export function formatSimulationValue( return data.map((bit) => (bit ? "1" : "0")).join(""); case "hex": return chunk(padBits(data, bitsPerHexDigit), bitsPerHexDigit) - .map((digit) => fromBits(digit).toString(16)) + .map((digit) => numberOf(digit).toString(16)) .join(""); case "utf-8": { const bytes = Uint8Array.from( chunk(padBits(data, bitsPerByte), bitsPerByte), - fromBits, + numberOf, ); return new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes); } @@ -61,13 +50,13 @@ export function parseSimulationValue( const digits = text.replace(/\s/g, "").replace(/^0x/i, ""); if (!/^[0-9a-f]+$/i.test(digits)) return null; return [...digits].flatMap((digit) => - toBits(Number.parseInt(digit, 16), bitsPerHexDigit), + bitsOf(Number.parseInt(digit, 16), bitsPerHexDigit), ); } case "utf-8": { const bytes = new TextEncoder().encode(text); if (bytes.length === 0) return null; - return [...bytes].flatMap((byte) => toBits(byte, bitsPerByte)); + return [...bytes].flatMap((byte) => bitsOf(byte, bitsPerByte)); } } } diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx index 4fb9171..28778dd 100644 --- a/src/pages/tutorial/stage.tsx +++ b/src/pages/tutorial/stage.tsx @@ -30,7 +30,7 @@ import { theme } from "../../style"; import { type CheckResult, checkCombinational, - truthTableOfCheck, + goalTableOf, } from "../../tutorial/check"; import { describeFailure } from "../../tutorial/failure"; import { markStageCleared } from "../../tutorial/progress"; @@ -71,7 +71,7 @@ function StageView({ stage }: { stage: TutorialStage }) { const stageIndex = tutorialStages.indexOf(stage); const nextStage = tutorialStages[stageIndex + 1]; const titleOf: StageTitleOf = (id) => texts.stageTexts[id].title; - const goalTable = truthTableOfCheck(stage.check); + const goalTable = goalTableOf(stage.check, stage.examples); const stageTexts = texts.stageTexts[stage.id]; const [store, setStore] = useState(() => @@ -191,16 +191,16 @@ function StageView({ stage }: { stage: TutorialStage }) { } /> ))} - {stage.givenParts.map((id) => ( - - ))} + {stage.givenParts + .map((id) => nullthrows(findTutorialStage(id))) + .map((given) => ( + + ))} diff --git a/src/store/intrinsics/truthTable.test.ts b/src/store/intrinsics/truthTable.test.ts index 11df91b..6d3d482 100644 --- a/src/store/intrinsics/truthTable.test.ts +++ b/src/store/intrinsics/truthTable.test.ts @@ -20,24 +20,24 @@ describe("truthTableOf", () => { inputs: ["A", "B"], outputs: ["Out"], rows: [ - { inputs: [false, false], outputs: [false] }, - { inputs: [false, true], outputs: [false] }, - { inputs: [true, false], outputs: [false] }, - { inputs: [true, true], outputs: [true] }, + { inputs: [[false], [false]], outputs: [[false]] }, + { inputs: [[false], [true]], outputs: [[false]] }, + { inputs: [[true], [false]], outputs: [[false]] }, + { inputs: [[true], [true]], outputs: [[true]] }, ], }); expect(truthTableOf(xor)?.rows.map((row) => row.outputs[0])).toEqual([ - false, - true, - true, - false, + [false], + [true], + [true], + [false], ]); expect(truthTableOf(not)?.rows).toEqual([ - { inputs: [false], outputs: [true] }, - { inputs: [true], outputs: [false] }, + { inputs: [[false]], outputs: [[true]] }, + { inputs: [[true]], outputs: [[false]] }, ]); expect(truthTableOf(true_)?.rows).toEqual([ - { inputs: [], outputs: [true] }, + { inputs: [], outputs: [[true]] }, ]); }); diff --git a/src/store/intrinsics/truthTable.ts b/src/store/intrinsics/truthTable.ts index cd9cd38..4a03b3f 100644 --- a/src/store/intrinsics/truthTable.ts +++ b/src/store/intrinsics/truthTable.ts @@ -1,11 +1,12 @@ import { mapValues } from "es-toolkit"; import nullthrows from "nullthrows"; +import type { SimulationValue } from "../simulation"; import { IntrinsicComponentDefinition } from "./base"; export type TruthTable = { inputs: string[]; outputs: string[]; - rows: { inputs: boolean[]; outputs: boolean[] }[]; + rows: { inputs: SimulationValue[]; outputs: SimulationValue[] }[]; }; const maxInputCount = 2; @@ -45,9 +46,9 @@ export function truthTableOf( }, ); return { - inputs, + inputs: inputs.map((input) => [input]), outputs: outputKeys.map((key) => - nullthrows(values[key]?.[0]?.[0], `No value for ${key}`), + nullthrows(values[key]?.[0], `No value for ${key}`), ), }; }); diff --git a/src/store/testUtils.ts b/src/store/testUtils.ts index a8309ec..52e86d2 100644 --- a/src/store/testUtils.ts +++ b/src/store/testUtils.ts @@ -1,6 +1,7 @@ import nullthrows from "nullthrows"; import invariant from "tiny-invariant"; import { expect, vi } from "vitest"; +import { bitsOf, numberOf } from "../common/bits"; import CCStore from "."; import { type CCComponent, @@ -189,18 +190,10 @@ export function testComponentPin( ); } -/** MSB-first bit array of `value` in `width` bits. */ -export function testBits(value: number, width: number): SimulationValue { - return Array.from( - { length: width }, - (_, i) => ((value >> (width - 1 - i)) & 1) === 1, - ); -} +export const testBits = bitsOf; -/** Decimal reading of an MSB-first bit array. */ export function testNumber(value: SimulationValue | undefined): number | null { - if (!value) return null; - return Number.parseInt(value.map((bit) => (bit ? "1" : "0")).join(""), 2); + return value ? numberOf(value) : null; } export function thrownBy( diff --git a/src/tutorial/check.test.ts b/src/tutorial/check.test.ts index 7ef472b..d05602e 100644 --- a/src/tutorial/check.test.ts +++ b/src/tutorial/check.test.ts @@ -15,8 +15,8 @@ import { import { type CombinationalCheck, checkCombinational, + goalTableOf, inputCombinations, - truthTableOfCheck, } from "./check"; import { findTutorialStage, @@ -69,16 +69,16 @@ describe("inputCombinations", () => { }); }); -describe("truthTableOfCheck", () => { +describe("goalTableOf", () => { it("lists what the stage asks for, in the order the check tries the inputs", () => { - expect(truthTableOfCheck(xorStage.check)).toEqual({ + expect(goalTableOf(xorStage.check, [])).toEqual({ inputs: ["A", "B"], outputs: ["Out"], rows: [ - { inputs: [false, false], outputs: [false] }, - { inputs: [false, true], outputs: [true] }, - { inputs: [true, false], outputs: [true] }, - { inputs: [true, true], outputs: [false] }, + { inputs: [[false], [false]], outputs: [[false]] }, + { inputs: [[false], [true]], outputs: [[true]] }, + { inputs: [[true], [false]], outputs: [[true]] }, + { inputs: [[true], [true]], outputs: [[false]] }, ], }); }); @@ -86,32 +86,25 @@ describe("truthTableOfCheck", () => { it("lists several outputs in the order the stage names them", () => { const halfAdder = nullthrows(findTutorialStage("half-adder")); - expect(truthTableOfCheck(halfAdder.check)).toEqual({ - inputs: ["A", "B"], - outputs: ["C", "S"], - rows: [ - { inputs: [false, false], outputs: [false, false] }, - { inputs: [false, true], outputs: [false, true] }, - { inputs: [true, false], outputs: [false, true] }, - { inputs: [true, true], outputs: [true, false] }, - ], - }); + expect(goalTableOf(halfAdder.check, [])?.rows).toEqual([ + { inputs: [[false], [false]], outputs: [[false], [false]] }, + { inputs: [[false], [true]], outputs: [[false], [true]] }, + { inputs: [[true], [false]], outputs: [[false], [true]] }, + { inputs: [[true], [true]], outputs: [[true], [false]] }, + ]); }); - it("gives no table when a pin carries more than one bit", () => { - const wideInput: CombinationalCheck = { + it("shows only the examples when an input has several bits", () => { + const wide: CombinationalCheck = { inputs: [{ name: "A", bitWidth: 2 }], outputs: ["Out"], - expected: () => ({ Out: [false] }), - }; - const wideOutput: CombinationalCheck = { - inputs: [{ name: "A", bitWidth: 1 }], - outputs: ["Out"], - expected: () => ({ Out: [false, false] }), + expected: (values) => ({ Out: [...nullthrows(values.A)].reverse() }), }; - expect(truthTableOfCheck(wideInput)).toBeNull(); - expect(truthTableOfCheck(wideOutput)).toBeNull(); + expect(goalTableOf(wide, [])).toBeNull(); + expect(goalTableOf(wide, [{ A: [true, false] }])?.rows).toEqual([ + { inputs: [[true, false]], outputs: [[false, true]] }, + ]); }); it("refuses a check that gives no value for an output", () => { @@ -121,7 +114,7 @@ describe("truthTableOfCheck", () => { expected: () => ({}), }; - expect(() => truthTableOfCheck(check)).toThrow("Out"); + expect(() => goalTableOf(check, [])).toThrow("Out"); }); }); diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts index 6a96534..5632203 100644 --- a/src/tutorial/check.ts +++ b/src/tutorial/check.ts @@ -60,27 +60,28 @@ function expectedValueOf(expected: PinValues, name: string) { return nullthrows(expected[name], `The check gives no value for ${name}`); } -/** null when a pin carries more than one bit */ -export function truthTableOfCheck( +/** + * Every combination of the inputs when each is one bit, or else the given examples, + * with what the outputs should be; null when there is nothing to show + */ +export function goalTableOf( check: CombinationalCheck, + examples: readonly PinValues[], ): TruthTable | null { - if (check.inputs.some(({ bitWidth }) => bitWidth !== 1)) return null; - const rows: TruthTable["rows"] = []; - for (const inputs of inputCombinations(check.inputs)) { - const expected = check.expected(inputs); - const outputs = check.outputs.map((name) => - expectedValueOf(expected, name), - ); - if (outputs.some((value) => value.length !== 1)) return null; - rows.push({ - inputs: check.inputs.map(({ name }) => nullthrows(inputs[name]?.[0])), - outputs: outputs.map((value) => nullthrows(value[0])), - }); - } + const rows = check.inputs.every(({ bitWidth }) => bitWidth === 1) + ? [...inputCombinations(check.inputs)] + : examples; + if (rows.length === 0) return null; return { inputs: check.inputs.map(({ name }) => name), outputs: [...check.outputs], - rows, + rows: rows.map((inputs) => { + const expected = check.expected(inputs); + return { + inputs: check.inputs.map(({ name }) => nullthrows(inputs[name])), + outputs: check.outputs.map((name) => expectedValueOf(expected, name)), + }; + }), }; } diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index 01ed1a3..dd3acb7 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -16,7 +16,7 @@ import { xor, } from "../store/intrinsics/definitions"; import { type CCNodeId, CCNodeStore } from "../store/node"; -import type { CombinationalCheck } from "./check"; +import type { CombinationalCheck, PinValues } from "./check"; import { StageCircuit } from "./circuit"; export const tutorialStageIds = [ @@ -41,6 +41,8 @@ export type TutorialStage = { tableNotation: BitNotation; /** also the input and output pins the stage starts with */ check: CombinationalCheck; + /** inputs the goal shows when every combination of them is too many */ + examples: readonly PinValues[]; /** how far left and right of the middle the input and output pins sit */ pinDistance: number; /** @@ -62,7 +64,12 @@ const oneBitInputs = (...names: string[]) => type Solving = { solve(circuit: StageCircuit): void }; type StageDefinition = Pick & - Partial> & + Partial< + Pick< + TutorialStage, + "givenParts" | "tableNotation" | "pinDistance" | "examples" + > + > & (Pick | Solving); function defineStage( @@ -75,6 +82,7 @@ function defineStage( givenParts = [], tableNotation = "onOff", pinDistance = 300, + examples = [], } = definition; return { id, @@ -84,6 +92,7 @@ function defineStage( givenParts, tableNotation, pinDistance, + examples, allowsNewComponents: false, layOut: "layOut" in definition From 28152eac3489be88d0f6673f8b8bbf2333e725d7 Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 01:48:48 +0900 Subject: [PATCH 3/9] feat(tutorial): add the four-digit adder stage Stage 6, "Adding four digits", adds two four-bit numbers with four of stage 5's part. It starts with Decompose and Aggregate split into single digits and wired to A, B and S, and a 7seg and a 4x7 Display showing S. Its goal shows three examples, and its steps say which pin is which digit and how the carries chain. Decompose and Aggregate get summaries, and a stage now offers only the parts it hands over directly, not those built into them. Co-Authored-By: Claude Opus 5.5 --- src/i18n/en.ts | 14 +++++ src/i18n/ja.ts | 12 ++++ src/tutorial/stages.test.ts | 17 +++++ src/tutorial/stages.ts | 122 ++++++++++++++++++++++++++++++++++-- 4 files changed, 161 insertions(+), 4 deletions(-) diff --git a/src/i18n/en.ts b/src/i18n/en.ts index c5d81cf..4a3e914 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -43,6 +43,16 @@ const stageTexts: Record = { goal: 'Output A + B + Cin as a two-digit binary number to C and S. Cin is the carry coming up from the next lower digit. The answer is 0 to 3, and 3 is 11 in binary. "Adding one digit" is ready to use as a part: add A and B with one, then add Cin to its S with another. This circuit is called a full adder.', steps: [], }, + "four-bit-adder": { + title: "Adding four digits", + goal: "A and B are four-digit binary numbers. Output A + B in four digits to S, and turn C ON when it overflows into a fifth digit. The table shows some examples.", + steps: [ + 'Place four "Adding with a carry". From the top, the pins of Decompose and Aggregate are the eights, fours, twos and ones digits.', + "For each digit, connect that digit of A and of B to the A and B of one adder, and its S to the same digit of Aggregate.", + "Connect the C of each digit to the Cin of the digit above. The ones digit gets False on its Cin, and the C of the eights digit goes to the output C.", + "While playing, click a digit of A or B to switch it between 0 and 1. The sum also shows as a numeral on the right, with 10 to 15 as A to F.", + ], + }, }; export const en = { @@ -62,6 +72,10 @@ 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", }, about: (name: string) => `About ${name}`, ofStage: "Available parts", diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index 450d0d1..e876a80 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -21,6 +21,8 @@ export const ja: Messages = { XOR: "片方だけが ON のとき ON", TRUE: "いつも ON", FALSE: "いつも OFF", + DECOMPOSE: "何けたもある数を、上のけたから順に分ける", + AGGREGATE: "上のピンを大きいけたとして、1つの数にまとめる", }, about: (name) => `${name} について`, ofStage: "使える部品", @@ -155,6 +157,16 @@ export const ja: Messages = { goal: "A+B+Cin の答えを、2けたの2進数で C と S に出しましょう。Cin は、下のけたから来る桁上がりです。答えは 0 から 3 で、3 は2進数で 11 です。「1けたの足し算」を部品として使えます。1つで A と B を足し、もう1つでその S と Cin を足します。この回路を「全加算器」といいます。", steps: [], }, + "four-bit-adder": { + title: "4けたの足し算", + goal: "A と B は4けたの2進数です。A+B を4けたで S に出し、5けた目にあふれたら C を ON にしましょう。表はその例です。", + steps: [ + "「桁上がりつきの足し算」を4つ置きます。Decompose と Aggregate のピンは、上から8の位・4の位・2の位・1の位です。", + "けたごとに、A と B のそのけたを1つの足し算の A と B に、その S を Aggregate の同じけたにつなぎます。", + "それぞれのけたの C を、1つ上のけたの Cin につなぎます。1の位の Cin には False を、8の位の C は出力の C につなぎます。", + "再生中は、A と B のけたをクリックして 0 と 1 を切り替えられます。答えは右の数字にも出ます(10 から 15 は A から F)。", + ], + }, }, }, componentProperties: { diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts index 536a35f..42cd7e0 100644 --- a/src/tutorial/stages.test.ts +++ b/src/tutorial/stages.test.ts @@ -156,6 +156,23 @@ describe("isStagePart", () => { expect(isStagePart(stage, xor.component, own.id)).toBe(false); }); + it("offers only the parts handed over directly, not those built into them", () => { + const fourBit = nullthrows(findTutorialStage("four-bit-adder")); + const store = createTestStore(); + setUpTutorialStage(store, fourBit, titleOf); + const componentOf = (id: TutorialStageId) => + nullthrows( + store.components.get(nullthrows(findTutorialStage(id)).componentId), + ); + + expect( + isStagePart(fourBit, componentOf("full-adder"), fourBit.componentId), + ).toBe(true); + expect( + isStagePart(fourBit, componentOf("half-adder"), fourBit.componentId), + ).toBe(false); + }); + it("offers inside a part handed over what its own stage offers, and no pins", () => { const inGiven = (component: Parameters[1]) => isStagePart(xorStage, component, aOnlyStage.componentId); diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index dd3acb7..6cc1df9 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -1,5 +1,6 @@ import nullthrows from "nullthrows"; import type { BitNotation } from "../common/bitLabel"; +import { bitsOf, numberOf } from "../common/bits"; import type CCStore from "../store"; import { type CCComponent, @@ -8,11 +9,16 @@ import { } from "../store/component"; import type { CCComponentPin } from "../store/componentPin"; import { + aggregate, and, + decompose, + display, + false_, input, not, or, output, + seven_segment, xor, } from "../store/intrinsics/definitions"; import { type CCNodeId, CCNodeStore } from "../store/node"; @@ -25,6 +31,7 @@ export const tutorialStageIds = [ "xor", "half-adder", "full-adder", + "four-bit-adder", ] as const; export type TutorialStageId = (typeof tutorialStageIds)[number]; export type StageTitleOf = (id: TutorialStageId) => string; @@ -248,12 +255,114 @@ const fullAdderStage = defineStage("full-adder", { }, }); +const digitCount = 4; + +const fourBitAdderStage = defineStage("four-bit-adder", { + parts: [decompose, aggregate, false_].map((part) => part.component.id), + givenParts: ["full-adder"], + tableNotation: "digits", + pinDistance: 390, + check: { + inputs: [ + { name: "A", bitWidth: digitCount }, + { name: "B", bitWidth: digitCount }, + ], + outputs: ["C", "S"], + expected: (values) => { + const total = + numberOf(nullthrows(values.A)) + numberOf(nullthrows(values.B)); + return { + C: bit(total >= 2 ** digitCount), + S: bitsOf(total % 2 ** digitCount, digitCount), + }; + }, + }, + examples: [ + [3, 5], + [6, 7], + [9, 8], + ].map(([a, b]) => ({ + A: bitsOf(nullthrows(a), digitCount), + B: bitsOf(nullthrows(b), digitCount), + })), + layOut(circuit, { decorate }) { + const single = new Array(digitCount).fill(1); + const splitA = circuit.place(decompose.component.id, { x: -230, y: -170 }); + const splitB = circuit.place(decompose.component.id, { x: -230, y: 170 }); + const joined = circuit.place(aggregate.component.id, { x: 160, y: 100 }); + circuit.split(splitA, decompose.outputPin.Out, single); + circuit.split(splitB, decompose.outputPin.Out, single); + circuit.split(joined, aggregate.inputPin.In, single); + circuit.connect( + circuit.pin("A"), + circuit.pinOf(splitA, decompose.inputPin.In), + ); + circuit.connect( + circuit.pin("B"), + circuit.pinOf(splitB, decompose.inputPin.In), + ); + const sum = circuit.pinOf(joined, aggregate.outputPin.Out); + circuit.connect(sum, circuit.pin("S")); + if (decorate) { + const digit = circuit.place(seven_segment.component.id, { + x: 170, + y: 250, + }); + const screen = circuit.place( + display.component.id, + { x: 330, y: 240 }, + { resolution: { x: 4, y: 7 }, pixelOrder: "row-major" }, + ); + circuit.connect(sum, circuit.pinOf(digit, seven_segment.inputPin.In)); + circuit.connect( + circuit.pinOf(digit, seven_segment.outputPin.Out), + circuit.pinOf(screen, display.inputPin.Pixels), + ); + } + return () => { + const adders = Array.from({ length: digitCount }, (_, index) => + circuit.place(fullAdderStage.componentId, { + x: -40, + y: -300 + 200 * index, + }), + ); + const noCarry = circuit.place(false_.component.id, { x: -200, y: 390 }); + for (const [index, adder] of adders.entries()) { + circuit.connect( + circuit.pinOf(splitA, decompose.outputPin.Out, index), + circuit.pinOf(adder, "A"), + ); + circuit.connect( + circuit.pinOf(splitB, decompose.outputPin.Out, index), + circuit.pinOf(adder, "B"), + ); + circuit.connect( + circuit.pinOf(adder, "S"), + circuit.pinOf(joined, aggregate.inputPin.In, index), + ); + const lower = adders[index + 1]; + circuit.connect( + lower + ? circuit.pinOf(lower, "C") + : circuit.pinOf(noCarry, false_.outputPin.Out), + circuit.pinOf(adder, "Cin"), + ); + } + circuit.connect( + circuit.pinOf(nullthrows(adders[0]), "C"), + circuit.pin("C"), + ); + }; + }, +}); + export const tutorialStages: readonly TutorialStage[] = [ andStage, aOnlyStage, xorStage, halfAdderStage, fullAdderStage, + fourBitAdderStage, ]; export function findTutorialStage(id: string | undefined) { @@ -289,14 +398,19 @@ export function isStagePart( editedComponentId: CCComponentId, ) { const owner = stageOwning(stage, editedComponentId); + const isGivenTo = (receiver: TutorialStage) => + receiver.givenParts.some( + (id) => tutorialStageById(id).componentId === component.id, + ); if (owner && owner !== stage) { return component.intrinsicType ? owner.parts.includes(component.id) - : owner.givenParts.some( - (id) => tutorialStageById(id).componentId === component.id, - ); + : isGivenTo(owner); + } + if (!component.intrinsicType) { + // A part handed over to a part handed over is built in, not offered + return !isStageComponent(stage, component.id) || isGivenTo(stage); } - if (!component.intrinsicType) return true; if (owner) return owner.parts.includes(component.id); // A component of the player's own gets its pins from Input and Output nodes return ( From 9d2c3c094417226897ae194c1f32fff829f75366 Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 01:54:25 +0900 Subject: [PATCH 4/9] fix(tutorial): leave width conflicts and open outputs to the simulation, and address the review - The width check skips a pin in a width conflict and an output nothing fixes, as the simulation tells what is wrong with those. - The English message counts "1 digit" for the expected width too. - Stage 6 calls C the fifth, sixteens digit, which is 1 when A + B is 16 or more, and names the letters the 7seg draws for 10 to 15 (A, b, C, d, E, F). - StageCircuit.split refuses a pin that is split already. Co-Authored-By: Claude Opus 5.5 --- src/i18n/en.ts | 7 ++--- src/i18n/ja.ts | 6 ++--- src/i18n/messages.test.ts | 5 +++- src/tutorial/check.test.ts | 52 ++++++++++++++++++++++++++++++++++++++ src/tutorial/check.ts | 17 ++++++++----- src/tutorial/circuit.ts | 10 +++++--- 6 files changed, 80 insertions(+), 17 deletions(-) diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 4a3e914..e9e6ce7 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -6,6 +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 themOf = (names: readonly string[]) => names.length === 1 ? "it" : "them"; @@ -45,12 +46,12 @@ const stageTexts: Record = { }, "four-bit-adder": { title: "Adding four digits", - goal: "A and B are four-digit binary numbers. Output A + B in four digits to S, and turn C ON when it overflows into a fifth digit. The table shows some examples.", + goal: "A and B are four-digit binary numbers. Output A + B in four digits to S, and its fifth digit, the sixteens digit, to C: C is 1 when A + B is 16 or more. The table shows some examples.", steps: [ 'Place four "Adding with a carry". From the top, the pins of Decompose and Aggregate are the eights, fours, twos and ones digits.', "For each digit, connect that digit of A and of B to the A and B of one adder, and its S to the same digit of Aggregate.", "Connect the C of each digit to the Cin of the digit above. The ones digit gets False on its Cin, and the C of the eights digit goes to the output C.", - "While playing, click a digit of A or B to switch it between 0 and 1. The sum also shows as a numeral on the right, with 10 to 15 as A to F.", + "While playing, click a digit of A or B to switch it between 0 and 1. The sum also shows on the right, with 10 to 15 shown as the letters A, b, C, d, E and F.", ], }, }; @@ -167,7 +168,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 ${expected} digits, but it has ${actual === 1 ? "1 digit" : `${actual} digits`}. Check what it is connected to.`, + `${pinName} should have ${digits(expected)}, but it has ${digits(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 e876a80..07c749a 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -113,7 +113,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} でした`}。`, simulationFailed: (detail) => @@ -159,12 +159,12 @@ export const ja: Messages = { }, "four-bit-adder": { title: "4けたの足し算", - goal: "A と B は4けたの2進数です。A+B を4けたで S に出し、5けた目にあふれたら C を ON にしましょう。表はその例です。", + goal: "A と B は4けたの2進数です。A+B を4けたで S に、5けた目(16の位)を C に出しましょう。A+B が 16 以上なら、C は 1 です。表はその例です。", steps: [ "「桁上がりつきの足し算」を4つ置きます。Decompose と Aggregate のピンは、上から8の位・4の位・2の位・1の位です。", "けたごとに、A と B のそのけたを1つの足し算の A と B に、その S を Aggregate の同じけたにつなぎます。", "それぞれのけたの C を、1つ上のけたの Cin につなぎます。1の位の Cin には False を、8の位の C は出力の C につなぎます。", - "再生中は、A と B のけたをクリックして 0 と 1 を切り替えられます。答えは右の数字にも出ます(10 から 15 は A から F)。", + "再生中は、A と B のけたをクリックして 0 と 1 を切り替えられます。答えは右にも出ます(10 から 15 は、A、b、C、d、E、F の字で出ます)。", ], }, }, diff --git a/src/i18n/messages.test.ts b/src/i18n/messages.test.ts index a1b3301..5a461a2 100644 --- a/src/i18n/messages.test.ts +++ b/src/i18n/messages.test.ts @@ -137,8 +137,11 @@ describe("the message on a pin of the wrong width", () => { 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.", ); + 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.", + ); expect(messagesByLanguage.ja.tutorial.wrongBitWidth("A", 4, 1)).toBe( - "A は 4けたのはずが、1けたになっています。つないだ先を確かめてください。", + "A は 4けたのはずですが、1けたになっています。つないだ先を確かめてください。", ); }); }); diff --git a/src/tutorial/check.test.ts b/src/tutorial/check.test.ts index d05602e..70cd6c4 100644 --- a/src/tutorial/check.test.ts +++ b/src/tutorial/check.test.ts @@ -11,6 +11,7 @@ import { registerTestOutputNode, splitTestNodePin, testNodePin, + tryConnectTestNodePins, } from "../store/testUtils"; import { type CombinationalCheck, @@ -217,6 +218,57 @@ describe("checkCombinational on pins of several bits", () => { }); }); + it("leaves an unconnected output to the simulation", () => { + const store = createTestStore(); + const component = registerTestComponent(store, "Wide"); + const a = registerTestInputNode(store, component.id, "A"); + registerTestOutputNode(store, component.id, "Out"); + const split = registerTestNode(store, component.id, decompose.component.id); + splitTestNodePin(store, split, decompose.outputPin.Out, [1, 1]); + connectTestNodePins( + store, + component.id, + a.out, + testNodePin(store, split, decompose.inputPin.In), + ); + + expect(checkCombinational(store, component.id, twoBitCheck)).toMatchObject({ + type: "simulationFailed", + }); + }); + + it("leaves a pin in a width conflict to the simulation", () => { + const store = createTestStore(); + const component = registerTestComponent(store, "Wide"); + const a = registerTestInputNode(store, component.id, "A"); + registerTestOutputNode(store, component.id, "Out"); + const split = registerTestNode(store, component.id, decompose.component.id); + splitTestNodePin(store, split, decompose.outputPin.Out, [1, 1]); + const joined = registerTestNode( + store, + component.id, + aggregate.component.id, + ); + connectTestNodePins( + store, + component.id, + a.out, + testNodePin(store, split, decompose.inputPin.In), + ); + tryConnectTestNodePins( + store, + component.id, + a.out, + testNodePin(store, joined, aggregate.inputPin.In), + { allowBitWidthConflict: true }, + ); + + expect(store.nodePins.isInBitWidthConflict(a.out)).toBe(true); + expect(checkCombinational(store, component.id, twoBitCheck)).toMatchObject({ + type: "simulationFailed", + }); + }); + it("tells an output fixed to another width", () => { const store = createTestStore(); const component = registerTestComponent(store, "Wide"); diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts index 5632203..2ec8482 100644 --- a/src/tutorial/check.ts +++ b/src/tutorial/check.ts @@ -117,10 +117,13 @@ export function checkCombinational( outputNodePinIds.set(name, pin.implementation); } - // A pin whose width nothing fixes is simulated as one bit wide - const bitWidthOf = (nodePinId: CCNodePinId) => { + // An input nothing fixes is simulated one bit wide. A conflict or an unconnected + // output is left to the simulation, which tells what is wrong with it. + const bitWidthOf = (nodePinId: CCNodePinId, pinType: "input" | "output") => { + if (store.nodePins.isInBitWidthConflict(nodePinId)) return null; const status = store.nodePins.getNodePinBitWidthStatus(nodePinId); - return status.isFixed ? status.bitWidth : DEFAULT_SIMULATION_BIT_WIDTH; + if (status.isFixed) return status.bitWidth; + return pinType === "input" ? DEFAULT_SIMULATION_BIT_WIDTH : null; }; const someExpected = check.expected( nullthrows(inputCombinations(check.inputs).next().value), @@ -128,6 +131,7 @@ export function checkCombinational( const expectedBitWidths = [ ...check.inputs.map(({ name, bitWidth }) => ({ name, + pinType: "input" as const, bitWidth, nodePinId: nullthrows( store.componentPins.get(nullthrows(inputPinIds.get(name))) @@ -136,13 +140,14 @@ export function checkCombinational( })), ...check.outputs.map((name) => ({ name, + pinType: "output" as const, bitWidth: expectedValueOf(someExpected, name).length, nodePinId: nullthrows(outputNodePinIds.get(name)), })), ]; - for (const { name, bitWidth, nodePinId } of expectedBitWidths) { - const actual = bitWidthOf(nodePinId); - if (actual !== bitWidth) { + for (const { name, pinType, bitWidth, nodePinId } of expectedBitWidths) { + const actual = bitWidthOf(nodePinId, pinType); + if (actual !== null && actual !== bitWidth) { return { type: "wrongBitWidth", pinName: name, diff --git a/src/tutorial/circuit.ts b/src/tutorial/circuit.ts index a84f12d..5e012c1 100644 --- a/src/tutorial/circuit.ts +++ b/src/tutorial/circuit.ts @@ -41,15 +41,17 @@ export class StageCircuit { return node; } - /** Splits a configurable pin of `node` into pins of the given bit widths */ split(node: CCNode, componentPin: CCComponentPin, widths: readonly number[]) { const [first, ...rest] = widths; - const [existing] = this.store.nodePins.getManyByNodeIdAndComponentPinId( + const existing = this.store.nodePins.getManyByNodeIdAndComponentPinId( node.id, componentPin.id, ); - invariant(first !== undefined && existing, "Nothing to split"); - this.store.nodePins.update(existing.id, { manualBitWidth: first }); + invariant( + first !== undefined && existing.length === 1 && existing[0], + "Only a pin not split yet can be split", + ); + this.store.nodePins.update(existing[0].id, { manualBitWidth: first }); for (const [index, manualBitWidth] of rest.entries()) { this.store.nodePins.register( CCNodePinStore.create({ From dc40232a1bd1460bdac49ad150cb97a5b9350c1b Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 02:00:42 +0900 Subject: [PATCH 5/9] =?UTF-8?q?fix(tutorial):=20write=20=E6=A1=81=20in=20k?= =?UTF-8?q?anji=20everywhere,=20as=20in=20=E6=A1=81=E4=B8=8A=E3=81=8C?= =?UTF-8?q?=E3=82=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- src/i18n/ja.ts | 22 +++++++++++----------- src/i18n/messages.test.ts | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index 07c749a..a415cde 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -21,8 +21,8 @@ export const ja: Messages = { XOR: "片方だけが ON のとき ON", TRUE: "いつも ON", FALSE: "いつも OFF", - DECOMPOSE: "何けたもある数を、上のけたから順に分ける", - AGGREGATE: "上のピンを大きいけたとして、1つの数にまとめる", + DECOMPOSE: "何桁もある数を、上の桁から順に分ける", + AGGREGATE: "上のピンを大きい桁として、1つの数にまとめる", }, about: (name) => `${name} について`, ofStage: "使える部品", @@ -113,7 +113,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} でした`}。`, simulationFailed: (detail) => @@ -148,23 +148,23 @@ export const ja: Messages = { steps: [], }, "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 を「和」といい、この回路を「半加算器」といいます。", + 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 を「和」といい、この回路を「半加算器」といいます。", steps: [], }, "full-adder": { title: "桁上がりつきの足し算", - goal: "A+B+Cin の答えを、2けたの2進数で C と S に出しましょう。Cin は、下のけたから来る桁上がりです。答えは 0 から 3 で、3 は2進数で 11 です。「1けたの足し算」を部品として使えます。1つで A と B を足し、もう1つでその S と Cin を足します。この回路を「全加算器」といいます。", + goal: "A+B+Cin の答えを、2桁の2進数で C と S に出しましょう。Cin は、下の桁から来る桁上がりです。答えは 0 から 3 で、3 は2進数で 11 です。「1桁の足し算」を部品として使えます。1つで A と B を足し、もう1つでその S と Cin を足します。この回路を「全加算器」といいます。", steps: [], }, "four-bit-adder": { - title: "4けたの足し算", - goal: "A と B は4けたの2進数です。A+B を4けたで S に、5けた目(16の位)を C に出しましょう。A+B が 16 以上なら、C は 1 です。表はその例です。", + title: "4桁の足し算", + goal: "A と B は4桁の2進数です。A+B を4桁で S に、5桁目(16の位)を C に出しましょう。A+B が 16 以上なら、C は 1 です。表はその例です。", steps: [ "「桁上がりつきの足し算」を4つ置きます。Decompose と Aggregate のピンは、上から8の位・4の位・2の位・1の位です。", - "けたごとに、A と B のそのけたを1つの足し算の A と B に、その S を Aggregate の同じけたにつなぎます。", - "それぞれのけたの C を、1つ上のけたの Cin につなぎます。1の位の Cin には False を、8の位の C は出力の C につなぎます。", - "再生中は、A と B のけたをクリックして 0 と 1 を切り替えられます。答えは右にも出ます(10 から 15 は、A、b、C、d、E、F の字で出ます)。", + "桁ごとに、A と B のその桁を1つの足し算の A と B に、その S を Aggregate の同じ桁につなぎます。", + "それぞれの桁の C を、1つ上の桁の Cin につなぎます。1の位の Cin には False を、8の位の C は出力の C につなぎます。", + "再生中は、A と B の桁をクリックして 0 と 1 を切り替えられます。答えは右にも出ます(10 から 15 は、A、b、C、d、E、F の字で出ます)。", ], }, }, diff --git a/src/i18n/messages.test.ts b/src/i18n/messages.test.ts index 5a461a2..17cf576 100644 --- a/src/i18n/messages.test.ts +++ b/src/i18n/messages.test.ts @@ -141,7 +141,7 @@ describe("the message on a pin of the wrong width", () => { "C should have 1 digit, but it has 4 digits. Check what it is connected to.", ); expect(messagesByLanguage.ja.tutorial.wrongBitWidth("A", 4, 1)).toBe( - "A は 4けたのはずですが、1けたになっています。つないだ先を確かめてください。", + "A は 4桁のはずですが、1桁になっています。つないだ先を確かめてください。", ); }); }); From 55ac0bce9644b4c697923a892b506f85bcc56402 Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 02:22:12 +0900 Subject: [PATCH 6/9] fix(tutorial): fit the editor to a stage's nodes, and catch failures of the check itself - The editor can fit its view to the nodes when it first gets its size, zooming out only as far as needed and leaving room for the title bar and the play button (fitsNodesInView). The tutorial turns it on, so a stage's nodes are in view on any window; the free mode keeps its view. - Stage 6 places the 7seg right of Aggregate's output, so the wire to it no longer crosses its name, and the Display at the top right, away from the play button. - An exception from the check outside the simulation is caught and logged, and the stage says that something went wrong instead of showing nothing. Co-Authored-By: Claude Opus 5.5 --- src/i18n/en.ts | 2 + src/i18n/ja.ts | 2 + src/pages/edit/Editor/store/index.tsx | 3 + .../store/slices/perspective/fit.test.ts | 69 +++++++++++++++++++ .../Editor/store/slices/perspective/fit.ts | 35 ++++++++++ .../Editor/store/slices/perspective/index.tsx | 29 ++++++-- src/pages/edit/Editor/store/types.ts | 2 + src/pages/tutorial/stage.tsx | 9 ++- src/tutorial/check.ts | 2 + src/tutorial/failure.ts | 2 + src/tutorial/stages.ts | 16 ++--- 11 files changed, 157 insertions(+), 14 deletions(-) create mode 100644 src/pages/edit/Editor/store/slices/perspective/fit.test.ts create mode 100644 src/pages/edit/Editor/store/slices/perspective/fit.ts diff --git a/src/i18n/en.ts b/src/i18n/en.ts index e9e6ce7..2054c90 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -176,6 +176,8 @@ export const en = { actual: string | null, ) => `When ${listOf(inputs.map(({ name, value }) => `${name} is ${value}`))}, ${pinName} should be ${expected}, but it ${actual === null ? "has no value" : `is ${actual}`}.`, + checkFailed: + 'Something went wrong while checking. "Reset this stage" may fix it.', simulationFailed: (detail: string) => `The circuit could not be simulated. ${detail}`, resetStage: "Reset this stage", diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index a415cde..6400e15 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -116,6 +116,8 @@ export const ja: Messages = { `${pinName} は ${expected}桁のはずですが、${actual}桁になっています。つないだ先を確かめてください。`, wrongOutput: (inputs, pinName, expected, actual) => `${inputs.map(({ name, value }) => `${name} が ${value}`).join("、")} のとき、${pinName} は ${expected} になるはずが、${actual === null ? "値がありませんでした" : `${actual} でした`}。`, + checkFailed: + "確かめる途中で問題が起きました。「この課題をやり直す」で直ることがあります。", simulationFailed: (detail) => `回路をシミュレーションできませんでした。${detail}`, resetStage: "この課題をやり直す", diff --git a/src/pages/edit/Editor/store/index.tsx b/src/pages/edit/Editor/store/index.tsx index 55463e3..7d415dd 100644 --- a/src/pages/edit/Editor/store/index.tsx +++ b/src/pages/edit/Editor/store/index.tsx @@ -15,6 +15,7 @@ export type EditorStoreOptions = { isProtectedNode?: (nodeId: CCNodeId) => boolean; isOffered?: OffersComponent; canCreateComponents?: boolean; + fitsNodesInView?: boolean; hasProperties?: (componentId: CCComponentId) => boolean; }; @@ -26,6 +27,7 @@ export function createEditorStore( isOffered = () => true, hasProperties = () => true, canCreateComponents = true, + fitsNodesInView = false, }: EditorStoreOptions = {}, ) { const props = { store, componentId }; @@ -38,6 +40,7 @@ export function createEditorStore( isOffered, hasProperties, canCreateComponents, + fitsNodesInView, ...coreSlice.define(set, get), ...perspectiveSlice.define(set, get), ...contextMenuSlice.define(set, get), diff --git a/src/pages/edit/Editor/store/slices/perspective/fit.test.ts b/src/pages/edit/Editor/store/slices/perspective/fit.test.ts new file mode 100644 index 0000000..506698f --- /dev/null +++ b/src/pages/edit/Editor/store/slices/perspective/fit.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from "vitest"; +import type { Perspective } from "../../../../../../common/types"; +import type { Vector2 } from "../../../../../../common/vector2"; +import { fitPadding, perspectiveFitting } from "./fit"; + +const rendererSize = { x: 900, y: 800 }; + +function toCanvas(point: Vector2, { center, scale }: Perspective): Vector2 { + return { + x: (point.x - center.x) / scale + rendererSize.x / 2, + y: (point.y - center.y) / scale + rendererSize.y / 2, + }; +} + +function expectInsideRoom( + rects: { position: Vector2; size: Vector2 }[], + perspective: Perspective, +) { + for (const { position, size } of rects) { + const topLeft = toCanvas(position, perspective); + const bottomRight = toCanvas( + { x: position.x + size.x, y: position.y + size.y }, + perspective, + ); + expect(topLeft.x).toBeGreaterThanOrEqual(fitPadding.left - 1e-9); + expect(topLeft.y).toBeGreaterThanOrEqual(fitPadding.top - 1e-9); + expect(bottomRight.x).toBeLessThanOrEqual( + rendererSize.x - fitPadding.right + 1e-9, + ); + expect(bottomRight.y).toBeLessThanOrEqual( + rendererSize.y - fitPadding.bottom + 1e-9, + ); + } +} + +describe("perspectiveFitting", () => { + it("keeps the size of nodes that fit, and moves them clear of the edges", () => { + const rects = [ + { position: { x: -350, y: -115 }, size: { x: 100, y: 30 } }, + { position: { x: 250, y: -15 }, size: { x: 100, y: 30 } }, + ]; + const perspective = perspectiveFitting(rects, rendererSize); + + expect(perspective.scale).toBe(1); + expectInsideRoom(rects, perspective); + }); + + it("zooms out just enough for nodes that do not fit", () => { + const rects = [ + { position: { x: -500, y: -400 }, size: { x: 100, y: 100 } }, + { position: { x: 600, y: 500 }, size: { x: 100, y: 100 } }, + ]; + const perspective = perspectiveFitting(rects, rendererSize); + + expect(perspective.scale).toBeGreaterThan(1); + expectInsideRoom(rects, perspective); + expect( + perspectiveFitting(rects, rendererSize).scale * + (rendererSize.y - fitPadding.top - fitPadding.bottom), + ).toBeCloseTo(1000); + }); + + it("shows the middle when there are no nodes", () => { + expect(perspectiveFitting([], rendererSize)).toEqual({ + center: { x: 0, y: 0 }, + scale: 1, + }); + }); +}); diff --git a/src/pages/edit/Editor/store/slices/perspective/fit.ts b/src/pages/edit/Editor/store/slices/perspective/fit.ts new file mode 100644 index 0000000..3da7b59 --- /dev/null +++ b/src/pages/edit/Editor/store/slices/perspective/fit.ts @@ -0,0 +1,35 @@ +import type { Perspective } from "../../../../../../common/types"; +import type { Vector2 } from "../../../../../../common/vector2"; + +/** Room kept clear of nodes: the title bar is at the top and the play button at the bottom right */ +export const fitPadding = { top: 130, right: 30, bottom: 110, left: 30 }; + +/** + * The perspective showing every rectangle inside a renderer of `rendererSize`, zoomed + * out only as far as needed, never in + */ +export function perspectiveFitting( + rects: readonly { position: Vector2; size: Vector2 }[], + rendererSize: Vector2, +): Perspective { + if (rects.length === 0) return { center: { x: 0, y: 0 }, scale: 1 }; + const left = Math.min(...rects.map((rect) => rect.position.x)); + const top = Math.min(...rects.map((rect) => rect.position.y)); + const right = Math.max(...rects.map((rect) => rect.position.x + rect.size.x)); + const bottom = Math.max( + ...rects.map((rect) => rect.position.y + rect.size.y), + ); + const roomX = rendererSize.x - fitPadding.left - fitPadding.right; + const roomY = rendererSize.y - fitPadding.top - fitPadding.bottom; + const scale = Math.max(1, (right - left) / roomX, (bottom - top) / roomY); + // The middle of the room is off the middle of the renderer by half the uneven padding + return { + center: { + x: + (left + right) / 2 - ((fitPadding.left - fitPadding.right) / 2) * scale, + y: + (top + bottom) / 2 - ((fitPadding.top - fitPadding.bottom) / 2) * scale, + }, + scale, + }; +} diff --git a/src/pages/edit/Editor/store/slices/perspective/index.tsx b/src/pages/edit/Editor/store/slices/perspective/index.tsx index 593c87d..e124304 100644 --- a/src/pages/edit/Editor/store/slices/perspective/index.tsx +++ b/src/pages/edit/Editor/store/slices/perspective/index.tsx @@ -1,10 +1,12 @@ import { vector2 } from "../../../../../../common/vector2"; +import { getCCComponentEditorRendererNodeGeometry } from "../../../renderer/Node/geometry"; import type { ComponentEditorSliceCreator } from "../../types"; +import { perspectiveFitting } from "./fit"; import type { PerspectiveStoreSlice } from "./types"; const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< PerspectiveStoreSlice -> = () => { +> = ({ store, componentId }) => { let resizeObserver: ResizeObserver | null; let rendererElement: SVGSVGElement | null; const registerRendererElement = (element: SVGSVGElement | null) => { @@ -53,11 +55,28 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< postCreate(editorStore) { resizeObserver = new ResizeObserver((entries) => { if (!entries[0]) return; + const rendererSize = { + x: entries[0].contentRect.width, + y: entries[0].contentRect.height, + }; + const state = editorStore.getState(); + const isFirstSize = + state.rendererSize.x === 0 && state.rendererSize.y === 0; editorStore.setState({ - rendererSize: { - x: entries[0].contentRect.width, - y: entries[0].contentRect.height, - }, + rendererSize, + ...(isFirstSize && + state.fitsNodesInView && { + perspective: perspectiveFitting( + store.nodes + .getManyByParentComponentId(componentId) + .map( + (node) => + getCCComponentEditorRendererNodeGeometry(store, node.id) + .rect, + ), + rendererSize, + ), + }), }); }); }, diff --git a/src/pages/edit/Editor/store/types.ts b/src/pages/edit/Editor/store/types.ts index cb5ad00..d60c6a8 100644 --- a/src/pages/edit/Editor/store/types.ts +++ b/src/pages/edit/Editor/store/types.ts @@ -12,6 +12,8 @@ export type ComponentEditorStoreValue = { readonly isProtectedNode: (nodeId: CCNodeId) => boolean; readonly isOffered: OffersComponent; readonly canCreateComponents: boolean; + /** whether the view is fitted to the nodes when the editor first gets its size */ + readonly fitsNodesInView: boolean; readonly hasProperties: (componentId: CCComponentId) => boolean; } & EditorStoreCoreSlice & PerspectiveStoreSlice & diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx index 28778dd..a99c6f1 100644 --- a/src/pages/tutorial/stage.tsx +++ b/src/pages/tutorial/stage.tsx @@ -96,7 +96,13 @@ function StageView({ stage }: { stage: TutorialStage }) { }, [store]); const check = () => { - const checked = checkCombinational(store, stage.componentId, stage.check); + let checked: CheckResult; + try { + checked = checkCombinational(store, stage.componentId, stage.check); + } catch (error) { + console.error(error); + checked = { type: "checkFailed", error }; + } setResult(checked); if (checked.type === "passed") markStageCleared(stage.id); }; @@ -267,6 +273,7 @@ function StageView({ stage }: { stage: TutorialStage }) { isProtectedNode: (nodeId) => isStagePinNode(store, stage, nodeId), isOffered, canCreateComponents: stage.allowsNewComponents, + fitsNodesInView: true, hasProperties: (componentId) => !isStageComponent(stage, componentId), }} diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts index 2ec8482..225a302 100644 --- a/src/tutorial/check.ts +++ b/src/tutorial/check.ts @@ -29,6 +29,8 @@ export type CheckResult = actual: number; } | { type: "simulationFailed"; error: unknown } + /** the check itself failed, on a circuit it has no words for */ + | { type: "checkFailed"; error: unknown } | { type: "wrongOutput"; inputs: readonly { name: string; value: SimulationValue }[]; diff --git a/src/tutorial/failure.ts b/src/tutorial/failure.ts index 9da5d64..b29ffc1 100644 --- a/src/tutorial/failure.ts +++ b/src/tutorial/failure.ts @@ -29,6 +29,8 @@ export function describeFailure( valueLabel(result.expected), result.actual ? valueLabel(result.actual) : null, ); + case "checkFailed": + return texts.checkFailed; case "simulationFailed": return texts.simulationFailed( result.error instanceof SimulationNodeError diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index 6cc1df9..fd69b34 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -261,7 +261,7 @@ const fourBitAdderStage = defineStage("four-bit-adder", { parts: [decompose, aggregate, false_].map((part) => part.component.id), givenParts: ["full-adder"], tableNotation: "digits", - pinDistance: 390, + pinDistance: 420, check: { inputs: [ { name: "A", bitWidth: digitCount }, @@ -287,9 +287,9 @@ const fourBitAdderStage = defineStage("four-bit-adder", { })), layOut(circuit, { decorate }) { const single = new Array(digitCount).fill(1); - const splitA = circuit.place(decompose.component.id, { x: -230, y: -170 }); - const splitB = circuit.place(decompose.component.id, { x: -230, y: 170 }); - const joined = circuit.place(aggregate.component.id, { x: 160, y: 100 }); + const splitA = circuit.place(decompose.component.id, { x: -250, y: -170 }); + const splitB = circuit.place(decompose.component.id, { x: -250, y: 170 }); + const joined = circuit.place(aggregate.component.id, { x: 150, y: 100 }); circuit.split(splitA, decompose.outputPin.Out, single); circuit.split(splitB, decompose.outputPin.Out, single); circuit.split(joined, aggregate.inputPin.In, single); @@ -305,12 +305,12 @@ const fourBitAdderStage = defineStage("four-bit-adder", { circuit.connect(sum, circuit.pin("S")); if (decorate) { const digit = circuit.place(seven_segment.component.id, { - x: 170, - y: 250, + x: 290, + y: -250, }); const screen = circuit.place( display.component.id, - { x: 330, y: 240 }, + { x: 430, y: -250 }, { resolution: { x: 4, y: 7 }, pixelOrder: "row-major" }, ); circuit.connect(sum, circuit.pinOf(digit, seven_segment.inputPin.In)); @@ -322,7 +322,7 @@ const fourBitAdderStage = defineStage("four-bit-adder", { return () => { const adders = Array.from({ length: digitCount }, (_, index) => circuit.place(fullAdderStage.componentId, { - x: -40, + x: -50, y: -300 + 200 * index, }), ); From 65ba5e2a01dbbd172784386511a0f9140003c361 Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 02:26:08 +0900 Subject: [PATCH 7/9] fix(tutorial): fit the view once and safely, and catch failures inside the check - The editor fits its view only once, and only when both sides of the renderer have a size, and a renderer smaller than the padding still gets a finite scale. - checkCombinational itself turns an exception into checkFailed, which is now tested. The message no longer suggests resetting the stage, which would throw the circuit away. Co-Authored-By: Claude Opus 5.5 --- src/i18n/en.ts | 2 +- src/i18n/ja.ts | 2 +- .../store/slices/perspective/fit.test.ts | 14 ++++++-- .../Editor/store/slices/perspective/fit.ts | 11 ++++-- .../Editor/store/slices/perspective/index.tsx | 34 +++++++++++-------- src/pages/tutorial/stage.tsx | 9 ++--- src/tutorial/check.test.ts | 14 ++++++++ src/tutorial/check.ts | 13 ++++++- 8 files changed, 70 insertions(+), 29 deletions(-) diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 2054c90..5780691 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -177,7 +177,7 @@ export const en = { ) => `When ${listOf(inputs.map(({ name, value }) => `${name} is ${value}`))}, ${pinName} should be ${expected}, but it ${actual === null ? "has no value" : `is ${actual}`}.`, checkFailed: - 'Something went wrong while checking. "Reset this stage" may fix it.', + "Something went wrong while checking. Change the circuit a little and press Check again.", simulationFailed: (detail: string) => `The circuit could not be simulated. ${detail}`, resetStage: "Reset this stage", diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index 6400e15..4456c7b 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -117,7 +117,7 @@ export const ja: Messages = { wrongOutput: (inputs, pinName, expected, actual) => `${inputs.map(({ name, value }) => `${name} が ${value}`).join("、")} のとき、${pinName} は ${expected} になるはずが、${actual === null ? "値がありませんでした" : `${actual} でした`}。`, checkFailed: - "確かめる途中で問題が起きました。「この課題をやり直す」で直ることがあります。", + "確かめる途中で問題が起きました。回路を少し変えてから、もう一度押してください。", simulationFailed: (detail) => `回路をシミュレーションできませんでした。${detail}`, resetStage: "この課題をやり直す", diff --git a/src/pages/edit/Editor/store/slices/perspective/fit.test.ts b/src/pages/edit/Editor/store/slices/perspective/fit.test.ts index 506698f..a33d480 100644 --- a/src/pages/edit/Editor/store/slices/perspective/fit.test.ts +++ b/src/pages/edit/Editor/store/slices/perspective/fit.test.ts @@ -55,11 +55,21 @@ describe("perspectiveFitting", () => { expect(perspective.scale).toBeGreaterThan(1); expectInsideRoom(rects, perspective); expect( - perspectiveFitting(rects, rendererSize).scale * - (rendererSize.y - fitPadding.top - fitPadding.bottom), + perspective.scale * (rendererSize.y - fitPadding.top - fitPadding.bottom), ).toBeCloseTo(1000); }); + it("stays finite on a renderer smaller than the padding", () => { + const perspective = perspectiveFitting( + [{ position: { x: 0, y: 0 }, size: { x: 100, y: 100 } }], + { x: 50, y: 200 }, + ); + + expect(Number.isFinite(perspective.scale)).toBe(true); + expect(Number.isFinite(perspective.center.x)).toBe(true); + expect(Number.isFinite(perspective.center.y)).toBe(true); + }); + it("shows the middle when there are no nodes", () => { expect(perspectiveFitting([], rendererSize)).toEqual({ center: { x: 0, y: 0 }, diff --git a/src/pages/edit/Editor/store/slices/perspective/fit.ts b/src/pages/edit/Editor/store/slices/perspective/fit.ts index 3da7b59..4748959 100644 --- a/src/pages/edit/Editor/store/slices/perspective/fit.ts +++ b/src/pages/edit/Editor/store/slices/perspective/fit.ts @@ -19,8 +19,15 @@ export function perspectiveFitting( const bottom = Math.max( ...rects.map((rect) => rect.position.y + rect.size.y), ); - const roomX = rendererSize.x - fitPadding.left - fitPadding.right; - const roomY = rendererSize.y - fitPadding.top - fitPadding.bottom; + // A renderer smaller than the padding still gets a finite scale + const roomX = Math.max( + 1, + rendererSize.x - fitPadding.left - fitPadding.right, + ); + const roomY = Math.max( + 1, + rendererSize.y - fitPadding.top - fitPadding.bottom, + ); const scale = Math.max(1, (right - left) / roomX, (bottom - top) / roomY); // The middle of the room is off the middle of the renderer by half the uneven padding return { diff --git a/src/pages/edit/Editor/store/slices/perspective/index.tsx b/src/pages/edit/Editor/store/slices/perspective/index.tsx index e124304..ba1b3f0 100644 --- a/src/pages/edit/Editor/store/slices/perspective/index.tsx +++ b/src/pages/edit/Editor/store/slices/perspective/index.tsx @@ -9,6 +9,7 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< > = ({ store, componentId }) => { let resizeObserver: ResizeObserver | null; let rendererElement: SVGSVGElement | null; + let hasFitted = false; const registerRendererElement = (element: SVGSVGElement | null) => { if (!resizeObserver) return; if (rendererElement) resizeObserver.unobserve(rendererElement); @@ -60,23 +61,26 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< y: entries[0].contentRect.height, }; const state = editorStore.getState(); - const isFirstSize = - state.rendererSize.x === 0 && state.rendererSize.y === 0; + const fitsNow = + state.fitsNodesInView && + !hasFitted && + rendererSize.x > 0 && + rendererSize.y > 0; + if (fitsNow) hasFitted = true; editorStore.setState({ rendererSize, - ...(isFirstSize && - state.fitsNodesInView && { - perspective: perspectiveFitting( - store.nodes - .getManyByParentComponentId(componentId) - .map( - (node) => - getCCComponentEditorRendererNodeGeometry(store, node.id) - .rect, - ), - rendererSize, - ), - }), + ...(fitsNow && { + perspective: perspectiveFitting( + store.nodes + .getManyByParentComponentId(componentId) + .map( + (node) => + getCCComponentEditorRendererNodeGeometry(store, node.id) + .rect, + ), + rendererSize, + ), + }), }); }); }, diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx index a99c6f1..098db80 100644 --- a/src/pages/tutorial/stage.tsx +++ b/src/pages/tutorial/stage.tsx @@ -96,13 +96,8 @@ function StageView({ stage }: { stage: TutorialStage }) { }, [store]); const check = () => { - let checked: CheckResult; - try { - checked = checkCombinational(store, stage.componentId, stage.check); - } catch (error) { - console.error(error); - checked = { type: "checkFailed", error }; - } + const checked = checkCombinational(store, stage.componentId, stage.check); + if (checked.type === "checkFailed") console.error(checked.error); setResult(checked); if (checked.type === "passed") markStageCleared(stage.id); }; diff --git a/src/tutorial/check.test.ts b/src/tutorial/check.test.ts index 70cd6c4..1fef46c 100644 --- a/src/tutorial/check.test.ts +++ b/src/tutorial/check.test.ts @@ -171,6 +171,20 @@ describe("checkCombinational", () => { }); }); + it("reports a check that throws instead of throwing", () => { + const { store } = stageStore(andStage); + const error = new Error("broken"); + + expect( + checkCombinational(store, andStage.componentId, { + ...andStage.check, + expected: () => { + throw error; + }, + }), + ).toEqual({ type: "checkFailed", error }); + }); + it("reports a circuit that cannot be simulated", () => { const { store } = stageStore(andStage); diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts index 225a302..b2816cd 100644 --- a/src/tutorial/check.ts +++ b/src/tutorial/check.ts @@ -29,7 +29,6 @@ export type CheckResult = actual: number; } | { type: "simulationFailed"; error: unknown } - /** the check itself failed, on a circuit it has no words for */ | { type: "checkFailed"; error: unknown } | { type: "wrongOutput"; @@ -99,6 +98,18 @@ export function checkCombinational( store: CCStore, componentId: CCComponentId, check: CombinationalCheck, +): CheckResult { + try { + return checkCircuit(store, componentId, check); + } catch (error) { + return { type: "checkFailed", error }; + } +} + +function checkCircuit( + store: CCStore, + componentId: CCComponentId, + check: CombinationalCheck, ): CheckResult { const pins = store.componentPins.getManyByComponentId(componentId); const findPin = (pinType: "input" | "output", pinName: string) => From ce15b00dedf611fa6774230fbbcc08acd01c87f5 Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 02:33:10 +0900 Subject: [PATCH 8/9] fix(tutorial): make the stage texts say what is on the screen - Stages 1 to 3 say the lamp turns ON, as the Out node shows, not that it lights. - Stage 6 says which side of Decompose and Aggregate holds the digits, names the Decompose nodes and adders the wires run between, and where the output C is. - Stage 6 tells where the sum is shown, what the 7seg does, and which letter is which number in hexadecimal. Co-Authored-By: Claude Opus 5.5 --- src/i18n/en.ts | 14 +++++++------- src/i18n/ja.ts | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 5780691..d4923a9 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -15,7 +15,7 @@ type StageTexts = { title: string; goal: string; steps: readonly string[] }; const stageTexts: Record = { and: { title: "Both switches", - goal: "Make the lamp Out light up only when both switches A and B are ON. The stage is cleared when the circuit works as in the table below.", + goal: "Make the lamp Out turn ON only when both switches A and B are ON. The stage is cleared when the circuit works as in the table below.", steps: [ "Pick a part in the Parts list and drag it onto the editor on the right.", "The small squares on the edges of a part are its pins. A pin on the left side is an input, which receives ON or OFF, and a pin on the right side is an output, which sends ON or OFF. Drag between an output pin and an input pin to connect them with a wire.", @@ -26,12 +26,12 @@ const stageTexts: Record = { }, "a-only": { title: "Only switch A", - goal: "Make the lamp Out light up only when switch A is ON and B is OFF. This time, one part alone is not enough.", + goal: "Make the lamp Out turn ON only when switch A is ON and B is OFF. This time, one part alone is not enough.", steps: [], }, xor: { title: "Only one switch", - goal: 'Make the lamp Out light up when exactly one of the switches A and B is ON. It does not light up when both are ON. "Only switch A" is ready to use as a part.', + goal: 'Make the lamp Out turn ON when exactly one of the switches A and B is ON. It stays OFF when both are ON. "Only switch A" is ready to use as a part.', steps: [], }, "half-adder": { @@ -48,10 +48,10 @@ const stageTexts: Record = { title: "Adding four digits", goal: "A and B are four-digit binary numbers. Output A + B in four digits to S, and its fifth digit, the sixteens digit, to C: C is 1 when A + B is 16 or more. The table shows some examples.", steps: [ - 'Place four "Adding with a carry". From the top, the pins of Decompose and Aggregate are the eights, fours, twos and ones digits.', - "For each digit, connect that digit of A and of B to the A and B of one adder, and its S to the same digit of Aggregate.", - "Connect the C of each digit to the Cin of the digit above. The ones digit gets False on its Cin, and the C of the eights digit goes to the output C.", - "While playing, click a digit of A or B to switch it between 0 and 1. The sum also shows on the right, with 10 to 15 shown as the letters A, b, C, d, E and F.", + 'Place four "Adding with a carry". From the top, the pins on the right of Decompose and on the left of Aggregate are the eights, fours, twos and ones digits.', + "For each digit, connect that digit's pin on the upper Decompose, which A goes into, and on the lower one, which B goes into, to the A and B of one \"Adding with a carry\". Connect the S of that adder to the same digit's pin of Aggregate.", + "Connect the C of each digit's adder to the Cin of the adder one digit up. The ones digit's adder gets False on its Cin, and the C of the eights digit's adder goes to the output C on the right.", + "While playing, click a digit of A or B to switch it between 0 and 1. The sum S is shown as one character on the Display at the top right. The 7seg before it turns the binary number into the shape of a numeral. To write 10 to 15 with one character, A (10), b (11), C (12), d (13), E (14) and F (15) are used. This way of writing is called hexadecimal.", ], }, }; diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index 4456c7b..1c8c72f 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -130,7 +130,7 @@ export const ja: Messages = { stageTexts: { and: { title: "両方のスイッチ", - goal: "スイッチ A と B が両方 ON のときだけ、ランプ Out がつくようにしましょう。下の表のとおりに動けばクリアです。", + goal: "スイッチ A と B が両方 ON のときだけ、ランプ Out が ON になるようにしましょう。下の表のとおりに動けばクリアです。", steps: [ "「部品」の一覧から部品を選び、右のエディタにドラッグして置きます。", "部品の端にある小さな四角を「ピン」といいます。左側のピンは ON か OFF を受け取る「入力」、右側のピンは ON か OFF を送り出す「出力」です。出力のピンと入力のピンのあいだをドラッグして、線でつなぎます。", @@ -141,12 +141,12 @@ export const ja: Messages = { }, "a-only": { title: "A だけのスイッチ", - goal: "スイッチ A が ON で、B が OFF のときだけ、ランプ Out がつくようにしましょう。今度は、部品を1つ置くだけではできません。", + goal: "スイッチ A が ON で、B が OFF のときだけ、ランプ Out が ON になるようにしましょう。今度は、部品を1つ置くだけではできません。", steps: [], }, xor: { title: "片方だけのスイッチ", - goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out がつくようにしましょう。両方 ON のときはつきません。「A だけのスイッチ」を部品として使えます。", + goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out が ON になるようにしましょう。両方 ON のときは OFF です。「A だけのスイッチ」を部品として使えます。", steps: [], }, "half-adder": { @@ -163,10 +163,10 @@ export const ja: Messages = { title: "4桁の足し算", goal: "A と B は4桁の2進数です。A+B を4桁で S に、5桁目(16の位)を C に出しましょう。A+B が 16 以上なら、C は 1 です。表はその例です。", steps: [ - "「桁上がりつきの足し算」を4つ置きます。Decompose と Aggregate のピンは、上から8の位・4の位・2の位・1の位です。", - "桁ごとに、A と B のその桁を1つの足し算の A と B に、その S を Aggregate の同じ桁につなぎます。", - "それぞれの桁の C を、1つ上の桁の Cin につなぎます。1の位の Cin には False を、8の位の C は出力の C につなぎます。", - "再生中は、A と B の桁をクリックして 0 と 1 を切り替えられます。答えは右にも出ます(10 から 15 は、A、b、C、d、E、F の字で出ます)。", + "「桁上がりつきの足し算」を4つ置きます。Decompose の右側のピンと Aggregate の左側のピンは、どちらも上から8の位・4の位・2の位・1の位です。", + "桁ごとに、A につないだ上の Decompose と、B につないだ下の Decompose から、その桁のピンを1つの「桁上がりつきの足し算」の A と B につなぎます。その足し算の S は、Aggregate の同じ桁のピンにつなぎます。", + "それぞれの桁の足し算の C を、1つ上の桁の足し算の Cin につなぎます。1の位の足し算の Cin には False を、8の位の足し算の C は右の出力 C につなぎます。", + "再生中は、A と B の桁をクリックして 0 と 1 を切り替えられます。答えの S は、右上の Display に1文字で表示されます。その手前の 7seg が、2進数を数字の形に変えています。10 から 15 は1文字で書くために、A(10)、b(11)、C(12)、d(13)、E(14)、F(15)を使います。この書き方を16進数といいます。", ], }, }, From 11ee90ef97369fa46dce2f08a4df76bc810abef7 Mon Sep 17 00:00:00 2001 From: Rn86222 Date: Fri, 20 Nov 2026 02:40:17 +0900 Subject: [PATCH 9/9] fix: colour every 1 in a truth table, also inside values of several bits Only one-bit values were coloured, so a stage's example table showed C's 1 in green but the 1s of S in black. Each bit now carries its own colour, and digits keep their width. Co-Authored-By: Claude Opus 5.5 --- src/components/TruthTableView.tsx | 40 +++++++++++++++---------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/components/TruthTableView.tsx b/src/components/TruthTableView.tsx index 222ae9c..75f0630 100644 --- a/src/components/TruthTableView.tsx +++ b/src/components/TruthTableView.tsx @@ -7,14 +7,12 @@ import { theme } from "../style"; import { BitNotationContext } from "./bitNotation"; const divider = (muiTheme: Theme) => `1px solid ${muiTheme.palette.divider}`; +const onSx = { color: theme.colors.primary, fontWeight: "bold" } as const; +const binaryOf = (value: SimulationValue) => value.map(bitDigit).join(""); export function TruthTableView({ table }: { table: TruthTable }) { - const bitLabelOf = + const singleBitLabel = useContext(BitNotationContext) === "digits" ? bitDigit : bitLabel; - const labelOf = (value: SimulationValue) => - value.length === 1 && value[0] !== undefined - ? bitLabelOf(value[0]) - : value.map(bitDigit).join(""); const columns = [ ...table.inputs.map((name) => ({ key: `in-${name}`, name })), ...table.outputs.map((name) => ({ key: `out-${name}`, name })), @@ -31,7 +29,11 @@ export function TruthTableView({ table }: { table: TruthTable }) { return ( @@ -48,21 +50,19 @@ export function TruthTableView({ table }: { table: TruthTable }) { {table.rows.map((row) => ( - + {[...row.inputs, ...row.outputs].map((value, i) => ( - - {labelOf(value)} + + {value.map((bit, index) => ( + + {value.length === 1 ? singleBitLabel(bit) : bitDigit(bit)} + + ))} ))}