diff --git a/src/components/PartDescription.tsx b/src/components/PartDescription.tsx index e4d6bc5..88c1bf7 100644 --- a/src/components/PartDescription.tsx +++ b/src/components/PartDescription.tsx @@ -49,7 +49,7 @@ export function PartDescriptionView({ {summary && {summary}} {table && ( - + )} diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 0b2f91a..1b8e61d 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1,5 +1,5 @@ import { englishSimulationErrorTexts } from "../store/simulationErrorTexts"; -import type { TutorialStageId } from "../tutorial/stages"; +import type { TutorialPartId, TutorialStageId } from "../tutorial/stages"; const bitWidths = (widths: readonly number[]) => `${widths.join("/")} bit`; const listOf = (names: readonly string[]) => @@ -66,7 +66,7 @@ const stageTexts: Record = { }, "decimal-digit": { title: "One decimal digit", - goal: "Writing numbers with 0 to 9, carrying over after 9 as everyday numbers do, is called decimal. Make Count go up by 1 only at the time steps when Up is ON, and go back to 0000 after 1001. 1001 is 9, 8 plus 1. At a time step when Count is 1001 and Up is ON, make Carry turn ON: it tells the digit above to go up. Check turns Up ON for time steps 1 to 9, OFF for 10 and 11, and ON again from 12.", + goal: "Writing numbers with 0 to 9, carrying over after 9 as everyday numbers do, is called decimal. Make Count go up by 1 only at the time steps when Up is ON, and go back to 0000 after 1001. 1001 is 9, 8 plus 1. At a time step when Count is 1001 and Up is ON, make Carry turn ON: it tells the digit above to go up. Check turns Up ON until Count reaches 1001, then OFF for two time steps to see that Count stays at 1001 and Carry stays OFF, and then ON again to see that Count goes back to 0000.", steps: [ 'The Const, Broadcast and And on the left send 0001 to B of "Adding four digits" when Up is ON, and 0000 when it is OFF. A Broadcast spreads a one-bit value over several bits: 1111 for ON, 0000 for OFF. An And given values of several bits makes each bit 1 only where both are 1.', "Make Carry. From 0000 to 1001, only 1001 has 1 in both the eights and the ones digit. Join the top pin (eights) and the bottom pin (ones) on the right of the Decompose at the bottom with an And, join its output and Up with another And, and connect that to Carry.", @@ -75,6 +75,16 @@ const stageTexts: Record = { "While playing, click Up to switch it ON and OFF, and go through the time steps with the right arrow. The circuit works when the number on the Display goes up only while Up is ON, and goes back to 0 after 9.", ], }, + stopwatch: { + title: "Stopwatch", + goal: "Finally, a stopwatch counting minutes and seconds like 12:34. It goes on by one second at each time step when Start is ON. The Display at the top right shows, from the left, the tens digit of the minutes (M10), the ones digit of the minutes (M1), a colon, the tens digit of the seconds (S10) and the ones digit of the seconds (S1). M10 and S10 count 0 to 5, and M1 and S1 count 0 to 9. After 59:59 it goes back to 00:00. The 7segs, Const, Decompose and Aggregate left of the Display put the four numerals and the colon side by side on that one Display. Check keeps Start ON until 59:59 has gone back to 00:00, then turns it OFF for two time steps to see that the stopwatch stops, and ON again to see that it goes on.", + steps: [ + 'Place two "One base-6 digit" and two "One decimal digit". "One base-6 digit" is built like "One decimal digit", but counts 0 to 5 and carries over after 5, as decimal does after 9.', + 'Give each of the four parts one of M10, M1, S10 and S1: "One base-6 digit" for M10 and S10, and "One decimal digit" for M1 and S1. Connect the Count of each to the output on the right named after its digit, and to the 7seg of that digit. The 7segs are, from the top, for M10, M1, S10 and S1.', + "Connect Start to Up of the part connected to S1. Then connect Carry of the part for S1 to Up of the part for S10, Carry for S10 to Up for M1, and Carry for M1 to Up for M10. A digit then goes on only when the digit one lower goes back to 0.", + 'Press the play button. If Start is OFF at the first time step, click it to turn it ON. Press "Auto", and the Display goes on like a clock, one time step a second. To see what comes after 59:59, stop Auto, click the number at the bottom, enter 3600 and press the Enter key. It goes to that time step at once and shows 59:59, and the right arrow shows 00:00.', + ], + }, }; export const en = { @@ -188,6 +198,7 @@ export const en = { stepsHeading: "Steps", digitsLegend: "The tables write ON as 1 and OFF as 0.", check: "Check", + checking: "Checking…", passed: "Cleared! The circuit works for every combination of the inputs.", passedSteps: (count: number) => `Cleared! The circuit works at every time step up to time step ${count}.`, @@ -224,6 +235,10 @@ export const en = { }, resetStageFailed: "Could not reset the stage.", stageTexts, + partTitles: { "senary-digit": "One base-6 digit" } satisfies Record< + TutorialPartId, + string + >, }, componentProperties: { title: (componentName: string) => `${componentName} Properties`, diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index a657f16..64fb89e 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -113,6 +113,7 @@ export const ja: Messages = { stepsHeading: "手順", digitsLegend: "表では、ON を 1、OFF を 0 と書いています。", check: "確かめる", + checking: "確かめています…", passed: "クリア!どの入力の組み合わせでも正しく動きます。", passedSteps: (count) => `クリア!${count} ステップ目まで、どのステップでも正しく動きます。`, @@ -137,6 +138,7 @@ export const ja: Messages = { confirm: "やり直す", }, resetStageFailed: "課題をやり直せませんでした。", + partTitles: { "senary-digit": "6進の1桁" }, stageTexts: { and: { title: "両方のスイッチ", @@ -191,7 +193,7 @@ export const ja: Messages = { }, "decimal-digit": { title: "10進の1桁", - goal: "ふだんの数のように、0 から 9 までを使い、9 の次で桁が上がる書き方を10進数といいます。Up が ON のステップだけ Count が 1 増え、1001 の次は 0000 に戻るようにしましょう。1001 は、8 と 1 を足した 9 です。Count が 1001 で Up が ON のステップでは、Carry が ON になるようにします。Carry は、上の桁に桁上がりを知らせる合図です。「確かめる」を押すと、Up を 1〜9 ステップ目は ON、10・11 ステップ目は OFF、12 ステップ目からはまた ON にして調べます。", + goal: "ふだんの数のように、0 から 9 までを使い、9 の次で桁が上がる書き方を10進数といいます。Up が ON のステップだけ Count が 1 増え、1001 の次は 0000 に戻るようにしましょう。1001 は、8 と 1 を足した 9 です。Count が 1001 で Up が ON のステップでは、Carry が ON になるようにします。Carry は、上の桁に桁上がりを知らせる合図です。「確かめる」は、Up を ON にして Count を 1001 まで進めたあと、2ステップだけ Up を OFF にして、Count が 1001 のまま止まり、Carry が OFF のままかを調べます。そのあと Up をまた ON にして、0000 に戻るかを調べます。", steps: [ "左の Const・Broadcast・And は、Up が ON のときは 0001 を、OFF のときは 0000 を「4桁の足し算」の B に送っています。Broadcast は、1ビットの値を、同じ値が並んだ何ビットもの値に広げます(ON なら 1111、OFF なら 0000)。And に何ビットもの値をつなぐと、ビットごとに、両方が 1 のビットだけ 1 になります。", "Carry を作ります。0000 から 1001 のうち、8の位と1の位がどちらも 1 なのは 1001 だけです。一番下の Decompose の右側の、一番上(8の位)と一番下(1の位)のピンを And でまとめ、その出力と Up をもう1つの And でまとめて、Carry につなぎます。", @@ -200,6 +202,16 @@ export const ja: Messages = { "再生中は、Up をクリックして ON と OFF を切り替えながら、右の矢印でステップを進めます。Up が ON のときだけ Display の数が進み、9 の次に 0 に戻れば、うまく動いています。", ], }, + stopwatch: { + title: "ストップウォッチ", + goal: "いよいよ、分と秒を 12:34 のように数えるストップウォッチです。Start が ON のステップごとに、1秒ずつ進めます。右上の Display には、左から分の10の位(M10)、分の1の位(M1)、コロン、秒の10の位(S10)、秒の1の位(S1)が出ます。M10 と S10 は 0 から 5 を、M1 と S1 は 0 から 9 を数えます。59:59 の次は 00:00 に戻ります。Display の左にある 7seg・Const・Decompose・Aggregate は、4つの数字とコロンを1つの Display に並べるためのものです。「確かめる」は、Start を ON にしたまま、59:59 の次に 00:00 に戻るまで進めます。そのあと2ステップだけ Start を OFF にして止まるかを、また ON にしてまた進むかを調べます。", + steps: [ + "「6進の1桁」を2つと、「10進の1桁」を2つ置きます。「6進の1桁」は「10進の1桁」と同じつくりで、0 から 5 を数え、5 の次で 0 に戻って上の桁が上がります。10進数が 9 の次で桁が上がるのと同じです。", + "置いた4つの部品を、M10・M1・S10・S1 に1つずつ割り当てます。M10 と S10 には「6進の1桁」を、M1 と S1 には「10進の1桁」を使います。それぞれの Count を、割り当てた桁と同じ名前の右の出力と、その桁の 7seg につなぎます。7seg は、上から M10・M1・S10・S1 用です。", + "S1 につないだ部品の Up に Start をつなぎます。次に、S1 の部品の Carry を S10 の部品の Up に、S10 の Carry を M1 の Up に、M1 の Carry を M10 の Up につなぎます。こうすると、1つ下の桁が 0 に戻るときだけ、その上の桁が進みます。", + "再生ボタンを押します。最初のステップで Start が OFF なら、クリックして ON にします。「自動」を押すと、1秒に1ステップずつ、Display が時計のように進みます。59:59 の次を見るには、「自動」を止めて下の数字をクリックし、3600 と入れて Enter キーを押します。そのステップまで一度に進んで 59:59 になり、右の矢印を押すと 00:00 に戻ります。", + ], + }, }, }, componentProperties: { diff --git a/src/pages/edit/Editor/components/FrameControl.tsx b/src/pages/edit/Editor/components/FrameControl.tsx index 826f7d1..6b93fb0 100644 --- a/src/pages/edit/Editor/components/FrameControl.tsx +++ b/src/pages/edit/Editor/components/FrameControl.tsx @@ -8,6 +8,7 @@ import { isValidPlaybackSpeed, MAX_PLAYBACK_SPEED, MIN_PLAYBACK_SPEED, + parseTimeStepNumber, } from "../store/slices/core/types"; export default function CCComponentEditorFrameControl() { @@ -17,6 +18,7 @@ export default function CCComponentEditorFrameControl() { const [speedInput, setSpeedInput] = useState( String(componentEditorState.playbackSpeed), ); + const [stepDraft, setStepDraft] = useState(null); const isAutomatic = componentEditorState.playbackMode === "auto"; const isSpeedValid = isValidPlaybackSpeed(Number(speedInput)); @@ -92,12 +94,28 @@ export default function CCComponentEditorFrameControl() { outline: "none", fontSize: "20px", }} - value={componentEditorState.timeStep + 1} - onChange={(e) => { - const value = Number(e.target.value); - if (Number.isSafeInteger(value) && value > 0) { - componentEditorState.setTimeStep(value - 1); + inputMode="numeric" + value={stepDraft ?? String(componentEditorState.timeStep + 1)} + onFocus={(e) => { + const field = e.currentTarget; + // After the click, which in WebKit would undo a selection made now + requestAnimationFrame(() => field.select()); + }} + onChange={(e) => setStepDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && !e.nativeEvent.isComposing) { + e.currentTarget.blur(); + } + }} + // Every step up to the one entered is simulated, so a step is only + // gone to once it is typed in full, not at each key + onBlur={() => { + const stepNumber = + stepDraft === null ? null : parseTimeStepNumber(stepDraft); + if (stepNumber !== null) { + componentEditorState.setTimeStep(stepNumber - 1); } + setStepDraft(null); }} /> { + it("reads a step typed in half-width or full-width digits", () => { + expect(parseTimeStepNumber("3600")).toBe(3600); + expect(parseTimeStepNumber("3600")).toBe(3600); + expect(parseTimeStepNumber(" 12 ")).toBe(12); + }); + + it("refuses what is no step", () => { + expect(parseTimeStepNumber("")).toBeNull(); + expect(parseTimeStepNumber("0")).toBeNull(); + expect(parseTimeStepNumber("-3")).toBeNull(); + expect(parseTimeStepNumber("1.5")).toBeNull(); + expect(parseTimeStepNumber("abc")).toBeNull(); + }); + + it("stops a jump at the furthest step that can be gone to", () => { + expect(parseTimeStepNumber("153600")).toBe(MAX_TIME_STEP_NUMBER); + }); +}); diff --git a/src/pages/edit/Editor/store/slices/core/types.ts b/src/pages/edit/Editor/store/slices/core/types.ts index bc1daf3..0bfb9dc 100644 --- a/src/pages/edit/Editor/store/slices/core/types.ts +++ b/src/pages/edit/Editor/store/slices/core/types.ts @@ -26,6 +26,19 @@ export function isValidPlaybackSpeed(speed: number): boolean { ); } +/** Every time step up to the one gone to is simulated and kept, so a jump stops here */ +export const MAX_TIME_STEP_NUMBER = 10000; + +/** + * The time step, counted from 1, that the text typed in the step field asks for, or + * null for none. Full-width digits, as typed with a Japanese input method, count. + */ +export function parseTimeStepNumber(text: string): number | null { + const value = Number(text.normalize("NFKC").trim()); + if (!Number.isSafeInteger(value) || value < 1) return null; + return Math.min(value, MAX_TIME_STEP_NUMBER); +} + export type RangeSelect = { start: Vector2; end: Vector2 } | null; export type TimeStep = number; diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx index 28b294d..938afcc 100644 --- a/src/pages/tutorial/stage.tsx +++ b/src/pages/tutorial/stage.tsx @@ -9,7 +9,7 @@ import { Typography, } from "@mui/material"; import nullthrows from "nullthrows"; -import { type ReactNode, useEffect, useState } from "react"; +import { type ReactNode, useEffect, useRef, useState } from "react"; import { Navigate, Link as RouterLink, @@ -40,9 +40,11 @@ import { } from "../../tutorial/stageStore"; import { findTutorialStage, + givenPartById, isStageComponent, isStagePart, isStagePinNode, + isTutorialStageId, type StageTitleOf, stageAreaOf, type TutorialStage, @@ -71,7 +73,8 @@ function StageView({ stage }: { stage: TutorialStage }) { const navigate = useNavigate(); const stageIndex = tutorialStages.indexOf(stage); const nextStage = tutorialStages[stageIndex + 1]; - const titleOf: StageTitleOf = (id) => texts.stageTexts[id].title; + const titleOf: StageTitleOf = (id) => + isTutorialStageId(id) ? texts.stageTexts[id].title : texts.partTitles[id]; const goalTable = goalTableOf(stage.check); const stageTexts = texts.stageTexts[stage.id]; @@ -80,6 +83,7 @@ function StageView({ stage }: { stage: TutorialStage }) { ); const [editedComponentId, setEditedComponentId] = useState(stage.componentId); const [result, setResult] = useState(null); + const [isChecking, setIsChecking] = useState(false); const [isConfirmingReset, setIsConfirmingReset] = useState(false); const [hasResetFailed, setHasResetFailed] = useState(false); // The editor keeps state of the store it was made with, so it starts anew on a reset @@ -96,15 +100,39 @@ function StageView({ stage }: { stage: TutorialStage }) { }; }, [store]); + const cancelCheckRef = useRef<(() => void) | null>(null); + const cancelCheck = () => { + cancelCheckRef.current?.(); + cancelCheckRef.current = null; + setIsChecking(false); + }; + useEffect(() => () => cancelCheckRef.current?.(), []); + const check = () => { - const checked = checkCircuit(store, stage.componentId, stage.check); - if (checked.type === "checkFailed") console.error(checked.error); - setResult(checked); - if (checked.type === "passed") markStageCleared(stage.id); + setIsChecking(true); + const run = () => { + cancelCheckRef.current = null; + const checked = checkCircuit(store, stage.componentId, stage.check); + if (checked.type === "checkFailed") console.error(checked.error); + setResult(checked); + if (checked.type === "passed") markStageCleared(stage.id); + setIsChecking(false); + }; + // A check over many time steps holds the page for a moment, so the button says + // it is checking before the check starts + let timeout: ReturnType | undefined; + const frame = requestAnimationFrame(() => { + timeout = setTimeout(run); + }); + cancelCheckRef.current = () => { + cancelAnimationFrame(frame); + clearTimeout(timeout); + }; }; const resetStage = () => { setIsConfirmingReset(false); + cancelCheck(); try { setStore(resetTutorialStage(stage, titleOf)); setResetCount((count) => count + 1); @@ -129,7 +157,9 @@ function StageView({ stage }: { stage: TutorialStage }) {
@@ -161,7 +191,9 @@ function StageView({ stage }: { stage: TutorialStage }) { {stageTexts.goal} {goalTable && ( - + + + {stage.tableNotation === "digits" && ( {texts.digitsLegend} @@ -193,16 +225,14 @@ function StageView({ stage }: { stage: TutorialStage }) { } /> ))} - {stage.givenParts - .map((id) => nullthrows(findTutorialStage(id))) - .map((given) => ( - - ))} + {stage.givenParts.map(givenPartById).map((given) => ( + + ))}
@@ -223,9 +253,10 @@ function StageView({ stage }: { stage: TutorialStage }) { {result?.type === "passed" && ( <> diff --git a/src/tutorial/progress.ts b/src/tutorial/progress.ts index 74658c2..ad0e2d5 100644 --- a/src/tutorial/progress.ts +++ b/src/tutorial/progress.ts @@ -1,11 +1,7 @@ -import { type TutorialStageId, tutorialStageIds } from "./stages"; +import { isTutorialStageId, type TutorialStageId } from "./stages"; const progressStorageKey = "ccTutorialProgress"; -function isStageId(value: unknown): value is TutorialStageId { - return tutorialStageIds.some((id) => id === value); -} - // What was cleared only decorates the list of stages, so the tutorial goes on when the // storage cannot keep it, e.g. when it is full export function readClearedStages(): ReadonlySet { @@ -13,7 +9,9 @@ export function readClearedStages(): ReadonlySet { const parsed: unknown = JSON.parse( window.localStorage.getItem(progressStorageKey) ?? "[]", ); - return new Set(Array.isArray(parsed) ? parsed.filter(isStageId) : []); + return new Set( + Array.isArray(parsed) ? parsed.filter(isTutorialStageId) : [], + ); } catch (error) { console.warn("Could not read the tutorial progress", error); return new Set(); diff --git a/src/tutorial/stageStore.test.ts b/src/tutorial/stageStore.test.ts index e15ee6b..151ce7f 100644 --- a/src/tutorial/stageStore.test.ts +++ b/src/tutorial/stageStore.test.ts @@ -14,8 +14,8 @@ import { } from "./stageStore"; import { findTutorialStage, + type GivenPartId, setUpTutorialStage, - type TutorialStageId, tutorialStages, } from "./stages"; @@ -24,7 +24,7 @@ if (!firstStage || !secondStage) throw new Error("No stages"); const xorStage = nullthrows(findTutorialStage("xor")); const aOnlyStage = nullthrows(findTutorialStage("a-only")); const firstKey = `ccTutorialStage:${firstStage.id}`; -const titleOf = (id: TutorialStageId) => `Stage ${id}`; +const titleOf = (id: GivenPartId) => `Stage ${id}`; let saved: Map; beforeEach(() => { diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts index 42d5920..18f281d 100644 --- a/src/tutorial/stages.test.ts +++ b/src/tutorial/stages.test.ts @@ -1,12 +1,12 @@ import nullthrows from "nullthrows"; import { describe, expect, it } from "vitest"; +import { numberOf } from "../common/bits"; import { connectionStraightGap, pointsOnConnection, } from "../pages/edit/Editor/renderer/Connection/path"; import { nodeTitleHeight } from "../pages/edit/Editor/renderer/Node/components/Default/geometry"; import { getCCComponentEditorRendererNodeGeometry } from "../pages/edit/Editor/renderer/Node/geometry"; -import type { CCComponentId } from "../store/component"; import { and, display, @@ -27,10 +27,14 @@ import { import { checkCircuit, goalTableOf } from "./check"; import { findTutorialStage, + type GivenPartId, + givenPartById, isStagePart, isStagePinNode, + isTutorialStageId, setUpTutorialStage, type TutorialStageId, + tutorialParts, tutorialStages, } from "./stages"; @@ -38,7 +42,10 @@ const [stage] = tutorialStages; if (!stage) throw new Error("No stage"); const xorStage = nullthrows(findTutorialStage("xor")); const aOnlyStage = nullthrows(findTutorialStage("a-only")); -const titleOf = (id: TutorialStageId) => `Stage ${id}`; +const titleOf = (id: GivenPartId) => `Stage ${id}`; +const everyStageAndPart = [...tutorialStages, ...tutorialParts].map( + (s) => [s.id, s] as const, +); describe("tutorialStages", () => { it("writes tables in digits from the stage that teaches binary on", () => { @@ -51,17 +58,21 @@ describe("tutorialStages", () => { ); }); - it("hands over only the parts of earlier stages", () => { + it("hands over only earlier stages, or parts no stage builds", () => { for (const [index, later] of tutorialStages.entries()) { for (const id of later.givenParts) { - expect(tutorialStages.findIndex((s) => s.id === id)).toBeLessThan( - index, - ); + if (isTutorialStageId(id)) { + expect(tutorialStages.findIndex((s) => s.id === id)).toBeLessThan( + index, + ); + } else { + expect(tutorialParts.map((part) => part.id)).toContain(id); + } } } }); - it.each(tutorialStages.map((s) => [s.id, s] as const))( + it.each(everyStageAndPart)( "%s is cleared by its solution, made of the parts it offers", (_, solved) => { const store = createTestStore(); @@ -83,9 +94,7 @@ describe("tutorialStages", () => { .map((node) => node.componentId); const offered = [ ...solved.parts, - ...solved.givenParts.map( - (id) => nullthrows(findTutorialStage(id)).componentId, - ), + ...solved.givenParts.map((id) => givenPartById(id).componentId), ]; expect(placed.length).toBeGreaterThan(0); expect(offered).toEqual(expect.arrayContaining(placed)); @@ -94,7 +103,7 @@ describe("tutorialStages", () => { }); describe("the layout of every stage", () => { - it.each(tutorialStages.map((s) => [s.id, s] as const))( + it.each(everyStageAndPart)( "%s places no node or its name over another, also once solved", (_, laidOut) => { const store = createTestStore(); @@ -130,11 +139,47 @@ describe("the layout of every stage", () => { ); }); +describe("the size of every stage", () => { + // The first view shrinks to take in the whole stage, so a larger one is drawn small + const largest = { x: 1400, y: 850 }; + + it.each(tutorialStages.map((s) => [s.id, s] as const))( + "%s starts within the size the first view shows well", + (_, laidOut) => { + const store = createTestStore(); + setUpTutorialStage(store, laidOut, titleOf); + const rects = store.nodes + .getManyByParentComponentId(laidOut.componentId) + .map( + (node) => + getCCComponentEditorRendererNodeGeometry(store, node.id).rect, + ); + const left = Math.min( + -laidOut.pinDistance, + ...rects.map((rect) => rect.position.x), + ); + const right = Math.max( + laidOut.pinDistance, + ...rects.map((rect) => rect.position.x + rect.size.x), + ); + const top = Math.min( + ...rects.map((rect) => rect.position.y - nodeTitleHeight), + ); + const bottom = Math.max( + ...rects.map((rect) => rect.position.y + rect.size.y), + ); + + expect(right - left).toBeLessThanOrEqual(largest.x); + expect(bottom - top).toBeLessThanOrEqual(largest.y); + }, + ); +}); + describe("the wires every stage starts with", () => { // Below the straight part of a wire, which starts that far from its own node const clearance = connectionStraightGap - 4; - it.each(tutorialStages.map((s) => [s.id, s] as const))( + it.each(everyStageAndPart)( "%s runs no wire over a node or its name", (_, laidOut) => { const store = createTestStore(); @@ -249,25 +294,62 @@ describe("the decimal digit stage", () => { }); 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, - ); + it.each( + tutorialStages + .filter((s) => s.givenParts.length > 0) + .map((s) => [s.id, s] as const), + )( + "%s hands its parts over built and working, without their displays", + (_, receiver) => { + const store = createTestStore(); + setUpTutorialStage(store, receiver, titleOf); - expect(decorationsIn(counter.componentId)).toHaveLength(2); - expect(decorationsIn(fourBit.componentId)).toHaveLength(0); - expect(checkCircuit(store, fourBit.componentId, fourBit.check)).toEqual({ - type: "passed", - }); + for (const given of receiver.givenParts.map(givenPartById)) { + expect( + store.nodes + .getManyByParentComponentId(given.componentId) + .filter( + (node) => + node.componentId === seven_segment.component.id || + node.componentId === display.component.id, + ), + ).toEqual([]); + expect(checkCircuit(store, given.componentId, given.check)).toEqual({ + type: "passed", + }); + } + }, + ); +}); + +describe("the stopwatch stage", () => { + it("shows 59:59 going back to 00:00, and the pause while Start is OFF", () => { + const stopwatch = nullthrows(findTutorialStage("stopwatch")); + const table = nullthrows(goalTableOf(stopwatch.check)); + const clockOf = (values: boolean[][]) => { + const [m10, m1, s10, s1] = values.map(numberOf); + return `${m10}${m1}:${s10}${s1}`; + }; + + expect(table.outputs).toEqual(["M10", "M1", "S10", "S1"]); + expect( + table.rows.map(({ stepNumber, inputs, outputs }) => [ + stepNumber, + nullthrows(inputs[0]?.[0]), + clockOf(outputs), + ]), + ).toEqual([ + [1, true, "00:00"], + [2, true, "00:01"], + [60, true, "00:59"], + [61, true, "01:00"], + [3600, true, "59:59"], + [3601, true, "00:00"], + [3602, false, "00:01"], + [3603, false, "00:01"], + [3604, true, "00:01"], + [3605, true, "00:02"], + ]); }); }); diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index 645ff50..2c7710e 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -1,4 +1,5 @@ import nullthrows from "nullthrows"; +import invariant from "tiny-invariant"; import type { BitNotation } from "../common/bitLabel"; import { bitsOf, numberOf } from "../common/bits"; import type { Rect } from "../common/rect"; @@ -45,24 +46,36 @@ export const tutorialStageIds = [ "four-bit-adder", "counter", "decimal-digit", + "stopwatch", ] as const; export type TutorialStageId = (typeof tutorialStageIds)[number]; -export type StageTitleOf = (id: TutorialStageId) => string; -export type TutorialStage = { - id: TutorialStageId; +/** Parts handed over that no stage of the list builds */ +export const tutorialPartIds = ["senary-digit"] as const; +export type TutorialPartId = (typeof tutorialPartIds)[number]; +export type GivenPartId = TutorialStageId | TutorialPartId; +export type StageTitleOf = (id: GivenPartId) => string; + +export function isTutorialStageId(value: unknown): value is TutorialStageId { + return tutorialStageIds.some((id) => id === value); +} + +type StageOf = { + id: Id; /** the component the player builds, kept under this id so it is found after a reload */ componentId: CCComponentId; /** the intrinsic components the side panel offers */ parts: readonly CCComponentId[]; - /** earlier stages whose components the stage hands over, built and ready to use */ - givenParts: readonly TutorialStageId[]; + /** earlier stages or parts whose components the stage hands over, built and ready to use */ + givenParts: readonly GivenPartId[]; allowsNewComponents: boolean; tableNotation: BitNotation; /** also the input and output pins the stage starts with */ check: CircuitCheck; /** how far left and right of the middle the input and output pins sit */ pinDistance: number; + /** how far apart the pins in each column sit */ + pinSpacing: 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. @@ -70,6 +83,10 @@ export type TutorialStage = { layOut(circuit: StageCircuit, options: { decorate: boolean }): () => void; }; +export type TutorialStage = StageOf; +/** A stage, or a part that is built like one but not played */ +export type GivenPart = StageOf; + const gateParts = [and, or, not].map((gate) => gate.component.id); const bit = (value: boolean) => [value]; @@ -82,19 +99,25 @@ const oneBitInputs = (...names: string[]) => type Solving = { solve(circuit: StageCircuit): void }; type StageDefinition = Pick & - Partial> & + Partial< + Pick< + TutorialStage, + "givenParts" | "tableNotation" | "pinDistance" | "pinSpacing" + > + > & (Pick | Solving); -function defineStage( - id: TutorialStageId, +function defineStage( + id: Id, definition: StageDefinition, -): TutorialStage { +): StageOf { const { parts, check, givenParts = [], tableNotation = "onOff", pinDistance = 300, + pinSpacing = 200, } = definition; return { id, @@ -104,6 +127,7 @@ function defineStage( givenParts, tableNotation, pinDistance, + pinSpacing, allowsNewComponents: false, layOut: "layOut" in definition @@ -412,123 +436,318 @@ const counterStage = defineStage("counter", { }, }); -const decimalDigitCount = 10; +/** + * One digit of base `base`: Count goes up while Up is ON and back to 0 after the + * largest digit, and Carry is ON when it goes back. Up is OFF for two steps while + * Count stays at that digit, so a Carry that ignores Up is caught. + */ +function digitStage(id: Id, base: number) { + const largest = base - 1; + const offSteps = [base, base + 1]; + // The digits that are 1 in the largest digit, e.g. eights and ones in 1001 + const largestOnes = bitsOf(largest, digitCount).flatMap((isOne, index) => + isOne ? [index] : [], + ); + const [firstOne, secondOne] = largestOnes; + invariant( + largestOnes.length === 2 && + firstOne !== undefined && + secondOne !== undefined, + "Carry is told by two digits that are 1", + ); + return defineStage(id, { + parts: [flipflop, const_, broadcast, and, not, decompose].map( + (part) => part.component.id, + ), + givenParts: ["four-bit-adder"], + tableNotation: "digits", + pinDistance: 560, + check: sequentialCheck( + { inputs: oneBitInputs("Up"), outputs: ["Count", "Carry"] }, + { + initialState: 0, + step: (count, { Up }) => { + const isUp = isOn(Up); + const carries = isUp && count === largest; + return { + outputs: { Count: bitsOf(count, digitCount), Carry: bit(carries) }, + next: carries ? 0 : isUp ? count + 1 : count, + }; + }, + }, + Array.from({ length: 2 * base + 4 }, (_, index) => ({ + Up: bit(!offSteps.includes(index + 1)), + })), + [1, 2, ...offSteps, base + 2, base + 3], + ), + layOut(circuit, { decorate }) { + // Every wire placed here runs left to right, so that none crosses a node + const memory = circuit.place(flipflop.component.id, { x: -150, y: -150 }); + const adder = circuit.place(fourBitAdderStage.componentId, { + x: 100, + y: 0, + }); + const one = circuit.place( + const_.component.id, + { x: -400, y: -300 }, + { mode: "binary", data: bitsOf(1, digitCount) }, + ); + const spreadUp = circuit.place(broadcast.component.id, { + x: -400, + y: 120, + }); + const step = circuit.place(and.component.id, { x: -150, y: 120 }); + const digits = circuit.place(decompose.component.id, { x: 0, y: 250 }); + circuit.setBitWidth(spreadUp, broadcast.outputPin.Out, digitCount); + circuit.split( + digits, + decompose.outputPin.Out, + new Array(digitCount).fill(1), + ); + const count = circuit.pinOf(memory, flipflop.outputPin.Out); + circuit.connect(count, circuit.pin("Count")); + circuit.connect(count, circuit.pinOf(adder, "A")); + circuit.connect(count, circuit.pinOf(digits, decompose.inputPin.In)); + circuit.connect( + circuit.pin("Up"), + circuit.pinOf(spreadUp, broadcast.inputPin.In), + ); + circuit.connect( + circuit.pinOf(one, const_.outputPin.Out), + circuit.pinOf(step, and.inputPin.A), + ); + circuit.connect( + circuit.pinOf(spreadUp, broadcast.outputPin.Out), + circuit.pinOf(step, and.inputPin.B), + ); + circuit.connect( + circuit.pinOf(step, and.outputPin.Out), + circuit.pinOf(adder, "B"), + ); + if (decorate) { + circuit.connect(count, placeNumeral(circuit, { x: 380, y: -330 })); + } + return () => { + const largestAt = circuit.place(and.component.id, { x: 180, y: 290 }); + const carries = circuit.place(and.component.id, { x: 330, y: 200 }); + const stays = circuit.place(not.component.id, { x: 380, y: 40 }); + const spreadStays = circuit.place(broadcast.component.id, { + x: 380, + y: -30, + }); + const kept = circuit.place(and.component.id, { x: -320, y: -120 }); + circuit.setBitWidth(spreadStays, broadcast.outputPin.Out, digitCount); + const digit = (index: number) => + circuit.pinOf(digits, decompose.outputPin.Out, index); + circuit.connect( + digit(firstOne), + circuit.pinOf(largestAt, and.inputPin.A), + ); + circuit.connect( + digit(secondOne), + circuit.pinOf(largestAt, and.inputPin.B), + ); + circuit.connect( + circuit.pinOf(largestAt, and.outputPin.Out), + circuit.pinOf(carries, and.inputPin.A), + ); + circuit.connect( + circuit.pin("Up"), + circuit.pinOf(carries, and.inputPin.B), + ); + const carry = circuit.pinOf(carries, and.outputPin.Out); + circuit.connect(carry, circuit.pin("Carry")); + circuit.connect(carry, circuit.pinOf(stays, not.inputPin.In)); + circuit.connect( + circuit.pinOf(stays, not.outputPin.Out), + circuit.pinOf(spreadStays, broadcast.inputPin.In), + ); + circuit.connect( + circuit.pinOf(adder, "S"), + circuit.pinOf(kept, and.inputPin.A), + ); + circuit.connect( + circuit.pinOf(spreadStays, broadcast.outputPin.Out), + circuit.pinOf(kept, and.inputPin.B), + ); + circuit.connect( + circuit.pinOf(kept, and.outputPin.Out), + circuit.pinOf(memory, flipflop.inputPin.In), + ); + }; + }, + }); +} -/** Count goes up while Up is ON and back to 0 after 9; Carry is ON when it goes back */ -const decimalDigitStage = defineStage("decimal-digit", { - parts: [flipflop, const_, broadcast, and, not, decompose].map( - (part) => part.component.id, - ), - givenParts: ["four-bit-adder"], +const decimalDigitStage = digitStage("decimal-digit", 10); +/** Handed over to the stopwatch for the tens of seconds and of minutes */ +const senaryDigitPart = digitStage("senary-digit", 6); + +const partById = { + "senary-digit": senaryDigitPart, +} satisfies { [Id in TutorialPartId]: StageOf }; +export const tutorialParts: readonly GivenPart[] = Object.values(partById); + +const secondsInHour = 3600; +/** From the left of MM:SS, with where the 7seg of each sits */ +const stopwatchDigits = [ + { name: "M10", part: senaryDigitPart, numeralY: -570 }, + { name: "M1", part: decimalDigitStage, numeralY: -495 }, + { name: "S10", part: senaryDigitPart, numeralY: -345 }, + { name: "S1", part: decimalDigitStage, numeralY: -270 }, +] as const; +// Start is OFF for a while only after 59:59 has gone back to 00:00, so that the +// steps of the goal are those a player reaches with Start ON from the first step +const stopwatchOffSteps = [secondsInHour + 2, secondsInHour + 3]; +const numeralWidth = 4; +const numeralHeight = 7; +const blankColumn = new Array(numeralHeight).fill(false); +// The rows the dots of a colon light, as tall as a 7seg's numeral +const colonColumn = [false, false, true, false, true, false, false]; +/** The columns between the numerals: a gap; a gap, the colon and a gap; a gap */ +const spacerColumns = [ + [blankColumn], + [blankColumn, colonColumn, blankColumn], + [blankColumn], +]; +const spacerWidths = spacerColumns.map( + (columns) => columns.length * numeralHeight, +); +const spacers = spacerColumns.flat(2); + +/** MM:SS, one second a step while Start is ON, back to 00:00 after 59:59 */ +const stopwatchStage = defineStage("stopwatch", { + parts: [], + givenParts: ["decimal-digit", "senary-digit"], tableNotation: "digits", pinDistance: 560, + // Close enough for the outputs to sit below the display + pinSpacing: 120, check: sequentialCheck( - { inputs: oneBitInputs("Up"), outputs: ["Count", "Carry"] }, + { + inputs: oneBitInputs("Start"), + outputs: stopwatchDigits.map(({ name }) => name), + }, { initialState: 0, - step: (count, { Up }) => { - const isUp = isOn(Up); - const carries = isUp && count === decimalDigitCount - 1; + step: (seconds, { Start }) => { + const minutes = Math.floor(seconds / 60); + const values = [ + Math.floor(minutes / 10), + minutes % 10, + Math.floor((seconds % 60) / 10), + seconds % 10, + ]; return { - outputs: { Count: bitsOf(count, digitCount), Carry: bit(carries) }, - next: carries ? 0 : isUp ? count + 1 : count, + outputs: Object.fromEntries( + stopwatchDigits.map(({ name }, index) => [ + name, + bitsOf(nullthrows(values[index]), digitCount), + ]), + ), + next: isOn(Start) ? (seconds + 1) % secondsInHour : seconds, }; }, }, - // Up is OFF while Count stays at 9, so a Carry that ignores Up is caught - Array.from({ length: 24 }, (_, index) => ({ - Up: bit(index + 1 < 10 || index + 1 > 11), + Array.from({ length: secondsInHour + 5 }, (_, index) => ({ + Start: bit(!stopwatchOffSteps.includes(index + 1)), })), - [1, 2, 10, 11, 12, 13], + [ + 1, + 2, + 60, + 61, + ...Array.from({ length: 6 }, (_, index) => secondsInHour + index), + ], ), layOut(circuit, { decorate }) { - // Every wire placed here runs left to right, so that none crosses a node - const memory = circuit.place(flipflop.component.id, { x: -150, y: -150 }); - const adder = circuit.place(fourBitAdderStage.componentId, { - x: 100, - y: 0, - }); - const one = circuit.place( - const_.component.id, - { x: -400, y: -300 }, - { mode: "binary", data: bitsOf(1, digitCount) }, - ); - const spreadUp = circuit.place(broadcast.component.id, { x: -400, y: 120 }); - const step = circuit.place(and.component.id, { x: -150, y: 120 }); - const digits = circuit.place(decompose.component.id, { x: 0, y: 250 }); - circuit.setBitWidth(spreadUp, broadcast.outputPin.Out, digitCount); - circuit.split( - digits, - decompose.outputPin.Out, - new Array(digitCount).fill(1), - ); - const count = circuit.pinOf(memory, flipflop.outputPin.Out); - circuit.connect(count, circuit.pin("Count")); - circuit.connect(count, circuit.pinOf(adder, "A")); - circuit.connect(count, circuit.pinOf(digits, decompose.inputPin.In)); - circuit.connect( - circuit.pin("Up"), - circuit.pinOf(spreadUp, broadcast.inputPin.In), - ); - circuit.connect( - circuit.pinOf(one, const_.outputPin.Out), - circuit.pinOf(step, and.inputPin.A), - ); - circuit.connect( - circuit.pinOf(spreadUp, broadcast.outputPin.Out), - circuit.pinOf(step, and.inputPin.B), - ); - circuit.connect( - circuit.pinOf(step, and.outputPin.Out), - circuit.pinOf(adder, "B"), + const numerals = stopwatchDigits.map(({ numeralY }) => + decorate + ? circuit.place( + seven_segment.component.id, + { x: -150, y: numeralY }, + { pixelOrder: "column-major" }, + ) + : null, ); if (decorate) { - circuit.connect(count, placeNumeral(circuit, { x: 380, y: -330 })); - } - return () => { - const nineAt = circuit.place(and.component.id, { x: 180, y: 290 }); - const carries = circuit.place(and.component.id, { x: 330, y: 200 }); - const stays = circuit.place(not.component.id, { x: 380, y: 40 }); - const spreadStays = circuit.place(broadcast.component.id, { - x: 380, - y: -30, - }); - const kept = circuit.place(and.component.id, { x: -320, y: -120 }); - circuit.setBitWidth(spreadStays, broadcast.outputPin.Out, digitCount); - const digit = (index: number) => - circuit.pinOf(digits, decompose.outputPin.Out, index); - circuit.connect(digit(0), circuit.pinOf(nineAt, and.inputPin.A)); - circuit.connect( - digit(digitCount - 1), - circuit.pinOf(nineAt, and.inputPin.B), - ); - circuit.connect( - circuit.pinOf(nineAt, and.outputPin.Out), - circuit.pinOf(carries, and.inputPin.A), - ); - circuit.connect( - circuit.pin("Up"), - circuit.pinOf(carries, and.inputPin.B), + const spacing = circuit.place( + const_.component.id, + { x: -560, y: -430 }, + { mode: "binary", data: spacers }, ); - const carry = circuit.pinOf(carries, and.outputPin.Out); - circuit.connect(carry, circuit.pin("Carry")); - circuit.connect(carry, circuit.pinOf(stays, not.inputPin.In)); - circuit.connect( - circuit.pinOf(stays, not.outputPin.Out), - circuit.pinOf(spreadStays, broadcast.inputPin.In), + const spaces = circuit.place(decompose.component.id, { + x: -260, + y: -430, + }); + const joined = circuit.place(aggregate.component.id, { + x: 100, + y: -430, + }); + const screen = circuit.place( + display.component.id, + { x: 420, y: -430 }, + { + resolution: { + x: + stopwatchDigits.length * numeralWidth + + spacers.length / numeralHeight, + y: numeralHeight, + }, + pixelOrder: "column-major", + }, ); + circuit.split(spaces, decompose.outputPin.Out, spacerWidths); + const numeralBits = numeralWidth * numeralHeight; + circuit.split(joined, aggregate.inputPin.In, [ + numeralBits, + ...spacerWidths.flatMap((width) => [width, numeralBits]), + ]); circuit.connect( - circuit.pinOf(adder, "S"), - circuit.pinOf(kept, and.inputPin.A), + circuit.pinOf(spacing, const_.outputPin.Out), + circuit.pinOf(spaces, decompose.inputPin.In), ); + for (const [index, numeral] of numerals.entries()) { + circuit.connect( + circuit.pinOf(nullthrows(numeral), seven_segment.outputPin.Out), + circuit.pinOf(joined, aggregate.inputPin.In, 2 * index), + ); + } + for (const index of spacerWidths.keys()) { + circuit.connect( + circuit.pinOf(spaces, decompose.outputPin.Out, index), + circuit.pinOf(joined, aggregate.inputPin.In, 2 * index + 1), + ); + } circuit.connect( - circuit.pinOf(spreadStays, broadcast.outputPin.Out), - circuit.pinOf(kept, and.inputPin.B), + circuit.pinOf(joined, aggregate.outputPin.Out), + circuit.pinOf(screen, display.inputPin.Pixels), ); - circuit.connect( - circuit.pinOf(kept, and.outputPin.Out), - circuit.pinOf(memory, flipflop.inputPin.In), + } + return () => { + const nodes = stopwatchDigits.map(({ part }, index) => + circuit.place(part.componentId, { + x: 250 - 200 * index, + y: 300 - 150 * index, + }), ); + for (const [index, node] of nodes.entries()) { + const { name } = nullthrows(stopwatchDigits[index]); + const count = circuit.pinOf(node, "Count"); + circuit.connect(count, circuit.pin(name)); + const numeral = numerals[index]; + if (numeral) { + circuit.connect( + count, + circuit.pinOf(numeral, seven_segment.inputPin.In), + ); + } + const lower = nodes[index + 1]; + circuit.connect( + lower ? circuit.pinOf(lower, "Carry") : circuit.pin("Start"), + circuit.pinOf(node, "Up"), + ); + } }; }, }); @@ -542,6 +761,7 @@ export const tutorialStages: readonly TutorialStage[] = [ fourBitAdderStage, counterStage, decimalDigitStage, + stopwatchStage, ]; /** Between the columns of input and output pins, also for a stage without inputs */ @@ -556,23 +776,26 @@ export function findTutorialStage(id: string | undefined) { return tutorialStages.find((stage) => stage.id === id); } -function tutorialStageById(id: TutorialStageId): TutorialStage { - return nullthrows(findTutorialStage(id), `No stage ${id}`); +export function givenPartById(id: GivenPartId): GivenPart { + return nullthrows( + [...tutorialStages, ...tutorialParts].find((part) => part.id === id), + `No stage or part ${id}`, + ); } -function stagesBuiltIn(stage: TutorialStage): TutorialStage[] { +function stagesBuiltIn(stage: GivenPart): GivenPart[] { return [ stage, - ...stage.givenParts.flatMap((id) => stagesBuiltIn(tutorialStageById(id))), + ...stage.givenParts.flatMap((id) => stagesBuiltIn(givenPartById(id))), ]; } -function stageOwning(stage: TutorialStage, componentId: CCComponentId) { +function stageOwning(stage: GivenPart, componentId: CCComponentId) { return stagesBuiltIn(stage).find((s) => s.componentId === componentId); } export function isStageComponent( - stage: TutorialStage, + stage: GivenPart, componentId: CCComponentId, ): boolean { return stageOwning(stage, componentId) !== undefined; @@ -585,9 +808,9 @@ export function isStagePart( editedComponentId: CCComponentId, ) { const owner = stageOwning(stage, editedComponentId); - const isGivenTo = (receiver: TutorialStage) => + const isGivenTo = (receiver: GivenPart) => receiver.givenParts.some( - (id) => tutorialStageById(id).componentId === component.id, + (id) => givenPartById(id).componentId === component.id, ); if (owner && owner !== stage) { return component.intrinsicType @@ -640,7 +863,7 @@ function renamePinOfNode( function registerStageComponent( store: CCStore, - stage: TutorialStage, + stage: GivenPart, componentName: string, ) { store.components.register({ @@ -657,7 +880,10 @@ function registerStageComponent( const node = CCNodeStore.create({ parentComponentId: stage.componentId, componentId: interfaceComponentId, - position: { x, y: (index - (names.length - 1) / 2) * 200 }, + position: { + x, + y: (index - (names.length - 1) / 2) * stage.pinSpacing, + }, }); store.nodes.register(node); renamePinOfNode(store, node.id, componentPin, name); @@ -680,10 +906,10 @@ function registerStageComponent( /** Skips the parts `store` already has, as a save from before may lack only some */ export function registerGivenParts( store: CCStore, - stage: TutorialStage, + stage: GivenPart, titleOf: StageTitleOf, ): void { - for (const given of stage.givenParts.map(tutorialStageById)) { + for (const given of stage.givenParts.map(givenPartById)) { if (store.components.get(given.componentId)) continue; registerGivenParts(store, given, titleOf); registerStageComponent(store, given, titleOf(given.id)); @@ -700,7 +926,7 @@ export function registerGivenParts( */ export function setUpTutorialStage( store: CCStore, - stage: TutorialStage, + stage: GivenPart, titleOf: StageTitleOf, ): () => void { registerGivenParts(store, stage, titleOf);