diff --git a/src/components/PartDescription.tsx b/src/components/PartDescription.tsx index 900c883..e4d6bc5 100644 --- a/src/components/PartDescription.tsx +++ b/src/components/PartDescription.tsx @@ -2,7 +2,7 @@ import { Box, Typography } from "@mui/material"; import { type Messages, useMessages } from "../i18n"; import type { CCComponent } from "../store/component"; import { definitionByComponentId } from "../store/intrinsics/definitions"; -import { truthTableOf } from "../store/intrinsics/truthTable"; +import { type TruthTable, truthTableOf } from "../store/intrinsics/truthTable"; import { TruthTableView } from "./TruthTableView"; type Summaries = Messages["parts"]["summaries"]; @@ -19,10 +19,25 @@ export function partSummary( export function PartDescription({ component }: { component: CCComponent }) { const messages = useMessages(); - const summary = partSummary(messages, component); const definition = definitionByComponentId.get(component.id); - const table = definition && truthTableOf(definition); + return ( + + ); +} +export function PartDescriptionView({ + name, + summary, + table, +}: { + name: string; + summary: string | null; + table: TruthTable | null; +}) { return (
- {component.name} + {name} {summary && {summary}} {table && ( diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 726a0ef..1dad934 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -134,9 +134,13 @@ export const en = { title: "Both switches", goal: "Make the lamp Out light up only when both switches A and B are ON. Drag parts from the Parts list onto the editor, and drag from pin to pin to connect them. The play button at the bottom right lets you try the switches. When it works, press Check.", }, + "a-only": { + title: "Only switch A", + goal: "Make the lamp Out light up only when switch A is ON and B is OFF. This time, one part alone is not enough.", + }, xor: { title: "Only one switch", - goal: "Make the lamp Out light up when exactly one of the switches A and B is ON. It does not light up when both are ON.", + 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.', }, }, }, diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index aac3d55..aa26f47 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -124,9 +124,13 @@ export const ja: Messages = { title: "両方のスイッチ", goal: "スイッチ A と B が両方 ON のときだけ、ランプ Out がつくようにしましょう。「部品」の一覧から部品をエディタにドラッグして置き、ピンからピンへドラッグしてつなぎます。右下の再生ボタンで、スイッチを切り替えて試せます。できたら「確かめる」を押してください。", }, + "a-only": { + title: "A だけのスイッチ", + goal: "スイッチ A が ON で、B が OFF のときだけ、ランプ Out がつくようにしましょう。今度は、部品を1つ置くだけではできません。", + }, xor: { title: "片方だけのスイッチ", - goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out がつくようにしましょう。両方 ON のときはつきません。", + goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out がつくようにしましょう。両方 ON のときはつきません。「A だけのスイッチ」を部品として使えます。", }, }, }, diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx index 26a0103..4909b1e 100644 --- a/src/pages/tutorial/stage.tsx +++ b/src/pages/tutorial/stage.tsx @@ -18,7 +18,10 @@ import { } from "react-router"; import { valueLabel } from "../../common/bitLabel"; import { ConfirmDialog } from "../../components/ConfirmDialog"; -import { PartDescription } from "../../components/PartDescription"; +import { + PartDescription, + PartDescriptionView, +} from "../../components/PartDescription"; import { TruthTableView } from "../../components/TruthTableView"; import { type Messages, useMessages } from "../../i18n"; import type CCStore from "../../store"; @@ -38,8 +41,10 @@ import { } from "../../tutorial/stageStore"; import { findTutorialStage, + isStageComponent, isStagePart, isStagePinNode, + type StageTitleOf, type TutorialStage, tutorialStages, } from "../../tutorial/stages"; @@ -96,11 +101,11 @@ function StageView({ stage }: { stage: TutorialStage }) { const navigate = useNavigate(); const stageIndex = tutorialStages.indexOf(stage); const nextStage = tutorialStages[stageIndex + 1]; - const componentName = texts.stageTexts[stage.id].title; + const titleOf: StageTitleOf = (id) => texts.stageTexts[id].title; const goalTable = truthTableOfCheck(stage.check); const [store, setStore] = useState(() => - getTutorialStageStore(stage, componentName), + getTutorialStageStore(stage, titleOf), ); const [editedComponentId, setEditedComponentId] = useState(stage.componentId); const [result, setResult] = useState(null); @@ -129,7 +134,7 @@ function StageView({ stage }: { stage: TutorialStage }) { const resetStage = () => { setIsConfirmingReset(false); try { - setStore(resetTutorialStage(stage, componentName)); + setStore(resetTutorialStage(stage, titleOf)); setResetCount((count) => count + 1); setEditedComponentId(stage.componentId); setResult(null); @@ -217,6 +222,16 @@ function StageView({ stage }: { stage: TutorialStage }) { } /> ))} + {stage.givenParts.map((id) => ( + + ))}
@@ -254,7 +269,8 @@ function StageView({ stage }: { stage: TutorialStage }) { isProtectedNode: (nodeId) => isStagePinNode(store, stage, nodeId), isOffered, canCreateComponents: stage.allowsNewComponents, - hasProperties: (componentId) => componentId !== stage.componentId, + hasProperties: (componentId) => + !isStageComponent(stage, componentId), }} onEditComponent={setEditedComponentId} onClose={() => { diff --git a/src/tutorial/check.test.ts b/src/tutorial/check.test.ts index 7c150b3..b8411d3 100644 --- a/src/tutorial/check.test.ts +++ b/src/tutorial/check.test.ts @@ -1,6 +1,7 @@ +import nullthrows from "nullthrows"; import { describe, expect, it } from "vitest"; import { extractNodesIntoNewComponent } from "../store/extractComponent"; -import { and, not, or } from "../store/intrinsics/definitions"; +import { and, or } from "../store/intrinsics/definitions"; import { connectTestNodePins, createTestStore, @@ -14,14 +15,14 @@ import { truthTableOfCheck, } from "./check"; import { + findTutorialStage, setUpTutorialStage, type TutorialStage, - tutorialStages, } from "./stages"; function stageStore(stage: TutorialStage) { const store = createTestStore(); - setUpTutorialStage(store, stage, "Lamp"); + setUpTutorialStage(store, stage, (id) => id); const pins = store.componentPins.getManyByComponentId(stage.componentId); const pinOf = (name: string) => { const pin = pins.find((p) => p.name === name); @@ -44,8 +45,8 @@ function wireGate(stage: TutorialStage, gate: typeof and | typeof or) { return store; } -const [andStage, xorStage] = tutorialStages; -if (!andStage || !xorStage) throw new Error("Two stages are expected"); +const andStage = nullthrows(findTutorialStage("and")); +const xorStage = nullthrows(findTutorialStage("xor")); describe("inputCombinations", () => { it("counts up with the first input as the high bits", () => { @@ -116,43 +117,6 @@ describe("checkCombinational", () => { }); }); - it("passes the second stage built from AND, OR and NOT", () => { - const { store, pinOf } = stageStore(xorStage); - const id = xorStage.componentId; - const either = registerTestNode(store, id, or.component.id); - const both = registerTestNode(store, id, and.component.id); - const notBoth = registerTestNode(store, id, not.component.id); - const only = registerTestNode(store, id, and.component.id); - const connect = ( - from: Parameters[2], - to: typeof from, - ) => connectTestNodePins(store, id, from, to); - for (const [node, gate] of [ - [either, or], - [both, and], - ] as const) { - connect(pinOf("A"), testNodePin(store, node, gate.inputPin.A)); - connect(pinOf("B"), testNodePin(store, node, gate.inputPin.B)); - } - connect( - testNodePin(store, both, and.outputPin.Out), - testNodePin(store, notBoth, not.inputPin.In), - ); - connect( - testNodePin(store, either, or.outputPin.Out), - testNodePin(store, only, and.inputPin.A), - ); - connect( - testNodePin(store, notBoth, not.outputPin.Out), - testNodePin(store, only, and.inputPin.B), - ); - connect(testNodePin(store, only, and.outputPin.Out), pinOf("Out")); - - expect(checkCombinational(store, id, xorStage.check)).toEqual({ - type: "passed", - }); - }); - it("passes a circuit grouped into a component of the player's own", async () => { const store = wireGate(andStage, and); const gates = store.nodes diff --git a/src/tutorial/circuit.ts b/src/tutorial/circuit.ts new file mode 100644 index 0000000..534e5b5 --- /dev/null +++ b/src/tutorial/circuit.ts @@ -0,0 +1,65 @@ +import nullthrows from "nullthrows"; +import invariant from "tiny-invariant"; +import type { Vector2 } from "../common/vector2"; +import type CCStore from "../store"; +import type { CCComponentId } from "../store/component"; +import type { CCComponentPin } from "../store/componentPin"; +import { CCConnectionStore } from "../store/connection"; +import { type CCNode, CCNodeStore } from "../store/node"; +import type { CCNodePinId } from "../store/nodePin"; + +/** Builds a circuit inside one component, as the editor would when drawn by hand */ +export class StageCircuit { + constructor( + private readonly store: CCStore, + readonly componentId: CCComponentId, + ) {} + + /** The pin inside the component behind its own pin `name` */ + pin(name: string): CCNodePinId { + const componentPin = this.store.componentPins + .getManyByComponentId(this.componentId) + .find((pin) => pin.name === name); + return nullthrows( + componentPin?.implementation, + `The component has no pin named ${name}`, + ); + } + + place(componentId: CCComponentId, position: Vector2): CCNode { + const node = CCNodeStore.create({ + parentComponentId: this.componentId, + componentId, + position, + }); + this.store.nodes.register(node); + return node; + } + + /** By name only on a stage's component, as intrinsic pins are named for display */ + pinOf(node: CCNode, pin: CCComponentPin | string): CCNodePinId { + const nodePin = this.store.nodePins + .getManyByNodeId(node.id) + .find((nodePin) => + typeof pin === "string" + ? this.store.componentPins.get(nodePin.componentPinId)?.name === pin + : nodePin.componentPinId === pin.id, + ); + return nullthrows( + nodePin, + `The node has no pin ${typeof pin === "string" ? pin : pin.name}`, + ).id; + } + + connect(from: CCNodePinId, to: CCNodePinId): void { + const rejection = this.store.connections.register( + CCConnectionStore.create({ + parentComponentId: this.componentId, + from, + to, + bentPortion: 0.5, + }), + ); + invariant(!rejection, `The connection was rejected: ${rejection?.type}`); + } +} diff --git a/src/tutorial/stageStore.test.ts b/src/tutorial/stageStore.test.ts index b5bd8a0..e15ee6b 100644 --- a/src/tutorial/stageStore.test.ts +++ b/src/tutorial/stageStore.test.ts @@ -1,17 +1,30 @@ +import nullthrows from "nullthrows"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { CCStoreAutoSaver } from "../store/autoSaver"; -import { registerTestComponent, stubLocalStorage } from "../store/testUtils"; +import { + createTestStore, + registerTestComponent, + stubLocalStorage, +} from "../store/testUtils"; import { markStageCleared, readClearedStages } from "./progress"; import { getTutorialStageStore, resetTutorial, resetTutorialStage, } from "./stageStore"; -import { tutorialStages } from "./stages"; +import { + findTutorialStage, + setUpTutorialStage, + type TutorialStageId, + tutorialStages, +} from "./stages"; const [firstStage, secondStage] = tutorialStages; -if (!firstStage || !secondStage) throw new Error("Two stages are expected"); +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}`; let saved: Map; beforeEach(() => { @@ -27,7 +40,7 @@ afterEach(() => { describe("getTutorialStageStore", () => { it("saves apart from the free mode", () => { saved.set(CCStoreAutoSaver.localStorageKey, "free mode"); - const store = getTutorialStageStore(firstStage, "Lamp"); + const store = getTutorialStageStore(firstStage, titleOf); registerTestComponent(store, "Mine"); vi.advanceTimersByTime(2000); @@ -37,7 +50,7 @@ describe("getTutorialStageStore", () => { }); it("lays out the stage, and saves it only once it changes", () => { - const store = getTutorialStageStore(firstStage, "Lamp"); + const store = getTutorialStageStore(firstStage, titleOf); expect(store.components.get(firstStage.componentId)).toBeDefined(); expect( @@ -53,13 +66,13 @@ describe("getTutorialStageStore", () => { }); it("gives the same store while the page is open", () => { - expect(getTutorialStageStore(firstStage, "Lamp")).toBe( - getTutorialStageStore(firstStage, "Lamp"), + expect(getTutorialStageStore(firstStage, titleOf)).toBe( + getTutorialStageStore(firstStage, titleOf), ); }); it("brings back a stage saved earlier", () => { - const earlier = getTutorialStageStore(firstStage, "Lamp"); + const earlier = getTutorialStageStore(firstStage, titleOf); registerTestComponent(earlier, "Mine"); vi.advanceTimersByTime(2000); const json = earlier.toJSON(); @@ -68,15 +81,40 @@ describe("getTutorialStageStore", () => { vi.resetModules(); return import("./stageStore").then(({ getTutorialStageStore: fresh }) => { - expect(fresh(firstStage, "Lamp").toJSON()).toBe(json); + expect(fresh(firstStage, titleOf).toJSON()).toBe(json); }); }); + it("brings back a stage with the parts it hands over as saved", async () => { + const earlier = getTutorialStageStore(xorStage, titleOf); + registerTestComponent(earlier, "Mine"); + vi.advanceTimersByTime(2000); + const json = earlier.toJSON(); + earlier.autoSaver.unwatch(); + vi.resetModules(); + + const { getTutorialStageStore: fresh } = await import("./stageStore"); + expect(fresh(xorStage, titleOf).toJSON()).toBe(json); + }); + + it("adds a part handed over to a save made before, keeping the player's circuit", async () => { + const earlier = createTestStore(); + setUpTutorialStage(earlier, xorStage, titleOf); + await earlier.components.unregister(aOnlyStage.componentId); + const mine = registerTestComponent(earlier, "Mine"); + saved.set(`ccTutorialStage:${xorStage.id}`, earlier.toJSON()); + + const store = getTutorialStageStore(xorStage, titleOf); + + expect(store.components.get(aOnlyStage.componentId)).toBeDefined(); + expect(store.components.get(mine.id)).toBeDefined(); + }); + it("starts a stage over when what was saved is broken", () => { saved.set(firstKey, "broken"); vi.spyOn(console, "warn").mockImplementation(() => {}); - const store = getTutorialStageStore(firstStage, "Lamp"); + const store = getTutorialStageStore(firstStage, titleOf); expect(store.components.get(firstStage.componentId)).toBeDefined(); }); @@ -84,10 +122,10 @@ describe("getTutorialStageStore", () => { describe("resetTutorialStage", () => { it("lays the stage out anew and stops the old store from saving", () => { - const old = getTutorialStageStore(firstStage, "Lamp"); + const old = getTutorialStageStore(firstStage, titleOf); registerTestComponent(old, "Mine"); - const store = resetTutorialStage(firstStage, "Lamp"); + const store = resetTutorialStage(firstStage, titleOf); vi.advanceTimersByTime(2000); expect(store).not.toBe(old); @@ -100,7 +138,7 @@ describe("resetTutorialStage", () => { describe("resetTutorial", () => { it("forgets every stage and what was cleared", () => { - const store = getTutorialStageStore(secondStage, "Lamp"); + const store = getTutorialStageStore(secondStage, titleOf); registerTestComponent(store, "Mine"); vi.advanceTimersByTime(2000); markStageCleared(firstStage.id); @@ -109,6 +147,6 @@ describe("resetTutorial", () => { expect(saved.size).toBe(0); expect(readClearedStages().size).toBe(0); - expect(getTutorialStageStore(secondStage, "Lamp")).not.toBe(store); + expect(getTutorialStageStore(secondStage, titleOf)).not.toBe(store); }); }); diff --git a/src/tutorial/stageStore.ts b/src/tutorial/stageStore.ts index 18064fd..f7d0dd7 100644 --- a/src/tutorial/stageStore.ts +++ b/src/tutorial/stageStore.ts @@ -3,6 +3,8 @@ import { CCStoreAutoSaver } from "../store/autoSaver"; import { importStoreJson } from "../store/savedStore"; import { forgetClearedStages } from "./progress"; import { + registerGivenParts, + type StageTitleOf, setUpTutorialStage, type TutorialStage, tutorialStages, @@ -15,15 +17,18 @@ function storageKeyOf(stage: TutorialStage) { // One store per stage for the whole visit, so that rendering twice reuses it const storeByStageId = new Map(); -function createStageStore(stage: TutorialStage, componentName: string) { +function createStageStore(stage: TutorialStage, titleOf: StageTitleOf) { const store = new CCStore({ storageKey: storageKeyOf(stage) }); store.mount(); - setUpTutorialStage(store, stage, componentName); + setUpTutorialStage(store, stage, titleOf); store.autoSaver.watch(); return store; } -function restoreStageStore(stage: TutorialStage): CCStore | null { +function restoreStageStore( + stage: TutorialStage, + titleOf: StageTitleOf, +): CCStore | null { const json = CCStoreAutoSaver.readSaved(storageKeyOf(stage)); if (!json) return null; let store: CCStore; @@ -37,6 +42,8 @@ function restoreStageStore(stage: TutorialStage): CCStore | null { } if (!store.components.get(stage.componentId)) return null; store.mount(); + // A save from before the stage handed a part over keeps the player's circuit + registerGivenParts(store, stage, titleOf); store.autoSaver.watch(); return store; } @@ -47,11 +54,12 @@ function restoreStageStore(stage: TutorialStage): CCStore | null { */ export function getTutorialStageStore( stage: TutorialStage, - componentName: string, + titleOf: StageTitleOf, ): CCStore { let store = storeByStageId.get(stage.id); if (!store) { - store = restoreStageStore(stage) ?? createStageStore(stage, componentName); + store = + restoreStageStore(stage, titleOf) ?? createStageStore(stage, titleOf); storeByStageId.set(stage.id, store); } return store; @@ -66,10 +74,10 @@ function forgetStage(stage: TutorialStage) { export function resetTutorialStage( stage: TutorialStage, - componentName: string, + titleOf: StageTitleOf, ): CCStore { forgetStage(stage); - return getTutorialStageStore(stage, componentName); + return getTutorialStageStore(stage, titleOf); } /** Forget every stage and what was cleared, for the next player */ diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts index 086dd98..fbb7f37 100644 --- a/src/tutorial/stages.test.ts +++ b/src/tutorial/stages.test.ts @@ -1,24 +1,92 @@ +import nullthrows from "nullthrows"; import { describe, expect, it } from "vitest"; -import { and, input, output, xor } from "../store/intrinsics/definitions"; +import { + and, + input, + not, + or, + output, + xor, +} from "../store/intrinsics/definitions"; import { createTestStore, registerTestComponent, registerTestNode, } from "../store/testUtils"; +import { checkCombinational } from "./check"; +import { StageCircuit } from "./circuit"; import { + findTutorialStage, isStagePart, isStagePinNode, setUpTutorialStage, + type TutorialStageId, tutorialStages, } from "./stages"; 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}`; + +describe("tutorialStages", () => { + it("hands over only the parts of earlier stages", () => { + for (const [index, later] of tutorialStages.entries()) { + for (const id of later.givenParts) { + expect(tutorialStages.findIndex((s) => s.id === id)).toBeLessThan( + index, + ); + } + } + }); + + it.each(tutorialStages.map((s) => [s.id, s] as const))( + "%s is cleared by its solution, made of the parts it offers", + (_, solved) => { + const store = createTestStore(); + setUpTutorialStage(store, solved, titleOf); + + solved.solve(new StageCircuit(store, solved.componentId)); + + expect( + checkCombinational(store, solved.componentId, solved.check), + ).toEqual({ type: "passed" }); + const placed = store.nodes + .getManyByParentComponentId(solved.componentId) + .filter((node) => !isStagePinNode(store, solved, node.id)) + .map((node) => node.componentId); + const offered = [ + ...solved.parts, + ...solved.givenParts.map( + (id) => nullthrows(findTutorialStage(id)).componentId, + ), + ]; + expect(placed.length).toBeGreaterThan(0); + expect(offered).toEqual(expect.arrayContaining(placed)); + }, + ); +}); + +describe("setUpTutorialStage", () => { + it("hands over the parts of earlier stages, built and named after them", () => { + const store = createTestStore(); + + setUpTutorialStage(store, xorStage, titleOf); + + expect(store.components.get(aOnlyStage.componentId)?.name).toBe( + "Stage a-only", + ); + expect( + checkCombinational(store, aOnlyStage.componentId, aOnlyStage.check), + ).toEqual({ type: "passed" }); + }); +}); describe("isStagePinNode", () => { it("tells the pins the stage placed from the nodes the player adds", () => { const store = createTestStore(); - setUpTutorialStage(store, stage, "Lamp"); + setUpTutorialStage(store, stage, titleOf); const placed = store.nodes.getManyByParentComponentId(stage.componentId); const gate = registerTestNode(store, stage.componentId, and.component.id); const own = registerTestComponent(store, "Mine"); @@ -31,6 +99,25 @@ describe("isStagePinNode", () => { expect(isStagePinNode(store, stage, gate.id)).toBe(false); expect(isStagePinNode(store, stage, pinOfOwn.id)).toBe(false); }); + + it("keeps the pins of a part handed over too", () => { + const store = createTestStore(); + setUpTutorialStage(store, xorStage, titleOf); + const nodesOfGiven = store.nodes.getManyByParentComponentId( + aOnlyStage.componentId, + ); + const isPin = (componentId: string) => + componentId === input.component.id || componentId === output.component.id; + + expect(nodesOfGiven.filter((node) => isPin(node.componentId))).toHaveLength( + 3, + ); + for (const node of nodesOfGiven) { + expect(isStagePinNode(store, xorStage, node.id)).toBe( + isPin(node.componentId), + ); + } + }); }); describe("isStagePart", () => { @@ -54,4 +141,30 @@ describe("isStagePart", () => { expect(isStagePart(stage, output.component, own.id)).toBe(true); expect(isStagePart(stage, xor.component, own.id)).toBe(false); }); + + it("offers inside a part handed over what its own stage offers, and no pins", () => { + const inGiven = (component: Parameters[1]) => + isStagePart(xorStage, component, aOnlyStage.componentId); + + expect(isStagePart(xorStage, not.component, xorStage.componentId)).toBe( + false, + ); + expect(inGiven(not.component)).toBe(true); + expect(inGiven(or.component)).toBe(true); + expect(inGiven(xor.component)).toBe(false); + expect(inGiven(input.component)).toBe(false); + }); + + it("offers inside a part handed over none of the components outside it", () => { + const store = createTestStore(); + const own = registerTestComponent(store, "Mine"); + setUpTutorialStage(store, xorStage, titleOf); + const xorComponent = nullthrows(store.components.get(xorStage.componentId)); + + expect(isStagePart(xorStage, own, aOnlyStage.componentId)).toBe(false); + expect(isStagePart(xorStage, xorComponent, aOnlyStage.componentId)).toBe( + false, + ); + expect(isStagePart(xorStage, own, xorStage.componentId)).toBe(true); + }); }); diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts index c086665..560fde6 100644 --- a/src/tutorial/stages.ts +++ b/src/tutorial/stages.ts @@ -9,9 +9,11 @@ import type { CCComponentPin } from "../store/componentPin"; import { and, input, not, or, output } from "../store/intrinsics/definitions"; import { type CCNodeId, CCNodeStore } from "../store/node"; import type { CombinationalCheck } from "./check"; +import { StageCircuit } from "./circuit"; -export const tutorialStageIds = ["and", "xor"] as const; +export const tutorialStageIds = ["and", "a-only", "xor"] as const; export type TutorialStageId = (typeof tutorialStageIds)[number]; +export type StageTitleOf = (id: TutorialStageId) => string; export type TutorialStage = { id: TutorialStageId; @@ -19,22 +21,30 @@ export type TutorialStage = { 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[]; allowsNewComponents: boolean; /** also the input and output pins the stage starts with */ check: CombinationalCheck; + solve(circuit: StageCircuit): void; }; +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( id: TutorialStageId, + definition: Pick & + Partial>, lampIsOn: (a: boolean, b: boolean) => boolean, ): TutorialStage { return { id, componentId: `tutorial-${id}` as CCComponentId, - parts: [and.component.id, or.component.id, not.component.id], + givenParts: [], + ...definition, allowsNewComponents: false, check: { inputs: [ @@ -49,28 +59,128 @@ function twoSwitchesStage( }; } +const andStage = twoSwitchesStage( + "and", + { + parts: gateParts, + solve(circuit) { + const gate = circuit.place(and.component.id, { x: 0, y: 0 }); + circuit.connect(circuit.pin("A"), circuit.pinOf(gate, and.inputPin.A)); + circuit.connect(circuit.pin("B"), circuit.pinOf(gate, and.inputPin.B)); + circuit.connect( + circuit.pinOf(gate, and.outputPin.Out), + circuit.pin("Out"), + ); + }, + }, + (a, b) => a && b, +); + +const aOnlyStage = twoSwitchesStage( + "a-only", + { + parts: gateParts, + solve(circuit) { + const notB = circuit.place(not.component.id, { x: -120, y: 100 }); + const gate = circuit.place(and.component.id, { x: 120, y: 0 }); + circuit.connect(circuit.pin("A"), circuit.pinOf(gate, and.inputPin.A)); + circuit.connect(circuit.pin("B"), circuit.pinOf(notB, not.inputPin.In)); + circuit.connect( + circuit.pinOf(notB, not.outputPin.Out), + circuit.pinOf(gate, and.inputPin.B), + ); + circuit.connect( + circuit.pinOf(gate, and.outputPin.Out), + circuit.pin("Out"), + ); + }, + }, + (a, b) => a && !b, +); + +const xorStage = twoSwitchesStage( + "xor", + { + parts: [or.component.id], + givenParts: ["a-only"], + solve(circuit) { + const aOnly = circuit.place(aOnlyStage.componentId, { x: -40, y: -100 }); + const bOnly = circuit.place(aOnlyStage.componentId, { x: -40, y: 100 }); + const either = circuit.place(or.component.id, { x: 140, y: 0 }); + circuit.connect(circuit.pin("A"), circuit.pinOf(aOnly, "A")); + circuit.connect(circuit.pin("B"), circuit.pinOf(aOnly, "B")); + circuit.connect(circuit.pin("B"), circuit.pinOf(bOnly, "A")); + circuit.connect(circuit.pin("A"), circuit.pinOf(bOnly, "B")); + circuit.connect( + circuit.pinOf(aOnly, "Out"), + circuit.pinOf(either, or.inputPin.A), + ); + circuit.connect( + circuit.pinOf(bOnly, "Out"), + circuit.pinOf(either, or.inputPin.B), + ); + circuit.connect( + circuit.pinOf(either, or.outputPin.Out), + circuit.pin("Out"), + ); + }, + }, + (a, b) => a !== b, +); + export const tutorialStages: readonly TutorialStage[] = [ - twoSwitchesStage("and", (a, b) => a && b), - twoSwitchesStage("xor", (a, b) => a !== b), + andStage, + aOnlyStage, + xorStage, ]; 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}`); +} + +function stagesBuiltIn(stage: TutorialStage): TutorialStage[] { + return [ + stage, + ...stage.givenParts.flatMap((id) => stagesBuiltIn(tutorialStageById(id))), + ]; +} + +function stageOwning(stage: TutorialStage, componentId: CCComponentId) { + return stagesBuiltIn(stage).find((s) => s.componentId === componentId); +} + +export function isStageComponent( + stage: TutorialStage, + componentId: CCComponentId, +): boolean { + return stageOwning(stage, componentId) !== undefined; +} + +/** Inside a given part, its own parts are offered, so that what was deleted can be put back */ export function isStagePart( stage: TutorialStage, component: CCComponent, editedComponentId: CCComponentId, ) { - if (!component.intrinsicType || stage.parts.includes(component.id)) { - return true; + const owner = stageOwning(stage, editedComponentId); + if (owner && owner !== stage) { + return component.intrinsicType + ? owner.parts.includes(component.id) + : owner.givenParts.some( + (id) => tutorialStageById(id).componentId === component.id, + ); } + if (!component.intrinsicType) return true; + if (owner) return owner.parts.includes(component.id); // A component of the player's own gets its pins from Input and Output nodes return ( - editedComponentId !== stage.componentId && - (component.id === input.component.id || - component.id === output.component.id) + stage.parts.includes(component.id) || + component.id === input.component.id || + component.id === output.component.id ); } @@ -81,7 +191,8 @@ export function isStagePinNode( ): boolean { const node = store.nodes.get(nodeId); return ( - node?.parentComponentId === stage.componentId && + node !== undefined && + isStageComponent(stage, node.parentComponentId) && (node.componentId === input.component.id || node.componentId === output.component.id) ); @@ -104,12 +215,11 @@ function renamePinOfNode( store.componentPins.update(exposed.id, { name }); } -/** Lay out the component of `stage`, with its input and output pins, in a mounted store */ -export function setUpTutorialStage( +function registerStageComponent( store: CCStore, stage: TutorialStage, componentName: string, -): void { +) { store.components.register({ ...CCComponentStore.create({ name: componentName }), id: stage.componentId, @@ -138,3 +248,30 @@ export function setUpTutorialStage( ); place(output.component.id, output.inputPin.In, stage.check.outputs, 300); } + +/** Skips the parts `store` already has, as a save from before may lack only some */ +export function registerGivenParts( + store: CCStore, + stage: TutorialStage, + titleOf: StageTitleOf, +): void { + for (const given of stage.givenParts.map(tutorialStageById)) { + if (store.components.get(given.componentId)) continue; + registerGivenParts(store, given, titleOf); + registerStageComponent(store, given, titleOf(given.id)); + given.solve(new StageCircuit(store, given.componentId)); + } +} + +/** + * Lay out the component of `stage`, with its input and output pins, and the components + * it hands over, in a mounted store + */ +export function setUpTutorialStage( + store: CCStore, + stage: TutorialStage, + titleOf: StageTitleOf, +): void { + registerGivenParts(store, stage, titleOf); + registerStageComponent(store, stage, titleOf(stage.id)); +}