towerdef/e2e/scenarios/09-touch-precision.js
Claude a5bd09d505 Phone UI and touch precision overhaul, proxy fixes, Orbital Uplink, four new maps
Phone panels (reviewed + QA'd, matrix of 22 layouts with real taps/bounding boxes):
- selected-tower action bar over the board (Upgrade/Sell/Target/close), info panel
  updated in place so taps are never lost, scrollable palette for 7+ towers,
  overlays with pinned footers (Help "Got it", Play solo, Join always visible),
  tappable room chip to invite, reduced-motion/contrast/forced-colors fixes,
  paused state, partner cursor labels, bigger level pips and owner flags
- touch input rewritten around "pointerdown commits nothing": pinch never builds,
  10px tap slop, palm-proof pinch, long-press pings with any tool armed, nudge
  arrows for precise placement, hotkey repeat guard, proportional wheel zoom
- new e2e: select/sell, info-panel stability, UI states, touch precision;
  camera unit tests

Proxy/server (reproduced against real nginx 1.26 with NPM v2.16 config):
- Origin check works when the proxy drops a non-default port, TRUSTED_PROXIES for
  proxies on global IPv6/CGNAT addresses, service worker no longer serves nginx's
  502 page, DEPLOY.md corrected (NPM default read timeout is 90 s, Advanced-tab
  limits, path-prefix, cookie size, per-IP cap behaviour)

Content:
- Orbital Uplink: 4-level endgame tower (450 + 500/800/1200 credits): piercing
  armour-ignoring beam, blast and lingering slow, ground+air, range 11-14;
  glyph, beam effect, sound, help text, unit tests
- Maps: The Canyon, Archipelago, Fortress, Pinwheel (7 maps total)

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

464 lines
33 KiB
JavaScript

// Touch precision: a pinch or a pan must never build or move anything, a long press pings, a tap with a little drift still builds,
// the nudge buttons move the pending cell one cell on screen (also when the board is drawn turned 90 degrees), and the partner sees
// where a touch is aiming. Plus the keyboard / wheel / sound fixes that went in with it (touch-1 2 9 10 11 12 16 17, coop-7,
// code-6 8 22 23). Real touch events (CDP) and real clicks, no calls into the game's own handlers. Every failure is collected, so the
// old code lists all of them.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
module.exports = async function ({ browser, url: URL, out: OUT }) {
const failures = [], errors = [];
let tag = '';
const assert = (c, m) => { if (!c) { failures.push(`[${tag}] ${m}`); console.log(`FAIL - [${tag}] ${m}`); } else console.log(`ok - [${tag}] ${m}`); };
// a fresh solo game in a phone-sized touch context (or a desktop mouse context)
async function open(w, h, kind) {
const touch = kind !== 'mouse';
const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: 2, isMobile: touch, hasTouch: touch });
const page = await ctx.newPage();
page.on('pageerror', (e) => errors.push(`[${tag}] pageerror: ${e.message}`));
page.on('console', (m) => { if (m.type() === 'error') errors.push(`[${tag}] console.error: ${m.text()}`); });
const cdp = touch ? await ctx.newCDPSession(page) : null;
await page.goto(URL); await sleep(300);
await page.evaluate(() => document.getElementById('btnSolo').click()); await sleep(200);
await page.evaluate(() => { const b = document.getElementById('btnHelpClose'); if (!document.getElementById('help').hidden) b.click(); }); await sleep(150);
const T = { ctx, page, box: await page.locator('#board').boundingBox() };
T.touch = (type, pts) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: pts.map((p, i) => ({ x: p.x, y: p.y, id: p.id || i + 1 })) });
T.pt = async (cx, cy) => { const r = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: T.box.x + r.x, y: T.box.y + r.y }; };
T.cs = () => page.evaluate(() => NW.app.renderer.cellSizePx());
T.st = () => page.evaluate(() => {
const a = NW.app, v = a.ctrl.view, r = a.renderer, c = document.getElementById('confirm');
return { towers: v.towers.length, walls: v.towers.filter((t) => t.type === 'wall').length, gold: v.gold, pending: a.pending, selType: a.selType, selTower: a.selTower,
zoom: r.zoom, marks: r.marks.length, barHidden: c.hidden, hint: document.getElementById('confirmHint').textContent, wave: v.wave };
});
T.tap = async (p, hold) => { await T.touch('touchStart', [p]); await sleep(hold || 40); await T.touch('touchEnd', []); await sleep(70); };
// arm a tower type; `fresh` re-arms it from scratch (no pending cell left over)
T.arm = async (type, fresh) => { await page.evaluate(([t, f]) => { const b = document.querySelector(`.tbtn[data-type="${t}"]`); if (f && NW.app.selType === t) b.click(); if (NW.app.selType !== t) b.click(); }, [type, !!fresh]); await sleep(80); };
// a canvas point just inside the stage edge that is NOT a board cell
T.outside = () => page.evaluate(() => { const r = NW.app.renderer, b = NW.app.ctrl.board, W = r.W, H = r.H; const cv = document.getElementById('board'), bb = cv.getBoundingClientRect();
for (const [x, y] of [[W / 2, 8], [8, H / 2], [W / 2, H - 8], [W - 8, H / 2], [10, 10], [W - 10, 10], [10, H - 10], [W - 10, H - 10]]) { const c = r.screenToCell(x, y); if (!b.inBounds(c.x, c.y) && document.elementFromPoint(bb.left + x, bb.top + y) === cv) return { x, y }; } return null; });
T.build = (type, x, y) => page.evaluate(([t, a, b]) => NW.app.ctrl.send({ c: 'place', type: t, x: a, y: b }), [type, x, y]);
return T;
}
const close = (T) => T.ctx.close();
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
for (const [w, h] of [[390, 844], [844, 390]]) {
tag = `${w}x${h}`;
console.log('=== ' + tag);
// ---- touch-1: Firewall armed, pinch: no wall, no credits spent
{
const T = await open(w, h); await T.arm('wall');
const a = await T.pt(8, 6), b = await T.pt(12, 6), s0 = await T.st();
await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30);
await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]);
for (let i = 1; i <= 10; i++) { await T.touch('touchMove', [{ x: a.x - i * 4, y: a.y, id: 1 }, { x: b.x + i * 4, y: b.y, id: 2 }]); await sleep(12); }
await T.touch('touchEnd', []); await sleep(100);
const s = await T.st();
assert(s.walls === 0 && s.gold === s0.gold, `touch-1: a pinch with the Firewall armed builds no wall and spends nothing (walls ${s.walls}, gold ${s0.gold} -> ${s.gold})`);
assert(s.zoom > 1.2, `touch-1: ...and it still zooms (zoom ${s.zoom.toFixed(2)})`);
await close(T);
}
// ---- touch-2: turret armed with a pending cell: a pinch, or one finger left after it, never moves the pending cell
{
const T = await open(w, h); await T.arm('filter');
await T.tap(await T.pt(10, 8));
const p0 = (await T.st()).pending;
assert(p0 && p0.x === 10 && p0.y === 8, 'touch-2: first tap previews the cell (pending 10,8)');
const a = await T.pt(6, 5), b = await T.pt(14, 5);
await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30);
await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]);
for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x - i * 3, y: a.y, id: 1 }, { x: b.x + i * 3, y: b.y, id: 2 }]); await sleep(12); }
const mid = (await T.st()).pending;
await T.touch('touchEnd', [{ x: b.x + 24, y: b.y, id: 2 }]); await sleep(40); // finger 1 up, finger 2 stays down
for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: b.x + 24 + i * 5, y: b.y + i * 3, id: 2 }]); await sleep(12); }
const left = await T.st();
await T.touch('touchEnd', []); await sleep(100);
const end = await T.st();
assert(same(mid, p0), `touch-2: pending stays ${JSON.stringify(p0)} during a pinch (${JSON.stringify(mid)})`);
assert(same(left.pending, p0) && same(end.pending, p0) && end.towers === 0, `touch-2: ...and with one finger left and after lifting (${JSON.stringify(left.pending)}, ${JSON.stringify(end.pending)}, towers ${end.towers})`);
assert(!end.barHidden, 'touch-2: the build bar is still up');
await close(T);
}
// ---- touch-2 (b): a pinch whose first finger lands on a tower must not select it and drop the armed type
{
const T = await open(w, h); await T.build('filter', 9, 6); await T.arm('filter');
const a = await T.pt(9, 6), b = await T.pt(14, 6);
await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30);
await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]);
for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: a.x - i * 3, y: a.y, id: 1 }, { x: b.x + i * 3, y: b.y, id: 2 }]); await sleep(12); }
await T.touch('touchEnd', []); await sleep(100);
const s = await T.st();
assert(s.selType === 'filter' && s.selTower === 0, `touch-2: a pinch that starts on a tower keeps the armed type and selects nothing (selType ${s.selType}, selTower ${s.selTower})`);
await close(T);
}
// ---- touch-12: a third finger (palm) neither freezes the pinch nor makes the zoom jump when it lifts
{
const T = await open(w, h); const c = await T.pt(13, 8);
const f = (dx, dy, id) => ({ x: c.x + dx, y: c.y + dy, id });
await T.touch('touchStart', [f(-30, 0, 1), f(30, 0, 2)]);
for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [f(-30 - i * 6, 0, 1), f(30 + i * 6, 0, 2)]); await sleep(12); }
const z1 = (await T.st()).zoom;
await T.touch('touchStart', [f(-66, 0, 1), f(66, 0, 2), f(0, 90, 3)]); await sleep(30);
const zs = [];
for (let i = 1; i <= 4; i++) { await T.touch('touchMove', [f(-66 - i * 4, 0, 1), f(66 + i * 4, 0, 2), f(0, 90, 3)]); await sleep(12); zs.push((await T.st()).zoom); }
assert(zs[3] > z1 + 0.15, `touch-12: the pinch keeps tracking the two fingers while a palm rests on the screen (zoom ${z1.toFixed(2)} -> ${zs[3].toFixed(2)})`);
await T.touch('touchEnd', [f(-82, 0, 1), f(82, 0, 2)]); await sleep(40); // the palm lifts
const z2 = (await T.st()).zoom;
await T.touch('touchMove', [f(-84, 0, 1), f(84, 0, 2)]); await sleep(30);
const z3 = (await T.st()).zoom;
assert(Math.abs(z3 - z2) < 0.12, `touch-12: the zoom does not jump when the palm lifts (${z2.toFixed(2)} -> ${z3.toFixed(2)})`);
await T.touch('touchEnd', []);
await close(T);
}
// ---- the cell under the fingertip, after a real pinch-zoom and a two-finger pan (rotated on the tall phone): random taps pick the cell they hit
{
const T = await open(w, h);
const d0 = await T.page.evaluate(() => { const c = document.getElementById('board').getBoundingClientRect(), st = document.getElementById('stage').getBoundingClientRect(), r = NW.app.renderer; return { c: [c.width, c.height], st: [st.width, st.height], r: [r.W, r.H] }; });
assert(Math.abs(d0.c[0] - d0.r[0]) < 0.6 && Math.abs(d0.c[1] - d0.r[1]) < 0.6 && Math.abs(d0.c[0] - d0.st[0]) < 0.6 && Math.abs(d0.c[1] - d0.st[1]) < 0.6, `hit cell: the canvas, the stage and the renderer agree on the size (${JSON.stringify(d0)})`);
const c = await T.pt(10, 8), f = (dx, dy, id) => ({ x: c.x + dx, y: c.y + dy, id });
await T.touch('touchStart', [f(-30, 0, 1), f(30, 0, 2)]);
for (let i = 1; i <= 10; i++) { await T.touch('touchMove', [f(-30 - i * 6, 0, 1), f(30 + i * 6, 0, 2)]); await sleep(12); }
for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [f(-90 - i * 5, i * 4, 1), f(90 - i * 5, i * 4, 2)]); await sleep(12); } // pan with both fingers
await T.touch('touchEnd', []); await sleep(150);
const z = await T.page.evaluate(() => ({ zoom: NW.app.renderer.zoom, px: NW.app.renderer.cam.px, py: NW.app.renderer.cam.py, rot: NW.app.renderer.rot }));
assert(z.zoom > 1.8 && (z.px !== 0 || z.py !== 0), `hit cell: zoomed and panned for real (zoom ${z.zoom.toFixed(2)}, pan ${z.px.toFixed(0)},${z.py.toFixed(0)}, rot ${z.rot.toFixed(2)})`);
let seed = 12345; const rand = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; };
const vis = await T.page.evaluate(() => { // every cell whose centre is comfortably on screen at this zoom and pan
const r = NW.app.renderer, b = NW.app.ctrl.board, out = [];
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) { const p = r.cellToScreen(x, y), m = r.cellSizePx() * 0.5 + 6; if (p.x >= m && p.y >= m && p.x <= r.W - m && p.y <= r.H - m) out.push({ x, y, sx: p.x, sy: p.y, cs: r.cellSizePx() }); }
return out;
});
let tried = 0; const wrong = [];
for (let k = vis.length - 1; k > 0; k--) { const j = Math.floor(rand() * (k + 1)); [vis[k], vis[j]] = [vis[j], vis[k]]; }
for (const v of vis) {
if (tried >= 14) break;
await T.arm('filter', true);
const p = { x: T.box.x + v.sx + (rand() - 0.5) * 0.7 * v.cs, y: T.box.y + v.sy + (rand() - 0.5) * 0.7 * v.cs };
const top = await T.page.evaluate(([x, y]) => { const e = document.elementFromPoint(x, y); return e && e.id; }, [p.x, p.y]);
if (top !== 'board') continue; // (under a floating bar)
await T.tap(p); tried++;
const got = (await T.st()).pending;
if (!got || got.x !== v.x || got.y !== v.y) wrong.push(`${v.x},${v.y} -> ${got ? got.x + ',' + got.y : 'none'}`);
}
assert(tried >= 8 && wrong.length === 0, `hit cell: ${tried} random taps after a pinch-zoom and pan all picked the cell they hit (wrong: ${wrong.join(' ') || 'none'})`);
await close(T);
}
// ---- touch-10: a long press pings whatever is armed, and never builds or moves the pending cell
{
const T = await open(w, h); await T.arm('filter');
await T.page.evaluate(() => { const c = NW.app.ctrl, o = c.sendMark.bind(c); window.__pings = []; c.sendMark = (x, y) => { window.__pings.push([x, y]); return o(x, y); }; }); // count the real ping calls (marks fade after 1.6 s)
const pings = () => T.page.evaluate(() => window.__pings.map((p) => p.join(',')));
await T.tap(await T.pt(10, 8)); // pending 10,8
const lp = await T.pt(14, 5);
await T.touch('touchStart', [lp]); await sleep(700); await T.touch('touchEnd', []); await sleep(100);
const s = await T.st();
assert(same(await pings(), ['14,5']), `touch-10: a long press pings cell 14,5 once with a turret armed (pings ${JSON.stringify(await pings())})`);
assert(same(s.pending, { x: 10, y: 8 }) && s.towers === 0, `touch-10: ...and leaves the pending cell alone (${JSON.stringify(s.pending)}, towers ${s.towers})`);
const on = await T.pt(10, 8); // a long press ON the pending cell must not count as "tap again to build"
await T.touch('touchStart', [on]); await sleep(700); await T.touch('touchEnd', []); await sleep(100);
assert((await T.st()).towers === 0 && (await pings()).length === 2, `touch-10: a long press on the previewed cell pings and does not build it (pings ${(await pings()).length})`);
await T.arm('wall');
const wp = await T.pt(6, 9);
await T.touch('touchStart', [wp]); await sleep(700); await T.touch('touchEnd', []); await sleep(100);
const s1 = await T.st();
assert((await pings()).length === 3 && (await pings())[2] === '6,9' && s1.walls === 0, `touch-10: a long press with the Firewall armed pings 6,9 and builds no wall (pings ${JSON.stringify(await pings())}, walls ${s1.walls})`);
await close(T);
}
// ---- touch-11: the second tap on the preview, with the finger drifting across the cell edge but inside the tap slop, still builds
{
const T = await open(w, h); await T.arm('filter');
const c = await T.pt(10, 8), cs = await T.cs();
await T.tap(c);
const start = { x: c.x + cs / 2 - 2, y: c.y }; // 2 px inside the cell edge ...
await T.touch('touchStart', [start]); await sleep(40);
await T.touch('touchMove', [{ x: start.x + 4, y: start.y }]); await sleep(40); // ... drifts 4 px: over the edge, under the slop
await T.touch('touchEnd', []); await sleep(120);
const s = await T.st();
assert(s.towers === 1, `touch-11: tapping the previewed cell again with 4 px of drift builds it (towers ${s.towers}, pending ${JSON.stringify(s.pending)})`);
await close(T);
}
// ---- touch-17: a wall stroke that starts on a turret keeps the tool and paints; a plain tap on the turret still selects it
{
const T = await open(w, h); await T.build('filter', 10, 5); await T.arm('wall');
const a = await T.pt(10, 5), b = await T.pt(10, 9);
await T.touch('touchStart', [a]);
for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 8, y: a.y + (b.y - a.y) * i / 8 }]); await sleep(16); }
await T.touch('touchEnd', []); await sleep(100);
const s = await T.st();
assert(s.selType === 'wall' && s.selTower === 0 && s.walls >= 3, `touch-17: the stroke from a turret keeps the Firewall tool and paints (selType ${s.selType}, walls ${s.walls})`);
await T.tap(a); await sleep(100);
const s2 = await T.st();
assert(s2.selTower > 0 && s2.selType === null, `touch-17: a plain tap on the turret selects it (selTower ${s2.selTower})`);
await close(T);
}
// ---- drag-paint still paints every cell including the first, and tap-confirm still builds
{
const T = await open(w, h); await T.arm('wall');
const a = await T.pt(8, 5), b = await T.pt(8, 11);
await T.touch('touchStart', [a]);
for (let i = 1; i <= 12; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 12, y: a.y + (b.y - a.y) * i / 12 }]); await sleep(14); }
await T.touch('touchEnd', []); await sleep(100);
const cells = await T.page.evaluate(() => NW.app.ctrl.view.towers.filter((t) => t.type === 'wall').map((t) => t.x + ',' + t.y));
const want = []; for (let y = 5; y <= 11; y++) want.push('8,' + y);
const missing = want.filter((c) => !cells.includes(c));
assert(missing.length === 0, `drag-paint: every cell of the stroke gets a wall, including the first (missing ${missing.join(' ') || 'none'})`);
await T.arm('filter');
await T.tap(await T.pt(12, 8));
const p = await T.st();
await T.page.tap('#btnConfirmBuild'); await sleep(150);
const s = await T.st();
assert(p.pending && p.pending.x === 12 && !p.barHidden && s.towers === cells.length + 1, `tap + Build button still builds (towers ${s.towers})`);
await close(T);
}
// ---- code-23: tapping off the board clears the pending cell and hides the build bar
{
const T = await open(w, h); await T.arm('filter');
await T.tap(await T.pt(10, 8));
const before = await T.st();
const out = await T.outside();
await T.tap({ x: T.box.x + out.x, y: T.box.y + out.y });
const s = await T.st();
assert(!before.barHidden && s.pending === null && s.barHidden, `code-23: a tap outside the board clears the pending cell (pending ${JSON.stringify(s.pending)}, bar hidden ${s.barHidden})`);
await close(T);
}
// ---- pointercancel: a cancelled aim drag puts the pending cell back; a cancelled stroke stops; the next tap works
{
const T = await open(w, h); await T.arm('filter');
await T.tap(await T.pt(10, 8));
const a = await T.pt(14, 5), b = await T.pt(15, 6);
await T.touch('touchStart', [a]); await sleep(30);
await T.touch('touchMove', [{ x: a.x + 12, y: a.y + 12 }]); await sleep(30);
const dragging = (await T.st()).pending;
await T.touch('touchCancel', []); await sleep(60);
const s = await T.st();
assert(!same(dragging, { x: 10, y: 8 }), `pointercancel: (the aim drag did move the pending cell: ${JSON.stringify(dragging)})`);
assert(same(s.pending, { x: 10, y: 8 }), `pointercancel: a cancelled aim drag restores the pending cell (${JSON.stringify(s.pending)})`);
await T.tap(await T.pt(12, 8));
await T.tap(await T.pt(12, 8));
assert((await T.st()).towers === 1, 'pointercancel: a fresh tap-tap builds normally afterwards');
await T.arm('wall');
const w0 = (await T.st()).walls, c0 = await T.pt(6, 3), c1 = await T.pt(6, 6), c2 = await T.pt(6, 9);
await T.touch('touchStart', [c0]); await T.touch('touchMove', [c1]); await sleep(30);
await T.touch('touchCancel', []); await sleep(40);
const w1 = (await T.st()).walls;
await T.touch('touchStart', [c1]); await sleep(20); await T.touch('touchEnd', []); await sleep(60); // (a tap: one wall at most)
assert(w1 > w0, `pointercancel: the stroke before the cancel painted (${w0} -> ${w1})`);
await close(T);
}
// ---- touch-16: a stroke that is rejected cell after cell plays the error sound once
{
const T = await open(w, h);
await T.page.evaluate(() => { NW.app.ctrl.sim.gold = 12; window.__sfx = {}; const o = NW.Audio.sfx; NW.Audio.sfx = function (n) { window.__sfx[n] = (window.__sfx[n] || 0) + 1; return o.apply(this, arguments); }; });
await T.arm('wall');
const a = await T.pt(5, 4), b = await T.pt(5, 13);
await T.touch('touchStart', [a]);
for (let i = 1; i <= 3; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 3, y: a.y + (b.y - a.y) * i / 3 }]); await sleep(20); }
await T.touch('touchEnd', []); await sleep(100);
const n = await T.page.evaluate(() => window.__sfx.error || 0);
assert(n >= 1 && n <= 1, `touch-16: one error sound for the whole stroke, not one per cell (${n})`);
await close(T);
}
// ---- coop-7: the partner builds on the previewed cell -> the preview is dropped with a toast; aiming over your own tower is not
{
const T = await open(w, h); await T.arm('filter');
await T.tap(await T.pt(10, 8));
await T.build('wall', 10, 8); await sleep(250);
const s = await T.st();
const toast = await T.page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|'));
assert(s.pending === null && s.barHidden && /just built there/.test(toast), `coop-7: a tower appearing on the previewed cell drops the preview with a toast (pending ${JSON.stringify(s.pending)}, "${toast}")`);
await T.build('filter', 12, 8);
await T.tap(await T.pt(11, 5));
const a = await T.pt(11, 5), b = await T.pt(12, 8); // drag-aim the preview onto the tower you already own
await T.touch('touchStart', [a]); await sleep(30);
for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 6, y: a.y + (b.y - a.y) * i / 6 }]); await sleep(20); }
await T.touch('touchEnd', []); await sleep(300);
const s2 = await T.st();
assert(same(s2.pending, { x: 12, y: 8 }), `coop-7: aiming at a cell that already holds a tower is not wiped (${JSON.stringify(s2.pending)})`);
await close(T);
}
await sleep(50);
}
// ================================================================ nudge buttons (several sizes, also rotated)
for (const [w, h] of [[390, 844], [844, 390], [360, 640], [568, 320], [320, 568]]) {
tag = `nudge ${w}x${h}`;
console.log('=== ' + tag);
const T = await open(w, h); const page = T.page;
await T.arm('filter');
const info = () => page.evaluate(() => {
const r = NW.app.renderer, p = NW.app.pending; if (!p) return null;
const s = r.cellToScreen(p.x, p.y), b = document.getElementById('board').getBoundingClientRect(), c = document.getElementById('confirm').getBoundingClientRect();
return { x: p.x, y: p.y, sx: s.x + b.left, sy: s.y + b.top, cs: r.cellSizePx(), bar: { l: c.left, t: c.top, r: c.right, b: c.bottom }, hint: (document.getElementById('app').dataset.barrows === '0' ? document.getElementById('hint') : document.getElementById('confirmHint')).textContent, rot: r.rot };
});
const btnRect = (dir) => page.evaluate((d) => {
const el = document.querySelector(`#nudge [data-dx="${d[0]}"][data-dy="${d[1]}"]`); if (!el) return null;
const r = el.getBoundingClientRect(), hit = (x, y) => { const e = document.elementFromPoint(x, y); return e && (e === el || el.contains(e)); };
return { l: r.left, t: r.top, r: r.right, b: r.bottom, w: r.width, h: r.height, on: r.left >= 0 && r.top >= 0 && r.right <= innerWidth && r.bottom <= innerHeight,
free: hit(r.left + 5, r.top + 5) && hit(r.right - 5, r.bottom - 5) && hit((r.left + r.right) / 2, (r.top + r.bottom) / 2) };
}, dir);
const tapBtn = async (dir) => { const r = await btnRect(dir); await page.touchscreen.tap((r.l + r.r) / 2, (r.t + r.b) / 2); await sleep(90); };
const overlap = (a, r, pad) => !(a.r + pad <= r.l || a.l - pad >= r.r || a.b + pad <= r.t || a.t - pad >= r.b);
// the buttons exist, are big, on screen, uncovered, and never cover the cell being aimed at (five different cells)
let all = true, why = '';
for (const [cx, cy] of [[3, 3], [16, 3], [3, 11], [16, 11], [10, 7]]) {
await T.arm('filter', true); // (a fresh preview each time: the bar covers part of the other half)
await T.tap(await T.pt(cx, cy));
const i = await info();
if (!i) { all = false; why += ` no pending at ${cx},${cy};`; continue; }
for (const d of [[-1, 0], [0, -1], [0, 1], [1, 0]]) {
const r = await btnRect(d);
if (!r) { all = false; why += ` button ${d} missing;`; continue; }
if (!r.on || !r.free || r.w < 43.5 || r.h < 43.5) { all = false; why += ` button ${d} at cell ${cx},${cy}: on=${r.on} free=${r.free} ${r.w}x${r.h};`; }
}
const cell = { l: i.sx - i.cs / 2, r: i.sx + i.cs / 2, t: i.sy - i.cs / 2, b: i.sy + i.cs / 2 };
if (overlap(i.bar, cell, 0)) { all = false; why += ` the build bar covers cell ${cx},${cy};`; }
}
assert(all, `nudge: four on-screen, uncovered buttons of at least 44 px, and the bar never covers the aimed cell${why}`);
await page.screenshot({ path: `${OUT}touch-nudge-${w}x${h}.png` });
if (!all) { await close(T); continue; } // (no buttons: the rest of this size cannot run)
// each button moves the cell by one cell in that SCREEN direction (the board may be turned 90 degrees)
const dirs = { left: [-1, 0], up: [0, -1], down: [0, 1], right: [1, 0] };
let ok = true, detail = '';
for (const [name, d] of Object.entries(dirs)) {
const i0 = await info(); await tapBtn(d); const i1 = await info();
const ex = i0.cs * d[0], ey = i0.cs * d[1];
if (!i1 || Math.abs((i1.sx - i0.sx) - ex) > 1.5 || Math.abs((i1.sy - i0.sy) - ey) > 1.5) { ok = false; detail += ` ${name}: moved (${(i1.sx - i0.sx).toFixed(1)}, ${(i1.sy - i0.sy).toFixed(1)}) not (${ex.toFixed(1)}, ${ey.toFixed(1)});`; }
}
assert(ok, `nudge: left/up/down/right move the cell one cell on screen (rot ${(await info()).rot.toFixed(2)})${detail}`);
// Build builds at the nudged cell
const i2 = await info(), t0 = (await T.st()).towers;
await page.tap('#btnConfirmBuild'); await sleep(150);
const built = await page.evaluate(() => NW.app.ctrl.view.towers.map((t) => t.x + ',' + t.y));
assert((await T.st()).towers === t0 + 1 && built.includes(i2.x + ',' + i2.y), `nudge: Build builds at the nudged cell ${i2.x},${i2.y}`);
// the preview and route hint follow: nudge onto a dead node and the hint turns into the reason
const dead = await page.evaluate(() => {
const b = NW.app.ctrl.board, r = NW.app.renderer;
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
if (b.obst[y * b.cols + x]) continue;
const n = r.stepCell(x, y, 0, -1);
if (b.inBounds(n.x, n.y) && b.obst[n.y * b.cols + n.x] && !NW.app.ctrl.view.towers.some((t) => t.x === x && t.y === y)) return { x, y, nx: n.x, ny: n.y };
}
return null;
});
await T.arm('filter', true);
if (dead) {
await T.tap(await T.pt(dead.x, dead.y));
const h0 = (await info()).hint; await tapBtn([0, -1]); const i3 = await info();
assert(i3.x === dead.nx && i3.y === dead.ny && /dead|✕/.test(i3.hint) && h0 !== i3.hint, `nudge: the route hint follows the nudged cell ("${h0}" -> "${i3.hint}")`);
}
// the edge of the board: nudging past it stays put (no error, no off-board cell)
await T.tap(await T.pt(0, 0));
const e0 = await info(); for (let k = 0; k < 2; k++) { await tapBtn([-1, 0]); await tapBtn([0, -1]); } const e1 = await info();
assert(e1 && e1.x >= 0 && e1.y >= 0, `nudge: the cell stays on the board when nudged past the edge (${e1 && e1.x},${e1 && e1.y})`);
// the bar does not hop to the other half while you nudge across the middle: tap down, down, down... on the SAME button
await T.arm('filter', true);
await T.tap(await T.pt(2, 2));
let flips = 0, landed = 0, steps = 0, covered = false, lastBar = (await info()).bar.t;
for (let k = 0; k < 12; k++) {
const i0 = await info(); if (!i0) break;
const r = await btnRect([0, 1]); if (!r) break;
await page.touchscreen.tap((r.l + r.r) / 2, (r.t + r.b) / 2); await sleep(90);
const i1 = await info(); steps++;
if (i1 && Math.abs((i1.sy - i0.sy) - i0.cs) < 1.5) landed++;
if (i1 && Math.abs(i1.bar.t - lastBar) > 2) { flips++; lastBar = i1.bar.t; }
if (i1 && overlap(i1.bar, { l: i1.sx - i1.cs / 2, r: i1.sx + i1.cs / 2, t: i1.sy - i1.cs / 2, b: i1.sy + i1.cs / 2 }, 0)) covered = true;
if (i1 && (i1.y >= 15 || i1.x >= 19)) break;
}
assert(landed >= 6 && flips <= 1 && !covered, `nudge: ${landed}/${steps} taps on the same button each moved the cell, the bar flipped ${flips}x and never covered the cell`);
await close(T);
}
// ================================================================ co-op: the partner sees the touch aim and it goes away again (touch-9)
{
tag = 'coop 390x844';
console.log('=== ' + tag);
const T = await open(390, 844); const page = T.page;
await page.evaluate(() => document.getElementById('btnMenu').click()); await sleep(100);
await page.evaluate(() => document.getElementById('btnCoop').click()); await sleep(100);
await page.fill('#inName', 'Tess');
await page.evaluate(() => document.getElementById('btnCreate').click());
await page.waitForFunction(() => NW.app.ctrl && NW.app.ctrl.kind === 'remote' && NW.app.ctrl.room && !document.getElementById('lobby').hidden === false, null, { timeout: 8000 }).catch(() => {});
await sleep(600);
const remote = await page.evaluate(() => NW.app.ctrl.kind === 'remote' && !!NW.app.ctrl.room);
assert(remote, 'co-op room created');
if (remote) {
T.box = await page.locator('#board').boundingBox();
await page.evaluate(() => { const c = NW.app.ctrl; window.__cur = []; const o = c._send.bind(c); c._send = (m) => { if (m.t === 'cursor') window.__cur.push({ x: m.x, y: m.y }); return o(m); }; });
const cur = () => page.evaluate(() => window.__cur.slice());
await T.arm('filter');
await T.tap(await T.pt(10, 8)); await sleep(150);
let c = await cur();
assert(c.some((m) => m.x === 10.5 && m.y === 8.5), `touch-9: a plain tap shows a cursor on the partner's board (${JSON.stringify(c.slice(-2))})`);
await page.tap('#btnCancelBuild'); await sleep(150);
c = await cur();
assert(c.length && c[c.length - 1].x === null, `touch-9: Cancel clears it (last ${JSON.stringify(c[c.length - 1])})`);
await T.arm('wall'); const before = (await cur()).length;
const a = await T.pt(6, 4), b = await T.pt(6, 9);
await T.touch('touchStart', [a]);
for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 8, y: a.y + (b.y - a.y) * i / 8 }]); await sleep(40); }
c = await cur();
const during = c.slice(before).some((m) => m.x !== null);
await T.touch('touchEnd', []); await sleep(150);
c = await cur();
assert(during && c[c.length - 1].x === null, `touch-9: a wall stroke shows the cursor and lifting the finger clears it (shown ${during}, last ${JSON.stringify(c[c.length - 1])})`);
// a clear straight after a move is not swallowed by the 70 ms throttle
const r = await page.evaluate(() => { const c = NW.app.ctrl; c.lastCursor = -1e9; window.__cur.length = 0; c.sendCursor(3, 3); c.sendCursor(null, null); return window.__cur.slice(); });
assert(r.length === 2 && r[1].x === null, `touch-9: sendCursor(null) bypasses the throttle (${JSON.stringify(r)})`);
}
await close(T);
}
// ================================================================ desktop: keyboard, wheel, mouse
{
tag = 'desktop 1280x800';
console.log('=== ' + tag);
// code-6: a held Space is one wave
let T = await open(1280, 800, 'mouse'); let page = T.page;
await page.keyboard.down(' ');
for (let i = 0; i < 20; i++) { await page.keyboard.down(' '); await sleep(15); }
await page.keyboard.up(' '); await sleep(150);
let s = await T.st();
assert(s.wave === 1, `code-6: holding Space (20 key repeats) starts one wave (wave ${s.wave})`);
// code-8: Enter on the focused Menu button opens the menu instead of starting a wave
await page.focus('#btnMenu'); await page.keyboard.press('Enter'); await sleep(200);
const menuOpen = await page.evaluate(() => !document.getElementById('menu').hidden);
s = await T.st();
assert(menuOpen && s.wave === 1, `code-8: Enter on the focused Menu button opens the menu and starts no wave (menu open ${menuOpen}, wave ${s.wave})`);
await page.keyboard.press('Escape'); await sleep(100);
// code-22: the wheel zooms in proportion to the scroll distance
const c = await T.pt(10, 8);
await page.mouse.move(c.x, c.y);
for (let i = 0; i < 6; i++) await page.mouse.wheel(0, -1);
await sleep(100);
const z1 = (await T.st()).zoom;
assert(z1 < 1.05, `code-22: six tiny wheel events barely zoom (zoom ${z1.toFixed(3)})`);
await page.mouse.wheel(0, -100); await sleep(100);
const z2 = (await T.st()).zoom;
assert(z2 > 1.08 && z2 < 1.3, `code-22: one 100-unit wheel notch is about 1.16x (zoom ${z2.toFixed(3)})`);
await close(T);
// touch-17 with the mouse: press on a turret with the Firewall armed and drag
T = await open(1280, 800, 'mouse'); page = T.page;
await T.build('filter', 10, 5); await T.arm('wall');
const a = await T.pt(10, 5), b = await T.pt(10, 9);
await page.mouse.move(a.x, a.y); await page.mouse.down();
for (let i = 1; i <= 8; i++) { await page.mouse.move(a.x + (b.x - a.x) * i / 8, a.y + (b.y - a.y) * i / 8); await sleep(16); }
await page.mouse.up(); await sleep(100);
s = await T.st();
assert(s.selType === 'wall' && s.selTower === 0 && s.walls >= 3, `touch-17 (mouse): a stroke from a turret keeps the Firewall tool and paints (selType ${s.selType}, walls ${s.walls})`);
await page.mouse.click(a.x, a.y); await sleep(100);
s = await T.st();
assert(s.selTower > 0, `touch-17 (mouse): a plain click on the turret selects it (selTower ${s.selTower})`);
await close(T);
}
if (errors.length) failures.push('console errors:\n' + errors.join('\n'));
if (failures.length) throw new Error(failures.length + ' check(s) failed:\n ' + failures.join('\n '));
console.log('touch precision: all checks passed');
};