towerdef/e2e/scenarios/10-gallery.js
Claude 28502984ec Co-op robustness, audio/a11y, new towers and enemies, Uplink rebalance
Co-op (QA'd with two to three real browsers, TCP-proxy chaos scenarios):
- partner's tower changes are never dropped after a render stall or snapshot burst
- half-open connections show "reconnecting" in ~6 s instead of 45-65 s
- upgrade and next-wave are idempotent (stale commands refused), restart message,
  promoted host gets Play again, failed joins never kill a live game, listener leaks

Audio / keyboard / a11y:
- one Audio element per track, fade/stinger supersede tokens, play() retry on the
  next gesture, 5 s fallback to the synth, mute works everywhere, dialogs with
  role/aria-modal/focus handling, accessible names for sound/speed/pause

New content:
- enemies: Daemon (healer), Proxy (regenerating shield), Botnet (flyer swarm);
  waves weave them in from wave 9 (waves 1-8 unchanged)
- towers: Sandbox (stun pulse), Load Balancer (fire-rate aura); hotkeys 1-9
- glyphs/shapes, stun/heal effects, gallery e2e that pixel-checks every kind

Orbital Uplink rebalanced after playtesting (was affordable by wave ~6 and buyable
in bulk from boss rewards): 1500 credits, upgrades 1200/2000/3200, and every Uplink
already owned makes the next one 25% dearer to buy AND to upgrade (each tower
remembers its multiplier, carried in the tower list as a 9th field). Shared
TD.priceFor/upgradePrice so the UI shows exactly what the sim charges.

Also: tablet/foldable viewports in the layout matrix (tolerant colour check),
docs (README tower/enemy tables, PROTOCOL shield/stun/pm encodings, NEXT roadmap).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
2026-10-10 21:18:43 +00:00

434 lines
34 KiB
JavaScript

// Gallery: every tower at every level and every enemy kind, drawn by the real renderer, checked by pixels and saved as PNGs
// in e2e/out/ so a person can LOOK at them: gallery-towers-enemies, gallery-links-14px, gallery-scene-14px-{a,b-stun,c-heal,d-swarm},
// gallery-legend, gallery-game-{desktop,phone}[-balancer].
//
// "Draws something non-empty" is not enough (a tower the renderer does not know is still a plate with a dot, an enemy it does not
// know is still a filled circle), so every tile is compared with that fallback and must differ clearly from it. The new kinds must
// also have a silhouette of their own. Then the renderer is driven with real sim state at 14 px cells (the smallest the board
// gets on a phone): stun and heal pulses, the Load Balancer links, the shield bubble, the stun effect in co-op (where the wire has only
// a 0/1 "slow" flag), and no effect may linger.
module.exports = async function ({ browser, url: URL, out: OUT }) {
const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const errors = [];
const watch = (page, tag) => {
page.on('pageerror', (e) => errors.push(`[${tag}] pageerror: ${e.message}`));
page.on('console', (m) => { if ((m.type() === 'error' || m.type() === 'warning') && !/willReadFrequently/.test(m.text())) errors.push(`[${tag}] console.${m.type()}: ${m.text()}`); });
};
// a blank same-origin page that loads only the shared rules and the renderer
const blank = async (page) => {
await page.route('**/gallery-blank.html', (r) => r.fulfill({ contentType: 'text/html', body: '<!doctype html><meta charset="utf-8"><title>gallery</title><body style="margin:0;background:#050810;color:#9db4d8;font:12px system-ui,sans-serif"><div id="root"></div></body>' }));
await page.goto(URL + 'gallery-blank.html');
await page.addScriptTag({ url: URL + 'js/sim.js' });
await page.addScriptTag({ url: URL + 'js/render.js' });
};
// ------------------------------------------------------------------ 1. the sheet: towers x levels, enemies x states
{
const ctx = await browser.newContext({ viewport: { width: 1180, height: 900 }, deviceScaleFactor: 2 });
const page = await ctx.newPage(); watch(page, 'sheet');
await blank(page);
const res = await page.evaluate(() => {
const root = document.getElementById('root');
const C = NW.CELL, BOARD = '#09101f';
const mk = (w, h, css) => { const c = document.createElement('canvas'); c.width = w; c.height = h; if (css) { c.style.width = css + 'px'; c.style.height = css + 'px'; } return c; };
const data = (cv) => cv.getContext('2d').getImageData(0, 0, cv.width, cv.height).data;
const diffMask = (a, b, thr) => { const m = new Uint8Array(a.length / 4); for (let i = 0; i < m.length; i++) { const j = i * 4; if (Math.abs(a[j] - b[j]) + Math.abs(a[j + 1] - b[j + 1]) + Math.abs(a[j + 2] - b[j + 2]) + Math.abs(a[j + 3] - b[j + 3]) > (thr || 48)) m[i] = 1; } return m; };
const count = (m) => { let n = 0; for (let i = 0; i < m.length; i++) n += m[i]; return n; };
const bg = (ctx2, w, h) => { ctx2.fillStyle = BOARD; ctx2.fillRect(0, 0, w, h); };
// normalised silhouette: crop to the ink's bounding box, resample to 24x24 (shape only, not size)
const sil = (alpha, w, h) => {
let x0 = w, y0 = h, x1 = -1, y1 = -1;
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (alpha[y * w + x]) { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
const out = new Uint8Array(24 * 24); if (x1 < 0) return out;
const side = Math.max(x1 - x0 + 1, y1 - y0 + 1), cx = (x0 + x1) / 2, cy = (y0 + y1) / 2;
for (let j = 0; j < 24; j++) for (let i = 0; i < 24; i++) {
const sx = Math.round(cx + ((i + 0.5) / 24 - 0.5) * side), sy = Math.round(cy + ((j + 0.5) / 24 - 0.5) * side);
if (sx >= 0 && sy >= 0 && sx < w && sy < h) out[j * 24 + i] = alpha[sy * w + sx];
}
return out;
};
const iou = (a, b) => { let i = 0, u = 0; for (let k = 0; k < a.length; k++) { if (a[k] && b[k]) i++; if (a[k] || b[k]) u++; } return u ? i / u : 1; };
const label = (txt, css) => { const d = document.createElement('div'); d.textContent = txt; d.style.cssText = 'font:12px ui-monospace,monospace;color:#9db4d8;' + (css || ''); return d; };
const row = () => { const d = document.createElement('div'); d.style.cssText = 'display:flex;align-items:center;gap:8px;padding:3px 10px'; root.appendChild(d); return d; };
// ---- towers: S=64 tile per level; baseline = the same tile drawn for a type the renderer has no glyph for (plate + pips only)
const towers = [], masks = {};
root.appendChild(label('TOWERS: level 1..n at 64 px | palette icon 34 px | on the board at 14 px', 'padding:8px 10px'));
for (const type of TD.TOWER_ORDER) {
const def = TD.TOWERS[type], r = row();
r.appendChild(label(def.key + ' ' + def.name, 'width:120px'));
TD.TOWERS.__plate = Object.assign({}, def);
for (let lv = 1; lv <= def.levels.length; lv++) {
const cv = mk(64, 64), c2 = cv.getContext('2d'); bg(c2, 64, 64);
NW.drawGlyph(c2, type, lv, 32, 32, 64, -0.6, 0.3, 1);
const base = mk(64, 64), b2 = base.getContext('2d'); bg(b2, 64, 64);
NW.drawGlyph(b2, type === 'wall' ? '__none' : '__plate', lv, 32, 32, 64, -0.6, 0.3, 1);
const dm = diffMask(data(cv), data(base));
towers.push({ type, level: lv, diff: count(dm) });
if (lv === 1) masks[type] = dm;
r.appendChild(cv);
}
delete TD.TOWERS.__plate;
const ic = mk(34, 34, 34); ic.style.background = '#0a1124'; r.appendChild(ic); NW.drawIcon(ic, type, 1);
const ic3 = mk(34, 34, 34); ic3.style.background = '#0a1124'; r.appendChild(ic3); NW.drawIcon(ic3, type, def.levels.length);
const small = mk(42, 42, 14); small.style.background = BOARD; r.appendChild(small); // 14 px cell at 3x density
const s2 = small.getContext('2d'); s2.setTransform(3, 0, 0, 3, 0, 0); NW.drawGlyph(s2, type, 1, 7, 7, 14, -0.6, 0.3, 1);
const small3 = mk(42, 42, 14); small3.style.background = BOARD; r.appendChild(small3);
const s3 = small3.getContext('2d'); s3.setTransform(3, 0, 0, 3, 0, 0); NW.drawGlyph(s3, type, def.levels.length, 7, 7, 14, -0.6, 0.3, 1);
}
// pairwise: the ink of two different towers must not be the same shape (normalised, so it is not about colour or size)
let towerIou = 0, towerPair = '';
const tl = TD.TOWER_ORDER.filter((t) => t !== 'wall');
const tsil = {}; for (const t of tl) tsil[t] = sil(masks[t], 64, 64);
for (let i = 0; i < tl.length; i++) for (let j = i + 1; j < tl.length; j++) { const v = iou(tsil[tl[i]], tsil[tl[j]]); if (v > towerIou) { towerIou = v; towerPair = tl[i] + '/' + tl[j]; } }
// ---- enemies
const SC = 2.5, W = 200;
const mon = (kind, o) => { // o: hp (fraction of max), sh (shield fraction or undefined), slow, stun, wire
o = o || {};
const def = TD.ENEMIES[kind], hpMax = def.hp, shMax = def.shield || 0;
const hp = Math.round(hpMax * (o.hp === undefined ? 1 : o.hp)), sh = Math.round(shMax * (o.sh === undefined ? 1 : o.sh));
const m = { id: 7, kind, x: 0, y: 0, air: !!def.air };
if (o.wire) { m.hp = hp + sh; m.maxhp = hpMax + shMax; m.slow = o.slow || o.stun ? 1 : 0; }
else { m.hp = hp; m.maxhp = hpMax; m.shield = sh; m.maxShield = shMax; m.slow = o.slow ? 0.5 : 0; m.stunT = o.stun ? 1 : 0; }
return m;
};
const tile = (kind, o, flash) => {
const cv = mk(W, W), c2 = cv.getContext('2d');
c2.setTransform(SC, 0, 0, SC, 0, 0);
const m = mon(kind, o); m.x = W / 2 / SC / C; m.y = (W / 2 + 10) / SC / C;
NW.drawMonster(c2, m, 0.5, 0.4, flash || 0, 0, !!(o && o.stun));
return cv;
};
const circle = (kind) => {
const def = TD.ENEMIES[kind], cv = mk(W, W), c2 = cv.getContext('2d');
c2.fillStyle = def.color; c2.beginPath(); c2.arc(W / 2, W / 2 + 10, def.r * C * SC, 0, Math.PI * 2); c2.fill();
return cv;
};
const inkMask = (cv) => { const d = data(cv), m = new Uint8Array(d.length / 4); for (let i = 0; i < m.length; i++) m[i] = d[i * 4 + 3] > 120 ? 1 : 0; return m; };
const states = [['full', {}], ['hurt', { hp: 0.5 }], ['slowed', { slow: 1 }], ['stunned', { stun: 1 }], ['flash', {}, 0.1]];
const enemies = [], esil = {};
root.appendChild(label('ENEMIES: full | hurt | slowed | stunned | hit flash (2.5x) | shield 100 / 50 / 0 for the Proxy | 14 px board size (3x density)', 'padding:8px 10px'));
for (const kind of TD.ENEMY_ORDER) {
const def = TD.ENEMIES[kind], r = row();
r.appendChild(label(def.name + (def.air ? ' (air)' : ''), 'width:90px'));
const tiles = states.map(([nm, o, fl]) => { const cv = tile(kind, o, fl); cv.style.cssText = 'width:100px;height:100px;background:' + BOARD; r.appendChild(cv); return cv; });
if (def.shield) for (const sh of [1, 0.5, 0]) { const cv = tile(kind, { sh }); cv.style.cssText = 'width:100px;height:100px;background:' + BOARD; r.appendChild(cv); }
const small = mk(42, 42, 14); small.style.background = BOARD; r.appendChild(small);
const s2 = small.getContext('2d'); s2.setTransform(3 * 0.35, 0, 0, 3 * 0.35, 0, 0); { const m = mon(kind, { hp: 0.6 }); m.x = 7 / 0.35 / C; m.y = 7 / 0.35 / C; NW.drawMonster(s2, m, 0.5, 0.4, 0, 0, false); }
const m0 = inkMask(tiles[0]), base = inkMask(circle(kind));
let x = 0, u = 0; for (let i = 0; i < m0.length; i++) { if (m0[i] !== base[i]) x++; if (m0[i] || base[i]) u++; }
const dTile = diffMask(data(tiles[0]), data(tiles[3]), 60);
esil[kind] = sil(m0, W, W);
enemies.push({ kind, ink: count(m0), vsCircle: x / u, stunDiff: count(dTile), slowDiff: count(diffMask(data(tiles[0]), data(tiles[2]), 60)), hurtDiff: count(diffMask(data(tiles[0]), data(tiles[1]), 60)) });
}
const newKinds = ['daemon', 'proxy', 'botnet'], silPairs = [];
for (const k of newKinds) for (const o of TD.ENEMY_ORDER) if (o !== k) silPairs.push([k, o, iou(esil[k], esil[o])]);
// ---- the shield: the bubble must thin as it drops, and solo (hp and shield apart) and co-op (hp + shield out of both maxima) must look the same
const bub = [1, 0.5, 0].map((sh) => count(inkMask(tile('proxy', { sh }))) + 0);
const bubAlpha = [1, 0.5, 0].map((sh) => { const d = data(tile('proxy', { sh })); let s = 0; for (let i = 3; i < d.length; i += 4) s += d[i]; return s; });
// (hit points hurt while the shield is up cannot be told apart from the total alone: that case is the renderer's job, see section 2)
let wireDiff = 0;
for (const [sh, hp] of [[1, 1], [0.5, 1], [0, 1], [0, 0.4], [0, 0.1]]) wireDiff += count(diffMask(data(tile('proxy', { sh, hp })), data(tile('proxy', { sh, hp, wire: true })), 8));
// a health bar is drawn when only the shield is hurt (proxy at full hp, half shield) and not when all is full
const barFull = count(diffMask(data(tile('proxy', {})), data(tile('proxy', { sh: 0.5 })), 30));
return { towers, towerIou, towerPair, enemies, silPairs, bubAlpha, bub, wireDiff, barFull, order: TD.ENEMY_ORDER.slice() };
});
await page.locator('#root').screenshot({ path: OUT + 'gallery-towers-enemies.png' });
for (const t of res.towers) assert(t.diff > (t.type === 'wall' ? 500 : 120), `tower ${t.type} level ${t.level} draws its own glyph (${t.diff} px differ from the bare plate)`);
assert(res.towerIou < 0.8, `no two towers share a shape (most similar: ${res.towerPair}, IoU ${res.towerIou.toFixed(2)})`);
for (const e of res.enemies) {
assert(e.ink > 150, `enemy ${e.kind} draws something (${e.ink} px)`);
assert(e.stunDiff > 60, `enemy ${e.kind} looks different when stunned (${e.stunDiff} px)`);
assert(e.slowDiff > 20, `enemy ${e.kind} looks different when slowed (${e.slowDiff} px)`);
if (e.kind === 'botnet') assert(e.hurtDiff < 10, `enemy ${e.kind} (a swarm) draws no health bar (${e.hurtDiff} px)`);
else assert(e.hurtDiff > 10, `enemy ${e.kind} shows a health bar when hurt (${e.hurtDiff} px)`);
if (['daemon', 'proxy', 'botnet'].includes(e.kind)) assert(e.vsCircle > 0.3, `enemy ${e.kind} is not the fallback filled circle (XOR ${e.vsCircle.toFixed(2)})`);
}
for (const [k, o, v] of res.silPairs) assert(v < 0.8, `${k} and ${o} have different silhouettes (IoU ${v.toFixed(2)})`);
assert(res.bubAlpha[0] > res.bubAlpha[1] && res.bubAlpha[1] > res.bubAlpha[2], 'the proxy bubble thins as the shield drops: ' + res.bubAlpha.join(' > '));
assert(res.wireDiff < 60, `solo and co-op objects draw the same proxy (${res.wireDiff} px differ)`);
assert(res.barFull > 10, 'a proxy with a damaged shield shows a health bar even at full hit points');
await ctx.close();
}
// ------------------------------------------------------------------ 2. the renderer with real sim state at 14 px cells, phone density
{
const ctx = await browser.newContext({ viewport: { width: 380, height: 260 }, deviceScaleFactor: 3 });
const page = await ctx.newPage(); watch(page, 'scene');
await blank(page);
const res = await page.evaluate(async () => {
const cv = document.createElement('canvas'); cv.style.cssText = 'display:block;width:380px;height:260px';
document.body.appendChild(cv);
const R = new NW.Renderer(cv); R.fx = 1;
const mkSim = () => { const s = new TD.Sim({ map: 'open', gold: 1e7 }); return s; };
const sim = mkSim(); R.setBoard(sim.board); R.resize(380, 260, 3);
const cell = R.cellSizePx();
const px = () => cv.getContext('2d').getImageData(0, 0, cv.width, cv.height).data;
// pixels that differ by more than thr, inside box [x0,y0,x1,y1] (device px; default: the middle of the board, clear of the animated gateway and server)
// and outside the skip boxes
const MID = () => { const a = R.cellToScreen(4, 0), b = R.cellToScreen(22, 0); return [a.x * 3, 0, b.x * 3, cv.height]; };
const diff = (a, b, thr, box, skip) => {
let n = 0; const w = cv.width; box = box || MID();
for (let i = 0; i < a.length; i += 4) {
{ const p = i / 4, x = p % w, y = (p / w) | 0; if (x < box[0] || x > box[2] || y < box[1] || y > box[3]) continue; if (skip && skip.some((k) => x >= k[0] && x <= k[2] && y >= k[1] && y <= k[3])) continue; }
if (Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2]) > (thr || 40)) n++;
}
return n;
};
const view = (s) => ({ towers: s.towers, monsters: s.monsters, bullets: s.bullets, cursors: [], lives: 20, maxLives: 20 });
const ui = (o) => Object.assign({ hover: null, selType: null, selTower: 0, preview: null, valid: true, coop: false, names: {} }, o || {});
let now = 1000;
const frame = (v, u, ms) => { now += ms === undefined ? 100 : ms; R.frame(now, v, u || ui()); };
const out = { cell };
// --- pulses: a Sandbox pulse and a Daemon heal must show, and be gone again after their life
{
const s = mkSim(); R.setBoard(s.board); R.resize(380, 260, 3);
s.place('sandbox', 10, 7); const v = view(s);
s.board.routes = []; // the dashed route lines animate with time: leave them out so only the effect under test can change pixels
const tp = R.cellToScreen(10, 7), tile = [(tp.x - cell / 2 - 2) * 3, (tp.y - cell / 2 - 2) * 3, (tp.x + cell / 2 + 2) * 3, (tp.y + cell / 2 + 2) * 3];
frame(v); frame(v); const a = px();
R.addEvents([{ e: 'stun', x: 10.5, y: 7.5, r: 3.4, n: 2 }]); frame(v, ui(), 120); const b = px();
frame(v, ui(), 100); frame(v, ui(), 100); frame(v, ui(), 100); frame(v, ui(), 100); frame(v, ui(), 100); frame(v, ui(), 100); frame(v, ui(), 100); frame(v, ui(), 100); frame(v, ui(), 100); frame(v, ui(), 100);
const c = px();
out.stunRing = diff(a, b, 40, null, [tile]); out.stunGone = diff(a, c, 40, null, [tile]);
R.addEvents([{ e: 'heal', x: 15.5, y: 7.5, r: 2.2 }]); frame(v, ui(), 120); const d = px();
for (let i = 0; i < 14; i++) frame(v, ui(), 100); const e = px();
out.healRing = diff(c, d, 40, null, [tile]); out.healGone = diff(c, e, 40, null, [tile]);
// a daemon wave flooding the ring pool must not starve the other effects: 60 heal events, then a leak ring must still start
R.addEvents(Array.from({ length: 60 }, (_, i) => ({ e: 'heal', x: 3 + i % 20, y: 5 + (i % 4), r: 2.2 })));
frame(v, ui(), 50);
const before = R.rings.length;
R.addEvents([{ e: 'leak', x: 25, y: 8, n: 1 }, { e: 'boom', x: 12, y: 9, r: 1.5 }]);
out.ringsKept = R.rings.length - before;
for (let i = 0; i < 20; i++) frame(v, ui(), 100);
}
// --- co-op proxy: the wire sends hp + shield as one number. Hurt to 20 hp, then the shield regrows to 120: the total (140) alone would read as
// "full hp, 50 shield"; the renderer follows the split over time and must draw what solo draws for hp 20 + shield 120.
{
const s = mkSim(); R.setBoard(s.board); R.resize(380, 260, 3);
const wire = (id, hp) => ({ id, kind: 'proxy', x: 12.5, y: 7.5, hp, maxhp: 210, slow: 0, air: false });
s.board.routes = [];
const w = wire(1, 210), vw = { towers: [], monsters: [w], bullets: [], cursors: [], lives: 20, maxLives: 20 };
frame(vw);
for (const hp of [150, 90, 40, 20]) { w.hp = hp; frame(vw, ui(), 100); } // shield soaks 60, then hp 90 -> 20
for (let i = 0; i < 70; i++) { frame(vw, ui(), 100); if (i >= 33) w.hp = Math.min(140, 20 + 4 * (i - 32)); } // 3 s later the shield regrows
frame(vw, ui(), 100);
const solo = { id: 2, kind: 'proxy', x: 12.5, y: 7.5, hp: 20, maxhp: 90, shield: 120, maxShield: 120, slow: 0, stunT: 0, air: false };
const naive = wire(3, 140);
const p = R.cellToScreen(12, 7), box = [(p.x - 30) * 3, (p.y - 40) * 3, (p.x + 30) * 3, (p.y + 30) * 3];
const draw = (mons) => { R.frame(now, { towers: [], monsters: mons, bullets: [], cursors: [], lives: 20, maxLives: 20 }, ui()); return px(); };
const A = draw([w]), B = draw([solo]);
R.trk.delete(3); const Cc = draw([naive]);
out.proxyTracked = diff(A, B, 40, box); out.proxyNaive = diff(Cc, B, 40, box);
}
// --- co-op stun: the wire has only a 0/1 "slowed or stunned" flag. A flagged packet that stands still is frozen; one that moves is just slowed
{
const s = mkSim(); R.setBoard(s.board); R.resize(380, 260, 3);
s.board.routes = [];
const m = { id: 1, kind: 'ping', x: 12.5, y: 7.5, hp: 30, maxhp: 30, slow: 1, air: false };
const v = { towers: [], monsters: [m], bullets: [], cursors: [], lives: 20, maxLives: 20 };
const p = R.cellToScreen(12, 7), box = [(p.x - 30) * 3, (p.y - 30) * 3, (p.x + 30) * 3, (p.y + 30) * 3];
const ice = () => { // near-white pixels around the packet: the ice shell (a ping is red, its slow ring cyan)
const d = px(), w = cv.width; let n = 0;
for (let y = box[1] | 0; y < box[3]; y++) for (let x = box[0] | 0; x < box[2]; x++) { const i = (y * w + x) * 4; if (d[i] > 225 && d[i + 1] > 240 && d[i + 2] > 245) n++; }
return n;
};
for (let i = 0; i < 8; i++) { m.x += 0.03; frame(v, ui(), 100); }
out.iceMoving = ice();
for (let i = 0; i < 6; i++) frame(v, ui(), 100);
out.iceStill = ice();
for (let i = 0; i < 4; i++) frame(v, ui(), 100);
out.iceStable = ice();
m.slow = 0; frame(v, ui(), 100); out.iceUnflagged = ice();
m.slow = 1; for (let i = 0; i < 6; i++) { m.x += 0.03; frame(v, ui(), 100); }
out.iceResumed = ice();
const view2 = { towers: [], monsters: [{ id: 9, kind: 'ping', x: 12.5, y: 7.5, hp: 30, maxhp: 30, slow: 1, air: false }], bullets: [], cursors: [], lives: 20, maxLives: 20, paused: true };
for (let i = 0; i < 8; i++) frame(view2, ui(), 100);
out.icePausedFlag = ice();
}
// --- Load Balancer links: only while it is hovered or selected, to the attack towers in its range; the dash pattern is reset
{
const s = mkSim(); R.setBoard(s.board); R.resize(380, 260, 3);
const bal = s.place('balancer', 10, 9), f1 = s.place('filter', 12, 9), f2 = s.place('ids', 10, 11), far = s.place('mortar', 20, 3), sb = s.place('sandbox', 8, 9);
const v = view(s); s.board.routes = [];
frame(v, ui({ hover: { x: 3, y: 3 } })); frame(v, ui({ hover: { x: 3, y: 3 } }), 16);
const a = px();
frame(v, ui({ hover: { x: 10, y: 9 } }), 16); const b = px();
const tiles = [[10, 9], [12, 9], [10, 11], [8, 9], [3, 3]].map(([x, y]) => { const p = R.cellToScreen(x, y), h = cell / 2 + 3; return [(p.x - h) * 3, (p.y - h) * 3, (p.x + h) * 3, (p.y + h) * 3]; });
const inTile = (i) => { const w = cv.width, x = (i / 4) % w, y = Math.floor(i / 4 / w); return tiles.some((t) => x >= t[0] && x <= t[2] && y >= t[1] && y <= t[3]); };
let n = 0; for (let i = 0; i < a.length; i += 4) if (!inTile(i) && Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2]) > 40) n++;
out.linkPx = n;
out.dashAfter = R.ctx.getLineDash().length;
frame(v, ui({ selTower: bal.id }), 16); const c = px();
frame(v, ui({ selTower: far.id }), 16); const d = px();
out.selLinks = diff(c, d, 40) ;
// not drawn without hover or selection
frame(v, ui(), 16); const e = px();
out.noLinks = diff(a, e, 40);
frame(v, ui({ hover: { x: 10, y: 9 } }), 16);
cv.dataset.links = '1';
}
return out;
});
await page.screenshot({ path: OUT + 'gallery-links-14px.png' });
assert(res.cell > 13 && res.cell < 15, `the scene runs at ~14 px cells (${res.cell.toFixed(1)})`);
assert(res.stunRing > 300, `a stun event draws a visible pulse (${res.stunRing} px)`);
assert(res.stunGone < 40, `the stun pulse is gone again after its life (${res.stunGone} px left)`);
assert(res.healRing > 300, `a heal event draws a visible pulse (${res.healRing} px)`);
assert(res.healGone < 40, `the heal pulse is gone again after its life (${res.healGone} px left)`);
assert(res.proxyTracked < 40, `a co-op proxy hurt to 20 hp with a regrown shield draws like solo (${res.proxyTracked} px differ)`);
assert(res.proxyNaive > 40, `... and differs from reading the total naively (${res.proxyNaive} px): the split is followed over time`);
assert(res.iceMoving < 5, `a slowed packet that keeps moving is not drawn frozen (${res.iceMoving} ice px)`);
assert(res.iceStill > 30, `a flagged packet that stands still is drawn frozen in co-op (${res.iceStill} ice px)`);
assert(res.iceStable > 30 && res.iceUnflagged < 5, `... it stays frozen (${res.iceStable}) and thaws when the flag clears (${res.iceUnflagged})`);
assert(res.iceResumed < 5, `... and is not frozen once it moves again (${res.iceResumed} ice px)`);
assert(res.icePausedFlag < 5, `a paused game does not turn every slowed packet to ice (${res.icePausedFlag} ice px)`);
assert(res.ringsKept >= 2, `heal pulses do not starve the leak and mortar rings (${res.ringsKept} of 2 kept)`);
assert(res.linkPx > 60, `a hovered Load Balancer draws links to the towers it boosts (${res.linkPx} px outside the tiles)`);
assert(res.dashAfter === 0, 'the dash pattern is reset after the frame');
assert(res.selLinks > 60, `selecting the Load Balancer shows its links (${res.selLinks} px differ from selecting a far tower)`);
assert(res.noLinks < 20, `no links without hover or selection (${res.noLinks} px)`);
await ctx.close();
}
// ------------------------------------------------------------------ 3. a busy scene at 14 px cells: every tower, every enemy, live sim
{
const ctx = await browser.newContext({ viewport: { width: 380, height: 260 }, deviceScaleFactor: 3 });
const page = await ctx.newPage(); watch(page, 'live');
await blank(page);
const res = await page.evaluate(async () => {
const cv = document.createElement('canvas'); cv.style.cssText = 'display:block;width:380px;height:260px';
document.body.appendChild(cv);
const R = new NW.Renderer(cv); R.fx = 1;
const s = new TD.Sim({ map: 'open', gold: 1e7 }); R.setBoard(s.board); R.resize(380, 260, 3);
const place = (type, x, y, lv) => { const r = s.place(type, x, y); for (let i = 1; i < lv; i++) s.upgrade(r.id); return r; };
place('sandbox', 8, 5, 3); place('balancer', 10, 5, 3); place('filter', 12, 5, 3); place('ids', 14, 5, 1);
place('throttle', 8, 10, 3); place('mortar', 10, 10, 2); place('arc', 12, 10, 2); place('uplink', 14, 10, 1);
for (const y of [6, 7, 8, 9]) place('wall', 17, y, 1);
// a wave 20 mix: daemons escorting trojans, proxies, a botnet swarm, a boss
s.wave = 29;
const q = (t, k) => s.spawnQ.push({ t: s.time + t, k, wave: 30 });
for (let i = 0; i < 4; i++) q(i * 0.8, 'trojan');
for (let i = 0; i < 3; i++) q(1.5 + i * 0.9, 'daemon');
for (let i = 0; i < 5; i++) q(0.5 + i * 0.7, 'proxy');
for (let i = 0; i < 30; i++) q(1 + i * 0.12, 'botnet');
for (let i = 0; i < 4; i++) q(2 + i * 0.5, 'ping');
q(4, 'ghost'); q(5, 'worm'); q(5.3, 'spam'); q(6, 'rootkit');
s.spawnQ.sort((a, b) => a.t - b.t);
const view = { towers: s.towers, monsters: s.monsters, bullets: s.bullets, cursors: [], lives: 20, maxLives: 20 };
const seen = new Set(), evs = new Set(); let now = 1000, peak = 0, stunned = 0, frames = 0, drawMs = 0, ticks = 0;
// advance the sim; draw every 4th tick; optionally stop right after the first event of the given kind (plus a few frames of its effect)
window.__sim = s; window.__R = R;
window.__adv = (maxTicks, stopOn) => {
let after = -1;
for (let n = 0; n < maxTicks; n++) {
s.tick(TD.STEP); ticks++;
if (ticks % 4 === 0) {
const ev = s.drainEvents(); for (const e of ev) { evs.add(e.e); if (stopOn && e.e === stopOn && after < 0) after = 3; }
R.addEvents(ev);
now += 66; const a = performance.now(); R.frame(now, view, { hover: null, selType: null, selTower: 0, preview: null, valid: true, coop: false, names: {} }); drawMs += performance.now() - a; frames++;
for (const m of s.monsters) { seen.add(m.kind); if (m.stunT > 0) stunned++; }
peak = Math.max(peak, s.monsters.length);
if (after === 0) break;
if (after > 0) after--;
}
}
return { seen: [...seen], evs: [...evs], peak, stunned, frames, drawMs: drawMs / frames, t: s.time };
};
return window.__adv(60 * 5);
});
await page.screenshot({ path: OUT + 'gallery-scene-14px-a.png' });
await page.evaluate(() => window.__adv(60 * 6, 'stun'));
await page.screenshot({ path: OUT + 'gallery-scene-14px-b-stun.png' });
await page.evaluate(() => window.__adv(60 * 6, 'heal'));
await page.screenshot({ path: OUT + 'gallery-scene-14px-c-heal.png' });
Object.assign(res, await page.evaluate(() => window.__adv(60 * 8)));
// a 120-drone swarm on the board at once: every frame must still be cheap
res.swarm = await page.evaluate(() => {
const s = window.__sim, R = window.__R;
for (let i = 0; i < 120; i++) s.spawnMonster({ k: 'botnet', wave: 30 });
s.monsters.forEach((m, i) => { m.x = 3 + (i * 7) % 20 + (i % 3) * 0.2; m.y = 2 + (i * 5) % 12; });
const t0 = performance.now(); let now = 1e6;
for (let i = 0; i < 30; i++) { now += 16; R.frame(now, { towers: s.towers, monsters: s.monsters, bullets: s.bullets, cursors: [], lives: 20, maxLives: 20 }, { hover: null, selType: null, selTower: 0, preview: null, valid: true, coop: false, names: {} }); }
return { n: s.monsters.filter((m) => m.kind === 'botnet').length, ms: (performance.now() - t0) / 30 };
});
await page.screenshot({ path: OUT + 'gallery-scene-14px-d-swarm.png' });
assert(['daemon', 'proxy', 'botnet', 'trojan', 'rootkit'].every((k) => res.seen.includes(k)), 'the live scene had daemons, proxies, botnets, trojans and a rootkit: ' + res.seen.join(','));
assert(res.evs.includes('stun') && res.evs.includes('heal'), 'the sim emitted stun and heal events: ' + res.evs.join(','));
assert(res.peak >= 20, 'a crowd of ' + res.peak + ' enemies drew without trouble');
assert(res.swarm.n >= 100, 'a swarm of ' + res.swarm.n + ' botnet drones drew in ' + res.swarm.ms.toFixed(1) + ' ms per frame (headless software canvas, 380x260 at 3x)');
assert(res.stunned > 0, 'enemies were stunned in the scene');
console.log(` avg frame ${res.drawMs.toFixed(2)} ms over ${res.frames} frames (headless, software canvas)`);
await ctx.close();
}
// ------------------------------------------------------------------ 4. the real game page: all 9 towers, all 9 kinds, then the Load Balancer selected
for (const [name, opts, touch] of [
['desktop', { viewport: { width: 1280, height: 800 } }, false],
['phone', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 3, isMobile: true, hasTouch: true }, true],
]) {
const ctx = await browser.newContext(opts);
const page = await ctx.newPage(); watch(page, 'game-' + name);
await page.goto(URL); await sleep(300);
await page.click('#btnSolo'); await sleep(200); await page.click('#btnHelpClose'); await sleep(200);
await page.evaluate(() => {
const s = NW.app.ctrl.sim; s.gold = 1e7;
const put = (type, x, y, lv) => { const r = s.place(type, x, y); for (let i = 1; i < lv; i++) s.upgrade(r.id); };
put('sandbox', 8, 5, 3); put('balancer', 10, 5, 3); put('filter', 12, 5, 2); put('ids', 14, 5, 2);
put('throttle', 8, 10, 2); put('mortar', 10, 10, 2); put('arc', 12, 10, 2); put('uplink', 14, 10, 2); put('wall', 17, 7, 1); put('wall', 17, 8, 1);
s.wave = 29;
const q = (t, k) => s.spawnQ.push({ t: s.time + t, k, wave: 30 });
for (let i = 0; i < 2; i++) { q(i * 0.8, 'trojan'); q(0.6 + i, 'daemon'); q(0.3 + i * 0.7, 'proxy'); q(i, 'ping'); }
for (let i = 0; i < 14; i++) q(0.5 + i * 0.12, 'botnet');
q(1.5, 'ghost'); q(2, 'worm'); q(2.2, 'spam'); q(2.4, 'rootkit');
s.spawnQ.sort((a, b) => a.t - b.t);
});
await sleep(3500);
await page.screenshot({ path: OUT + 'gallery-game-' + name + '.png' });
if (!touch) {
// the next-wave legend: every kind of wave 30 has its own shape (clip-path or round), not just a colour
const readLegend = () => page.evaluate(() => [...document.querySelectorAll('#nextwave .e i')].map((i) => ({ k: i.className.replace('sh-', ''), clip: getComputedStyle(i).clipPath, round: getComputedStyle(i).borderRadius })));
await page.evaluate(() => { NW.app.ctrl.sim.wave = 4; }); await sleep(400);
const legend = await readLegend(); // wave 5: spoofs
await page.evaluate(() => { NW.app.ctrl.sim.wave = 29; }); await sleep(400);
for (const l of await readLegend()) if (!legend.some((x) => x.k === l.k)) legend.push(l); // wave 30: trojan, worm, daemon, proxy, botnet, rootkit
const kinds = legend.map((l) => l.k);
assert(['daemon', 'proxy', 'botnet', 'ghost'].every((k) => kinds.includes(k)), 'the legends of waves 5 and 30 list spoofs, daemons, proxies and botnets: ' + kinds.join(','));
const shapes = legend.map((l) => (l.clip !== 'none' ? l.clip : l.round !== '0px' ? 'round' : 'square'));
assert(!shapes.includes('square'), 'no legend entry is a plain square: ' + legend.map((l, i) => l.k + '=' + (shapes[i] === 'round' ? 'round' : shapes[i].slice(0, 20))).join(' '));
for (const k of ['daemon', 'proxy', 'botnet', 'ghost']) assert(shapes.filter((x, i) => kinds[i] !== k && x === shapes[kinds.indexOf(k)]).length === 0, `the ${k} legend shape is not shared with another kind`);
await page.locator('#nextwave').screenshot({ path: OUT + 'gallery-legend.png' });
}
// select the Load Balancer: its links show and the info panel has the new stats
const box = await page.locator('#board').boundingBox();
const p = await page.evaluate(() => NW.app.renderer.cellToScreen(10, 5));
if (touch) await page.touchscreen.tap(box.x + p.x, box.y + p.y); else await page.mouse.click(box.x + p.x, box.y + p.y);
await sleep(300);
const info = await page.locator('#info').innerText();
assert(/Load Balancer/.test(info) && /fire rate/i.test(info), `${name}: the Load Balancer info panel shows its fire-rate bonus`);
await page.screenshot({ path: OUT + 'gallery-game-' + name + '-balancer.png' });
assert(/Range\s*3\.0/.test(info) && /\+35%/.test(info), `${name}: the Load Balancer panel gives range and the +35% bonus of level 3`);
assert(await page.locator('#info [data-act="mode"]').count() === 0, `${name}: a Load Balancer has no Target button (it does not shoot)`);
const tapCell = async (cx, cy) => { const pp = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); if (touch) await page.touchscreen.tap(box.x + pp.x, box.y + pp.y); else await page.mouse.click(box.x + pp.x, box.y + pp.y); await sleep(300); };
await tapCell(8, 5);
const sinfo = await page.locator('#info').innerText();
assert(/Sandbox/.test(sinfo) && /Stun\s*1\.6 s/.test(sinfo) && /Pulse\s*every 4\.0 s/.test(sinfo), `${name}: the Sandbox panel shows stun time and pulse interval: ` + sinfo.replace(/\s+/g, ' ').slice(0, 200));
assert(await page.locator('#info [data-act="mode"]').count() === 0, `${name}: a Sandbox has no Target button`);
await tapCell(12, 5);
assert(await page.locator('#info [data-act="mode"]').count() === 1, `${name}: a Packet Filter still has its Target button`);
const q = await page.evaluate(() => NW.app.ctrl.sim.monsters.map((m) => m.kind));
assert(q.length > 3, `${name}: enemies are on the board (${[...new Set(q)].join(',')})`);
await ctx.close();
}
assert(errors.length === 0, 'no console errors or warnings: ' + errors.slice(0, 5).join(' | '));
};