Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/common/bits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { SimulationValue } from "../store/simulation";

/** `value` in `width` bits, the most significant first, as in `SimulationValue` */
export function bitsOf(value: number, width: number): SimulationValue {
return Array.from(
{ length: width },
(_, i) => ((value >> (width - 1 - i)) & 1) === 1,
);
}

export function numberOf(bits: SimulationValue): number {
return bits.reduce((value, bit) => value * 2 + (bit ? 1 : 0), 0);
}
36 changes: 21 additions & 15 deletions src/components/TruthTableView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ import { Box, type Theme } from "@mui/material";
import { useContext } from "react";
import { bitDigit, bitLabel } from "../common/bitLabel";
import type { TruthTable } from "../store/intrinsics/truthTable";
import type { SimulationValue } from "../store/simulation";
import { theme } from "../style";
import { BitNotationContext } from "./bitNotation";

const divider = (muiTheme: Theme) => `1px solid ${muiTheme.palette.divider}`;
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 labelOf =
const singleBitLabel =
useContext(BitNotationContext) === "digits" ? bitDigit : bitLabel;
const columns = [
...table.inputs.map((name) => ({ key: `in-${name}`, name })),
Expand All @@ -26,7 +29,11 @@ export function TruthTableView({ table }: { table: TruthTable }) {
return (
<Box
component="table"
sx={{ borderCollapse: "collapse", fontSize: "0.875rem" }}
sx={{
borderCollapse: "collapse",
fontSize: "0.875rem",
fontVariantNumeric: "tabular-nums",
}}
>
<thead>
<tr>
Expand All @@ -43,20 +50,19 @@ export function TruthTableView({ table }: { table: TruthTable }) {
</thead>
<tbody>
{table.rows.map((row) => (
<tr key={row.inputs.join()}>
<tr key={row.inputs.map(binaryOf).join()}>
{[...row.inputs, ...row.outputs].map((value, i) => (
<Box
key={columns[i]?.key}
component="td"
sx={{
...cellSx(i),
...(value && {
color: theme.colors.primary,
fontWeight: "bold",
}),
}}
>
{labelOf(value)}
<Box key={columns[i]?.key} component="td" sx={cellSx(i)}>
{value.map((bit, index) => (
<Box
// biome-ignore lint/suspicious/noArrayIndexKey: bits are identified by their index
key={index}
component="span"
sx={bit ? onSx : {}}
>
{value.length === 1 ? singleBitLabel(bit) : bitDigit(bit)}
</Box>
))}
</Box>
))}
</tr>
Expand Down
25 changes: 22 additions & 3 deletions src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const listOf = (names: readonly string[]) =>
names.length < 2
? names.join("")
: `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
const digits = (count: number) => (count === 1 ? "1 digit" : `${count} digits`);
const themOf = (names: readonly string[]) =>
names.length === 1 ? "it" : "them";

Expand All @@ -14,7 +15,7 @@ type StageTexts = { title: string; goal: string; steps: readonly string[] };
const stageTexts: Record<TutorialStageId, StageTexts> = {
and: {
title: "Both switches",
goal: "Make the lamp Out light up only when both switches A and B are ON. The stage is cleared when the circuit works as in the table below.",
goal: "Make the lamp Out turn ON only when both switches A and B are ON. The stage is cleared when the circuit works as in the table below.",
steps: [
"Pick a part in the Parts list and drag it onto the editor on the right.",
"The small squares on the edges of a part are its pins. A pin on the left side is an input, which receives ON or OFF, and a pin on the right side is an output, which sends ON or OFF. Drag between an output pin and an input pin to connect them with a wire.",
Expand All @@ -25,12 +26,12 @@ const stageTexts: Record<TutorialStageId, StageTexts> = {
},
"a-only": {
title: "Only switch A",
goal: "Make the lamp Out light up only when switch A is ON and B is OFF. This time, one part alone is not enough.",
goal: "Make the lamp Out turn ON only when switch A is ON and B is OFF. This time, one part alone is not enough.",
steps: [],
},
xor: {
title: "Only one switch",
goal: 'Make the lamp Out light up when exactly one of the switches A and B is ON. It does not light up when both are ON. "Only switch A" is ready to use as a part.',
goal: 'Make the lamp Out turn ON when exactly one of the switches A and B is ON. It stays OFF when both are ON. "Only switch A" is ready to use as a part.',
steps: [],
},
"half-adder": {
Expand All @@ -43,6 +44,16 @@ const stageTexts: Record<TutorialStageId, StageTexts> = {
goal: 'Output A + B + Cin as a two-digit binary number to C and S. Cin is the carry coming up from the next lower digit. The answer is 0 to 3, and 3 is 11 in binary. "Adding one digit" is ready to use as a part: add A and B with one, then add Cin to its S with another. This circuit is called a full adder.',
steps: [],
},
"four-bit-adder": {
title: "Adding four digits",
goal: "A and B are four-digit binary numbers. Output A + B in four digits to S, and its fifth digit, the sixteens digit, to C: C is 1 when A + B is 16 or more. The table shows some examples.",
steps: [
'Place four "Adding with a carry". From the top, the pins on the right of Decompose and on the left of Aggregate are the eights, fours, twos and ones digits.',
"For each digit, connect that digit's pin on the upper Decompose, which A goes into, and on the lower one, which B goes into, to the A and B of one \"Adding with a carry\". Connect the S of that adder to the same digit's pin of Aggregate.",
"Connect the C of each digit's adder to the Cin of the adder one digit up. The ones digit's adder gets False on its Cin, and the C of the eights digit's adder goes to the output C on the right.",
"While playing, click a digit of A or B to switch it between 0 and 1. The sum S is shown as one character on the Display at the top right. The 7seg before it turns the binary number into the shape of a numeral. To write 10 to 15 with one character, A (10), b (11), C (12), d (13), E (14) and F (15) are used. This way of writing is called hexadecimal.",
],
},
};

export const en = {
Expand All @@ -62,6 +73,10 @@ export const en = {
XOR: "ON when exactly one input is ON",
TRUE: "Always ON",
FALSE: "Always OFF",
DECOMPOSE:
"Splits a number of several digits, from the highest digit down",
AGGREGATE:
"Joins values into one number, the upper pins as the higher digits",
},
about: (name: string) => `About ${name}`,
ofStage: "Available parts",
Expand Down Expand Up @@ -152,13 +167,17 @@ export const en = {
backToStages: "Back to the stages",
missingPin: (pinType: "input" | "output", pinName: string) =>
`There is no ${pinType} pin named ${pinName}. "Reset this stage" brings back how the stage started.`,
wrongBitWidth: (pinName: string, expected: number, actual: number) =>
`${pinName} should have ${digits(expected)}, but it has ${digits(actual)}. Check what it is connected to.`,
wrongOutput: (
inputs: readonly { name: string; value: string }[],
pinName: string,
expected: string,
actual: string | null,
) =>
`When ${listOf(inputs.map(({ name, value }) => `${name} is ${value}`))}, ${pinName} should be ${expected}, but it ${actual === null ? "has no value" : `is ${actual}`}.`,
checkFailed:
"Something went wrong while checking. Change the circuit a little and press Check again.",
simulationFailed: (detail: string) =>
`The circuit could not be simulated. ${detail}`,
resetStage: "Reset this stage",
Expand Down
28 changes: 22 additions & 6 deletions src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export const ja: Messages = {
XOR: "片方だけが ON のとき ON",
TRUE: "いつも ON",
FALSE: "いつも OFF",
DECOMPOSE: "何桁もある数を、上の桁から順に分ける",
AGGREGATE: "上のピンを大きい桁として、1つの数にまとめる",
},
about: (name) => `${name} について`,
ofStage: "使える部品",
Expand Down Expand Up @@ -110,8 +112,12 @@ export const ja: Messages = {
backToStages: "課題の一覧へ",
missingPin: (pinType, pinName) =>
`${pinName} という名前の${pinType === "input" ? "入力" : "出力"}ピンが見つかりません。「この課題をやり直す」で最初の状態に戻せます。`,
wrongBitWidth: (pinName, expected, actual) =>
`${pinName} は ${expected}桁のはずですが、${actual}桁になっています。つないだ先を確かめてください。`,
wrongOutput: (inputs, pinName, expected, actual) =>
`${inputs.map(({ name, value }) => `${name} が ${value}`).join("、")} のとき、${pinName} は ${expected} になるはずが、${actual === null ? "値がありませんでした" : `${actual} でした`}。`,
checkFailed:
"確かめる途中で問題が起きました。回路を少し変えてから、もう一度押してください。",
simulationFailed: (detail) =>
`回路をシミュレーションできませんでした。${detail}`,
resetStage: "この課題をやり直す",
Expand All @@ -124,7 +130,7 @@ export const ja: Messages = {
stageTexts: {
and: {
title: "両方のスイッチ",
goal: "スイッチ A と B が両方 ON のときだけ、ランプ Out がつくようにしましょう。下の表のとおりに動けばクリアです。",
goal: "スイッチ A と B が両方 ON のときだけ、ランプ Out が ON になるようにしましょう。下の表のとおりに動けばクリアです。",
steps: [
"「部品」の一覧から部品を選び、右のエディタにドラッグして置きます。",
"部品の端にある小さな四角を「ピン」といいます。左側のピンは ON か OFF を受け取る「入力」、右側のピンは ON か OFF を送り出す「出力」です。出力のピンと入力のピンのあいだをドラッグして、線でつなぎます。",
Expand All @@ -135,24 +141,34 @@ export const ja: Messages = {
},
"a-only": {
title: "A だけのスイッチ",
goal: "スイッチ A が ON で、B が OFF のときだけ、ランプ Out がつくようにしましょう。今度は、部品を1つ置くだけではできません。",
goal: "スイッチ A が ON で、B が OFF のときだけ、ランプ Out が ON になるようにしましょう。今度は、部品を1つ置くだけではできません。",
steps: [],
},
xor: {
title: "片方だけのスイッチ",
goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out がつくようにしましょう。両方 ON のときはつきません。「A だけのスイッチ」を部品として使えます。",
goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out が ON になるようにしましょう。両方 ON のときは OFF です。「A だけのスイッチ」を部品として使えます。",
steps: [],
},
"half-adder": {
title: "1けたの足し算",
goal: "ここからは ON を 1、OFF を 0 と考え、表もそう書きます。すると、A+B は 0、1、2 のどれかです。2進数では、0 と 1 だけで数を書きます。ふだんの数で 9+1 が繰り上がって 10 になるように、2進数では 1+1 が繰り上がって 10 になります。そのため、0、1、2 は2けたで 00、01、10 です。左のけた(2の位)を C に、右のけた(1の位)を S に出しましょう。C を「桁上がり」、S を「和」といい、この回路を「半加算器」といいます。",
title: "1桁の足し算",
goal: "ここからは ON を 1、OFF を 0 と考え、表もそう書きます。すると、A+B は 0、1、2 のどれかです。2進数では、0 と 1 だけで数を書きます。ふだんの数で 9+1 が繰り上がって 10 になるように、2進数では 1+1 が繰り上がって 10 になります。そのため、0、1、2 は2桁で 00、01、10 です。左の桁(2の位)を C に、右の桁(1の位)を S に出しましょう。C を「桁上がり」、S を「和」といい、この回路を「半加算器」といいます。",
steps: [],
},
"full-adder": {
title: "桁上がりつきの足し算",
goal: "A+B+Cin の答えを、2けたの2進数で C と S に出しましょう。Cin は、下のけたから来る桁上がりです。答えは 0 から 3 で、3 は2進数で 11 です。「1けたの足し算」を部品として使えます。1つで A と B を足し、もう1つでその S と Cin を足します。この回路を「全加算器」といいます。",
goal: "A+B+Cin の答えを、2桁の2進数で C と S に出しましょう。Cin は、下の桁から来る桁上がりです。答えは 0 から 3 で、3 は2進数で 11 です。「1桁の足し算」を部品として使えます。1つで A と B を足し、もう1つでその S と Cin を足します。この回路を「全加算器」といいます。",
steps: [],
},
"four-bit-adder": {
title: "4桁の足し算",
goal: "A と B は4桁の2進数です。A+B を4桁で S に、5桁目(16の位)を C に出しましょう。A+B が 16 以上なら、C は 1 です。表はその例です。",
steps: [
"「桁上がりつきの足し算」を4つ置きます。Decompose の右側のピンと Aggregate の左側のピンは、どちらも上から8の位・4の位・2の位・1の位です。",
"桁ごとに、A につないだ上の Decompose と、B につないだ下の Decompose から、その桁のピンを1つの「桁上がりつきの足し算」の A と B につなぎます。その足し算の S は、Aggregate の同じ桁のピンにつなぎます。",
"それぞれの桁の足し算の C を、1つ上の桁の足し算の Cin につなぎます。1の位の足し算の Cin には False を、8の位の足し算の C は右の出力 C につなぎます。",
"再生中は、A と B の桁をクリックして 0 と 1 を切り替えられます。答えの S は、右上の Display に1文字で表示されます。その手前の 7seg が、2進数を数字の形に変えています。10 から 15 は1文字で書くために、A(10)、b(11)、C(12)、d(13)、E(14)、F(15)を使います。この書き方を16進数といいます。",
],
},
},
},
componentProperties: {
Expand Down
14 changes: 14 additions & 0 deletions src/i18n/messages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,20 @@ describe("the message on a wrong output", () => {
});
});

describe("the message on a pin of the wrong width", () => {
it("counts digits in both languages", () => {
expect(messagesByLanguage.en.tutorial.wrongBitWidth("A", 4, 1)).toBe(
"A should have 4 digits, but it has 1 digit. Check what it is connected to.",
);
expect(messagesByLanguage.en.tutorial.wrongBitWidth("C", 1, 4)).toBe(
"C should have 1 digit, but it has 4 digits. Check what it is connected to.",
);
expect(messagesByLanguage.ja.tutorial.wrongBitWidth("A", 4, 1)).toBe(
"A は 4桁のはずですが、1桁になっています。つないだ先を確かめてください。",
);
});
});

describe("English messages", () => {
it("lists the inputs reset with their bit widths", () => {
expect(
Expand Down
21 changes: 5 additions & 16 deletions src/pages/edit/Editor/components/ValueEditor/value.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,13 @@
import { chunk } from "es-toolkit";
import invariant from "tiny-invariant";
import { bitsOf, numberOf } from "../../../../../common/bits";
import type { Messages } from "../../../../../i18n/messages";
import type { CCIntrinsicComponentConstSpecConfigViewMode as Mode } from "../../../../../store/intrinsics/types";
import type { SimulationValue } from "../../../../../store/simulation";

const bitsPerHexDigit = 4;
const bitsPerByte = 8;

/** Bits are ordered from the most significant one, as in `SimulationValue`. */
function toBits(value: number, bitCount: number): boolean[] {
return Array.from(
{ length: bitCount },
(_, i) => ((value >> (bitCount - 1 - i)) & 1) === 1,
);
}

function fromBits(bits: boolean[]): number {
return bits.reduce((value, bit) => value * 2 + (bit ? 1 : 0), 0);
}

/** Pads the head with zeros so that the length becomes a multiple of `unit`. */
function padBits(bits: SimulationValue, unit: number): boolean[] {
const padding = (unit - (bits.length % unit)) % unit;
Expand All @@ -34,12 +23,12 @@ export function formatSimulationValue(
return data.map((bit) => (bit ? "1" : "0")).join("");
case "hex":
return chunk(padBits(data, bitsPerHexDigit), bitsPerHexDigit)
.map((digit) => fromBits(digit).toString(16))
.map((digit) => numberOf(digit).toString(16))
.join("");
case "utf-8": {
const bytes = Uint8Array.from(
chunk(padBits(data, bitsPerByte), bitsPerByte),
fromBits,
numberOf,
);
return new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
}
Expand All @@ -61,13 +50,13 @@ export function parseSimulationValue(
const digits = text.replace(/\s/g, "").replace(/^0x/i, "");
if (!/^[0-9a-f]+$/i.test(digits)) return null;
return [...digits].flatMap((digit) =>
toBits(Number.parseInt(digit, 16), bitsPerHexDigit),
bitsOf(Number.parseInt(digit, 16), bitsPerHexDigit),
);
}
case "utf-8": {
const bytes = new TextEncoder().encode(text);
if (bytes.length === 0) return null;
return [...bytes].flatMap((byte) => toBits(byte, bitsPerByte));
return [...bytes].flatMap((byte) => bitsOf(byte, bitsPerByte));
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/pages/edit/Editor/store/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type EditorStoreOptions = {
isProtectedNode?: (nodeId: CCNodeId) => boolean;
isOffered?: OffersComponent;
canCreateComponents?: boolean;
fitsNodesInView?: boolean;
hasProperties?: (componentId: CCComponentId) => boolean;
};

Expand All @@ -26,6 +27,7 @@ export function createEditorStore(
isOffered = () => true,
hasProperties = () => true,
canCreateComponents = true,
fitsNodesInView = false,
}: EditorStoreOptions = {},
) {
const props = { store, componentId };
Expand All @@ -38,6 +40,7 @@ export function createEditorStore(
isOffered,
hasProperties,
canCreateComponents,
fitsNodesInView,
...coreSlice.define(set, get),
...perspectiveSlice.define(set, get),
...contextMenuSlice.define(set, get),
Expand Down
Loading
Loading