Rebuild Tetris as ten behaviors that pass values around

The board is a list of 200 numbers now instead of 200 characters, so a cell is
Item at and a landing is Set item instead of seven nodes of string surgery.

The bigger change is that the one 219-node graph is gone. Each step of a frame is
a behavior of its own - Spawn piece, Next move, Fits, Draw piece, Lock piece,
Clear lines, Show lines, Draw board, plus Piece cell for where one of the four
cells of a piece sits. None of them holds state: what they need arrives through
their inputs, every answer leaves through their outputs. That is what lets Fits
answer for turning, moving and falling alike, and Piece cell serve the fit test,
the drawing and the landing instead of being the same twenty nodes three times.

Tetris itself is down to 84 nodes and only says in which order the steps run and
which variable each answer lands in. The smoke test holds it to that: it fails if
a loop or a list access reappears in the master graph.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
rootandClaude Opus 5 committed 2026-09-09 21:27:01 +02:00
1 parent a9c3111377
commit 558365d33f
5 files changed
+1022 -628

No files matched your search

+28 -9
View File
@@ -91,7 +91,13 @@ shown on the node and editable in the inspector.
- **Variables** are the behavior's own property schema (`BehaviorAsset.variables`): they
appear in the inspector, can be overridden per placed instance, and each running instance
gets its own mutable copy. `Get variable` / `Set variable` read and write them.
gets its own mutable copy. `Get variable` / `Set variable` read and write them. A variable is a
**number, a yes/no, a text or a list**; a list holds numbers, texts, yes/nos or colours (its
item kind decides how the inspector reads the one comma-separated line it is typed as) and is
compared by its items, never by identity – otherwise every reload would look like an override.
There is no list *of objects*: a list is stored in the project file and an object is a live
handle that no reload survives. A set of objects is a list of their names, walked with `Repeat`
and `Object by name`.
- **Owner** = parent: a placed behavior is usually parented to the object it controls
(inspector → Parent, or drag it onto that object in the hierarchy; dashed line in the
viewport). The `Owner` node returns it; `Self` returns the behavior itself; `Parent` walks up
@@ -102,6 +108,9 @@ shown on the node and editable in the inspector.
variable`, `Get/Set property`, `Get position` (local and world), `Is enabled`, literals, `Add/Subtract/Multiply/Divide`,
`Min/Max/Abs/Sqrt/Clamp`, `Floor/Ceil/Round`, `Modulo`, `Random`, `Time`, `To text`, `To number`, `Join text`,
`Substring`, `Find text`, `Equals`,
lists `List` (a constant), `Fill` (one value repeated – how an empty board is made), `Count`,
`Item at`, `Set item` (a *new* list, the one that came in is left alone), `Sub list`,
`Join lists`, `Index of`,
`Length`, `Distance`, `Normalize`, `Axis input` (four keys → a
normalized direction, so diagonals are not faster), `Compare`, `And/Or/Not`, `Key is down`,
`Mouse position`, `Mouse button`, `Is hovered`, `Is touching` ·
@@ -580,15 +589,25 @@ and picking one up destroys the container, not just the sprite the collider repo
text, mouse and platformer physics need.
**The second example** (`tools/seed-tetris.mjs`, project *Tetris*) is the same idea with data
instead of physics. The board is a **text of 200 characters**, one per cell – `.` for empty,
otherwise the digit of the shape that came to rest there. A cell is `Substring(grid, row · 10 +
column, 1)`, and clearing a full line is one expression: an empty row joined in front of
everything above and below it. What the player sees is a pool of objects the graph addresses by
name – `c0…c199` for the well, `p0…p3` for the piece that is falling – so nothing is spawned or
instead of physics. The board is a **list of 200 numbers**, one per cell – `-1` for empty,
otherwise the shape that came to rest there. A cell is `Item at(grid, row · 10 + column)`, a
landing is `Set item`, and clearing a full line is an empty row joined in front of everything
above and below it. What the player sees is a pool of objects the graphs address by name –
`c0…c199` for the well, `p0…p3` for the piece that is falling – so nothing is spawned or
destroyed while playing. Every frame tries exactly **one** move (turning beats moving beats
falling), which is why the graph needs only a single "does it fit?" test instead of one per key.
`tools/smoke-tetris.mjs` plays it in a headless browser (fall, move, turn, drop, land, clear a
line, fill the well) – it is the regression test for loops, text nodes and names built at runtime.
falling), which is why the game needs only a single "does it fit?" test instead of one per key.
It is **ten behaviors**, not one graph. `Tetris` owns the state and does none of the work: each
step of a frame is a behavior of its own, called as a node – `Spawn piece`, `Next move`, `Fits`,
`Draw piece`, `Lock piece`, `Clear lines`, `Show lines`, `Draw board`, with `Piece cell` (where
one of the four cells of a piece sits) used by three of them. None of them holds state: what they
need arrives through their inputs and every answer leaves through their outputs, which is what
lets `Fits` answer for turning, moving and falling alike, and `Piece cell` serve the fit test,
the drawing and the landing instead of being the same twenty nodes three times. What is left in
the master graph is the order the steps run in and which variable each answer lands in – it holds
no loop and no list access of its own, which `tools/smoke-tetris.mjs` checks. That script plays
the game in a headless browser (fall, move, turn, drop, land, clear a line, fill the well) – it
is the regression test for loops, lists and behaviors used as nodes.
The workspace folder itself is what nginx serves, so `npm run build` is the deployment.
+94
View File
@@ -0,0 +1,94 @@
## Tetris Game verbessern
das ist erst relevant wenn behavior als node funktionieren
hier ein paar fragen vorweg:
- habe ich gesehen dass es die variablen `grid`, `shapes`, `colors` und `spawnX` gibt. diese sind sehr kryptisch. welche nodes fehlen, bzw. wie kann man das schöner gestalten.
- man könnte jetzt das ganze auch in mehrere behavior strukturell aufsplitten und diese in das `Tetris`-Behavior als Node einbetten
---
## Beantwortet und umgesetzt
Beide Punkte hatten dieselbe Ursache, und die lag nicht im Tetris-Projekt: **der Engine fehlte
ein Datentyp.** Eine Variable konnte nur Zahl, Text oder Ja/Nein sein (`PropertyValue`), also
musste jede Menge von Werten in einen String kodiert werden. Genau daher kamen deine vier
kryptischen Variablen — nicht aus einer schlechten Wahl beim Bauen.
### 1. Die kryptischen Variablen: es fehlte die Liste
`list` ist jetzt eine Variablen- und eine Port-Art. Sie hält Zahlen, Texte, Ja/Neins oder
**Farben** und wird im Inspector als eine kommagetrennte Zeile getippt.
| Variable | vorher | jetzt |
|---|---|---|
| `grid` | 200-Zeichen-Text, `.` = leer | Liste aus 200 Zahlen, `-1` = leer |
| `shapes` | 224 Ziffern am Stück | Liste aus 224 Zahlen |
| `colors` | `"03066326048763714..."` – Farben als 8-stellig gepaddete Dezimalzahlen | Farbliste: `#2ec9d6, #f5c542, …` |
| `spawnX` | `"3433333"` | `3, 4, 3, 3, 3, 3, 3` |
Dazu acht neue Nodes, alle allgemein statt Tetris-eigen: **`List`** (Konstante), **`Fill`**
(ein Wert wiederholt – so entsteht ein leeres Brett), **`Count`**, **`Item at`**, **`Set item`**,
**`Sub list`**, **`Join lists`**, **`Index of`**.
Was das im Graphen ausmacht: eine Zelle lesen war `Substring(grid, i, 1)` + `Equals '.'`, jetzt
`Item at(grid, i) >= 0`. Eine Landung schreiben war **sieben** Nodes (zweimal `Substring`,
zweimal `Join`, `To text`, `Add`), jetzt **einer**: `Set item`.
**Bewusst nicht gebaut:** eine Liste *von Objekten*. Eine Liste wird in die Projektdatei
geschrieben, ein Objekt ist ein Handle, das keinen Reload überlebt — eine Objektliste wäre die
erste Wertsorte, die beim nächsten Laden still verschwindet. Objekte gehen weiter über Namen
(`Repeat` + `Item at` + `Object by name`), und eine spätere Item-Art `reference` (stabile Id)
wäre reines Hinzufügen, kein Bruch.
### 2. Aufgesplittet: aus einem Graphen sind zehn geworden
Erst waren es fünf; auf deinen Einwurf hin habe ich auch die einzelnen **Schritte** eines Frames
zu Behaviors gemacht, die das Master-Behavior nur noch setzt.
| Behavior | Aufgabe | Nodes |
|---|---|---|
| `Spawn piece` | welcher Stein als nächstes kommt und in welcher Spalte | 5 |
| `Next move` | welchen **einen** Zug dieser Frame versucht | 44 |
| `Fits` | passen die vier Zellen dorthin? | 18 |
| `Draw piece` | den fallenden Stein an seinen Platz stellen | 14 |
| `Lock piece` | die gelandeten vier Zellen ins Brett schreiben | 20 |
| `Clear lines` | volle Reihen entfernen und zählen | 29 |
| `Show lines` | den Zähler auf den Schirm schreiben | 5 |
| `Draw board` | das Brett zeichnen | 11 |
| `Piece cell` | wo eine der vier Zellen eines Steins sitzt | 12 |
| **`Tetris`** | **nur noch: in welcher Reihenfolge, und wohin die Antwort** | **84** (vorher 219) |
`Piece cell` war der erste Gewinn: dieselben zwanzig Nodes standen **zweimal** im Graphen. Jetzt
einmal — und drei der anderen rufen es auf, Sub-Behaviors im Sub-Behavior.
**Keins der neun hält Zustand**, genau dein „kann man über input/output lösen". `Next move` ist
das Beispiel dafür: es *bewegt* nichts, es schlägt einen Zug vor und gibt ihn zurück
(`nx, ny, nrot, kind, fall, wantDx, wantRot`). Ein eingelöster Tastenwunsch kommt als `0`
zurück — so wird ein Tastendruck genau einmal ausgegeben, ohne dass das Sub-Behavior die
Variablen des Aufrufers kennt.
**Woran man misst, dass der Master wirklich nur noch dirigiert:** in seinen 84 Nodes steckt
**keine Schleife und kein Listenzugriff mehr** — kein `Repeat`, `Item at`, `Set item`,
`Get position`, `Set position`, `Set text`. Das prüft der Smoke-Lauf, damit die Arbeit nicht
unbemerkt zurückwandert:
```
PASS the master calls every step as a node, and does none of their work itself
calls: spawn-piece, next-move, fits, draw-piece, lock-piece, clear-lines, show-lines, draw-board
work: []
```
`Draw piece`, `Draw board` und `Show lines` haben **keinen End-Node**: sie beantworten nichts,
sie zeichnen nur.
### Ein Fehlschlag unterwegs
Der Game-Over-Check fiel um — und die Messung nannte den Grund selbst: `lines: 20`. Meine
Vorlage für „Brunnen voll" bestand aus 19 **vollen** Reihen, die `Clear lines` wegräumte, bevor
der neue Stein überhaupt anstand. Der Check maß also das Aufräumen statt das Spielende. Jetzt
lässt jede Reihe ihre letzte Spalte frei: blockiert, aber nirgends vollständig.
Und beim Gegenprüfen fiel auf, dass mein erster Persistenz-Test nichts bewies — er lief über den
schema-geführten Weg, während der Filter, den ich repariert hatte, für Container-Instanzen gilt.
Beide Wege sind jetzt einzeln abgedeckt.
-7
View File
@@ -1,7 +0,0 @@
## Tetris Game verbessern
das ist erst relevant wenn behavior als node funktionieren
hier ein paar fragen vorweg:
- habe ich gesehen dass es die variablen `grid`, `shapes`, `colors` und `spawnX` gibt. diese sind sehr kryptisch. welche nodes fehlen, bzw. wie kann man das schöner gestalten.
- man könnte jetzt das ganze auch in mehrere behavior strukturell aufsplitten und diese in das `Tetris`-Behavior als Node einbetten
+822 -593
View File
File diff suppressed because it is too large. Load diff
+78 -19
View File
@@ -25,12 +25,43 @@ const STORED_COUNT = 8;
/** Those eight, the board instance keeping its place, plus the well, 200 cells and 4 piece cells. */
const OBJECT_COUNT = STORED_COUNT + 1 + COLS * ROWS + 4;
const GRAPH = { nodes: 219, edges: 248 };
/** The master graph and the nine behaviors the game is split into. */
const GRAPHS = {
tetris: { nodes: 84, edges: 94 },
'spawn-piece': { nodes: 5, edges: 6 },
'next-move': { nodes: 44, edges: 63 },
fits: { nodes: 18, edges: 29 },
'draw-piece': { nodes: 14, edges: 26 },
'lock-piece': { nodes: 20, edges: 23 },
'clear-lines': { nodes: 29, edges: 36 },
'show-lines': { nodes: 5, edges: 5 },
'draw-board': { nodes: 11, edges: 17 },
'piece-cell': { nodes: 12, edges: 19 },
};
/** The steps the master calls. `piece-cell` is missing on purpose: three of these call it. */
const STEPS = [
'spawn-piece',
'next-move',
'fits',
'draw-piece',
'lock-piece',
'clear-lines',
'show-lines',
'draw-board',
];
/** Node types that would mean the master is still doing a step's work itself. */
const WORK_NODES = ['Repeat', 'ItemAt', 'SetItem', 'GetPosition', 'SetText', 'SetPosition'];
const PIECE = (i) => instanceChild('oboard', `piece${i}`);
const EMPTY_ROW = '.'.repeat(COLS);
const FULL_ROW = '0'.repeat(COLS);
/** The board is a list of numbers: -1 is empty, anything else the shape that came to rest. */
const EMPTY = -1;
/** Named here rather than read from the project: a test that copies the answer proves nothing. */
const SHAPE_COLORS = [0x2ec9d6, 0xf5c542, 0xa35fd6, 0x63c74d, 0xe0553f, 0x4a7de0, 0xe08a3f];
const emptyRows = (n) => Array.from({ length: n * COLS }, () => EMPTY);
const fullRows = (n) => Array.from({ length: n * COLS }, () => 0);
await runChecks({ projectId, baseUrl, port: 9337, shotPrefix: 'gm-tetris' }, async (t) => {
const {
@@ -51,7 +82,7 @@ await runChecks({ projectId, baseUrl, port: 9337, shotPrefix: 'gm-tetris' }, asy
/** The variables of the Tetris behavior, live from the running world. */
const vars = async () => (await entity('ogame')).props;
const filledCells = (grid) => grid.split('').filter((c) => c !== '.').length;
const filledCells = (grid) => grid.filter((c) => c !== EMPTY).length;
const pieceCells = async () => {
const w = await world();
return [0, 1, 2, 3].map((i) => w.entities.find((e) => e.objectId === PIECE(i)));
@@ -82,14 +113,26 @@ await runChecks({ projectId, baseUrl, port: 9337, shotPrefix: 'gm-tetris' }, asy
await navigate();
// 1. The document survived the loader: 219 nodes and 248 edges is the whole game.
const graph = await json(
`(() => { const a = __gm.state.project.assets.find((x) => x.id === 'tetris'); return { nodes: a.graph.nodes.length, edges: a.graph.edges.length }; })()`,
// 1. The document survived the loader: ten graphs, no unknown node type, no dropped edge.
const graphs = await json(
`Object.fromEntries(__gm.state.project.assets.filter((a) => a.type === 'behavior').map((a) => [a.id, { nodes: a.graph.nodes.length, edges: a.graph.edges.length }]))`,
);
check(
'the whole graph loads – no unknown node type, no dropped edge',
graph.nodes === GRAPH.nodes && graph.edges === GRAPH.edges,
JSON.stringify(graph),
'all ten graphs load – no unknown node type, no dropped edge',
Object.entries(GRAPHS).every(
([id, want]) => graphs[id]?.nodes === want.nodes && graphs[id]?.edges === want.edges,
),
JSON.stringify(graphs),
);
const types = await json(
`__gm.state.project.assets.find((a) => a.id === 'tetris').graph.nodes.map((n) => n.type === 'RunBehavior' ? 'run:' + n.params.behavior : n.type)`,
);
const calls = types.filter((t) => t.startsWith('run:')).map((t) => t.slice(4));
const work = types.filter((t) => WORK_NODES.includes(t));
check(
'the master calls every step as a node, and does none of their work itself',
STEPS.every((id) => calls.includes(id)) && work.length === 0,
JSON.stringify({ calls, work }),
);
const stored = await evaluate('__gm.state.activeScene.objects.length');
const listed = await evaluate('__gm.sceneObjects().length');
@@ -153,7 +196,7 @@ await runChecks({ projectId, baseUrl, port: 9337, shotPrefix: 'gm-tetris' }, asy
await shot('03-moved');
// 5. Holding down drops it, and where it lands is written into the board text.
await setVariable('grid', '.'.repeat(COLS * ROWS));
await setVariable('grid', emptyRows(ROWS));
await holdKey('ArrowDown', 1600);
await sleep(300);
const landedVars = await vars();
@@ -167,19 +210,34 @@ await runChecks({ projectId, baseUrl, port: 9337, shotPrefix: 'gm-tetris' }, asy
(await litCells()) === filledCells((await vars()).grid),
JSON.stringify({ lit: await litCells(), inText: filledCells((await vars()).grid) }),
);
// The colour is the one proof that goes all the way through the colour list: the board is drawn
// by `Draw board`, which picks it with `Item at(colors, cell)`.
const painted = await json(
`(() => {
const grid = __gm.world().entities.find((e) => e.name === 'Tetris').props.grid;
const index = grid.findIndex((c) => c !== -1);
const cell = __gm.world().entities.find((e) => e.name === 'c' + index);
return { index, shape: grid[index], color: cell && cell.props.color };
})()`,
);
check(
'a cell that came to rest is painted in its shape colour, straight out of the colour list',
painted.color === SHAPE_COLORS[painted.shape],
JSON.stringify({ ...painted, expected: SHAPE_COLORS[painted.shape] }),
);
await shot('04-landed');
// 6. A full line disappears and counts. The bottom row is filled in beforehand, so whatever the
// piece is and wherever it comes down, landing on top of it completes that line.
await setVariable('lines', 0);
await setVariable('grid', EMPTY_ROW.repeat(ROWS - 1) + FULL_ROW);
await setVariable('grid', [...emptyRows(ROWS - 1), ...fullRows(1)]);
await holdKey('ArrowDown', 2200);
await sleep(400);
const cleared = await vars();
check(
'a full line disappears and is counted',
cleared.lines === 1,
`lines ${cleared.lines}, bottom row "${cleared.grid.slice((ROWS - 1) * COLS)}"`,
`lines ${cleared.lines}, bottom row [${cleared.grid.slice((ROWS - 1) * COLS).join(',')}]`,
);
check(
'the counter on screen says so too',
@@ -189,13 +247,15 @@ await runChecks({ projectId, baseUrl, port: 9337, shotPrefix: 'gm-tetris' }, asy
const bottom = cleared.grid.slice((ROWS - 1) * COLS);
check(
'the row that was full is gone, and what stood on it dropped into its place',
bottom.includes('.') && bottom !== EMPTY_ROW,
`bottom row "${bottom}", ${filledCells(cleared.grid)} cells taken in all`,
bottom.includes(EMPTY) && bottom.some((c) => c !== EMPTY),
`bottom row [${bottom.join(',')}], ${filledCells(cleared.grid)} cells taken in all`,
);
await shot('05-line-cleared');
// 7. A well filled to the top ends the run: the new piece cannot come down even once.
await setVariable('grid', EMPTY_ROW + FULL_ROW.repeat(ROWS - 1));
// 7. A well filled to the top ends the run: the new piece cannot come down even once. Every row
// keeps its last column free – a full row would be cleared away before the piece ever stands.
const blocked = Array.from({ length: COLS }, (_, column) => (column === COLS - 1 ? EMPTY : 0));
await setVariable('grid', [...emptyRows(1), ...Array.from({ length: ROWS - 1 }, () => blocked).flat()]);
await setVariable('hasPiece', false);
await waitFor(async () => (await evaluate('__gm.state.mode')) === 'edit');
const mode = await evaluate('__gm.state.mode');
@@ -209,9 +269,8 @@ await runChecks({ projectId, baseUrl, port: 9337, shotPrefix: 'gm-tetris' }, asy
py: over.py,
hasPiece: over.hasPiece,
kind: over.kind,
ok: over.ok,
lines: over.lines,
top: over.grid.slice(0, 30),
top: over.grid.slice(0, 30).join(','),
})
: 'stopped',
);