towerdef/e2e/scenarios/05-layout-matrix.js
Claude b4ae6cb57d Difficulty picker (Easy/Normal/Hard) and a balance pass
Difficulty:
- TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated
  create-room / newgame option, state carries it; solo menu picker and co-op lobby
  picker (44px segmented control, reachable on every layout), HUD/room/end-screen
  labels, best-wave record per map AND difficulty (Normal keeps the legacy key),
  Play again keeps the running game's difficulty for host and guest

Balance (12 bot runs, deterministic, 48/48 games replay identically in QA):
- Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open
- credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling
  eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at
  wave 30: 1309 -> 335
- IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only
  dies by wave 7); Mortar, Arc and Filter buffed
- Orbital Uplink price step per owned unit 30% (buy and upgrade)
- remaining imbalances documented in docs/BALANCE.md

Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix
reachability of the picker. 156 unit tests, 17 e2e scenarios.

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

330 lines
25 KiB
JavaScript

// Layout matrix: every control a player needs must be fully on screen, uncovered and big enough at every viewport size,
// for 6 towers (today) and for a stress palette of 10 towers and 8 maps (the planned content).
//
// For each size we drive the real UI (taps on phones, clicks on desktop) and ask the browser where things really are
// (getBoundingClientRect + document.elementFromPoint at the corners and centre), so overlapping panels, content cut by
// the screen edge and tiny targets all show up as failures. Failures are collected per size and thrown at the end.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// [width, height, kind, towers] kind: 'touch' = phone/tablet (coarse pointer), 'mouse' = desktop (fine pointer);
// towers: 10 = stress palette (10+ towers, 8 maps), 6 = the content as it ships (whatever the sim defines)
const SIZES = [];
for (const [w, h] of [[320, 568], [360, 640], [375, 667], [390, 844], [414, 896], [768, 1024], [1024, 768], [568, 320], [667, 375], [740, 360], [844, 390], [932, 430], [1280, 720], [1920, 1080]]) {
SIZES.push([w, h, Math.min(w, h) < 800 ? 'touch' : 'mouse', 10]);
}
SIZES.push([1280, 720, 'mouse', 10], [1024, 768, 'mouse', 10], [800, 600, 'mouse', 10], [640, 400, 'mouse', 10]); // desktop windows (incl. 200% zoom of 1280x800)
SIZES.push([320, 568, 'touch', 6], [667, 375, 'touch', 6], [390, 844, 'touch', 6], [1280, 720, 'mouse', 6]); // the palette as it ships today
// tablets and foldables (CSS px). Near-square unfolded screens sit right on the portrait/landscape switch; the half-folded
// "flex" posture is a very short wide viewport; the cover screen is a narrow tall phone.
SIZES.push(
[344, 800, 'touch', 6], // Galaxy Z Fold cover screen
[690, 830, 'touch', 6], // Galaxy Z Fold inner screen, portrait-ish
[830, 690, 'touch', 6], // ... and landscape-ish
[701, 841, 'touch', 6], [841, 701, 'touch', 6], // Pixel Fold inner screen
[841, 400, 'touch', 6], // half-folded flex posture
[1114, 705, 'touch', 6], // dual-screen device spanned across both panels
[820, 1180, 'touch', 6], [1180, 820, 'touch', 6], // iPad Air
[1024, 1366, 'touch', 6], [1366, 1024, 'touch', 6], // iPad Pro 12.9
);
// MATRIX_ONLY="344x800,690x830" runs just those sizes (quick local runs)
if (process.env.MATRIX_ONLY) {
const only = process.env.MATRIX_ONLY.split(',');
for (let i = SIZES.length - 1; i >= 0; i--) if (!only.includes(SIZES[i][0] + 'x' + SIZES[i][1])) SIZES.splice(i, 1);
}
// the selected border fades in over 120 ms; on a loaded machine it can be sampled mid-fade, so compare with a tolerance
const nearCyan = (c) => { const m = /rgb\((\d+), (\d+), (\d+)\)/.exec(c || ''); return !!m && Math.abs(m[1] - 77) <= 12 && Math.abs(m[2] - 227) <= 12 && Math.abs(m[3] - 255) <= 12; };
// pretend the game ships 10 towers and 8 maps (the sim is untouched: clones of existing definitions)
function stressContent() {
let td;
Object.defineProperty(window, 'TD', {
configurable: true,
get() { return td; },
set(v) {
td = v;
if (!v || !v.TOWERS || v.TOWERS.x7) return;
[['x7', '7', 'Test Seven'], ['x8', '8', 'Test Eight'], ['x9', '9', 'Test Nine'], ['x0', '0', 'Test Ten']].forEach(([id, key, name]) => {
v.TOWERS[id] = Object.assign({}, v.TOWERS.filter, { name, key });
v.TOWER_ORDER.push(id);
});
for (let i = 4; i <= 8; i++) {
const id = 'm' + i;
v.MAPS[id] = Object.assign({}, v.MAPS.open, { id, name: 'Test Map ' + i, difficulty: 1 + (i % 3) });
v.MAP_ORDER.push(id);
}
},
});
}
// ---------------------------------------------------------------- in-page probes
// Where is this element, is it entirely on screen, and does it receive pointer events at its centre and corners?
function probeFn(sel) {
const el = typeof sel === 'string' ? document.querySelector(sel) : sel;
if (!el) return { err: 'missing' };
const cs = getComputedStyle(el), b = el.getBoundingClientRect();
if (cs.display === 'none' || cs.visibility === 'hidden' || b.width < 1 || b.height < 1) return { err: 'hidden' };
const e = 0.6;
const on = b.left >= -e && b.top >= -e && b.right <= innerWidth + e && b.bottom <= innerHeight + e;
let blocked = 0;
const ins = Math.min(5, b.width / 4, b.height / 4);
for (const [x, y] of [[b.left + b.width / 2, b.top + b.height / 2], [b.left + ins, b.top + ins], [b.right - ins, b.top + ins], [b.left + ins, b.bottom - ins], [b.right - ins, b.bottom - ins]]) {
const hit = document.elementFromPoint(x, y);
if (!hit || !(hit === el || el.contains(hit))) blocked++;
}
return { on, blocked, w: +b.width.toFixed(1), h: +b.height.toFixed(1), l: +b.left.toFixed(1), t: +b.top.toFixed(1), r: +b.right.toFixed(1), b: +b.bottom.toFixed(1) };
}
const centre = (p) => ({ x: (p.l + p.r) / 2, y: (p.t + p.b) / 2 });
module.exports = async function ({ browser, url: URL, out: OUT }) {
let bad = 0;
const allFails = [];
for (const [w, h, kind, nTowers] of SIZES) {
const touch = kind === 'touch';
const tag = `${w}x${h} ${kind} t${nTowers}`;
const fails = [];
const check = (ok, what) => { if (!ok) fails.push(what); };
const mk = async (extra) => {
const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: 1, isMobile: touch, hasTouch: touch, ...(extra || {}) });
if (nTowers > 6) await ctx.addInitScript(stressContent);
const page = await ctx.newPage();
const errors = [];
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
return { ctx, page, errors };
};
const probe = (page, sel) => page.evaluate(probeFn, sel).then((p) => p, () => ({ err: 'probe failed' }));
const tapAt = (page, x, y) => (touch ? page.touchscreen.tap(x, y) : page.mouse.click(x, y));
// the element is on screen, fully uncovered, and (on phones) big enough to hit
const must = async (page, sel, what, o) => {
const p = await probe(page, sel);
if (p.err) { fails.push(`${what} [${sel}] ${p.err}`); return p; }
if (!p.on) fails.push(`${what} [${sel}] not fully on screen (${p.l},${p.t} - ${p.r},${p.b} in ${w}x${h})`);
if (p.blocked) fails.push(`${what} [${sel}] covered by another element (${p.blocked}/5 probe points)`);
if (touch && !(o && o.small) && Math.min(p.w, p.h) < 43.5) fails.push(`${what} [${sel}] touch target ${p.w}x${p.h} < 44`);
return p;
};
const tapBtn = async (page, sel, what) => {
const p = await must(page, sel, what);
if (p.err) return p;
const c = centre(p); await tapAt(page, c.x, c.y); await sleep(touch ? 170 : 120);
return p;
};
const noOverflow = async (page, what) => {
const o = await page.evaluate(() => ({ sw: document.documentElement.scrollWidth, bw: document.body.scrollWidth, iw: innerWidth, sh: document.documentElement.scrollHeight, ih: innerHeight }));
check(o.sw <= o.iw + 1 && o.bw <= o.iw + 1, `${what}: horizontal page overflow (${o.sw}/${o.bw} > ${o.iw})`);
check(o.sh <= o.ih + 1, `${what}: vertical page overflow (${o.sh} > ${o.ih})`);
};
const allButtonsBigEnough = async (page, what) => {
if (!touch) return;
const small = await page.evaluate(() => [...document.querySelectorAll('button')].filter((b) => {
const cs = getComputedStyle(b), r = b.getBoundingClientRect();
if (cs.display === 'none' || cs.visibility === 'hidden' || r.width < 1) return false;
if (r.bottom <= 0 || r.right <= 0 || r.top >= innerHeight || r.left >= innerWidth) return false;
let p = b.parentElement; while (p) { if (p.hidden) return false; p = p.parentElement; }
return Math.min(r.width, r.height) < 43.5;
}).map((b) => (b.id || b.className || b.textContent.trim().slice(0, 12)) + ' ' + Math.round(b.getBoundingClientRect().width) + 'x' + Math.round(b.getBoundingClientRect().height)));
if (small.length) fails.push(`${what}: touch targets < 44px: ${small.join(', ')}`);
};
// ------------------------------------------------ solo: menu -> help -> palette -> build -> select tower
{
const { ctx, page, errors } = await mk();
await page.goto(URL); await sleep(300);
// main menu: primary buttons always reachable (with 8 maps in the picker)
await must(page, '#btnSolo', 'menu Play solo'); await must(page, '#btnCoop', 'menu Co-op');
// the difficulty picker: every segment on screen, uncovered and (on phones) a 44px target; a real tap picks one, a second tap puts it back
const diffIds = await page.evaluate(() => TD.DIFFICULTY_ORDER.slice());
check(diffIds.length >= 3, `the picker offers only ${diffIds.length} difficulties`);
for (const id of diffIds) await must(page, `#diffPick [data-diff="${id}"]`, `menu difficulty ${id}`);
const diffState = () => page.evaluate(() => [...document.querySelectorAll('#diffPick button')].filter((b) => b.getAttribute('aria-checked') === 'true').map((b) => b.dataset.diff).join());
check(await diffState() === 'normal', 'the difficulty picker does not start on normal');
await tapBtn(page, `#diffPick [data-diff="${diffIds[diffIds.length - 1]}"]`, 'menu difficulty (last)');
check(await diffState() === diffIds[diffIds.length - 1], `tapping the last difficulty did not pick it (${await diffState()})`);
await tapBtn(page, '#diffPick [data-diff="normal"]', 'menu difficulty normal');
check(await diffState() === 'normal', 'tapping normal did not pick it again');
await noOverflow(page, 'menu'); await allButtonsBigEnough(page, 'menu');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-menu.png` });
const p0 = await probe(page, '#btnSolo');
await tapAt(page, centre(p0).x, centre(p0).y); await sleep(250);
// first-run help opens by itself: it must have a visible "Got it"
const helpOpen = await page.evaluate(() => !document.getElementById('help').hidden);
check(helpOpen, 'first run: help overlay did not open');
await must(page, '#btnHelpClose', 'help Got it');
await noOverflow(page, 'help'); await allButtonsBigEnough(page, 'help');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-help.png` });
const p1 = await probe(page, '#btnHelpClose');
if (!p1.err) await tapAt(page, centre(p1).x, centre(p1).y);
await sleep(250);
check(await page.evaluate(() => document.getElementById('help').hidden && NW.app.inGame), 'Got it did not close the help overlay');
// HUD: nothing clipped, no overflow, targets big enough
await noOverflow(page, 'game');
const hud = await page.evaluate(() => {
const tb = document.getElementById('topbar');
const kids = [...tb.children].filter((c) => !c.hidden && getComputedStyle(c).display !== 'none' && getComputedStyle(c).visibility !== 'hidden').map((c) => c.getBoundingClientRect());
return { tbOver: tb.scrollWidth > tb.clientWidth + 1, clipped: kids.some((k) => k.right > innerWidth + 1 || k.left < -1), tbH: Math.round(tb.getBoundingClientRect().height), cell: NW.app.renderer.cellSizePx(), rot: NW.app.renderer.rot > 0 };
});
check(!hud.tbOver && !hud.clipped, 'top bar content overflows or is cut off');
// stacked (portrait) layout: the stage hugs the board (no dead band above/below it, touch-4 / visual-10) and the cells are not smaller than before
const lay = await page.evaluate(() => { const st = document.getElementById('stage').getBoundingClientRect(), r = NW.app.renderer, b = r.board, rot = r.rot > 0; return { stacked: matchMedia('(orientation: portrait), (max-width: 760px) and (min-height: 521px)').matches, deadY: st.height - (rot ? b.cols : b.rows) * r.cellSizePx(), cell: r.cellSizePx() }; });
if (lay.stacked) check(lay.deadY <= Math.max(26, h * 0.025), `stage has ${Math.round(lay.deadY)}px of dead band above/below the board`); // 26px on phones, 2.5% of the height on big tablets
const minCell = { '320x568': 11.5, '360x640': 14.3, '375x667': 15, '390x844': 19.5, '414x896': 21, '768x1024': 27 }[`${w}x${h}`];
if (minCell && touch) check(lay.cell >= minCell, `board cells are ${lay.cell.toFixed(1)}px, expected at least ${minCell}px`);
if (touch) console.log(` ${w}x${h} cell ${lay.cell.toFixed(1)}px, stage dead band ${Math.round(lay.deadY)}px`);
await allButtonsBigEnough(page, 'game HUD');
for (const id of ['btnMenu', 'btnWave', 'btnAuto', 'btnSpeed', 'btnPause', 'btnSound']) await must(page, '#' + id, 'top bar ' + id);
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-game.png` });
// every tower in the palette can be picked with a real tap, and the selected state is visible
const order = await page.evaluate(() => TD.TOWER_ORDER.slice());
check(order.length >= (nTowers > 6 ? 10 : 1), `palette has only ${order.length} towers`);
let reachable = 0;
for (const type of order) {
let p = await probe(page, `.tbtn[data-type="${type}"]`);
if (p.err) { fails.push(`palette tile ${type}: ${p.err}`); continue; }
if (!p.on || p.blocked) { // off screen: scrolling the palette is allowed (and must be possible)
await page.evaluate((t) => { // what a swipe on the palette does: scroll it so the tile sits in the middle
const pal = document.getElementById('palette'), el = pal.querySelector(`.tbtn[data-type="${t}"]`), pr = pal.getBoundingClientRect(), er = el.getBoundingClientRect();
pal.scrollLeft += er.left + er.width / 2 - (pr.left + pr.width / 2); pal.scrollTop += er.top + er.height / 2 - (pr.top + pr.height / 2);
}, type);
await sleep(60);
p = await probe(page, `.tbtn[data-type="${type}"]`);
}
if (!p.on || p.blocked) { fails.push(`palette tile ${type} cannot be brought fully on screen (on=${p.on} blocked=${p.blocked})`); continue; }
await tapAt(page, centre(p).x, centre(p).y); await sleep(260); // (the selected border fades in over 120 ms)
const st = await page.evaluate((t) => ({ selType: NW.app.selType, sel: !!document.querySelector(`.tbtn[data-type="${t}"].sel`) }), type);
if (st.selType !== type) { fails.push(`palette tile ${type}: tap did not select it (selType=${st.selType})`); continue; }
const sp = await probe(page, `.tbtn[data-type="${type}"]`);
const vis = await page.evaluate((t) => { const e = document.querySelector(`.tbtn[data-type="${t}"]`); return { pressed: e.getAttribute('aria-pressed'), border: getComputedStyle(e).borderTopColor, cls: e.classList.contains('sel') }; }, type);
if (!sp.on || sp.blocked || !st.sel || vis.pressed !== 'true' || !nearCyan(vis.border)) fails.push(`palette tile ${type}: selected state not visible (${JSON.stringify({ on: sp.on, blocked: sp.blocked, ...vis })})`);
else reachable++;
}
check(reachable === order.length, `only ${reachable}/${order.length} palette towers selectable and visibly selected`);
// a palette that scrolls must say so (fade / chevron hint)
const pal = await page.evaluate(() => { const p = document.getElementById('palette'); return { sx: p.scrollWidth > p.clientWidth + 1, sy: p.scrollHeight > p.clientHeight + 1, more: p.dataset.more || '' }; });
if (pal.sx || pal.sy) check(!!pal.more, 'palette scrolls but shows no scroll affordance (data-more is empty)');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-armed.png` });
// build a Packet Filter at cell (10,8) with real input
const board = await page.locator('#board').boundingBox();
const cellPt = async (cx, cy) => { const r = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: board.x + r.x, y: board.y + r.y }; };
await page.evaluate(() => { document.querySelector('.tbtn[data-type="filter"]').click(); });
let cp = await cellPt(10, 8);
await tapAt(page, cp.x, cp.y); await sleep(200);
if (touch) {
await must(page, '#btnConfirmBuild', 'build bar Build'); await must(page, '#btnCancelBuild', 'build bar Cancel');
const bar = await probe(page, '#confirm');
const cellBox = await page.evaluate(([a, b]) => { const r = NW.app.renderer, p = r.cellToScreen(a, b), s = r.cellSizePx() / 2; const bb = document.getElementById('board').getBoundingClientRect(); return { l: bb.left + p.x - s, r: bb.left + p.x + s, t: bb.top + p.y - s, b: bb.top + p.y + s }; }, [10, 8]);
if (!bar.err) check(bar.r < cellBox.l || bar.l > cellBox.r || bar.b < cellBox.t || bar.t > cellBox.b, 'build bar covers the cell being previewed');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-confirm.png` });
await tapBtn(page, '#btnConfirmBuild', 'build bar Build');
}
await sleep(150);
check(await page.evaluate(() => NW.app.ctrl.view.towers.length === 1), 'tower was not built');
if (!touch) await page.keyboard.press('Escape');
// select the placed tower (tap on the board)
cp = await cellPt(10, 8);
await tapAt(page, cp.x, cp.y); await sleep(250);
check(await page.evaluate(() => NW.app.selTower > 0), 'tapping the tower did not select it');
const compact = await page.evaluate(() => matchMedia('(pointer: coarse), (orientation: portrait), (max-width: 760px) and (min-height: 521px), (orientation: landscape) and (max-height: 520px)').matches);
const acts = {};
for (const a of ['up', 'sell', 'mode']) acts[a] = await must(page, `[data-act="${a}"]`, `selected tower ${a}`);
if (compact) acts.close = await must(page, '[data-act="close"]', 'selected tower close');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-selected.png` });
// the action bar must stay clear of the selected tower
const tb = await page.evaluate(() => { const r = NW.app.renderer, t = NW.app.ctrl.view.towers[0]; if (!t) return null; const p = r.cellToScreen(t.x, t.y), s = r.cellSizePx() / 2, bb = document.getElementById('board').getBoundingClientRect(); return { l: bb.left + p.x - s, r: bb.left + p.x + s, t: bb.top + p.y - s, b: bb.top + p.y + s }; });
if (compact && tb) for (const [a, p] of Object.entries(acts)) {
if (p.err) continue;
if (!(p.r < tb.l || p.l > tb.r || p.b < tb.t || p.t > tb.b)) fails.push(`action ${a} covers the selected tower`);
}
await allButtonsBigEnough(page, 'tower actions');
// upgrade and target with real taps on the buttons
if (acts.up && !acts.up.err) { const c = centre(acts.up); await tapAt(page, c.x, c.y); await sleep(200); }
check(await page.evaluate(() => (NW.app.ctrl.view.towers[0] || {}).level === 2), 'Upgrade tap did not upgrade');
const am = await probe(page, '[data-act="mode"]');
if (!am.err) { await tapAt(page, centre(am).x, centre(am).y); await sleep(200); }
check(await page.evaluate(() => (NW.app.ctrl.view.towers[0] || { mode: 'first' }).mode !== 'first'), 'Target tap did not change the targeting mode');
for (const a of ['up', 'sell', 'mode']) await must(page, `[data-act="${a}"]`, `after upgrade ${a}`);
// deselect: close button (phones), then tapping empty board
if (compact) {
await tapBtn(page, '[data-act="close"]', 'close');
check(await page.evaluate(() => NW.app.selTower === 0), 'close button did not deselect');
cp = await cellPt(10, 8); await tapAt(page, cp.x, cp.y); await sleep(200);
check(await page.evaluate(() => NW.app.selTower > 0), 'could not select the tower again');
}
const empty = await cellPt(11, 8); // an empty cell next to the tower (the action bar is on the other half of the stage)
await tapAt(page, empty.x, empty.y); await sleep(250);
check(await page.evaluate(() => NW.app.selTower === 0), 'tapping empty board did not deselect');
// sell
cp = await cellPt(10, 8); await tapAt(page, cp.x, cp.y); await sleep(200);
await tapBtn(page, '[data-act="sell"]', 'Sell');
check(await page.evaluate(() => NW.app.ctrl.view.towers.length === 0), 'Sell tap did not sell');
// end overlay buttons
await page.evaluate(() => { NW.app.ctrl.sim.lives = 0; NW.app.ctrl.sim.state = 'lost'; });
await sleep(400);
if (await page.evaluate(() => !document.getElementById('end').hidden)) {
await must(page, '#btnAgain', 'end Play again'); await must(page, '#btnEndMenu', 'end Menu');
await noOverflow(page, 'end'); await allButtonsBigEnough(page, 'end');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-end.png` });
} else fails.push('end overlay did not open when the game was lost');
for (const e of errors) fails.push(e);
await ctx.close();
}
// ------------------------------------------------ co-op host waiting for a partner (real room on the real server)
{
const { ctx, page, errors } = await mk();
await page.goto(URL); await sleep(250);
await tapBtn(page, '#btnCoop', 'menu Co-op');
await must(page, '#btnCreate', 'lobby Create room'); await must(page, '#btnJoin', 'lobby Join'); await must(page, '#btnLobbyBack', 'lobby Back');
// the host picks the difficulty here: reachable at every size, and the room is created on it
const lobbyIds = await page.evaluate(() => TD.DIFFICULTY_ORDER.slice());
for (const id of lobbyIds) await must(page, `#lobbyDiff [data-diff="${id}"]`, `lobby difficulty ${id}`);
await tapBtn(page, `#lobbyDiff [data-diff="hard"]`, 'lobby difficulty hard');
check(await page.evaluate(() => [...document.querySelectorAll('#lobbyDiff button')].filter((b) => b.getAttribute('aria-checked') === 'true').map((b) => b.dataset.diff).join()) === 'hard', 'tapping Hard in the lobby did not pick it');
await noOverflow(page, 'lobby'); await allButtonsBigEnough(page, 'lobby');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-lobby.png` });
await tapBtn(page, '#btnCreate', 'lobby Create room');
let joined = false;
for (let i = 0; i < 60 && !joined; i++) { joined = await page.evaluate(() => NW.app.inGame && NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'); if (!joined) await sleep(100); }
if (!joined) fails.push('could not create a co-op room');
else {
await sleep(300);
check(await page.evaluate(() => NW.app.ctrl.view.difficulty) === 'hard', 'the room was not created on the difficulty picked in the lobby');
// a first-time co-op player gets the first-run help too (code-26): same rule as solo, it needs a visible "Got it"
check(await page.evaluate(() => !document.getElementById('help').hidden), 'co-op first run: help overlay did not open');
await must(page, '#btnHelpClose', 'co-op help Got it');
const ph = await probe(page, '#btnHelpClose');
if (!ph.err) await tapAt(page, centre(ph).x, centre(ph).y);
await sleep(250);
check(await page.evaluate(() => document.getElementById('help').hidden), 'Got it did not close the co-op help overlay');
const room = await page.evaluate(() => NW.app.ctrl.room);
const chip = await must(page, '#netChip', 'room chip');
const txt = await page.evaluate(() => document.getElementById('netChip').innerText + ' ' + (document.getElementById('netChip').getAttribute('aria-label') || ''));
check(txt.includes(room), `room chip does not show the room code ${room}: "${txt}"`);
check(/invite|share/i.test(txt), `room chip does not offer to invite/share: "${txt}"`);
await noOverflow(page, 'co-op game');
const hud = await page.evaluate(() => { const tb = document.getElementById('topbar'); const kids = [...tb.children].filter((c) => !c.hidden && getComputedStyle(c).display !== 'none').map((c) => c.getBoundingClientRect()); return { clipped: kids.some((k) => k.right > innerWidth + 1 || k.left < -1), tbOver: tb.scrollWidth > tb.clientWidth + 1 }; });
check(!hud.clipped && !hud.tbOver, 'co-op top bar content overflows or is cut off');
for (const id of ['btnMenu', 'btnWave', 'btnPause', 'btnSound']) await must(page, '#' + id, 'co-op top bar ' + id);
await allButtonsBigEnough(page, 'co-op HUD');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-coop.png` });
void chip;
}
for (const e of errors) fails.push(e);
await page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } }); // leave the room for good (no 60 s grace period)
await ctx.close();
}
if (fails.length) { bad++; console.log('FAIL', tag); for (const f of fails) console.log(' - ' + f); allFails.push(tag + ': ' + fails.length); }
else console.log('ok ', tag);
}
if (bad) throw new Error(bad + ' of ' + SIZES.length + ' layouts have problems: ' + allFails.join(' | '));
console.log('all ' + SIZES.length + ' layouts ok');
};