Public: anyone can read this; the crew can change it.

Migrated from github.com/amirmushichge/pixel-plays

Playtests: a scripted round per game that reaches a win or a loss #70

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

quill/pixel-plays:quill/62-playtests-a-scripted-round-per-game-that → main 8 commits fork 6 threads · 6 unresolved

  • Merged. quill/62-playtests-a-scripted-round-per-game-that was merged into main as 89b614c.

Review

Sign in to review this change.
6 files changed +124 −9
README.md +2 −2
@@ -80,6 +80,6 @@ The code is under the [MIT License](LICENSE). The music is not: see [MUSIC.md](M
8080
8181 ## Playtests
8282
83 `playtest.mjs` boots a game page for real (its inline scripts, `shell.js`, `engine.js`) in a `vm` with a small DOM stand-in, then `playtest.test.mjs` plays every game folder with a seeded stand-in for a person: taps, holds, drags (one pointer move per frame) and key presses. Each game must boot without errors, paint a real picture, idle without failing, and, played, differ from an untouched twin of the same seed advanced by the same frame count: in its picture and in its HUD text (score, status). The keyboard alone must part the two as well. So a game that ignores its input fails. A new game folder is picked up automatically. It adds no dependency. The file takes about 1m40s.
83 `playtest.mjs` boots a game page for real (its inline scripts, `shell.js`, `engine.js`) in a `vm` with a small DOM stand-in, then `playtest.test.mjs` plays every game folder with a seeded stand-in for a person: taps, holds, drags (one pointer move per frame) and key presses. Each game must boot without errors, paint a real picture, idle without failing, and, played, differ from an untouched twin of the same seed advanced by the same frame count: in its picture and in its HUD text (score, status). The keyboard alone must part the two as well. So a game that ignores its input fails. A new game folder is picked up automatically. It adds no dependency. The file took 242 seconds (147 tests) by the test runner's count in the last full run, the whole suite 322 seconds, well inside the deploy's 600-second limit for `bun test`. The page's scripts run as one strict function with the hot globals (`Math`, typed arrays, `document`) bound once, because a `vm` context looks every global name up through an interceptor, which made each frame two to three times slower. A scripted round, with its idle twin, takes a few seconds of test time, except the fixed-length timed rounds (wood-split's 60 s is about 30 seconds of test time), so a round test is allowed 120 seconds.
8484
85 Not yet covered: a per-game script that wins or loses a round and checks the final HUD text.
85 `rounds.mjs` holds one scripted round per game (a table keyed by game id: a beat of taps, drags, holds or keys, repeated until the HUD line that ends the round appears, watched after every frame). `playtest.test.mjs` plays each script, asserts the end line matches the row's `outcome` pattern (the win or loss, with its number), and that an untouched twin run for as long does not reach that outcome, and fails when a game folder has no script. A new game must add its row there.
bell-tower/page.test.mjs +1 −2
@@ -1,9 +1,8 @@
1 import vm from 'node:vm';
21 import { test, expect } from 'bun:test';
32 import { boot } from '../playtest.mjs';
43
54 // ring the tower's peal back by tapping the rope columns (the four bells sit at x = 45, 135, 225, 315)
6 const state = g => vm.runInContext('P', g.window);
5 const state = g => g.read('P');
76 function untilTurn(g) { for (let n = 0; state(g).phase !== 'ring' && n < 400; n++) g.run(.05); expect(state(g).phase).toBe('ring'); }
87
98 test('the HUD peal length follows the peal the tower is ringing', () => {
goalkeeper/page.test.mjs +1 −2
@@ -1,11 +1,10 @@
11 import { test, expect, setDefaultTimeout } from 'bun:test';
2 import vm from 'node:vm';
32 import { boot } from '../playtest.mjs';
43 setDefaultTimeout(60000);
54
65 const KEY = 'pixel-plays-goalkeeper-best';
76 const X = { '-1': 40, 0: 180, 1: 320 };
8 const read = (g, code) => vm.runInContext(code, g.window);
7 const read = (g, code) => g.read(code);
98 // the side the current taker will shoot, once any early-dive switch is settled (the player here never dives early)
109 const shotSide = g => read(g, 'K.pickShot(G.seed, G.n).side');
1110 // wait for the tell window of the current penalty to open
playtest.mjs +17 −3
@@ -42,7 +42,7 @@ function fakeDate(now) {
4242 }
4343
4444 export function boot(id, { seed = 1 } = {}) {
45 const els = {}, errors = [], frames = [], timers = [];
45 const els = {}, errors = [], frames = [], timers = [], watchers = [];
4646 const store = {};
4747 let clock = 1000, image = null;
4848 const get = i => (els[i] ??= new Element(i));
@@ -77,14 +77,23 @@ export function boot(id, { seed = 1 } = {}) {
7777 ctx.removeEventListener = () => {};
7878 ctx.__errors = errors;
7979
80 // The page's scripts run as one strict function body, as a browser runs them in one realm: their top-level
81 // names are function locals, and the hot globals are bound once, because a vm looks up every global name
82 // (a top-level `function` too) through an interceptor, which made a frame two to three times slower.
83 // A script that does not compile is reported and left out; one that throws stops the scripts after it.
8084 const html = readFileSync(new URL(`${id}/index.html`, ROOT), 'utf8');
8185 const scripts = [...html.matchAll(/<script(?:\s+src="([^"]+)")?[^>]*>([\s\S]*?)<\/script>/g)];
86 const parts = [];
8287 for (const [, src, inline] of scripts) {
83 const file = src ?? 'inline';
8488 const code = src ? readFileSync(new URL(`${id}/${src}`, ROOT), 'utf8') : inline;
85 try { new vm.Script(code, { filename: `${id}/${file}` }).runInContext(ctx); }
89 try { new vm.Script(`(function () { 'use strict';\n${code}\n})`, { filename: `${id}/${src ?? 'inline'}` }); parts.push(code); }
8690 catch (e) { errors.push(e); }
8791 }
92 const HOT = ['Math', 'Object', 'Array', 'Number', 'String', 'JSON', 'Date', 'Uint8Array', 'Uint8ClampedArray', 'Uint32Array', 'Float32Array', 'Float64Array', 'Int32Array', 'document', 'performance', 'requestAnimationFrame', 'localStorage'];
93 let evaluate = () => undefined;
94 try {
95 evaluate = new vm.Script(`(function () { 'use strict'; const { ${HOT.join(', ')} } = globalThis;\n${parts.join('\n;\n')}\n;return expr => eval(expr); })()`, { filename: `${id}/page` }).runInContext(ctx);
96 } catch (e) { errors.push(e); }
8897
8998 const api = {
9099 errors, els, canvas, window: ctx,
@@ -112,8 +121,13 @@ export function boot(id, { seed = 1 } = {}) {
112121 for (const t of timers) if (t.fn && t.at <= clock) { const f = t.fn; t.fn = null; try { f(); } catch (e) { errors.push(e); } }
113122 const queue = frames.splice(0);
114123 for (const f of queue) { try { f(clock); } catch (e) { errors.push(e); } }
124 for (const w of watchers) w();
115125 }
116126 },
127 // the value of an expression in the page's own scope (its `let`s too): what a player would read off the picture
128 read(expr) { return evaluate(expr); },
129 // call `fn` after every frame, so a line of text that is on screen for a moment is still seen
130 watch(fn) { watchers.push(fn); },
117131 // pointer and key input, in canvas pixels (360 by 280)
118132 down(x, y) { canvas.fire('pointerdown', { clientX: x, clientY: y }); },
119133 move(x, y, buttons = 1) { canvas.fire('pointermove', { clientX: x, clientY: y, buttons }); },
playtest.test.mjs +17
@@ -1,6 +1,7 @@
11 import { test, expect, setDefaultTimeout } from 'bun:test';
22 import { readdirSync } from 'node:fs';
33 import { boot } from './playtest.mjs';
4 import { ROUNDS, playRound } from './rounds.mjs';
45 setDefaultTimeout(60000);
56
67 // Every game page is booted for real (its scripts, the shell and the engine) and played by a
@@ -23,6 +24,10 @@ function gesture(g, r) {
2324 // bring the untouched twin to the same frame as the played copy
2425 function sync(idle, played) { idle.step(played.frames - idle.frames); expect(idle.frames).toBe(played.frames); }
2526
27 test('every game has a scripted round, and every script has a game', () => {
28 expect(Object.keys(ROUNDS).sort()).toEqual(GAMES);
29 });
30
2631 test('the games folder is not empty', () => { expect(GAMES.length).toBeGreaterThanOrEqual(19); });
2732
2833 for (const id of GAMES) {
@@ -69,4 +74,16 @@ for (const id of GAMES) {
6974 expect(played.errors.map(e => e.message)).toEqual([]);
7075 expect(parted).toBe(true);
7176 });
77
78 test(`${id}: a scripted round reaches its end and the HUD names the outcome`, () => {
79 const { ended, seconds, errors } = playRound(id);
80 expect(errors.map(e => e.message)).toEqual([]);
81 expect(ended).not.toBeNull();
82 expect(ended).toMatch(ROUNDS[id].outcome); // the win or the loss, with its number
outdated

Any digit passes, e.g. a lives counter. Consider an outcome regex per row, so the test checks that the line names the win or loss.

83 expect(seconds).toBeLessThan(100);
84 // an untouched game does not reach that outcome in the same time (it may still end, by failing)
85 const idle = boot(id);
outdated

This reads the twin at frame 0, so it can never fail. Run it for seconds first: const idle = boot(id); idle.run(seconds); expect(idle.text()).not.toMatch(ROUNDS[id].over);

86 idle.run(seconds);
87 expect(idle.text()).not.toMatch(ROUNDS[id].outcome);
88 }, 120_000); // a timed round (wood-split's 60 s) is played twice in the engine's software renderer
7289 }
rounds.mjs added +86
@@ -0,0 +1,86 @@
1 // One scripted round per game: a beat of play (where to tap, drag or hold, and for how long) that is
2 // repeated until the game says the round is over. `over` matches the line the player reads at the end.
3 import { boot } from './playtest.mjs';
4
5 const MID = [180, 140];
6 const tapping = (wait = .3) => g => { g.tap(...MID); g.run(wait); };
7 const idling = seconds => g => g.run(seconds);
8
9 export const ROUNDS = {

No tram-line row. Main has had tram-line since #63, so after the merge the coverage test fails and playRound('tram-line') throws. Rebase and add it.

10 'balote': { over: /you win|rival wins/, outcome: /(you win|rival wins) \d+–\d+/, beat: g => { g.drag([180, 140], [150, 120], .4); g.run(2); g.tap(...MID); } },
11 'beekeeper': { over: /play again/, outcome: /swarmed · \d+ honey/, beat: tapping() },
12 // ring the wrong bell on purpose: three wrong peals end the game
13 'bell-tower': { over: /ring again/, outcome: /three wrong peals · \d+/, beat: g => {
outdated

idling(1): an untouched campfire ends with the same line at 23 s. This script doesn't play the game. Give it a beat that tends the fire.

14 if (g.read('P.phase') === 'ring') { const k = (g.read('P.seq[P.got]') + 1) % 4; g.press(String(k + 1)); }
15 g.run(.5);
16 } },
17 'bread-oven': { over: /bake again/, outcome: /three strikes · \d+/, beat: g => { for (let i = 0; i < 3; i++) { g.press(' '); g.press('ArrowRight'); } g.run(14); for (let i = 0; i < 3; i++) { g.press('Enter'); g.press('ArrowLeft'); } } },
18 // tend the fire: a twig whenever the flames sink toward the lower mark
19 'campfire': { over: /play again/, outcome: /dawn, the fire held · \d+ s/, beat: g => { if (g.read('G.heat') < 55 && g.read('G.fuel.length') < 3) g.press(' '); g.step(5); } },
20 'domino-run': { over: /play again/, outcome: /\d+ points/, beat: g => { g.press(' '); g.press('ArrowRight'); g.press('Enter'); g.run(1); } },
21 'free-throw': { over: /play again/, outcome: /\d+ of 30/, beat: g => { g.hold(...MID, .6); g.run(.45); g.tap(...MID); g.run(1.5); g.tap(...MID); } },
22 // dive the way the taker leans, once the tell shows
23 'goalkeeper': { over: /play again/, outcome: /you win: \d+ saves/, beat: g => {
24 const side = g.read('K.lean(G)');
25 if (side !== null && !g.read('G.dive')) g.press(side < 0 ? 'ArrowLeft' : side > 0 ? 'ArrowRight' : 'ArrowUp');
26 g.step(1);
27 } },
28 'harbour-crane': { over: /play again/, outcome: /\d+ of 10 crates/, beat: tapping(1.3) },
29 'ice-fishing': { over: /play again/, outcome: /three lines snapped · \d+ points/, beat: g => g.hold(...MID, 3) },
30 'kite-hill': { over: /fly again/, outcome: /\d+ · (new best|best)/, beat: g => g.hold(...MID, 1) },
31 'laundry': { over: /hang it again/, outcome: /\d+ dry · \d+ wet/, beat: g => { g.press(' '); g.run(1); } },
outdated

idling(2): an untouched tightrope falls three times and shows "walk again" at 18 s, the same as this run. Give it a beat that leans.

32 'lighthouse': { over: /play again/, outcome: /\d+ boats? saved before the third wreck/, beat: g => { g.tap(...MID); g.run(2); } },
33 'market-scale': { over: /play again/, outcome: /\d+ of 15/, beat: g => { g.press('Enter'); g.press(' '); g.run(.3); } },
34 'mini-ramp': { over: /skate again/, outcome: /highest air [\d.]+ m/, beat: g => { g.hold(...MID, .5); g.run(.4); } },
35 'orchard': { over: /play again/, outcome: /\d+ points/, beat: g => { g.drag([180, 200], [181, 200], .1); g.run(2); } },
36 'paper-route': { over: /play again/, outcome: /\d+ points/, beat: tapping(.5) },
37 'pizza-toss': { over: /play again/, outcome: /\d+ px across/, beat: g => { g.hold(...MID, 1); g.run(1); g.tap(...MID); } },
38 'pottery-wheel': { over: /new round/, outcome: /\d+ px in total/, beat: g => { g.hold(...MID, 2); g.drag([180, 200], [180, 60], 1); g.tap(...MID); } },
39 'row-home': { over: /row again/, outcome: /[\d.]+s · (new best|best)|you won/, beat: tapping(.8) },
40 'sled-run': { over: /ride again/, outcome: /[1-9]\d* m · \d+ clean/, beat: g => { g.hold(...MID, .6); g.run(.6); } },
41 'stari-most': { over: /dive again/, outcome: /total [\d.]+/, beat: g => { g.hold(...MID, .4); g.run(.5); g.hold(...MID, .6); g.run(2); g.tap(...MID); } },
42 'stone-skip': { over: /play again/, outcome: /\d+ bounces/, beat: g => { g.drag([180, 140], [140, 170], .4); g.run(3); g.tap(...MID); } },
43 // brake for the mark by the distance it takes to stop, drive off when the doors close
44 'tram-line': { over: /drive again/, outcome: /end of the line · \+\d+ for time/, beat: g => {
45 const d = g.read('Line.distanceToMark(R)'), v = g.read('R.v');
46 const k = d <= g.read(`Line.brakingDistance(${v})`) + .2 ? 'ArrowDown' : 'ArrowUp';
47 g.keyDown(k); g.step(1); g.keyUp(k);
48 } },
49 'archery': { over: /play again/, outcome: /\d+ points · (new best|best)/, beat: g => { g.drag([180, 100], [120, 160], .4); g.run(3); } },
50 'tie-break': { over: /play again/, outcome: /(you win|rival wins) \d+–\d+/, beat: tapping() },
51 // lean against the lean, and against its speed
52 'tightrope': { over: /walk again/, outcome: /three crossings · \d+/, beat: g => {
53 const dir = g.read('R.phase') === 'walk' ? -Math.sign(g.read('R.lean') + g.read('R.vel') * .5) : 0;
54 if (dir) { const k = dir < 0 ? 'ArrowLeft' : 'ArrowRight'; g.keyDown(k); g.step(1); g.keyUp(k); } else g.step(1);
55 } },
56 // read the log, pick the moment of the hold whose swing lands best, and let go then
57 'wood-split': { over: /play again/, outcome: /time · [1-9]\d* points? · \d+ logs/, beat: (() => {
58 let log = null, at = 0;
59 return g => {
60 if (g.read('G.log') !== log) {
61 log = g.read('G.log');
62 let best = -1;
63 for (let h = .5; h < 2.5; h += .04) {
64 const p = g.read(`WoodSplit.judge(G.log, WoodSplit.aimAt(G.log.dir, ${h}), WoodSplit.strengthAt(${h})).points`);
65 if (p > best) { best = p; at = h; }
66 }
67 }
68 if (!g.read('G.holding')) { if (g.read('G.stuck') <= 0) g.keyDown(' '); }
69 else if (g.read('G.hold') >= at) g.keyUp(' ');
70 g.step(1);
71 };
72 })() },
73 'window-washer': { over: /play again/, outcome: /[1-9]\d* of 500/, beat: g => g.drag([60, 100], [300, 100], .6) },
74 };
75
76 const LIMIT = 150; // seconds of play, a game that has not ended by then is stuck
77
78 // play one round of `id`; returns the line that ended it (null if none did) and the seconds it took
79 export function playRound(id, seed = 1) {
80 const { over, beat } = ROUNDS[id];
81 const g = boot(id, { seed });
82 let ended = null;
83 g.watch(() => { if (!ended) { const t = g.text(); if (over.test(t)) ended = t; } });
84 while (!ended && g.frames < LIMIT * 25) beat(g);
85 return { ended, seconds: g.frames / 25, errors: g.errors };
86 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs