diff --git a/src/common/bitLabel.ts b/src/common/bitLabel.ts index b40e885..a99c590 100644 --- a/src/common/bitLabel.ts +++ b/src/common/bitLabel.ts @@ -1,11 +1,18 @@ import type { SimulationValue } from "../store/simulation"; +/** How a table writes a bit: digits once binary has been taught */ +export type BitNotation = "onOff" | "digits"; + export function bitLabel(bit: boolean): string { return bit ? "ON" : "OFF"; } +export function bitDigit(bit: boolean): string { + return bit ? "1" : "0"; +} + export function valueLabel(value: SimulationValue): string { const [bit] = value; if (value.length === 1 && bit !== undefined) return bitLabel(bit); - return value.map((b) => (b ? "1" : "0")).join(""); + return value.map(bitDigit).join(""); } diff --git a/src/components/TruthTableView.tsx b/src/components/TruthTableView.tsx index 0cf74a8..7cd6869 100644 --- a/src/components/TruthTableView.tsx +++ b/src/components/TruthTableView.tsx @@ -1,9 +1,15 @@ -import { Box } from "@mui/material"; -import { bitLabel } from "../common/bitLabel"; +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 { theme } from "../style"; +import { BitNotationContext } from "./bitNotation"; + +const divider = (muiTheme: Theme) => `1px solid ${muiTheme.palette.divider}`; export function TruthTableView({ table }: { table: TruthTable }) { + const labelOf = + useContext(BitNotationContext) === "digits" ? bitDigit : bitLabel; const columns = [ ...table.inputs.map((name) => ({ key: `in-${name}`, name })), ...table.outputs.map((name) => ({ key: `out-${name}`, name })), @@ -14,10 +20,7 @@ export function TruthTableView({ table }: { table: TruthTable }) { py: 0.25, textAlign: "center", ...(table.inputs.length > 0 && - column === table.inputs.length && { - borderLeft: 1, - borderColor: "divider", - }), + column === table.inputs.length && { borderLeft: divider }), }) as const; return ( @@ -31,7 +34,7 @@ export function TruthTableView({ table }: { table: TruthTable }) { {name} @@ -53,7 +56,7 @@ export function TruthTableView({ table }: { table: TruthTable }) { }), }} > - {bitLabel(value)} + {labelOf(value)} ))} diff --git a/src/components/bitNotation.ts b/src/components/bitNotation.ts new file mode 100644 index 0000000..cbcb618 --- /dev/null +++ b/src/components/bitNotation.ts @@ -0,0 +1,4 @@ +import { createContext } from "react"; +import type { BitNotation } from "../common/bitLabel"; + +export const BitNotationContext = createContext("onOff"); diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 62463c1..ff6dd0c 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -33,6 +33,16 @@ const stageTexts: Record = { 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.', steps: [], }, + "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.", + steps: [], + }, + "full-adder": { + title: "Adding with a carry", + 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: [], + }, }; export const en = { @@ -135,6 +145,7 @@ export const en = { parts: "Parts", goalHeading: "Goal", stepsHeading: "Steps", + digitsLegend: "In the tables, 1 is ON and 0 is OFF.", check: "Check", passed: "Cleared! The circuit works for every combination of the inputs.", next: "Next stage", @@ -147,7 +158,7 @@ export const en = { expected: string, actual: string | null, ) => - `When ${inputs.map(({ name, value }) => `${name} is ${value}`).join(" and ")}, ${pinName} should be ${expected}, but it ${actual === null ? "has no value" : `is ${actual}`}.`, + `When ${listOf(inputs.map(({ name, value }) => `${name} is ${value}`))}, ${pinName} should be ${expected}, but it ${actual === null ? "has no value" : `is ${actual}`}.`, 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 1dd86fd..ab50e73 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -103,6 +103,7 @@ export const ja: Messages = { parts: "部品", goalHeading: "目標", stepsHeading: "手順", + digitsLegend: "表の 1 は ON、0 は OFF です。", check: "確かめる", passed: "クリア!どの入力の組み合わせでも正しく動きます。", next: "次の課題へ", @@ -142,6 +143,16 @@ export const ja: Messages = { goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out がつくようにしましょう。両方 ON のときはつきません。「A だけのスイッチ」を部品として使えます。", 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 を「和」といい、この回路を「半加算器」といいます。", + 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 を足します。この回路を「全加算器」といいます。", + steps: [], + }, }, }, componentProperties: { diff --git a/src/i18n/messages.test.ts b/src/i18n/messages.test.ts index e7db275..2bf764c 100644 --- a/src/i18n/messages.test.ts +++ b/src/i18n/messages.test.ts @@ -100,6 +100,38 @@ describe("Japanese messages", () => { }); }); +describe("the message on a wrong output", () => { + const inputs = [ + { name: "A", value: "ON" }, + { name: "B", value: "OFF" }, + { name: "Cin", value: "ON" }, + ]; + + it("lists the inputs as a sentence in English", () => { + expect( + messagesByLanguage.en.tutorial.wrongOutput(inputs, "C", "ON", "OFF"), + ).toBe( + "When A is ON, B is OFF and Cin is ON, C should be ON, but it is OFF.", + ); + expect( + messagesByLanguage.en.tutorial.wrongOutput( + inputs.slice(0, 2), + "C", + "ON", + null, + ), + ).toBe("When A is ON and B is OFF, C should be ON, but it has no value."); + }); + + it("lists the inputs in Japanese", () => { + expect( + messagesByLanguage.ja.tutorial.wrongOutput(inputs, "C", "ON", "OFF"), + ).toBe( + "A が ON、B が OFF、Cin が ON のとき、C は ON になるはずが、OFF でした。", + ); + }); +}); + describe("English messages", () => { it("lists the inputs reset with their bit widths", () => { expect( diff --git a/src/pages/edit/Editor/renderer/Node/components/Interface/Value/index.tsx b/src/pages/edit/Editor/renderer/Node/components/Interface/Value/index.tsx index 2fac409..ae55061 100644 --- a/src/pages/edit/Editor/renderer/Node/components/Interface/Value/index.tsx +++ b/src/pages/edit/Editor/renderer/Node/components/Interface/Value/index.tsx @@ -1,5 +1,5 @@ import clsx from "clsx"; -import { bitLabel } from "../../../../../../../../common/bitLabel"; +import { bitDigit, bitLabel } from "../../../../../../../../common/bitLabel"; import type { SimulationValue } from "../../../../../../../../store/simulation"; import { stringifySimulationValue } from "../../../../../store/slices/core"; import { CCComponentEditorRendererNodeInterfaceRendererValueEditButton } from "./EditButton"; @@ -46,7 +46,7 @@ export function CCComponentEditorRendererNodeInterfaceRendererValue({ > {value.map((bit, index) => { const className = clsx(styles.bit, bit && styles.on); - const label = isSingleBit ? bitLabel(bit) : bit ? "1" : "0"; + const label = isSingleBit ? bitLabel(bit) : bitDigit(bit); return onChange ? ( - - - {/* Outside the scrolling, so that Check and its result stay in view */} - - - {result?.type === "passed" && ( - <> - {texts.passed} - - - )} - {result && result.type !== "passed" && ( - - {describeFailure(result, store, messages)} - - )} - - - - - - - {texts.parts} - - + + {hasResetFailed && ( + {texts.resetStageFailed} + )} + + + + {/* Outside the scrolling, so that Check and its result stay in view */} + + + {result?.type === "passed" && ( + <> + {texts.passed} + + + )} + {result && result.type !== "passed" && ( + + {describeFailure(result, store, messages)} + + )} + - isStagePinNode(store, stage, nodeId), - isOffered, - canCreateComponents: stage.allowsNewComponents, - hasProperties: (componentId) => - !isStageComponent(stage, componentId), - }} - onEditComponent={setEditedComponentId} - onClose={() => { - if (shownComponentId === stage.componentId) navigate("/tutorial"); - else setEditedComponentId(stage.componentId); - }} - /> - - {isConfirmingReset && ( - setIsConfirmingReset(false)} - > - {texts.resetStageDialog.body} - - )} - + + + + {texts.parts} + + + + + isStagePinNode(store, stage, nodeId), + isOffered, + canCreateComponents: stage.allowsNewComponents, + hasProperties: (componentId) => + !isStageComponent(stage, componentId), + }} + onEditComponent={setEditedComponentId} + onClose={() => { + if (shownComponentId === stage.componentId) navigate("/tutorial"); + else setEditedComponentId(stage.componentId); + }} + /> + + {isConfirmingReset && ( + setIsConfirmingReset(false)} + > + {texts.resetStageDialog.body} + + )} + + ); } diff --git a/src/tutorial/check.test.ts b/src/tutorial/check.test.ts index b8411d3..687a25c 100644 --- a/src/tutorial/check.test.ts +++ b/src/tutorial/check.test.ts @@ -79,6 +79,21 @@ 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] }, + ], + }); + }); + it("gives no table when a pin carries more than one bit", () => { const wideInput: CombinationalCheck = { inputs: [{ name: "A", bitWidth: 2 }], diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts index 7f36d02..291a767 100644 --- a/src/tutorial/check.ts +++ b/src/tutorial/check.ts @@ -53,7 +53,7 @@ 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, which a table of ON and OFF cannot show */ +/** null when a pin carries more than one bit */ export function truthTableOfCheck( check: CombinationalCheck, ): TruthTable | null { diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts index fbb7f37..aa77176 100644 --- a/src/tutorial/stages.test.ts +++ b/src/tutorial/stages.test.ts @@ -31,6 +31,16 @@ const aOnlyStage = nullthrows(findTutorialStage("a-only")); const titleOf = (id: TutorialStageId) => `Stage ${id}`; describe("tutorialStages", () => { + it("writes tables in digits from the stage that teaches binary on", () => { + const binaryFrom = tutorialStages.findIndex((s) => s.id === "half-adder"); + + expect(tutorialStages.map((s) => s.tableNotation)).toEqual( + tutorialStages.map((_, index) => + index < binaryFrom ? "onOff" : "digits", + ), + ); + }); + it("hands over only the parts of earlier stages", () => { for (const [index, later] of tutorialStages.entries()) { for (const id of later.givenParts) { diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index 560fde6..31e547f 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -1,4 +1,5 @@ import nullthrows from "nullthrows"; +import type { BitNotation } from "../common/bitLabel"; import type CCStore from "../store"; import { type CCComponent, @@ -6,12 +7,25 @@ import { CCComponentStore, } from "../store/component"; import type { CCComponentPin } from "../store/componentPin"; -import { and, input, not, or, output } from "../store/intrinsics/definitions"; +import { + and, + input, + not, + or, + output, + xor, +} from "../store/intrinsics/definitions"; import { type CCNodeId, CCNodeStore } from "../store/node"; import type { CombinationalCheck } from "./check"; import { StageCircuit } from "./circuit"; -export const tutorialStageIds = ["and", "a-only", "xor"] as const; +export const tutorialStageIds = [ + "and", + "a-only", + "xor", + "half-adder", + "full-adder", +] as const; export type TutorialStageId = (typeof tutorialStageIds)[number]; export type StageTitleOf = (id: TutorialStageId) => string; @@ -24,6 +38,7 @@ export type TutorialStage = { /** earlier stages whose components the stage hands over, built and ready to use */ givenParts: readonly TutorialStageId[]; allowsNewComponents: boolean; + tableNotation: BitNotation; /** also the input and output pins the stage starts with */ check: CombinationalCheck; solve(circuit: StageCircuit): void; @@ -34,28 +49,51 @@ const gateParts = [and, or, not].map((gate) => gate.component.id); const bit = (value: boolean) => [value]; const isOn = (value: readonly boolean[] | undefined) => nullthrows(value?.[0]); -function twoSwitchesStage( +const oneBitInputs = (...names: string[]) => + names.map((name) => ({ name, bitWidth: 1 })); + +type StageDefinition = Pick & + Partial>; + +function defineStage( id: TutorialStageId, - definition: Pick & - Partial>, - lampIsOn: (a: boolean, b: boolean) => boolean, + definition: StageDefinition, ): TutorialStage { return { id, componentId: `tutorial-${id}` as CCComponentId, givenParts: [], - ...definition, allowsNewComponents: false, + tableNotation: "onOff", + ...definition, + }; +} + +function twoSwitchesStage( + id: TutorialStageId, + definition: Omit, + lampIsOn: (a: boolean, b: boolean) => boolean, +): TutorialStage { + return defineStage(id, { + ...definition, check: { - inputs: [ - { name: "A", bitWidth: 1 }, - { name: "B", bitWidth: 1 }, - ], + inputs: oneBitInputs("A", "B"), outputs: ["Out"], expected: (values) => ({ Out: bit(lampIsOn(isOn(values.A), isOn(values.B))), }), }, + }); +} + +function addingCheck(...inputNames: string[]): CombinationalCheck { + return { + inputs: oneBitInputs(...inputNames), + outputs: ["C", "S"], + expected: (values) => { + const total = inputNames.filter((name) => isOn(values[name])).length; + return { C: bit(total >= 2), S: bit(total % 2 === 1) }; + }, }; } @@ -128,10 +166,60 @@ const xorStage = twoSwitchesStage( (a, b) => a !== b, ); +const halfAdderStage = defineStage("half-adder", { + parts: [and.component.id, xor.component.id], + tableNotation: "digits", + check: addingCheck("A", "B"), + solve(circuit) { + const carry = circuit.place(and.component.id, { x: 0, y: -100 }); + const sum = circuit.place(xor.component.id, { x: 0, y: 100 }); + for (const [node, gate] of [ + [carry, and], + [sum, xor], + ] as const) { + circuit.connect(circuit.pin("A"), circuit.pinOf(node, gate.inputPin.A)); + circuit.connect(circuit.pin("B"), circuit.pinOf(node, gate.inputPin.B)); + } + circuit.connect(circuit.pinOf(carry, and.outputPin.Out), circuit.pin("C")); + circuit.connect(circuit.pinOf(sum, xor.outputPin.Out), circuit.pin("S")); + }, +}); + +const fullAdderStage = defineStage("full-adder", { + parts: [or.component.id], + givenParts: ["half-adder"], + tableNotation: "digits", + check: addingCheck("A", "B", "Cin"), + solve(circuit) { + const first = circuit.place(halfAdderStage.componentId, { + x: -140, + y: -100, + }); + const second = circuit.place(halfAdderStage.componentId, { x: 0, y: 100 }); + const either = circuit.place(or.component.id, { x: 150, y: -100 }); + circuit.connect(circuit.pin("A"), circuit.pinOf(first, "A")); + circuit.connect(circuit.pin("B"), circuit.pinOf(first, "B")); + circuit.connect(circuit.pinOf(first, "S"), circuit.pinOf(second, "A")); + circuit.connect(circuit.pin("Cin"), circuit.pinOf(second, "B")); + circuit.connect( + circuit.pinOf(first, "C"), + circuit.pinOf(either, or.inputPin.A), + ); + circuit.connect( + circuit.pinOf(second, "C"), + circuit.pinOf(either, or.inputPin.B), + ); + circuit.connect(circuit.pinOf(either, or.outputPin.Out), circuit.pin("C")); + circuit.connect(circuit.pinOf(second, "S"), circuit.pin("S")); + }, +}); + export const tutorialStages: readonly TutorialStage[] = [ andStage, aOnlyStage, xorStage, + halfAdderStage, + fullAdderStage, ]; export function findTutorialStage(id: string | undefined) {