diff --git a/src/components/TruthTableView.tsx b/src/components/TruthTableView.tsx
index 75f0630..cd6a15c 100644
--- a/src/components/TruthTableView.tsx
+++ b/src/components/TruthTableView.tsx
@@ -1,30 +1,39 @@
import { Box, type Theme } from "@mui/material";
import { useContext } from "react";
import { bitDigit, bitLabel } from "../common/bitLabel";
+import { useMessages } from "../i18n";
import type { TruthTable } from "../store/intrinsics/truthTable";
import type { SimulationValue } from "../store/simulation";
import { theme } from "../style";
import { BitNotationContext } from "./bitNotation";
+import { truthTableColumnsOf, truthTableLinesOf } from "./truthTableLayout";
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 messages = useMessages();
const singleBitLabel =
useContext(BitNotationContext) === "digits" ? bitDigit : bitLabel;
- const columns = [
- ...table.inputs.map((name) => ({ key: `in-${name}`, name })),
- ...table.outputs.map((name) => ({ key: `out-${name}`, name })),
- ];
+ const columns = truthTableColumnsOf(table, messages.truthTable.timeStep);
const cellSx = (column: number) =>
({
px: 1,
py: 0.25,
textAlign: "center",
- ...(table.inputs.length > 0 &&
- column === table.inputs.length && { borderLeft: divider }),
+ ...(columns[column]?.startsGroup && { borderLeft: divider }),
}) as const;
+ const valueCell = (value: SimulationValue) =>
+ value.map((bit, index) => (
+
+ {value.length === 1 ? singleBitLabel(bit) : bitDigit(bit)}
+
+ ));
return (
- {table.rows.map((row) => (
-
- {[...row.inputs, ...row.outputs].map((value, i) => (
-
- {value.map((bit, index) => (
-
- {value.length === 1 ? singleBitLabel(bit) : bitDigit(bit)}
-
- ))}
-
- ))}
-
- ))}
+ {truthTableLinesOf(table).map((line) => {
+ const cells =
+ line.type === "gap"
+ ? columns.map(() => "⋮")
+ : [
+ ...(line.stepLabel === null ? [] : [line.stepLabel]),
+ ...line.values.map(valueCell),
+ ];
+ return (
+
+ {cells.map((cell, i) => (
+
+ {cell}
+
+ ))}
+
+ );
+ })}
);
diff --git a/src/components/truthTableLayout.test.ts b/src/components/truthTableLayout.test.ts
new file mode 100644
index 0000000..d334fed
--- /dev/null
+++ b/src/components/truthTableLayout.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vitest";
+import type { TruthTable } from "../store/intrinsics/truthTable";
+import { truthTableColumnsOf, truthTableLinesOf } from "./truthTableLayout";
+
+const overTime: TruthTable = {
+ inputs: [],
+ outputs: ["Count"],
+ rows: [1, 2, 16, 17].map((stepNumber) => ({
+ inputs: [],
+ outputs: [[stepNumber % 2 === 0]],
+ stepNumber,
+ })),
+};
+
+describe("truthTableColumnsOf", () => {
+ it("parts the inputs from the outputs", () => {
+ const table: TruthTable = { inputs: ["A"], outputs: ["Out"], rows: [] };
+
+ expect(truthTableColumnsOf(table, "Step")).toEqual([
+ { key: "in-A", name: "A", startsGroup: false },
+ { key: "out-Out", name: "Out", startsGroup: true },
+ ]);
+ });
+
+ it("puts the time steps first, parted from a table without inputs", () => {
+ expect(truthTableColumnsOf(overTime, "Step")).toEqual([
+ { key: "step", name: "Step", startsGroup: false },
+ { key: "out-Count", name: "Count", startsGroup: true },
+ ]);
+ });
+});
+
+describe("truthTableLinesOf", () => {
+ it("puts a gap only where steps are skipped, and keys rows by their step", () => {
+ expect(
+ truthTableLinesOf(overTime).map((line) =>
+ line.type === "gap" ? "gap" : `${line.key}:${line.stepLabel}`,
+ ),
+ ).toEqual(["1:1", "2:2", "gap", "16:16", "17:17"]);
+ });
+
+ it("gives no step to a table that does not run over time", () => {
+ const table: TruthTable = {
+ inputs: ["A"],
+ outputs: ["Out"],
+ rows: [false, true].map((a) => ({ inputs: [[a]], outputs: [[!a]] })),
+ };
+
+ expect(truthTableLinesOf(table)).toEqual([
+ { type: "row", key: "0", stepLabel: null, values: [[false], [true]] },
+ { type: "row", key: "1", stepLabel: null, values: [[true], [false]] },
+ ]);
+ });
+});
diff --git a/src/components/truthTableLayout.ts b/src/components/truthTableLayout.ts
new file mode 100644
index 0000000..b9be5d3
--- /dev/null
+++ b/src/components/truthTableLayout.ts
@@ -0,0 +1,68 @@
+import { bitDigit } from "../common/bitLabel";
+import type { TruthTable } from "../store/intrinsics/truthTable";
+import type { SimulationValue } from "../store/simulation";
+
+export type TruthTableColumn = {
+ key: string;
+ name: string;
+ /** A line on its left parts it from the columns before */
+ startsGroup: boolean;
+};
+
+export type TruthTableLine =
+ | {
+ type: "row";
+ key: string;
+ /** null when the table has no column of time steps */
+ stepLabel: string | null;
+ values: SimulationValue[];
+ }
+ | { type: "gap"; key: string };
+
+const binaryOf = (value: SimulationValue) => value.map(bitDigit).join("");
+
+const hasStepColumn = (table: TruthTable) =>
+ table.rows.some((row) => row.stepNumber !== undefined);
+
+export function truthTableColumnsOf(
+ table: TruthTable,
+ stepColumnName: string,
+): TruthTableColumn[] {
+ const groups = [
+ hasStepColumn(table) ? [{ key: "step", name: stepColumnName }] : [],
+ table.inputs.map((name) => ({ key: `in-${name}`, name })),
+ table.outputs.map((name) => ({ key: `out-${name}`, name })),
+ ].filter((group) => group.length > 0);
+ return groups.flatMap((group, groupIndex) =>
+ group.map((column, index) => ({
+ ...column,
+ startsGroup: groupIndex > 0 && index === 0,
+ })),
+ );
+}
+
+/** The rows of a table, with a gap where it skips time steps */
+export function truthTableLinesOf(table: TruthTable): TruthTableLine[] {
+ const hasSteps = hasStepColumn(table);
+ return table.rows.flatMap((row, index): TruthTableLine[] => {
+ const { stepNumber } = row;
+ const previousStepNumber = table.rows[index - 1]?.stepNumber;
+ const isAfterGap =
+ stepNumber !== undefined &&
+ previousStepNumber !== undefined &&
+ stepNumber > previousStepNumber + 1;
+ const key =
+ stepNumber === undefined
+ ? row.inputs.map(binaryOf).join()
+ : String(stepNumber);
+ return [
+ ...(isAfterGap ? [{ type: "gap" as const, key: `gap-${key}` }] : []),
+ {
+ type: "row",
+ key,
+ stepLabel: hasSteps ? String(stepNumber ?? "") : null,
+ values: [...row.inputs, ...row.outputs],
+ },
+ ];
+ });
+}
diff --git a/src/i18n/en.ts b/src/i18n/en.ts
index 25270f1..c35da6a 100644
--- a/src/i18n/en.ts
+++ b/src/i18n/en.ts
@@ -54,6 +54,16 @@ const stageTexts: Record = {
"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.",
],
},
+ counter: {
+ title: "Counter",
+ goal: "After pressing the play button, a number with an arrow button on each side appears at the bottom. The number is called the time step, and the right arrow goes to the next one. The circuit runs one time step at a time. Make Count go up by 1 at each time step, and go back to 0000 after 1111. 0000 to 1111 are 0 to F in hexadecimal.",
+ steps: [
+ "Place a FlipFlop. A FlipFlop outputs what it received at the time step before, and 0 at the first time step. Connect its output to Count and to the 7seg at the top right.",
+ "Place a Const. A Const always outputs the value written in it. Change 00000000 in its box to 0001 and press Apply (four digits, to match the B it connects to).",
+ 'Place "Adding four digits". Connect the output of the FlipFlop to its A, the Const to its B, and its S to the input of the FlipFlop. Then the number the FlipFlop outputs plus 1 comes out of the FlipFlop at the next time step. C is not used.',
+ 'Press the play button and go through the time steps with the right arrow. Press "Auto" to go on by itself, one time step a second. The circuit works when the Display at the top right shows 0 to F in turn.',
+ ],
+ },
};
export const en = {
@@ -77,6 +87,9 @@ export const en = {
"Splits a number of several digits, from the highest digit down",
AGGREGATE:
"Joins values into one number, the upper pins as the higher digits",
+ FLIPFLOP:
+ "Outputs what it received at the time step before (0 at the first time step)",
+ CONST: "Always outputs the value written in it",
},
about: (name: string) => `About ${name}`,
ofStage: "Available parts",
@@ -145,6 +158,9 @@ export const en = {
startOverFailed: "Could not start over.",
},
},
+ truthTable: {
+ timeStep: "Time step",
+ },
tutorial: {
lead: "Going from the top is recommended, but you can start from any stage.",
stageNumber: (number: number) => `Stage ${number}`,
@@ -160,7 +176,7 @@ export const en = {
parts: "Parts",
goalHeading: "Goal",
stepsHeading: "Steps",
- digitsLegend: "In the tables, 1 is ON and 0 is OFF.",
+ digitsLegend: "The tables write ON as 1 and OFF as 0.",
check: "Check",
passed: "Cleared! The circuit works for every combination of the inputs.",
passedSteps: (count: number) =>
diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts
index 73f8456..c02fc73 100644
--- a/src/i18n/ja.ts
+++ b/src/i18n/ja.ts
@@ -23,6 +23,8 @@ export const ja: Messages = {
FALSE: "いつも OFF",
DECOMPOSE: "何桁もある数を、上の桁から順に分ける",
AGGREGATE: "上のピンを大きい桁として、1つの数にまとめる",
+ FLIPFLOP: "1つ前のステップで受け取った値を出す(最初のステップでは 0)",
+ CONST: "中に書いた値をいつも出す",
},
about: (name) => `${name} について`,
ofStage: "使える部品",
@@ -90,6 +92,9 @@ export const ja: Messages = {
startOverFailed: "やり直せませんでした。",
},
},
+ truthTable: {
+ timeStep: "ステップ",
+ },
tutorial: {
lead: "上から順に進めるのがおすすめですが、どの課題からでも始められます。",
stageNumber: (number) => `課題 ${number}`,
@@ -105,7 +110,7 @@ export const ja: Messages = {
parts: "部品",
goalHeading: "目標",
stepsHeading: "手順",
- digitsLegend: "表の 1 は ON、0 は OFF です。",
+ digitsLegend: "表では、ON を 1、OFF を 0 と書いています。",
check: "確かめる",
passed: "クリア!どの入力の組み合わせでも正しく動きます。",
passedSteps: (count) =>
@@ -173,6 +178,16 @@ export const ja: Messages = {
"再生中は、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進数といいます。",
],
},
+ counter: {
+ title: "カウンタ",
+ goal: "再生ボタンを押すと、下に数字と、その左右に矢印のボタンが出ます。この数字を「ステップ」といい、右の矢印を押すと次のステップに進みます。回路はステップごとに動きます。Count が 1 ステップごとに 1 ずつ増え、1111 の次は 0000 に戻るようにしましょう。0000 から 1111 は、16進数の 0 から F です。",
+ steps: [
+ "FlipFlop を置きます。FlipFlop は、1つ前のステップで受け取った値を出します。最初のステップでは 0 を出します。FlipFlop の出力を、Count と、右上の 7seg につなぎます。",
+ "Const を置きます。Const は、中に書いた値をいつも出します。欄の 00000000 を 0001 に書きかえて、「適用」を押します(つなぐ先の B に合わせて、4桁で書きます)。",
+ "「4桁の足し算」を置き、FlipFlop の出力を A に、Const を B に、S を FlipFlop の入力につなぎます。こうすると、FlipFlop が出している数に 1 を足した数が、次のステップで FlipFlop から出てきます。C は使いません。",
+ "再生ボタンを押し、右の矢印でステップを進めます。「自動」を押すと、1秒に1ステップずつひとりでに進みます。右上の Display に 0 から F が順に出れば、うまく動いています。",
+ ],
+ },
},
},
componentProperties: {
diff --git a/src/pages/edit/Editor/store/index.tsx b/src/pages/edit/Editor/store/index.tsx
index 7d415dd..fa03d3e 100644
--- a/src/pages/edit/Editor/store/index.tsx
+++ b/src/pages/edit/Editor/store/index.tsx
@@ -1,6 +1,7 @@
import { createContext, useContext, useState } from "react";
import invariant from "tiny-invariant";
import { create } from "zustand";
+import type { Rect } from "../../../../common/rect";
import type CCStore from "../../../../store";
import type { CCComponentId } from "../../../../store/component";
import type { CCNodeId } from "../../../../store/node";
@@ -16,6 +17,7 @@ export type EditorStoreOptions = {
isOffered?: OffersComponent;
canCreateComponents?: boolean;
fitsNodesInView?: boolean;
+ areaToFit?: Rect | null;
hasProperties?: (componentId: CCComponentId) => boolean;
};
@@ -28,6 +30,7 @@ export function createEditorStore(
hasProperties = () => true,
canCreateComponents = true,
fitsNodesInView = false,
+ areaToFit = null,
}: EditorStoreOptions = {},
) {
const props = { store, componentId };
@@ -41,6 +44,7 @@ export function createEditorStore(
hasProperties,
canCreateComponents,
fitsNodesInView,
+ areaToFit,
...coreSlice.define(set, get),
...perspectiveSlice.define(set, get),
...contextMenuSlice.define(set, get),
diff --git a/src/pages/edit/Editor/store/slices/perspective/index.tsx b/src/pages/edit/Editor/store/slices/perspective/index.tsx
index ba1b3f0..a2053b5 100644
--- a/src/pages/edit/Editor/store/slices/perspective/index.tsx
+++ b/src/pages/edit/Editor/store/slices/perspective/index.tsx
@@ -71,13 +71,16 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator<
rendererSize,
...(fitsNow && {
perspective: perspectiveFitting(
- store.nodes
- .getManyByParentComponentId(componentId)
- .map(
- (node) =>
- getCCComponentEditorRendererNodeGeometry(store, node.id)
- .rect,
- ),
+ [
+ ...store.nodes
+ .getManyByParentComponentId(componentId)
+ .map(
+ (node) =>
+ getCCComponentEditorRendererNodeGeometry(store, node.id)
+ .rect,
+ ),
+ ...(state.areaToFit ? [state.areaToFit] : []),
+ ],
rendererSize,
),
}),
diff --git a/src/pages/edit/Editor/store/types.ts b/src/pages/edit/Editor/store/types.ts
index d60c6a8..0648e2a 100644
--- a/src/pages/edit/Editor/store/types.ts
+++ b/src/pages/edit/Editor/store/types.ts
@@ -1,4 +1,5 @@
import type { StoreApi } from "zustand";
+import type { Rect } from "../../../../common/rect";
import type CCStore from "../../../../store";
import type { CCComponentId } from "../../../../store/component";
import type { CCNodeId } from "../../../../store/node";
@@ -14,6 +15,8 @@ export type ComponentEditorStoreValue = {
readonly canCreateComponents: boolean;
/** whether the view is fitted to the nodes when the editor first gets its size */
readonly fitsNodesInView: boolean;
+ /** taken in too when the view is fitted, e.g. where the nodes are to be placed */
+ readonly areaToFit: Rect | null;
readonly hasProperties: (componentId: CCComponentId) => boolean;
} & EditorStoreCoreSlice &
PerspectiveStoreSlice &
diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx
index 4e3a248..28b294d 100644
--- a/src/pages/tutorial/stage.tsx
+++ b/src/pages/tutorial/stage.tsx
@@ -44,6 +44,7 @@ import {
isStagePart,
isStagePinNode,
type StageTitleOf,
+ stageAreaOf,
type TutorialStage,
tutorialStages,
} from "../../tutorial/stages";
@@ -71,7 +72,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 = goalTableOf(stage.check, stage.examples);
+ const goalTable = goalTableOf(stage.check);
const stageTexts = texts.stageTexts[stage.id];
const [store, setStore] = useState(() =>
@@ -199,7 +200,7 @@ function StageView({ stage }: { stage: TutorialStage }) {
key={given.id}
name={titleOf(given.id)}
summary={null}
- table={goalTableOf(given.check, given.examples)}
+ table={goalTableOf(given.check)}
/>
))}
@@ -273,6 +274,10 @@ function StageView({ stage }: { stage: TutorialStage }) {
isOffered,
canCreateComponents: stage.allowsNewComponents,
fitsNodesInView: true,
+ areaToFit:
+ shownComponentId === stage.componentId
+ ? stageAreaOf(stage)
+ : null,
hasProperties: (componentId) =>
!isStageComponent(stage, componentId),
}}
diff --git a/src/store/intrinsics/truthTable.ts b/src/store/intrinsics/truthTable.ts
index 4a03b3f..0a6c0db 100644
--- a/src/store/intrinsics/truthTable.ts
+++ b/src/store/intrinsics/truthTable.ts
@@ -6,7 +6,12 @@ import { IntrinsicComponentDefinition } from "./base";
export type TruthTable = {
inputs: string[];
outputs: string[];
- rows: { inputs: SimulationValue[]; outputs: SimulationValue[] }[];
+ rows: {
+ inputs: SimulationValue[];
+ outputs: SimulationValue[];
+ /** For a table over time, counted from 1 */
+ stepNumber?: number;
+ }[];
};
const maxInputCount = 2;
diff --git a/src/tutorial/check.test.ts b/src/tutorial/check.test.ts
index f0a3c53..f168b94 100644
--- a/src/tutorial/check.test.ts
+++ b/src/tutorial/check.test.ts
@@ -81,7 +81,7 @@ describe("inputCombinations", () => {
describe("goalTableOf", () => {
it("lists what the stage asks for, in the order the check tries the inputs", () => {
- expect(goalTableOf(xorStage.check, [])).toEqual({
+ expect(goalTableOf(xorStage.check)).toEqual({
inputs: ["A", "B"],
outputs: ["Out"],
rows: [
@@ -96,7 +96,7 @@ describe("goalTableOf", () => {
it("lists several outputs in the order the stage names them", () => {
const halfAdder = nullthrows(findTutorialStage("half-adder"));
- expect(goalTableOf(halfAdder.check, [])?.rows).toEqual([
+ expect(goalTableOf(halfAdder.check)?.rows).toEqual([
{ inputs: [[false], [false]], outputs: [[false], [false]] },
{ inputs: [[false], [true]], outputs: [[false], [true]] },
{ inputs: [[true], [false]], outputs: [[false], [true]] },
@@ -112,10 +112,35 @@ describe("goalTableOf", () => {
expected: (values) => ({ Out: [...nullthrows(values.A)].reverse() }),
};
- expect(goalTableOf(wide, [])).toBeNull();
- expect(goalTableOf(wide, [{ A: [true, false] }])?.rows).toEqual([
- { inputs: [[true, false]], outputs: [[false, true]] },
- ]);
+ expect(goalTableOf(wide)).toBeNull();
+ expect(
+ goalTableOf({ ...wide, examples: [{ A: [true, false] }] })?.rows,
+ ).toEqual([{ inputs: [[true, false]], outputs: [[false, true]] }]);
+ });
+
+ it("shows the steps a check over time picks, with their numbers", () => {
+ const counting = sequentialCheck(
+ { inputs: [{ name: "Up", bitWidth: 1 }], outputs: ["Odd"] },
+ {
+ initialState: false,
+ step: (isOdd, { Up }) => ({
+ outputs: { Odd: [isOdd] },
+ next: nullthrows(Up?.[0]) !== isOdd,
+ }),
+ },
+ [[true], [false], [true], [true]].map((Up) => ({ Up })),
+ [1, 3, 4],
+ );
+
+ expect(goalTableOf(counting)).toEqual({
+ inputs: ["Up"],
+ outputs: ["Odd"],
+ rows: [
+ { inputs: [[true]], outputs: [[false]], stepNumber: 1 },
+ { inputs: [[true]], outputs: [[true]], stepNumber: 3 },
+ { inputs: [[true]], outputs: [[false]], stepNumber: 4 },
+ ],
+ });
});
it("refuses a check that gives no value for an output", () => {
@@ -126,7 +151,7 @@ describe("goalTableOf", () => {
expected: () => ({}),
};
- expect(() => goalTableOf(check, [])).toThrow("Out");
+ expect(() => goalTableOf(check)).toThrow("Out");
});
});
@@ -335,6 +360,7 @@ describe("sequentialCheck", () => {
}),
},
[[true], [false], [true]].map((Up) => ({ Up })),
+ [],
);
expect(check.steps.map(({ outputs }) => outputs)).toEqual([
@@ -354,11 +380,32 @@ describe("sequentialCheck refuses steps that do not fit the pins", () => {
step: () => ({ outputs: { Count: [false] }, next: null }),
};
- expect(() => sequentialCheck(pins, model, [{ Up: [true, false] }])).toThrow(
- "Step 1",
+ expect(() =>
+ sequentialCheck(pins, model, [{ Up: [true, false] }], []),
+ ).toThrow("Step 1");
+ expect(() =>
+ sequentialCheck(pins, model, [{ Up: [true] }, {}], []),
+ ).toThrow("Step 2");
+ });
+
+ it("refuses shown steps that are not checked, or out of order", () => {
+ const model = {
+ initialState: null,
+ step: () => ({ outputs: { Count: [false] }, next: null }),
+ };
+ const twoSteps = [{ Up: [true] }, { Up: [true] }];
+
+ expect(() => sequentialCheck(pins, model, twoSteps, [3])).toThrow(
+ "steps shown",
+ );
+ expect(() => sequentialCheck(pins, model, twoSteps, [2, 1])).toThrow(
+ "steps shown",
+ );
+ expect(() => sequentialCheck(pins, model, twoSteps, [0])).toThrow(
+ "steps shown",
);
- expect(() => sequentialCheck(pins, model, [{ Up: [true] }, {}])).toThrow(
- "Step 2",
+ expect(() => sequentialCheck(pins, model, twoSteps, [1, 1])).toThrow(
+ "steps shown",
);
});
@@ -372,7 +419,7 @@ describe("sequentialCheck refuses steps that do not fit the pins", () => {
};
expect(() =>
- sequentialCheck(pins, model, [{ Up: [true] }, { Up: [true] }]),
+ sequentialCheck(pins, model, [{ Up: [true] }, { Up: [true] }], []),
).toThrow("Step 2");
});
});
@@ -392,6 +439,7 @@ describe("checkCircuit over time", () => {
}),
},
inputSteps,
+ [],
);
function registerPassThrough(throughFlipFlop: boolean) {
@@ -484,6 +532,7 @@ describe("checkCircuit over time", () => {
step: (isOn) => ({ outputs: { Out: [isOn] }, next: !isOn }),
},
new Array(4).fill({}),
+ [],
);
expect(checkCircuit(store, component.id, blink)).toEqual({
diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts
index bcdf6e5..909f5cc 100644
--- a/src/tutorial/check.ts
+++ b/src/tutorial/check.ts
@@ -22,6 +22,8 @@ type CheckPins = {
export type CombinationalCheck = CheckPins & {
kind: "combinational";
expected(inputs: PinValues): PinValues;
+ /** Inputs the goal shows when every combination of them is too many */
+ examples?: readonly PinValues[];
};
export type StepValues = { inputs: PinValues; outputs: PinValues };
@@ -30,6 +32,8 @@ export type StepValues = { inputs: PinValues; outputs: PinValues };
export type SequentialCheck = CheckPins & {
kind: "sequential";
steps: readonly StepValues[];
+ /** The steps the goal shows, counted from 1 */
+ shownStepNumbers: readonly number[];
};
export type CircuitCheck = CombinationalCheck | SequentialCheck;
@@ -45,6 +49,7 @@ export function sequentialCheck(
pins: CheckPins,
model: SequentialModel,
inputSteps: readonly PinValues[],
+ shownStepNumbers: readonly number[],
): SequentialCheck {
let state = model.initialState;
const steps = inputSteps.map((inputs) => {
@@ -69,7 +74,16 @@ export function sequentialCheck(
);
}
}
- return { ...pins, kind: "sequential", steps };
+ invariant(
+ shownStepNumbers.every(
+ (number, index) =>
+ number >= 1 &&
+ number <= steps.length &&
+ number > (shownStepNumbers[index - 1] ?? 0),
+ ),
+ "The steps shown must be checked steps, in order",
+ );
+ return { ...pins, kind: "sequential", steps, shownStepNumbers };
}
export type CheckResult =
@@ -121,29 +135,39 @@ function expectedValueOf(expected: PinValues, name: string) {
}
/**
- * 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
+ * What the outputs should be for every combination of the inputs when each is one bit,
+ * or else for the examples or at the steps the check shows; null when there is nothing
+ * to show
*/
-export function goalTableOf(
- check: CircuitCheck,
- examples: readonly PinValues[],
-): TruthTable | null {
- // TODO: show the first steps as the goal of a check over time
- if (check.kind === "sequential") return null;
+export function goalTableOf(check: CircuitCheck): TruthTable | null {
+ const names = {
+ inputs: check.inputs.map(({ name }) => name),
+ outputs: [...check.outputs],
+ };
+ const rowOf = ({ inputs, outputs }: StepValues) => ({
+ inputs: check.inputs.map(({ name }) => nullthrows(inputs[name])),
+ outputs: check.outputs.map((name) => expectedValueOf(outputs, name)),
+ });
+ if (check.kind === "sequential") {
+ const { shownStepNumbers } = check;
+ if (shownStepNumbers.length === 0) return null;
+ return {
+ ...names,
+ rows: shownStepNumbers.map((stepNumber) => ({
+ ...rowOf(nullthrows(check.steps[stepNumber - 1])),
+ stepNumber,
+ })),
+ };
+ }
const rows = check.inputs.every(({ bitWidth }) => bitWidth === 1)
? [...inputCombinations(check.inputs)]
- : examples;
+ : (check.examples ?? []);
if (rows.length === 0) return null;
return {
- inputs: check.inputs.map(({ name }) => name),
- outputs: [...check.outputs],
- 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)),
- };
- }),
+ ...names,
+ rows: rows.map((inputs) =>
+ rowOf({ inputs, outputs: check.expected(inputs) }),
+ ),
};
}
diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts
index 3515c33..eb88894 100644
--- a/src/tutorial/stages.test.ts
+++ b/src/tutorial/stages.test.ts
@@ -1,11 +1,14 @@
import nullthrows from "nullthrows";
import { describe, expect, it } from "vitest";
+import type { CCComponentId } from "../store/component";
import {
and,
+ display,
input,
not,
or,
output,
+ seven_segment,
xor,
} from "../store/intrinsics/definitions";
import {
@@ -13,7 +16,7 @@ import {
registerTestComponent,
registerTestNode,
} from "../store/testUtils";
-import { checkCircuit } from "./check";
+import { checkCircuit, goalTableOf } from "./check";
import {
findTutorialStage,
isStagePart,
@@ -97,6 +100,49 @@ describe("setUpTutorialStage", () => {
});
});
+describe("the counter stage", () => {
+ it("shows the first steps and the wrap from 1111 to 0000 as its goal", () => {
+ const counter = nullthrows(findTutorialStage("counter"));
+ const table = nullthrows(goalTableOf(counter.check));
+
+ expect(
+ table.rows.map(({ stepNumber, outputs }) => [
+ stepNumber,
+ outputs.map((value) => value.map(Number).join("")),
+ ]),
+ ).toEqual([
+ [1, ["0000"]],
+ [2, ["0001"]],
+ [3, ["0010"]],
+ [16, ["1111"]],
+ [17, ["0000"]],
+ ]);
+ });
+});
+
+describe("setUpTutorialStage with decorations", () => {
+ it("places the display only for the player, not inside the part handed over", () => {
+ const fourBit = nullthrows(findTutorialStage("four-bit-adder"));
+ const counter = nullthrows(findTutorialStage("counter"));
+ const store = createTestStore();
+ setUpTutorialStage(store, counter, titleOf);
+ const decorationsIn = (componentId: CCComponentId) =>
+ store.nodes
+ .getManyByParentComponentId(componentId)
+ .filter(
+ (node) =>
+ node.componentId === seven_segment.component.id ||
+ node.componentId === display.component.id,
+ );
+
+ expect(decorationsIn(counter.componentId)).toHaveLength(2);
+ expect(decorationsIn(fourBit.componentId)).toHaveLength(0);
+ expect(checkCircuit(store, fourBit.componentId, fourBit.check)).toEqual({
+ type: "passed",
+ });
+ });
+});
+
describe("isStagePinNode", () => {
it("tells the pins the stage placed from the nodes the player adds", () => {
const store = createTestStore();
diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts
index 212290a..1b49ab1 100644
--- a/src/tutorial/stages.ts
+++ b/src/tutorial/stages.ts
@@ -1,6 +1,7 @@
import nullthrows from "nullthrows";
import type { BitNotation } from "../common/bitLabel";
import { bitsOf, numberOf } from "../common/bits";
+import type { Rect } from "../common/rect";
import type CCStore from "../store";
import {
type CCComponent,
@@ -11,9 +12,11 @@ import type { CCComponentPin } from "../store/componentPin";
import {
aggregate,
and,
+ const_,
decompose,
display,
false_,
+ flipflop,
input,
not,
or,
@@ -22,7 +25,13 @@ import {
xor,
} from "../store/intrinsics/definitions";
import { type CCNodeId, CCNodeStore } from "../store/node";
-import type { CircuitCheck, CombinationalCheck, PinValues } from "./check";
+import type { CCNodePinId } from "../store/nodePin";
+import {
+ type CircuitCheck,
+ type CombinationalCheck,
+ type PinValues,
+ sequentialCheck,
+} from "./check";
import { StageCircuit } from "./circuit";
export const tutorialStageIds = [
@@ -32,6 +41,7 @@ export const tutorialStageIds = [
"half-adder",
"full-adder",
"four-bit-adder",
+ "counter",
] as const;
export type TutorialStageId = (typeof tutorialStageIds)[number];
export type StageTitleOf = (id: TutorialStageId) => string;
@@ -48,8 +58,6 @@ export type TutorialStage = {
tableNotation: BitNotation;
/** also the input and output pins the stage starts with */
check: CircuitCheck;
- /** 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;
/**
@@ -71,12 +79,7 @@ const oneBitInputs = (...names: string[]) =>
type Solving = { solve(circuit: StageCircuit): void };
type StageDefinition = Pick &
- Partial<
- Pick<
- TutorialStage,
- "givenParts" | "tableNotation" | "pinDistance" | "examples"
- >
- > &
+ Partial> &
(Pick | Solving);
function defineStage(
@@ -89,7 +92,6 @@ function defineStage(
givenParts = [],
tableNotation = "onOff",
pinDistance = 300,
- examples = [],
} = definition;
return {
id,
@@ -99,7 +101,6 @@ function defineStage(
givenParts,
tableNotation,
pinDistance,
- examples,
allowsNewComponents: false,
layOut:
"layOut" in definition
@@ -259,6 +260,21 @@ const fullAdderStage = defineStage("full-adder", {
const digitCount = 4;
+/** A 7seg showing a number on a Display at the top right; returns the 7seg's input */
+function placeNumeral(circuit: StageCircuit): CCNodePinId {
+ const digit = circuit.place(seven_segment.component.id, { x: 290, y: -250 });
+ const screen = circuit.place(
+ display.component.id,
+ { x: 430, y: -250 },
+ { resolution: { x: 4, y: 7 }, pixelOrder: "row-major" },
+ );
+ circuit.connect(
+ circuit.pinOf(digit, seven_segment.outputPin.Out),
+ circuit.pinOf(screen, display.inputPin.Pixels),
+ );
+ return circuit.pinOf(digit, seven_segment.inputPin.In);
+}
+
const fourBitAdderStage = defineStage("four-bit-adder", {
parts: [decompose, aggregate, false_].map((part) => part.component.id),
givenParts: ["full-adder"],
@@ -279,15 +295,15 @@ const fourBitAdderStage = defineStage("four-bit-adder", {
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),
+ })),
},
- 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: -250, y: -170 });
@@ -306,22 +322,7 @@ const fourBitAdderStage = defineStage("four-bit-adder", {
);
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: 290,
- y: -250,
- });
- const screen = circuit.place(
- display.component.id,
- { x: 430, y: -250 },
- { 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),
- );
- }
+ if (decorate) circuit.connect(sum, placeNumeral(circuit));
return () => {
const adders = Array.from({ length: digitCount }, (_, index) =>
circuit.place(fullAdderStage.componentId, {
@@ -359,6 +360,52 @@ const fourBitAdderStage = defineStage("four-bit-adder", {
},
});
+const counterStage = defineStage("counter", {
+ parts: [flipflop, const_].map((part) => part.component.id),
+ givenParts: ["four-bit-adder"],
+ tableNotation: "digits",
+ pinDistance: 420,
+ check: sequentialCheck(
+ { inputs: [], outputs: ["Count"] },
+ {
+ initialState: 0,
+ step: (count) => ({
+ outputs: { Count: bitsOf(count, digitCount) },
+ next: (count + 1) % 2 ** digitCount,
+ }),
+ },
+ new Array(2 * 2 ** digitCount).fill({}),
+ [1, 2, 3, 16, 17],
+ ),
+ layOut(circuit, { decorate }) {
+ const numeral = decorate ? placeNumeral(circuit) : null;
+ return () => {
+ const memory = circuit.place(flipflop.component.id, { x: 150, y: 0 });
+ const adder = circuit.place(fourBitAdderStage.componentId, {
+ x: -100,
+ y: 0,
+ });
+ const one = circuit.place(
+ const_.component.id,
+ { x: -450, y: 150 },
+ { mode: "binary", data: bitsOf(1, digitCount) },
+ );
+ const count = circuit.pinOf(memory, flipflop.outputPin.Out);
+ circuit.connect(count, circuit.pin("Count"));
+ if (numeral) circuit.connect(count, numeral);
+ circuit.connect(count, circuit.pinOf(adder, "A"));
+ circuit.connect(
+ circuit.pinOf(one, const_.outputPin.Out),
+ circuit.pinOf(adder, "B"),
+ );
+ circuit.connect(
+ circuit.pinOf(adder, "S"),
+ circuit.pinOf(memory, flipflop.inputPin.In),
+ );
+ };
+ },
+});
+
export const tutorialStages: readonly TutorialStage[] = [
andStage,
aOnlyStage,
@@ -366,8 +413,17 @@ export const tutorialStages: readonly TutorialStage[] = [
halfAdderStage,
fullAdderStage,
fourBitAdderStage,
+ counterStage,
];
+/** Between the columns of input and output pins, also for a stage without inputs */
+export function stageAreaOf(stage: TutorialStage): Rect {
+ return {
+ position: { x: -stage.pinDistance, y: 0 },
+ size: { x: 2 * stage.pinDistance, y: 0 },
+ };
+}
+
export function findTutorialStage(id: string | undefined) {
return tutorialStages.find((stage) => stage.id === id);
}