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
This commit is contained in:
parent
962189419a
commit
28502984ec
29 changed files with 3370 additions and 230 deletions
|
|
@ -16,11 +16,38 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
|||
// lose
|
||||
await page.evaluate(() => { NW.app.ctrl.sim.lives = 1; });
|
||||
await page.click('#btnSpeed'); await page.click('#btnSpeed');
|
||||
await page.evaluate(() => { const e = document.getElementById('end'); new MutationObserver(() => { if (!e.hidden) window.__endAt = performance.now(); }).observe(e, { attributes: true, attributeFilter: ['hidden'] }); });
|
||||
await page.click('#btnWave');
|
||||
await until(() => page.evaluate(() => !document.getElementById('end').hidden), 60000, 'end overlay after losing');
|
||||
// a key-style click (detail 0: what Enter or Space on the focused button produces) inside the first 0.6 s must not press Play again: a player
|
||||
// who was tapping Enter for waves would skip the result. Measured in the page, so a slow machine cannot make this flaky.
|
||||
const early = await page.evaluate(() => { const age = performance.now() - window.__endAt; document.getElementById('btnAgain').click(); return { age, state: NW.app.ctrl.view.state, hidden: document.getElementById('end').hidden }; });
|
||||
assert(early.age >= 600 || (early.state === 'lost' && !early.hidden), 'Enter / Space on Play again ' + Math.round(early.age) + ' ms after the dialog opened does not press it');
|
||||
assert((await page.evaluate(() => document.getElementById('endTitle').textContent)) === 'Breach!', 'lose title');
|
||||
await page.screenshot({ path: OUT + 'end-lose.png' });
|
||||
await page.click('#btnAgain'); await sleep(300);
|
||||
|
||||
// the end screen is a real dialog (code-8, code-9, code-13): labelled, modal, focus inside on the primary button, the page behind it inert
|
||||
const dlg = await page.evaluate(() => {
|
||||
const e = document.getElementById('end'), lab = document.getElementById(e.getAttribute('aria-labelledby'));
|
||||
return { role: e.getAttribute('role'), modal: e.getAttribute('aria-modal'), label: lab && lab.textContent, active: document.activeElement.id, inert: ['topbar', 'stage', 'side'].map((id) => document.getElementById(id).hasAttribute('inert')) };
|
||||
});
|
||||
assert(dlg.role === 'dialog' && dlg.modal === 'true' && dlg.label === 'Breach!', 'the end overlay is role=dialog, aria-modal, named by its title: ' + JSON.stringify(dlg));
|
||||
assert(dlg.active === 'btnAgain', 'focus moved onto Play again: ' + dlg.active);
|
||||
assert(dlg.inert.every(Boolean), 'the top bar, board and side panel are inert behind it');
|
||||
const outside = [];
|
||||
for (let i = 0; i < 8; i++) { await page.keyboard.press('Tab'); outside.push(await page.evaluate(() => (document.activeElement.closest('#end') ? '' : document.activeElement.id || document.activeElement.tagName))); }
|
||||
assert(outside.every((x) => x === ''), 'Tab and Shift+Tab stay inside the dialog (8 Tabs): ' + JSON.stringify(outside));
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
assert(await page.evaluate(() => !!document.activeElement.closest('#end')), 'Shift+Tab too');
|
||||
await page.keyboard.press('m'); // (before Escape: the old code let Escape dismiss the dialog, after which M worked again)
|
||||
assert(await page.evaluate(() => NW.Audio.muted), 'M mutes on the end screen');
|
||||
await until(() => page.evaluate(() => document.getElementById('btnEndSound').textContent === 'Sound: off'), 1500, 'the end dialog sound button shows it');
|
||||
await page.keyboard.press('m');
|
||||
assert(!(await page.evaluate(() => NW.Audio.muted)), 'and unmutes');
|
||||
await page.keyboard.press('Escape'); await sleep(250);
|
||||
assert(await page.evaluate(() => !document.getElementById('end').hidden && NW.app.ctrl.view.state === 'lost'), 'Escape does not dismiss the game-over dialog (it used to leave a dead board with no buttons)');
|
||||
await page.focus('#btnAgain'); await sleep(700);
|
||||
await page.keyboard.press('Enter'); await sleep(300); // the keyboard path: Enter on the focused button
|
||||
let st = await page.evaluate(() => ({ s: NW.app.ctrl.view.state, hidden: document.getElementById('end').hidden, lives: NW.app.ctrl.view.lives, towers: NW.app.ctrl.view.towers.length, map: NW.app.ctrl.board.mapId }));
|
||||
assert(st.s === 'playing' && st.hidden && st.lives === 20 && st.towers === 0 && st.map === 'hub', 'play again resets the same map: ' + JSON.stringify(st));
|
||||
|
||||
|
|
@ -43,11 +70,19 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
|||
assert((await page.evaluate(() => NW.app.selType)) === null, 'escape clears');
|
||||
await page.keyboard.press('p'); assert((await page.evaluate(() => NW.app.ctrl.view.paused)) === true, 'p pauses');
|
||||
await page.keyboard.press('p');
|
||||
// menu while playing
|
||||
await page.click('#btnMenu'); await sleep(200);
|
||||
// menu while playing, by keyboard: Enter on the focused Menu button opens it (it used to start a wave), focus goes into the dialog and back
|
||||
const wave0 = await page.evaluate(() => NW.app.ctrl.view.wave);
|
||||
await page.focus('#btnMenu'); await page.keyboard.press('Enter'); await sleep(250);
|
||||
assert(!(await page.locator('#btnCloseMenu').isHidden()), 'menu has back-to-game while playing');
|
||||
assert((await page.evaluate(() => NW.app.ctrl.view.wave)) === wave0, 'Enter on the focused Menu button did not start a wave');
|
||||
assert((await page.evaluate(() => document.activeElement.id)) === 'btnSolo', 'focus moved into the menu dialog, onto its primary button');
|
||||
const lost = [];
|
||||
for (let i = 0; i < 16; i++) { await page.keyboard.press('Tab'); lost.push(await page.evaluate(() => (document.activeElement.closest('#menu') ? '' : document.activeElement.id || document.activeElement.tagName))); }
|
||||
assert(lost.every((x) => x === ''), 'Tab never reaches the HUD behind the menu (16 Tabs): ' + JSON.stringify(lost.filter(Boolean)));
|
||||
await page.keyboard.press('Escape'); await sleep(200);
|
||||
assert(await page.locator('#menu').isHidden(), 'escape closes the menu');
|
||||
assert((await page.evaluate(() => document.activeElement.id)) === 'btnMenu', 'and focus returns to the Menu button');
|
||||
assert(await page.evaluate(() => ['topbar', 'stage', 'side'].every((id) => !document.getElementById(id).hasAttribute('inert'))), 'the page is live again');
|
||||
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
|
||||
console.log('no console errors');
|
||||
};
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
|||
await until(() => A.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'), 5000, 'host joined');
|
||||
const room = await A.page.evaluate(() => NW.app.ctrl.room);
|
||||
assert(/^[A-Z0-9]{4}$/.test(room), 'room code ' + room);
|
||||
// a first-time player gets the help whether they start solo or join co-op (code-26); it is not shown again once seen
|
||||
assert(await A.page.evaluate(() => !document.getElementById('help').hidden), 'the first-run help is shown to a new co-op host');
|
||||
await A.page.click('#btnHelpClose');
|
||||
assert(await A.page.evaluate(() => document.getElementById('help').hidden && NW.app.inGame && !NW.app.ctrl.view.paused), 'closing it returns to the game');
|
||||
|
||||
// guest opens the invite link
|
||||
await B.page.goto(URL + '?room=' + room); await sleep(300);
|
||||
|
|
@ -27,6 +31,8 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
|||
await B.page.fill('#inName', 'Bob');
|
||||
await B.page.tap('#btnJoin');
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'), 5000, 'guest joined');
|
||||
assert(await B.page.evaluate(() => !document.getElementById('help').hidden), 'and to an invited guest');
|
||||
await B.page.tap('#btnHelpClose');
|
||||
await until(() => A.page.evaluate(() => NW.app.ctrl.players.length === 2), 3000, 'host sees 2 players');
|
||||
const slots = await Promise.all([A, B].map(p => p.page.evaluate(() => NW.app.ctrl.you.slot)));
|
||||
assert(slots[0] === 0 && slots[1] === 1, 'slots 0 and 1: ' + slots);
|
||||
|
|
|
|||
|
|
@ -32,6 +32,8 @@ if (process.env.MATRIX_ONLY) {
|
|||
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;
|
||||
|
|
@ -186,7 +188,7 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
|||
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' || vis.border !== 'rgb(77, 227, 255)') fails.push(`palette tile ${type}: selected state not visible (${JSON.stringify({ on: sp.on, blocked: sp.blocked, ...vis })})`);
|
||||
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`);
|
||||
|
|
@ -279,6 +281,13 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
|||
if (!joined) fails.push('could not create a co-op room');
|
||||
else {
|
||||
await sleep(300);
|
||||
// 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') || ''));
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
|||
await page.evaluate(() => document.getElementById('btnCreate').click());
|
||||
for (let i = 0; i < 60 && !(await page.evaluate(() => NW.app.inGame && NW.app.ctrl.status === 'joined')); i++) await sleep(100);
|
||||
await sleep(300);
|
||||
await page.evaluate(() => { if (!document.getElementById('help').hidden) document.getElementById('btnHelpClose').click(); }); await sleep(150); // (a first-time co-op player gets the help too)
|
||||
const room = await page.evaluate(() => NW.app.ctrl.room);
|
||||
const chip = await page.evaluate(() => { const e = document.getElementById('netChip'), r = e.getBoundingClientRect(); return { text: e.innerText, waiting: e.classList.contains('waiting'), w: r.width, h: r.height, inView: r.left >= 0 && r.right <= innerWidth && r.top >= 0 && r.bottom <= innerHeight }; });
|
||||
assert(chip.text.includes(room) && chip.inView && chip.h >= 43.5, `room chip shows ${room}, is on screen and 44px tall (${JSON.stringify(chip)})`);
|
||||
|
|
|
|||
122
e2e/scenarios/09-a11y.js
Normal file
122
e2e/scenarios/09-a11y.js
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Keyboard, focus and screen-reader basics (code-8, code-9, code-27, code-28). The end dialog is in 03-endflow, the sound
|
||||
* parts are in 09-audio.
|
||||
*
|
||||
* dialogs menu, help, lobby: role=dialog + aria-modal + a name; focus goes in (never into a text field), Tab stays in, the page
|
||||
* behind is inert, focus returns to where it was; Escape and "Got it" behave
|
||||
* labels palette tiles say when you cannot afford them, state is in the names (pressed / selected), contrast of the dim states
|
||||
* sink a hostile room code from the server is shown as text, not parsed as HTML (co-op)
|
||||
*/
|
||||
const { createServer } = require('../../server');
|
||||
|
||||
const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); };
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
async function until(fn, ms, what) { const t0 = Date.now(); for (;;) { try { const v = await fn(); if (v) return v; } catch (e) { /* retry */ } if (Date.now() - t0 > ms) throw new Error('TIMEOUT: ' + what); await sleep(40); } }
|
||||
|
||||
const active = (page) => page.evaluate(() => document.activeElement.id || document.activeElement.tagName);
|
||||
const inside = (page, sel) => page.evaluate((s) => !!document.activeElement.closest(s), sel);
|
||||
async function tabsStayIn(page, sel, n) {
|
||||
const out = [];
|
||||
for (let i = 0; i < n; i++) { await page.keyboard.press(i % 5 === 4 ? 'Shift+Tab' : 'Tab'); if (!(await inside(page, sel))) out.push(await active(page)); }
|
||||
return out;
|
||||
}
|
||||
const lum = (c) => { const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }; return 0.2126 * f(c[0]) + 0.7152 * f(c[1]) + 0.0722 * f(c[2]); };
|
||||
const ratio = (a, b) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };
|
||||
|
||||
module.exports = async function ({ browser, url }) {
|
||||
const errors = [];
|
||||
const ctx = await browser.newContext({ viewport: { width: 1100, height: 700 }, serviceWorkers: 'block' });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } }); // (the first-run help is tested in 04-coop)
|
||||
const page = await ctx.newPage();
|
||||
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
|
||||
page.on('console', (m) => { if (m.type() === 'error') errors.push('console.error: ' + m.text()); });
|
||||
try {
|
||||
await page.goto(url); await sleep(350);
|
||||
|
||||
console.log('--- dialogs');
|
||||
const roles = await page.evaluate(() => ['menu', 'lobby', 'help', 'end'].map((id) => { const e = document.getElementById(id), l = document.getElementById(e.getAttribute('aria-labelledby') || '-'); return [id, e.getAttribute('role'), e.getAttribute('aria-modal'), l ? l.textContent.trim() : '']; }));
|
||||
for (const [id, role, modal, name] of roles) assert(role === 'dialog' && modal === 'true' && name.length > 2, id + ' is a modal dialog named "' + name + '"');
|
||||
assert((await active(page)) === 'btnSolo', 'the menu opens with focus on Play solo (' + (await active(page)) + ')');
|
||||
assert(await page.evaluate(() => ['topbar', 'stage', 'side'].every((id) => document.getElementById(id).hasAttribute('inert'))), 'the page behind the menu is inert');
|
||||
let strays = await tabsStayIn(page, '#menu', 25);
|
||||
assert(strays.length === 0, 'Tab and Shift+Tab never leave the menu (25 presses): ' + JSON.stringify(strays));
|
||||
|
||||
await page.click('#btnHelp');
|
||||
assert((await active(page)) === 'btnHelpClose', 'How to play: focus on "Got it" (' + (await active(page)) + ')');
|
||||
strays = await tabsStayIn(page, '#help', 6);
|
||||
assert(strays.length === 0, 'Tab stays in the help dialog');
|
||||
await page.keyboard.press('Enter'); await sleep(200);
|
||||
assert((await page.locator('#menu').isVisible()) && (await page.locator('#help').isHidden()), 'Enter on "Got it" returns to the menu');
|
||||
assert((await active(page)) === 'btnSolo', 'with focus back on Play solo');
|
||||
|
||||
await page.click('#btnCoop');
|
||||
assert((await active(page)) === 'btnCreate', 'the lobby puts focus on Create room, not into a text field (that would raise the keyboard on a phone): ' + (await active(page)));
|
||||
strays = await tabsStayIn(page, '#lobby', 14);
|
||||
assert(strays.length === 0, 'Tab stays in the lobby: ' + JSON.stringify(strays));
|
||||
await page.click('#btnLobbyBack'); await sleep(150);
|
||||
assert((await page.locator('#menu').isVisible()), 'Back returns to the menu');
|
||||
// an invite link opens the lobby with the code filled in: the focused button must join that room (Enter on Create room would open a new one)
|
||||
const pi = await ctx.newPage();
|
||||
try {
|
||||
await pi.goto(url + '?room=ABCD'); await sleep(350);
|
||||
assert((await pi.locator('#lobby').isVisible()) && (await pi.inputValue('#inCode')) === 'ABCD', 'an invite link opens the lobby with the code filled in');
|
||||
assert((await active(pi)) === 'btnJoin', 'and focus is on Join, not Create room (' + (await active(pi)) + ')');
|
||||
} finally { await pi.close(); }
|
||||
|
||||
await page.click('#btnSolo'); await sleep(200);
|
||||
assert(await page.evaluate(() => ['topbar', 'stage', 'side'].every((id) => !document.getElementById(id).hasAttribute('inert'))), 'in the game nothing is inert');
|
||||
// keyboard users: the help opens from a focused control and gives focus back to it
|
||||
await page.focus('#btnPause');
|
||||
await page.keyboard.press('?'); await sleep(200);
|
||||
assert((await page.locator('#help').isVisible()) && (await active(page)) === 'btnHelpClose', 'the ? key opens help with focus inside');
|
||||
await page.keyboard.press('Escape'); await sleep(200);
|
||||
assert(await page.locator('#help').isHidden(), 'Escape closes help');
|
||||
assert((await active(page)) === 'btnPause', 'and focus is back on the Pause button where it was (' + (await active(page)) + ')');
|
||||
|
||||
console.log('--- labels');
|
||||
await page.evaluate(() => { NW.app.ctrl.sim.gold = 0; });
|
||||
await until(() => page.evaluate(() => [...document.querySelectorAll('#palette .tbtn')].every((b) => /not enough credits/.test(b.getAttribute('aria-label')))), 1500, 'palette tiles say "not enough credits"');
|
||||
assert(await page.evaluate(() => [...document.querySelectorAll('#palette .tbtn')].every((b) => b.classList.contains('poor'))), 'the same tiles are the dimmed ones');
|
||||
await page.evaluate(() => { NW.app.ctrl.sim.gold = 100000; });
|
||||
await until(() => page.evaluate(() => [...document.querySelectorAll('#palette .tbtn')].every((b) => !/not enough/.test(b.getAttribute('aria-label')) && /credits$/.test(b.getAttribute('aria-label')))), 1500, 'and the plain name again once affordable');
|
||||
await page.keyboard.press('2');
|
||||
assert((await page.getAttribute('#palette .tbtn[data-type="filter"]', 'aria-pressed')) === 'true', 'the selected tower tile is aria-pressed');
|
||||
await page.keyboard.press('Escape');
|
||||
assert((await page.getAttribute('#mapPick .mapcard[aria-checked="true"]', 'role')) === 'radio', 'map cards are radios with a checked state');
|
||||
// contrast (guard: these were fixed before this work): the dimmed cost and a disabled button against their backgrounds, WCAG AA 4.5:1
|
||||
await page.evaluate(() => { NW.app.ctrl.sim.gold = 0; }); await sleep(200);
|
||||
const cols = await page.evaluate(() => {
|
||||
const rgb = (s) => (s.match(/[\d.]+/g) || []).slice(0, 3).map(Number);
|
||||
const cost = document.querySelector('#palette .tbtn.poor .cost'), nm = document.querySelector('#palette .tbtn.poor .nm'), tile = document.querySelector('#palette .tbtn.poor');
|
||||
const bg = rgb(getComputedStyle(tile).backgroundColor);
|
||||
const eff = (el) => { const cs = getComputedStyle(el); return { c: rgb(cs.color), op: parseFloat(cs.opacity) }; };
|
||||
return { bg, cost: eff(cost), nm: eff(nm), opTile: parseFloat(getComputedStyle(tile).opacity) };
|
||||
});
|
||||
assert(cols.cost.op === 1 && cols.nm.op === 1 && cols.opTile === 1, '(guard) the unaffordable state does not fade text with opacity');
|
||||
assert(ratio(cols.cost.c, cols.bg) >= 4.5 && ratio(cols.nm.c, cols.bg) >= 4.5, '(guard) unaffordable cost and name keep >= 4.5:1 contrast (' + ratio(cols.cost.c, cols.bg).toFixed(1) + ', ' + ratio(cols.nm.c, cols.bg).toFixed(1) + ')');
|
||||
|
||||
console.log('--- sink');
|
||||
const srv = await createServer({ port: 0, host: '127.0.0.1', log: () => {}, pingMs: 0 });
|
||||
const ctx2 = await browser.newContext({ viewport: { width: 1100, height: 700 }, serviceWorkers: 'block' });
|
||||
await ctx2.addInitScript(() => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } });
|
||||
const p2 = await ctx2.newPage();
|
||||
p2.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
|
||||
try {
|
||||
await p2.goto('http://127.0.0.1:' + srv.port + '/'); await sleep(300);
|
||||
await p2.click('#btnCoop'); await p2.fill('#inName', 'Alice'); await p2.click('#btnCreate');
|
||||
await until(() => p2.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'), 6000, 'joined');
|
||||
await p2.evaluate(() => { const c = NW.app.ctrl; c.room = '<b id="pwn">x</b><img src=x onerror="window.__xss=1">'; c.emit('players', c.players); });
|
||||
await sleep(300);
|
||||
const r = await p2.evaluate(() => ({ injected: !!document.querySelector('#players #pwn, #players img'), text: document.querySelector('#players h4').textContent, xss: window.__xss || 0 }));
|
||||
assert(!r.injected && r.xss === 0, 'a hostile room code creates no elements in the players panel');
|
||||
assert(r.text.includes('<b id="pwn">'), 'it is shown as plain text: ' + r.text.slice(0, 40));
|
||||
await p2.evaluate(() => { NW.app.ctrl.room = 'A&B C'; navigator.share = (d) => { window.__shared = d; return Promise.resolve(); }; });
|
||||
await p2.click('#netChip'); await sleep(150);
|
||||
const shared = await p2.evaluate(() => window.__shared);
|
||||
assert(shared && /\?room=A%26B%20C$/.test(shared.url), 'the invite link carries the code encoded: ' + (shared && shared.url));
|
||||
} finally { await ctx2.close(); await srv.close(); }
|
||||
} finally { await ctx.close(); }
|
||||
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
|
||||
console.log('no console errors');
|
||||
};
|
||||
397
e2e/scenarios/09-audio.js
Normal file
397
e2e/scenarios/09-audio.js
Normal file
|
|
@ -0,0 +1,397 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Real audio, real files (public/assets/music via tracks.json), real Chromium. Every check reads the HTMLAudioElement itself
|
||||
* (paused, volume, currentTime), not only NW.Audio.now: the old code said "playing" while the element had been paused.
|
||||
*
|
||||
* flow theme -> battle -> boss -> lose stinger -> Play again -> battle -> win stinger -> Keep going, with and without
|
||||
* --autoplay-policy=no-user-gesture-required; one element and one download per track; boss and stingers preloaded (code-12, code-16)
|
||||
* rapid five music() calls in one tick; M twice within 90 ms; M during the fade-in; Play again 100 ms after the end (code-7, code-16)
|
||||
* mute M and the sound buttons work on the end screen and stop the stinger; state in the labels (code-13, code-27)
|
||||
* late a stinger that loads late never plays over the next game (code-12)
|
||||
* fallback a track that never answers or fails: synth within seconds, the file is used again later (code-15)
|
||||
* gesture play() refused by the browser (iOS / Safari rules): retried at the next tap; strict "only inside a gesture" stub (code-14)
|
||||
* coop Play again and Keep going start the music for BOTH players and stop the stinger (code-5)
|
||||
*
|
||||
* Headless Chromium resolves play() without a gesture whatever --autoplay-policy says, so code-14 is proven with a stub of the
|
||||
* browser's rule, not with the flag.
|
||||
*/
|
||||
const { chromium } = require('playwright-core');
|
||||
const { createServer } = require('../../server');
|
||||
|
||||
const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); };
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
async function until(fn, ms, what) { const t0 = Date.now(); for (;;) { try { const v = await fn(); if (v) return v; } catch (e) { /* retry */ } if (Date.now() - t0 > ms) throw new Error('TIMEOUT: ' + what); await sleep(40); } }
|
||||
|
||||
// Injected before the game's scripts: every Audio element is recorded, so a test can look at all of them.
|
||||
function instrument() {
|
||||
window.__els = [];
|
||||
const A = window.Audio;
|
||||
window.Audio = function (src) { const el = src === undefined ? new A() : new A(src); window.__els.push(el); return el; };
|
||||
window.Audio.prototype = A.prototype;
|
||||
const nm = (e) => ((e.src || '').split('/').pop() || '').replace(/\.mp3$/, '');
|
||||
window.__info = () => window.__els.map((e) => ({ n: nm(e), playing: !e.paused && !e.ended, vol: +e.volume.toFixed(2), t: +e.currentTime.toFixed(2), rs: e.readyState, err: e.error ? e.error.code : 0 }));
|
||||
try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } // (the first-run help is tested elsewhere)
|
||||
}
|
||||
// The browser's rule on iOS / Safari, as a stub: play() is only allowed inside the dispatch of a tap, click or key press.
|
||||
function strictPolicy() {
|
||||
window.__gesture = false; window.__refused = 0;
|
||||
for (const ev of ['pointerdown', 'pointerup', 'keydown', 'click', 'touchend']) {
|
||||
window.addEventListener(ev, (e) => {
|
||||
if (ev === 'pointerdown' && e.pointerType !== 'mouse') return; // (HTML: only a mouse press activates the page; a finger counts when it lifts)
|
||||
window.__gesture = true; setTimeout(() => { window.__gesture = false; }, 0);
|
||||
}, true);
|
||||
}
|
||||
const P = HTMLMediaElement.prototype.play;
|
||||
HTMLMediaElement.prototype.play = function () {
|
||||
if (!window.__gesture) { window.__refused++; return Promise.reject(new DOMException('play() failed: not allowed', 'NotAllowedError')); }
|
||||
return P.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
// The refusal is the test's to switch: "the user has not allowed it yet" / "now they have".
|
||||
function denyPolicy() {
|
||||
window.__deny = true; window.__refused = 0;
|
||||
const P = HTMLMediaElement.prototype.play;
|
||||
HTMLMediaElement.prototype.play = function () {
|
||||
if (window.__deny) { window.__refused++; return Promise.reject(new DOMException('play() failed: not allowed', 'NotAllowedError')); }
|
||||
return P.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
|
||||
const FILES = { theme: 'menu', battle: 'battle', boss: 'boss', win: 'win', lose: 'lose' };
|
||||
const elsOf = async (page, n) => (await page.evaluate(() => window.__info())).filter((e) => e.n === n);
|
||||
const audible = async (page, n) => (await elsOf(page, n)).some((e) => e.playing && e.vol > 0.05);
|
||||
const silent = async (page, n) => (await elsOf(page, n)).every((e) => !e.playing);
|
||||
const nowOf = (page) => page.evaluate(() => { const n = NW.Audio.now; return n ? n.name + ':' + n.kind : null; });
|
||||
const state = (page) => page.evaluate(() => NW.app.ctrl.view.state);
|
||||
const endShown = (page) => page.evaluate(() => !document.getElementById('end').hidden);
|
||||
async function advancing(page, n) { // the file really plays: its clock runs
|
||||
const a = (await elsOf(page, n)).find((e) => e.playing); if (!a) return false;
|
||||
await sleep(450);
|
||||
const b = (await elsOf(page, n)).find((e) => e.playing);
|
||||
return !!b && b.t > a.t + 0.2;
|
||||
}
|
||||
async function newPage(browser, errors, setup, opts) {
|
||||
const ctx = await browser.newContext(Object.assign({ viewport: { width: 1100, height: 700 }, serviceWorkers: 'block' }, opts || {}));
|
||||
await ctx.addInitScript(instrument);
|
||||
if (setup) await ctx.addInitScript(setup);
|
||||
const page = await ctx.newPage();
|
||||
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
|
||||
page.on('console', (m) => { if (m.type() === 'error' && !/Failed to load resource|net::ERR/.test(m.text())) errors.push('console.error: ' + m.text()); });
|
||||
return { ctx, page };
|
||||
}
|
||||
async function startSolo(page, url) {
|
||||
await page.goto(url); await sleep(350);
|
||||
await page.click('#btnSolo');
|
||||
await until(() => page.evaluate(() => NW.app.inGame), 2000, 'in game');
|
||||
}
|
||||
const lose = (page) => page.evaluate(() => { NW.app.ctrl.sim.lives = 0; });
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ flow
|
||||
async function flow(browser, url, errors, tag) {
|
||||
console.log('--- flow (' + tag + ')');
|
||||
const { ctx, page } = await newPage(browser, errors);
|
||||
try {
|
||||
await page.goto(url); await sleep(350);
|
||||
const manifest = await page.evaluate(() => fetch('assets/music/tracks.json').then((r) => r.json()));
|
||||
for (const n of Object.keys(FILES)) assert(typeof manifest[n] === 'string', 'tracks.json names a real file for ' + n);
|
||||
assert((await nowOf(page)) === null, 'nothing plays before the first gesture');
|
||||
await page.mouse.click(8, 8);
|
||||
await until(async () => (await nowOf(page)) === 'theme:file' && await audible(page, 'menu'), 4000, 'menu theme plays from the file after the first tap');
|
||||
assert(await advancing(page, 'menu'), 'menu.mp3 clock runs');
|
||||
|
||||
await page.click('#btnSolo');
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 4000, 'battle music starts');
|
||||
await until(() => silent(page, 'menu'), 3000, 'the menu theme is paused after the crossfade');
|
||||
assert(await advancing(page, 'battle'), 'battle.mp3 clock runs');
|
||||
// the stingers load in the background once the battle track plays: the end screen has them ready
|
||||
await until(async () => (await elsOf(page, 'lose')).length === 1 && (await elsOf(page, 'win')).length === 1, 6000, 'win and lose are preloaded after the battle track starts');
|
||||
await until(async () => (await elsOf(page, 'lose'))[0].rs >= 3, 6000, 'lose.mp3 is ready before it is needed');
|
||||
|
||||
// boss: wave 8 is the wave before it, so the panel announces wave 9 and the boss track is fetched ahead
|
||||
await page.evaluate(() => { NW.app.ctrl.sim.wave = 8; });
|
||||
await until(async () => (await elsOf(page, 'boss')).length === 1, 3000, 'boss.mp3 is requested a wave or two ahead');
|
||||
assert(await silent(page, 'boss'), '... but not played');
|
||||
await until(async () => (await elsOf(page, 'boss'))[0].rs >= 3, 8000, 'boss.mp3 is ready before the boss');
|
||||
await page.evaluate(() => { const s = NW.app.ctrl.sim; s.wave = 10; s.spawnQ.push({ t: 0, k: 'rootkit', wave: 10 }); });
|
||||
await until(async () => (await nowOf(page)) === 'boss:file' && await audible(page, 'boss'), 4000, 'boss music takes over when the rootkit appears');
|
||||
await until(() => silent(page, 'battle'), 3000, 'battle is paused while the boss plays');
|
||||
await page.evaluate(() => { const s = NW.app.ctrl.sim; s.monsters.length = 0; s.spawnQ.length = 0; });
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 4000, 'battle music is back when the boss is gone');
|
||||
await until(() => silent(page, 'boss'), 3000, 'boss is paused again');
|
||||
|
||||
// lose: the music stops, the stinger plays
|
||||
await lose(page);
|
||||
await until(() => endShown(page), 4000, 'end screen');
|
||||
await until(async () => (await nowOf(page)) === null && await audible(page, 'lose'), 3000, 'the lose stinger plays, the music is off');
|
||||
await until(() => silent(page, 'battle'), 3000, 'battle is paused on the end screen');
|
||||
await sleep(700);
|
||||
await page.click('#btnAgain');
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 4000, 'Play again: battle music again');
|
||||
await until(() => silent(page, 'lose'), 3000, 'the lose stinger stops with the new game');
|
||||
assert(await advancing(page, 'battle'), 'battle clock runs after Play again');
|
||||
|
||||
// win and Keep going
|
||||
await page.evaluate(() => { const s = NW.app.ctrl.sim; s.wave = 1; s.winWave = 1; });
|
||||
await until(async () => (await state(page)) === 'won' && await audible(page, 'win'), 4000, 'the win stinger plays');
|
||||
await until(() => silent(page, 'battle'), 3000, 'battle is paused on the win screen');
|
||||
await sleep(700);
|
||||
await page.click('#btnContinue');
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 4000, 'Keep going: battle music again');
|
||||
await until(() => silent(page, 'win'), 3000, 'the win stinger stops');
|
||||
|
||||
const info = await page.evaluate(() => window.__info());
|
||||
for (const n of ['menu', 'battle', 'boss', 'win', 'lose']) assert(info.filter((e) => e.n === n).length === 1, 'exactly one audio element for ' + n + ' in the whole session');
|
||||
} finally { await ctx.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ rapid
|
||||
async function rapid(browser, url, errors) {
|
||||
console.log('--- rapid: calls faster than loads and fades');
|
||||
const { ctx, page } = await newPage(browser, errors);
|
||||
try {
|
||||
await page.goto(url); await sleep(350);
|
||||
await page.mouse.click(8, 8);
|
||||
await until(async () => (await nowOf(page)) === 'theme:file', 4000, 'theme');
|
||||
await page.evaluate(() => { for (const n of ['battle', 'theme', 'battle', 'theme', 'battle']) NW.Audio.music(n); });
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 4000, 'five music() calls in one tick end on battle');
|
||||
await until(() => silent(page, 'menu'), 3000, 'and the theme is stopped');
|
||||
const els = await page.evaluate(() => window.__info());
|
||||
assert(els.filter((e) => e.n === 'battle').length === 1 && els.filter((e) => e.n === 'menu').length === 1, 'one element per track (battle ' + els.filter((e) => e.n === 'battle').length + ', menu ' + els.filter((e) => e.n === 'menu').length + ')');
|
||||
// mute twice within 90 ms: net unmuted, the music must be playing and stay playing
|
||||
await page.evaluate(() => { NW.Audio.music(null); NW.Audio.music('battle'); });
|
||||
await page.click('#btnSolo'); await sleep(2500);
|
||||
await page.keyboard.press('m'); await sleep(90); await page.keyboard.press('m');
|
||||
await sleep(2500);
|
||||
assert(!(await page.evaluate(() => NW.Audio.muted)), 'M, M: not muted');
|
||||
assert(await audible(page, 'battle') && await advancing(page, 'battle'), 'M, M within 90 ms: the battle element still plays (a stale fade-out used to pause it)');
|
||||
// mute during the fade-in, then unmute during the fade-out
|
||||
await page.evaluate(() => { NW.Audio.music(null); }); await sleep(700);
|
||||
await page.evaluate(() => NW.Audio.music('battle')); await sleep(250); // fading in
|
||||
await page.keyboard.press('m');
|
||||
await until(() => silent(page, 'battle'), 2000, 'M during the fade-in silences the music');
|
||||
await sleep(1800);
|
||||
assert(await silent(page, 'battle') && (await nowOf(page)) === null, 'and the fade-in does not bring it back');
|
||||
await page.keyboard.press('m');
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 3000, 'unmute brings the music back');
|
||||
await page.keyboard.press('m'); await sleep(80); await page.keyboard.press('m'); // mute, and unmute inside the fade-out
|
||||
await sleep(2200);
|
||||
assert(await audible(page, 'battle') && await advancing(page, 'battle'), 'mute undone during its own fade-out: still playing');
|
||||
|
||||
// Play again 100 ms after the end screen opens: inside the old fade-out of the music
|
||||
await lose(page);
|
||||
await until(() => endShown(page), 4000, 'end screen');
|
||||
await sleep(100);
|
||||
await page.click('#btnAgain');
|
||||
await sleep(2500);
|
||||
assert(await audible(page, 'battle') && await advancing(page, 'battle'), 'Play again 100 ms after the end screen: battle plays');
|
||||
} finally { await ctx.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ mute
|
||||
async function mute(browser, url, errors) {
|
||||
console.log('--- mute: the end screen and the labels');
|
||||
const { ctx, page } = await newPage(browser, errors);
|
||||
try {
|
||||
await startSolo(page, url);
|
||||
await until(async () => await audible(page, 'battle'), 4000, 'battle plays');
|
||||
assert((await page.getAttribute('#btnSound', 'aria-label')) === 'Mute sound', 'Sound button: "Mute sound" while the sound is on');
|
||||
await page.click('#btnSpeed');
|
||||
await until(async () => (await page.getAttribute('#btnSpeed', 'aria-label')) === 'Game speed 2×', 1500, 'the speed button says the speed: Game speed 2×');
|
||||
await page.click('#btnSpeed'); await page.click('#btnSpeed');
|
||||
await until(async () => (await page.getAttribute('#btnSpeed', 'aria-label')) === 'Game speed 1×', 1500, 'and back to 1×');
|
||||
await page.click('#btnPause');
|
||||
await until(async () => (await page.getAttribute('#btnPause', 'aria-pressed')) === 'true', 1500, 'Pause is pressed while paused');
|
||||
assert((await page.getAttribute('#btnPause', 'aria-label')) === 'Pause', 'and keeps its name "Pause" (a toggle does not rename itself)');
|
||||
await page.click('#btnPause');
|
||||
await lose(page);
|
||||
await until(() => endShown(page), 4000, 'end screen');
|
||||
await until(async () => await audible(page, 'lose'), 3000, 'lose stinger plays');
|
||||
const covered = await page.evaluate(() => { const b = document.getElementById('btnSound').getBoundingClientRect(); const e = document.elementFromPoint(b.left + b.width / 2, b.top + b.height / 2); return !!e && !!e.closest('#end'); });
|
||||
assert(covered, 'the top-bar Sound button is behind the end dialog (so the dialog has its own)');
|
||||
await page.keyboard.press('m');
|
||||
assert(await page.evaluate(() => NW.Audio.muted), 'M on the end screen mutes');
|
||||
await until(() => silent(page, 'lose'), 2000, 'and the stinger stops');
|
||||
assert((await page.locator('#btnEndSound').count()) === 1 && (await page.isVisible('#btnEndSound')), 'the end dialog has its own sound button');
|
||||
await until(async () => (await page.textContent('#btnEndSound')) === 'Sound: off', 1500, 'the end dialog button follows: Sound: off');
|
||||
assert((await page.getAttribute('#btnSound', 'aria-label')) === 'Unmute sound', 'the top-bar button name is now "Unmute sound"');
|
||||
await sleep(700);
|
||||
await page.click('#btnAgain');
|
||||
await sleep(2200);
|
||||
assert((await nowOf(page)) === null && await silent(page, 'battle'), 'a new game while muted stays silent');
|
||||
await lose(page);
|
||||
await until(() => endShown(page), 4000, 'end screen again');
|
||||
await sleep(900);
|
||||
assert(await silent(page, 'lose'), 'no stinger while muted');
|
||||
await page.click('#btnEndSound');
|
||||
assert(!(await page.evaluate(() => NW.Audio.muted)), 'the end dialog button unmutes');
|
||||
await until(async () => (await page.textContent('#btnEndSound')) === 'Sound: on', 1500, 'and shows it');
|
||||
await sleep(700);
|
||||
await page.click('#btnAgain');
|
||||
await until(async () => await audible(page, 'battle'), 4000, 'unmuted: battle plays again');
|
||||
// menu: M and the menu's own button
|
||||
await page.click('#btnMenu');
|
||||
await page.keyboard.press('m');
|
||||
assert(await page.evaluate(() => NW.Audio.muted), 'M mutes in the menu');
|
||||
await until(async () => (await page.textContent('#btnMenuSound')) === 'Sound: off', 1500, 'the menu button follows: Sound: off');
|
||||
await page.click('#btnMenuSound');
|
||||
assert(!(await page.evaluate(() => NW.Audio.muted)), 'the menu button unmutes');
|
||||
} finally { await ctx.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ late stinger
|
||||
async function late(browser, url, errors) {
|
||||
console.log('--- late: a stinger that arrives after Play again');
|
||||
const { ctx, page } = await newPage(browser, errors);
|
||||
try {
|
||||
await page.route('**/assets/music/lose.mp3', async (route) => { await sleep(2500); try { await route.continue(); } catch (e) { /* page closed */ } });
|
||||
await startSolo(page, url);
|
||||
await until(async () => await audible(page, 'battle'), 4000, 'battle plays');
|
||||
await lose(page); // (before the stingers are preloaded: lose.mp3 is first requested now)
|
||||
await until(() => endShown(page), 4000, 'end screen');
|
||||
await sleep(700);
|
||||
await page.click('#btnAgain');
|
||||
const t0 = Date.now(); let bad = 0;
|
||||
while (Date.now() - t0 < 6500) { // (the first 1.5 s: a stinger that is still loading has `paused` false but makes no sound, and a loaded one is fading out)
|
||||
if (Date.now() - t0 > 1500 && (await elsOf(page, 'lose')).some((e) => e.playing && e.vol > 0.05 && e.rs >= 3)) bad++;
|
||||
await sleep(100);
|
||||
}
|
||||
assert(bad === 0, 'the late lose stinger never played over the new game');
|
||||
assert(await audible(page, 'battle'), 'the battle music plays');
|
||||
} finally { await ctx.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ fallback
|
||||
async function fallback(browser, url, errors) {
|
||||
console.log('--- fallback: a track that never answers, and one that fails');
|
||||
const { ctx, page } = await newPage(browser, errors);
|
||||
try {
|
||||
let held = null;
|
||||
await page.route('**/assets/music/battle.mp3', (route) => { if (!held) held = route; else route.continue().catch(() => {}); }); // the first request hangs: no bytes, no error
|
||||
await startSolo(page, url);
|
||||
const t0 = Date.now();
|
||||
await until(async () => (await nowOf(page)) === 'battle:synth', 9000, 'a file that never answers: the synth takes over');
|
||||
const took = Date.now() - t0;
|
||||
assert(took < 7500, 'within ' + took + ' ms (it was 10 to 35 s, or never)');
|
||||
assert(await silent(page, 'battle'), 'the stalled element is not playing');
|
||||
if (held) await held.continue().catch(() => {}); // the server answers at last
|
||||
await until(async () => (await elsOf(page, 'battle')).some((e) => e.rs >= 3), 8000, 'the file arrives');
|
||||
await page.evaluate(() => { NW.Audio.music('theme'); });
|
||||
await sleep(300);
|
||||
await page.evaluate(() => { NW.Audio.music('battle'); });
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 4000, 'the next time the track is wanted, the file plays');
|
||||
assert((await elsOf(page, 'battle')).length === 1, 'still one element');
|
||||
} finally { await ctx.close(); }
|
||||
|
||||
const b2 = await newPage(browser, errors);
|
||||
try {
|
||||
await b2.page.route('**/assets/music/battle.mp3', (route) => route.abort());
|
||||
await startSolo(b2.page, url);
|
||||
await until(async () => (await nowOf(b2.page)) === 'battle:synth', 3000, 'a file that fails: the synth takes over at once');
|
||||
await b2.page.unroute('**/assets/music/battle.mp3');
|
||||
await b2.page.evaluate(() => { if (NW.Audio.timing) NW.Audio.timing.retry = 500; });
|
||||
await sleep(800);
|
||||
await b2.page.evaluate(() => { NW.Audio.music('theme'); });
|
||||
await sleep(300);
|
||||
await b2.page.evaluate(() => { NW.Audio.music('battle'); });
|
||||
await until(async () => (await nowOf(b2.page)) === 'battle:file' && await audible(b2.page, 'battle'), 5000, 'after the server is back the file is tried again (it used to stay synth for the whole session)');
|
||||
} finally { await b2.ctx.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ gesture
|
||||
async function gesture(browser, url, errors) {
|
||||
console.log('--- gesture: play() refused until the user allows it (code-14)');
|
||||
let T = await newPage(browser, errors, denyPolicy);
|
||||
try {
|
||||
const page = T.page;
|
||||
await page.goto(url); await sleep(350);
|
||||
await page.mouse.click(8, 8);
|
||||
await sleep(900);
|
||||
assert((await nowOf(page)) === null && (await page.evaluate(() => window.__refused)) >= 1, 'the first tap: play() was refused, nothing plays (refused ' + (await page.evaluate(() => window.__refused)) + 'x)');
|
||||
await page.evaluate(() => { window.__deny = false; });
|
||||
await page.mouse.click(8, 8);
|
||||
await until(async () => (await nowOf(page)) === 'theme:file' && await audible(page, 'menu'), 3000, 'the next tap retries it: the theme plays');
|
||||
assert((await elsOf(page, 'menu')).length === 1, 'on the same element');
|
||||
} finally { await T.ctx.close(); }
|
||||
|
||||
console.log('--- gesture: play() only inside a tap (the strict stub)');
|
||||
T = await newPage(browser, errors, strictPolicy);
|
||||
try {
|
||||
const page = T.page;
|
||||
await page.goto(url); await sleep(500);
|
||||
await page.mouse.click(8, 8);
|
||||
await until(async () => (await nowOf(page)) === 'theme:file' && await audible(page, 'menu'), 3000, 'the first tap starts the theme: play() is called inside the tap');
|
||||
await page.click('#btnSolo');
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 3000, 'Play solo starts the battle music inside the tap');
|
||||
// the boss track is started by the game loop, outside any tap: refused, and waiting for the next one
|
||||
await page.evaluate(() => { const s = NW.app.ctrl.sim; s.wave = 10; s.spawnQ.push({ t: 0, k: 'rootkit', wave: 10 }); });
|
||||
await until(async () => (await page.evaluate(() => NW.Audio.blocked === true)) || (await nowOf(page)) === 'boss:file', 4000, 'the boss track is either refused or plays');
|
||||
await page.mouse.click(300, 300);
|
||||
await until(async () => (await nowOf(page)) === 'boss:file' && await audible(page, 'boss'), 3000, 'the next tap on the board starts it');
|
||||
} finally { await T.ctx.close(); }
|
||||
|
||||
console.log('--- gesture: a finger (pointerdown is no gesture, the lift is)');
|
||||
T = await newPage(browser, errors, strictPolicy, { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
|
||||
try {
|
||||
const page = T.page;
|
||||
await page.goto(url); await sleep(500);
|
||||
await page.touchscreen.tap(195, 30);
|
||||
await until(async () => (await nowOf(page)) === 'theme:file' && await audible(page, 'menu'), 3000, 'the first tap of a finger starts the theme (the press was refused, the lift retried it)');
|
||||
assert((await elsOf(page, 'menu')).length === 1, 'on one element');
|
||||
await page.tap('#btnSolo');
|
||||
await until(async () => (await nowOf(page)) === 'battle:file' && await audible(page, 'battle'), 3000, 'Play solo by finger starts the battle music');
|
||||
} finally { await T.ctx.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ coop
|
||||
async function coop(browser, errors) {
|
||||
console.log('--- coop: Play again and Keep going start the music for both players');
|
||||
const srv = await createServer({ port: 0, host: '127.0.0.1', log: () => {}, pingMs: 0 }), url = 'http://127.0.0.1:' + srv.port + '/';
|
||||
const A = await newPage(browser, errors), B = await newPage(browser, errors);
|
||||
try {
|
||||
const joined = (P) => P.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined');
|
||||
await A.page.goto(url); await sleep(300);
|
||||
await A.page.click('#btnCoop'); await A.page.fill('#inName', 'Alice'); await A.page.click('#btnCreate');
|
||||
await until(() => joined(A), 6000, 'host joined');
|
||||
const room = await A.page.evaluate(() => NW.app.ctrl.room);
|
||||
await B.page.goto(url + '?room=' + room); await sleep(300);
|
||||
await B.page.fill('#inName', 'Bob'); await B.page.click('#btnJoin');
|
||||
await until(() => joined(B), 6000, 'guest joined');
|
||||
const R = srv.rooms.get(room);
|
||||
const both = async (fn) => (await fn(A.page)) && (await fn(B.page));
|
||||
await until(() => both(async (p) => (await nowOf(p)) === 'battle:file' && await audible(p, 'battle')), 5000, 'both hear the battle music');
|
||||
|
||||
R.sim.lives = 0;
|
||||
await until(() => both(endShown), 5000, 'both see the end screen');
|
||||
await until(() => both(async (p) => (await nowOf(p)) === null && await audible(p, 'lose')), 4000, 'both: stinger on, music off');
|
||||
await sleep(700);
|
||||
await A.page.click('#btnAgain');
|
||||
await until(() => both(async (p) => (await state(p)) === 'playing' && !(await endShown(p))), 4000, 'new game on both');
|
||||
await until(() => both(async (p) => (await nowOf(p)) === 'battle:file' && await audible(p, 'battle')), 4000, 'Play again: the battle music plays on the host AND on the guest');
|
||||
await until(() => both((p) => silent(p, 'lose')), 3000, 'and the lose stinger stopped on both');
|
||||
|
||||
R.sim.wave = 1; R.sim.winWave = 1;
|
||||
await until(() => both(async (p) => (await state(p)) === 'won' && await audible(p, 'win')), 5000, 'both: win stinger');
|
||||
await sleep(700);
|
||||
await A.page.click('#btnContinue');
|
||||
await until(() => both(async (p) => (await state(p)) === 'playing' && !(await endShown(p))), 4000, 'the game goes on for both');
|
||||
await until(() => both(async (p) => (await nowOf(p)) === 'battle:file' && await audible(p, 'battle')), 4000, 'Keep going: the battle music plays on the host AND on the guest');
|
||||
await until(() => both((p) => silent(p, 'win')), 3000, 'and the win stinger stopped on both');
|
||||
} finally { await A.ctx.close(); await B.ctx.close(); await srv.close(); }
|
||||
}
|
||||
|
||||
module.exports = async function ({ url, out }) {
|
||||
const errors = [];
|
||||
const run = async (flag, fn) => { const b = await chromium.launch({ args: ['--no-sandbox'].concat(flag ? [flag] : []) }); try { await fn(b); } finally { await b.close(); } };
|
||||
await run('--autoplay-policy=no-user-gesture-required', (b) => flow(b, url, errors, 'no-user-gesture-required'));
|
||||
await run('--autoplay-policy=document-user-activation-required', (b) => flow(b, url, errors, 'document-user-activation-required'));
|
||||
await run(null, async (b) => {
|
||||
await rapid(b, url, errors);
|
||||
await mute(b, url, errors);
|
||||
await late(b, url, errors);
|
||||
await fallback(b, url, errors);
|
||||
await gesture(b, url, errors);
|
||||
await coop(b, errors);
|
||||
});
|
||||
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
|
||||
console.log('no console errors');
|
||||
};
|
||||
80
e2e/scenarios/10-content.js
Normal file
80
e2e/scenarios/10-content.js
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// New content in a real browser game: nine towers on keys 1-9 (Sandbox 7, Load Balancer 8, Orbital Uplink 9), a Sandbox and a
|
||||
// Load Balancer that can be built, selected and sold, the wave preview flagging botnet flyers, and the new enemy kinds
|
||||
// (Daemon, Proxy, Botnet) running through the renderer without a page error.
|
||||
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 ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
const page = await ctx.newPage();
|
||||
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
|
||||
page.on('console', (m) => { if (m.type() === 'error') errors.push('console.error: ' + m.text()); });
|
||||
await page.goto(URL); await sleep(300);
|
||||
await page.click('#btnSolo'); await sleep(200); await page.click('#btnHelpClose'); await sleep(200);
|
||||
const box = await page.locator('#board').boundingBox();
|
||||
const pt = async (cx, cy) => { const r = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: box.x + r.x, y: box.y + r.y }; };
|
||||
const sim = (fn, arg) => page.evaluate(fn, arg);
|
||||
|
||||
// palette: one tile per tower in table order, a unique key 1-9 on each
|
||||
const pal = await page.evaluate(() => ({
|
||||
order: TD.TOWER_ORDER.slice(),
|
||||
tiles: [...document.querySelectorAll('#palette .tbtn')].map((b) => b.dataset.type),
|
||||
keys: TD.TOWER_ORDER.map((t) => TD.TOWERS[t].key),
|
||||
}));
|
||||
assert(JSON.stringify(pal.tiles) === JSON.stringify(pal.order), 'the palette shows every tower in order: ' + pal.tiles.join(','));
|
||||
assert(pal.order.length === 9 && new Set(pal.keys).size === 9 && pal.keys.join('') === '123456789', 'nine towers, unique hotkeys 1-9');
|
||||
assert(pal.order[6] === 'sandbox' && pal.order[7] === 'balancer' && pal.order[8] === 'uplink', 'Sandbox 7, Load Balancer 8, Orbital Uplink 9');
|
||||
|
||||
// hotkeys select the new towers
|
||||
for (const [key, type] of [['7', 'sandbox'], ['8', 'balancer'], ['9', 'uplink'], ['3', 'ids']]) {
|
||||
await page.keyboard.press(key); await sleep(80);
|
||||
assert(await page.evaluate(() => NW.app.selType) === type, `key ${key} arms ${type}`);
|
||||
}
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
// build a Sandbox, a Load Balancer and an IDS next to it
|
||||
await sim(() => { NW.app.ctrl.sim.gold = 100000; });
|
||||
const build = async (key, cx, cy) => { await page.keyboard.press(key); await sleep(60); const p = await pt(cx, cy); await page.mouse.click(p.x, p.y); await sleep(120); };
|
||||
await build('7', 9, 5);
|
||||
await build('8', 9, 6);
|
||||
await build('3', 10, 6);
|
||||
await page.keyboard.press('Escape');
|
||||
await sleep(300);
|
||||
let v = await sim(() => NW.app.ctrl.sim.towers.map((t) => ({ type: t.type, x: t.x, y: t.y, buff: t.buff })));
|
||||
assert(v.length === 3 && v.some((t) => t.type === 'sandbox') && v.some((t) => t.type === 'balancer'), 'sandbox, balancer and ids were built');
|
||||
const ids = v.find((t) => t.type === 'ids');
|
||||
assert(ids.buff > 0, `the Load Balancer boosts the IDS next to it (buff ${ids.buff})`);
|
||||
|
||||
// select the Sandbox: info panel, upgrade, sell
|
||||
let p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(200);
|
||||
let info = await page.locator('#info').innerText();
|
||||
assert(/Sandbox/.test(info), 'selecting the Sandbox shows its info panel');
|
||||
await page.click('#info [data-act="up"]'); await sleep(200);
|
||||
assert(await sim(() => NW.app.ctrl.sim.towers.find((t) => t.type === 'sandbox').level) === 2, 'the Sandbox upgrades');
|
||||
const g0 = await sim(() => NW.app.ctrl.sim.gold);
|
||||
await page.click('#info [data-act="sell"]'); await sleep(200);
|
||||
assert((await sim(() => NW.app.ctrl.sim.gold)) > g0 && !(await sim(() => NW.app.ctrl.sim.towers.some((t) => t.type === 'sandbox'))), 'selling the Sandbox refunds credits and removes it');
|
||||
p = await pt(9, 6); await page.mouse.click(p.x, p.y); await sleep(200);
|
||||
assert(/Load Balancer/.test(await page.locator('#info').innerText()), 'selecting the Load Balancer shows its info panel');
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
// the wave preview flags the flyers of wave 14 (botnet swarm)
|
||||
await sim(() => { NW.app.ctrl.sim.wave = 13; });
|
||||
await sleep(400);
|
||||
const nw = await page.evaluate(() => ({ text: document.getElementById('nextwave').innerText, air: !!document.querySelector('#nextwave .tag.air'), titles: [...document.querySelectorAll('#nextwave .e')].map((e) => e.title) }));
|
||||
assert(/Botnet/.test(nw.text) && nw.air && nw.titles.includes('Botnet (flies)'), 'wave 14 preview lists the botnet swarm and the AIR tag: ' + nw.text.replace(/\s+/g, ' '));
|
||||
|
||||
// run the new kinds through the renderer
|
||||
await sim(() => {
|
||||
const s = NW.app.ctrl.sim; s.wave = 14;
|
||||
for (let i = 0; i < 3; i++) s.spawnQ.push({ t: s.time + i * 0.3, k: 'proxy', wave: 14 }, { t: s.time + i * 0.3 + 0.1, k: 'daemon', wave: 14 }, { t: s.time + i * 0.1, k: 'botnet', wave: 14 });
|
||||
s.spawnQ.sort((a, b) => a.t - b.t);
|
||||
});
|
||||
await sleep(2500);
|
||||
const kinds = await sim(() => [...new Set(NW.app.ctrl.sim.monsters.map((m) => m.kind))].sort());
|
||||
assert(['botnet', 'daemon', 'proxy'].every((k) => kinds.includes(k)), 'proxy, daemon and botnet are on the board: ' + kinds.join(','));
|
||||
await page.screenshot({ path: OUT + 'content-1-new-enemies.png' });
|
||||
await sleep(2500);
|
||||
assert(errors.length === 0, 'no page errors: ' + errors.join(' | '));
|
||||
await ctx.close();
|
||||
};
|
||||
434
e2e/scenarios/10-gallery.js
Normal file
434
e2e/scenarios/10-gallery.js
Normal file
|
|
@ -0,0 +1,434 @@
|
|||
// 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(' | '));
|
||||
};
|
||||
282
e2e/scenarios/11-coop-chaos.js
Normal file
282
e2e/scenarios/11-coop-chaos.js
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Co-op under stress: two real browsers against real servers (one per scenario, started here on random ports), plus a small
|
||||
* order-preserving TCP proxy that can freeze a connection (half-open: bytes swallowed, nothing closed) or delay what the server sends.
|
||||
*
|
||||
* stall a page that stops rendering for 1.5 s does not lose the partner's towers (coop-1, code-1)
|
||||
* freeze a half-open connection shows "reconnecting" within seconds and rejoins on a new socket (coop-2)
|
||||
* endhost the host leaves while the end screen is up: the promoted guest gets Play again (coop-3, code-11)
|
||||
* lobby a failed join from the menu keeps the live game; a double click makes one room; Back cancels a pending join (coop-4, code-4, code-3)
|
||||
* stale Upgrade / Next wave pressed from a stale view are refused, silently (coop-5)
|
||||
* restart after a server restart: the message says so; stale resume / reload rejoin tell the user (coop-6, code-24)
|
||||
*/
|
||||
const net = require('net');
|
||||
const { createServer } = require('../../server');
|
||||
const FILTER = require('../../public/js/sim.js').TOWERS.filter;
|
||||
|
||||
const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); };
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
async function until(fn, ms, what) { const t0 = Date.now(); for (;;) { try { const v = await fn(); if (v) return v; } catch (e) { /* retry */ } if (Date.now() - t0 > ms) throw new Error('TIMEOUT: ' + what); await sleep(40); } }
|
||||
|
||||
const newServer = (opts) => createServer(Object.assign({ port: 0, host: '127.0.0.1', log: () => {}, pingMs: 0 }, opts));
|
||||
const urlOf = (port) => 'http://127.0.0.1:' + port + '/';
|
||||
|
||||
// TCP proxy in front of the server. delay: ms added to what the server sends (order kept). freeze(): every connection that exists now
|
||||
// swallows all bytes in both directions and closes nothing, which is what a dead Wi-Fi / NAT path looks like to both ends.
|
||||
function startProxy(targetPort) {
|
||||
const st = { delay: 0, accepted: 0, pairs: new Set() };
|
||||
const server = net.createServer((c) => {
|
||||
st.accepted++;
|
||||
const u = net.connect(targetPort, '127.0.0.1');
|
||||
const pair = { c, u, frozen: false };
|
||||
st.pairs.add(pair);
|
||||
const pipe = (from, to, toClient) => {
|
||||
const q = []; let pumping = false;
|
||||
const pump = () => {
|
||||
pumping = false;
|
||||
while (q.length && q[0].at <= Date.now()) { const it = q.shift(); if (!pair.frozen && !to.destroyed) to.write(it.d); }
|
||||
if (q.length) { pumping = true; setTimeout(pump, Math.max(1, q[0].at - Date.now())); }
|
||||
};
|
||||
from.on('data', (d) => {
|
||||
if (pair.frozen) return;
|
||||
q.push({ at: Date.now() + (toClient ? st.delay : 0), d });
|
||||
if (!pumping) pump();
|
||||
});
|
||||
from.on('close', () => { st.pairs.delete(pair); if (!pair.frozen) to.destroy(); });
|
||||
from.on('error', () => {});
|
||||
};
|
||||
pipe(c, u, false); pipe(u, c, true);
|
||||
});
|
||||
const ready = new Promise((res) => server.listen(0, '127.0.0.1', res));
|
||||
st.ready = ready.then(() => { st.port = server.address().port; return st; });
|
||||
st.freeze = () => { for (const p of st.pairs) p.frozen = true; };
|
||||
st.close = () => { for (const p of st.pairs) { p.c.destroy(); p.u.destroy(); } server.close(); };
|
||||
return st;
|
||||
}
|
||||
|
||||
function maker(browser, errors) {
|
||||
return async (name, opts, seed) => {
|
||||
const ctx = await browser.newContext(opts || { viewport: { width: 1100, height: 700 } });
|
||||
if (seed !== false) await ctx.addInitScript(() => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } }); // the first-run help is tested in 04-coop
|
||||
const page = await ctx.newPage();
|
||||
page.on('pageerror', (e) => errors.push('[' + name + '] pageerror: ' + e.message));
|
||||
page.on('console', (m) => { if (m.type() === 'error' && !/WebSocket|ERR_|Failed to load/.test(m.text())) errors.push('[' + name + '] console.error: ' + m.text()); });
|
||||
return { ctx, page, name };
|
||||
};
|
||||
}
|
||||
const joined = (P) => P.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined');
|
||||
async function hostRoom(P, url, name) {
|
||||
await P.page.goto(url); await sleep(250);
|
||||
await P.page.click('#btnCoop'); await P.page.fill('#inName', name || 'Alice'); await P.page.click('#btnCreate');
|
||||
await until(() => joined(P), 6000, 'host joined');
|
||||
return P.page.evaluate(() => NW.app.ctrl.room);
|
||||
}
|
||||
async function guestJoin(P, url, room, name) {
|
||||
await P.page.goto(url + '?room=' + room); await sleep(250);
|
||||
await P.page.fill('#inName', name || 'Bob'); await P.page.click('#btnJoin');
|
||||
await until(() => joined(P), 6000, 'guest joined');
|
||||
}
|
||||
const send = (P, cmd) => P.page.evaluate((c) => NW.app.ctrl.send(c), cmd);
|
||||
const cellPt = async (P, cx, cy) => { const box = await P.page.locator('#board').boundingBox(); const r = await P.page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: box.x + r.x, y: box.y + r.y }; };
|
||||
const vis = (P, sel) => P.page.evaluate((s) => { const e = document.querySelector(s); return !!e && !e.hidden && e.getClientRects().length > 0; }, sel);
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ coop-1
|
||||
async function stall(mk) {
|
||||
console.log('--- stall: B stops rendering for 1.5 s while A builds');
|
||||
const srv = await newServer(), url = urlOf(srv.port);
|
||||
const A = await mk('A'), B = await mk('B');
|
||||
try {
|
||||
const room = await hostRoom(A, url); await guestJoin(B, url, room);
|
||||
const R = srv.rooms.get(room);
|
||||
await B.page.evaluate(() => { window.__held = []; window.__raf = window.requestAnimationFrame.bind(window); window.requestAnimationFrame = (cb) => { window.__held.push(cb); return 0; }; });
|
||||
await sleep(300);
|
||||
for (const [x, y] of [[14, 3], [14, 4]]) { await send(A, { c: 'place', type: 'wall', x, y }); await sleep(60); }
|
||||
await sleep(1500); // ~30 snapshots arrive while nothing is displayed; the buffer holds 10
|
||||
await B.page.evaluate(() => { window.requestAnimationFrame = window.__raf; for (const cb of window.__held.splice(0)) cb(performance.now()); });
|
||||
// no further tower change from here on: the old code stayed wrong until somebody built or sold something again
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length), 3000, 'B shows the walls');
|
||||
await sleep(1200);
|
||||
const b = await B.page.evaluate(() => ({ towers: NW.app.ctrl.view.towers.length, rev: NW.app.ctrl.rev, route: NW.app.ctrl.board.routeLen, gold: NW.app.ctrl.view.gold }));
|
||||
assert(R.sim.towers.length === 2 && b.towers === 2, 'B shows both walls the partner built while it was stalled (server ' + R.sim.towers.length + ', B ' + b.towers + ')');
|
||||
assert(b.rev === R.sim.rev, 'B\'s tower revision equals the server\'s (' + b.rev + ')');
|
||||
assert(Math.abs(b.route - R.sim.board.routeLen) < 1e-6, 'B\'s mirrored board has the same route length as the server');
|
||||
assert(b.gold === R.sim.gold, 'credits agree');
|
||||
} finally { await A.ctx.close(); await B.ctx.close(); await srv.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ coop-2
|
||||
async function freeze(mk) {
|
||||
console.log('--- freeze: B\'s connection goes half-open');
|
||||
const srv = await newServer(), px = startProxy(srv.port); await px.ready;
|
||||
const A = await mk('A'), B = await mk('B');
|
||||
try {
|
||||
const room = await hostRoom(A, urlOf(srv.port)); await guestJoin(B, urlOf(px.port), room);
|
||||
const R = srv.rooms.get(room);
|
||||
await send(A, { c: 'place', type: 'wall', x: 14, y: 3 });
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length === 1), 3000, 'B sees the first wall');
|
||||
await B.page.evaluate(() => { window.__ws1 = NW.app.ctrl.ws; });
|
||||
const acc0 = px.accepted;
|
||||
px.freeze(); const t0 = Date.now();
|
||||
await send(A, { c: 'place', type: 'wall', x: 14, y: 4 }); // built while B is cut off
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.status === 'reconnecting' && !document.getElementById('reconnect').hidden), 9000, 'B shows the reconnecting overlay');
|
||||
const tShown = Date.now() - t0;
|
||||
assert(tShown < 8500, 'the overlay is up ' + (tShown / 1000).toFixed(1) + ' s after the path died (it used to take 45 to 65 s)');
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.status === 'joined' && NW.app.ctrl.ws !== window.__ws1 && document.getElementById('reconnect').hidden), 9000, 'B is back on a fresh socket');
|
||||
const tBack = Date.now() - t0;
|
||||
assert(tBack < 10000 && px.accepted > acc0, 'B rejoined on a new connection after ' + (tBack / 1000).toFixed(1) + ' s without waiting for the dead one to close');
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length === 2), 3000, 'B has the wall built while it was cut off');
|
||||
assert(R.sim.towers.length === 2 && R.players.every((p) => p && p.conn), 'both players are online again in the same room and seats');
|
||||
} finally { await A.ctx.close(); await B.ctx.close(); px.close(); await srv.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ coop-3
|
||||
async function endhost(mk) {
|
||||
console.log('--- endhost: the host leaves while the end screen is up');
|
||||
const srv = await newServer(), url = urlOf(srv.port);
|
||||
const A = await mk('A'), B = await mk('B', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
|
||||
try {
|
||||
const room = await hostRoom(A, url); await guestJoin(B, url, room);
|
||||
const R = srv.rooms.get(room);
|
||||
R.sim.lives = 0; // the next tick is a breach
|
||||
await until(() => Promise.all([A, B].map((P) => vis(P, '#end'))).then((v) => v[0] && v[1]), 5000, 'both see the end screen');
|
||||
assert((await vis(A, '#btnAgain')) && !(await vis(A, '#endWait')), 'host: Play again is offered');
|
||||
assert(!(await vis(B, '#btnAgain')) && (await vis(B, '#endWait')), 'guest: waits for the host');
|
||||
await A.page.click('#btnEndMenu'); // the host goes to the menu: leaves the room
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.players.length === 1 && NW.app.ctrl.you.host), 4000, 'guest promoted');
|
||||
await until(() => vis(B, '#btnAgain'), 2000, 'the promoted guest gets Play again');
|
||||
assert(!(await vis(B, '#endWait')), 'and the "waiting for the host" text is gone');
|
||||
await B.page.tap('#btnAgain');
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.view.state === 'playing' && document.getElementById('end').hidden), 3000, 'B starts a new game');
|
||||
assert(R.sim.state === 'playing', 'the server runs a new game');
|
||||
} finally { await A.ctx.close(); await B.ctx.close(); await srv.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ coop-4, code-4, code-3
|
||||
async function lobby(mk) {
|
||||
console.log('--- lobby: failed join, double click, cancelled join');
|
||||
const srv = await newServer(), px = startProxy(srv.port); await px.ready;
|
||||
const url = urlOf(srv.port);
|
||||
const A = await mk('A'), B = await mk('B'), C = await mk('C'), D = await mk('D');
|
||||
try {
|
||||
// coop-4: a failed join from the in-game menu leaves the live game alone
|
||||
const room = await hostRoom(A, url); await guestJoin(B, url, room);
|
||||
const R = srv.rooms.get(room);
|
||||
await A.page.click('#btnMenu'); await A.page.click('#btnCoop');
|
||||
await A.page.fill('#inCode', 'ZZZZ'); await A.page.click('#btnJoin');
|
||||
await until(() => A.page.evaluate(() => /does not exist/.test(document.getElementById('lobbyMsg').textContent)), 4000, 'the lobby says the room does not exist');
|
||||
const a1 = await A.page.evaluate(() => ({ st: NW.app.ctrl.status, room: NW.app.ctrl.room, inGame: NW.app.inGame, ss: sessionStorage.getItem('nw.room'), ls: !!localStorage.getItem('nw.session'), joinOff: document.getElementById('btnJoin').disabled }));
|
||||
assert(a1.st === 'joined' && a1.room === room && a1.inGame, 'A is still in the live game after the failed join');
|
||||
assert(a1.ss === room && a1.ls, 'and its saved room is untouched');
|
||||
assert(!a1.joinOff, 'Join is usable again');
|
||||
await A.page.click('#btnLobbyBack');
|
||||
await send(A, { c: 'place', type: 'wall', x: 14, y: 3 });
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length === 1), 3000, 'A can still build and B sees it');
|
||||
assert(R.players.filter((p) => p && p.conn).length === 2, 'the partner never saw A leave');
|
||||
|
||||
// code-4: a double click on Create room makes one room
|
||||
const rooms0 = srv.rooms.size;
|
||||
await C.page.goto(url); await sleep(250);
|
||||
await C.page.click('#btnCoop'); await C.page.fill('#inName', 'Dbl');
|
||||
await C.page.dblclick('#btnCreate');
|
||||
await until(() => joined(C), 5000, 'C joined');
|
||||
await sleep(600);
|
||||
assert(srv.rooms.size === rooms0 + 1, 'one room was created, not two (' + srv.rooms.size + ' rooms)');
|
||||
|
||||
// code-3: Back and Play solo while a join is still connecting: the late answer must not take the solo game over
|
||||
await D.page.goto(urlOf(px.port)); await sleep(300);
|
||||
px.delay = 1200;
|
||||
await D.page.click('#btnCoop'); await D.page.fill('#inName', 'Late'); await D.page.click('#btnCreate');
|
||||
await sleep(300);
|
||||
assert(await D.page.evaluate(() => document.getElementById('btnCreate').disabled), 'Create is disabled while connecting');
|
||||
await D.page.click('#btnLobbyBack');
|
||||
await D.page.click('#btnSolo');
|
||||
for (const [x, y] of [[12, 3], [12, 4], [12, 5]]) await send(D, { c: 'place', type: 'wall', x, y });
|
||||
await sleep(4000); // the server's answer (and its 1.2 s delay, twice) is long over
|
||||
const d = await D.page.evaluate(() => ({ kind: NW.app.ctrl.kind, towers: NW.app.ctrl.view.towers.length, inGame: NW.app.inGame }));
|
||||
assert(d.kind === 'local' && d.towers === 3 && d.inGame, 'the solo game was not replaced by the late co-op join');
|
||||
assert(srv.rooms.size === rooms0 + 1, 'and the room the cancelled join had created is gone again');
|
||||
px.delay = 0;
|
||||
} finally { for (const P of [A, B, C, D]) await P.ctx.close(); px.close(); await srv.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ coop-5
|
||||
async function stale(mk) {
|
||||
console.log('--- stale: Upgrade / Next wave from a view that is behind');
|
||||
const srv = await newServer(), px = startProxy(srv.port); await px.ready;
|
||||
const A = await mk('A'), B = await mk('B');
|
||||
try {
|
||||
const room = await hostRoom(A, urlOf(srv.port)); await guestJoin(B, urlOf(px.port), room);
|
||||
const R = srv.rooms.get(room);
|
||||
R.sim.gold = 1000;
|
||||
await send(A, { c: 'place', type: 'filter', x: 10, y: 8 });
|
||||
const pt = await cellPt(B, 10, 8);
|
||||
await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.length === 1 && NW.app.ctrl.view.gold === 975), 3000, 'B sees the turret');
|
||||
await B.page.mouse.click(pt.x, pt.y); // B selects it
|
||||
await until(() => B.page.evaluate(() => !!document.querySelector('#info [data-act="up"]:not([disabled])')), 2000, 'B has an enabled Upgrade button');
|
||||
await B.page.evaluate(() => { window.__rej = []; NW.app.ctrl.on('reject', (r) => window.__rej.push(r.reason)); });
|
||||
px.delay = 1800; // from now B\'s picture of the game is 1.8 s behind
|
||||
await send(A, { c: 'upgrade', id: 1 }); // the partner upgrades it first...
|
||||
await until(() => R.sim.towers[0].level === 2, 2000, 'the server upgraded it');
|
||||
await B.page.click('#info [data-act="up"]'); // ...B still sees level 1 and presses Upgrade too
|
||||
await send(A, { c: 'wave' });
|
||||
await until(() => R.sim.wave === 1, 2000, 'wave 1 started');
|
||||
await B.page.click('#btnWave'); // same with Next wave: B still sees wave 0
|
||||
await until(() => B.page.evaluate(() => window.__rej.length >= 2), 6000, 'B got both rejections');
|
||||
assert((await B.page.evaluate(() => window.__rej.join(','))) === 'stale,stale', 'both were refused as stale');
|
||||
assert(R.sim.towers[0].level === 2 && R.sim.towers[0].spent === FILTER.levels[0].cost + FILTER.levels[1].cost, 'the turret was upgraded once and paid for once (level ' + R.sim.towers[0].level + ', spent ' + R.sim.towers[0].spent + ')');
|
||||
assert(R.sim.wave === 1, 'one wave started, not two');
|
||||
assert((await B.page.evaluate(() => document.querySelectorAll('#toasts .toast.bad').length)) === 0, 'and B was not shown an error for it');
|
||||
px.delay = 0;
|
||||
} finally { await A.ctx.close(); await B.ctx.close(); px.close(); await srv.close(); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ coop-6, code-24
|
||||
async function restart(mk) {
|
||||
console.log('--- restart: the server restarts, stale saved rooms');
|
||||
let srv = await newServer(); const port = srv.port, url = urlOf(port);
|
||||
const A = await mk('A'), B = await mk('B'), C = await mk('C'), D = await mk('D');
|
||||
try {
|
||||
const room = await hostRoom(A, url); await guestJoin(B, url, room);
|
||||
await srv.close();
|
||||
await until(() => A.page.evaluate(() => NW.app.ctrl.status === 'reconnecting' && !document.getElementById('reconnect').hidden), 4000, 'A shows the reconnecting overlay');
|
||||
await sleep(1200);
|
||||
srv = await newServer({ port }); // back up, with no rooms
|
||||
for (const P of [A, B]) await until(() => P.page.evaluate(() => NW.app.ctrl.kind === 'local' && /server restarted/.test(document.getElementById('lobbyMsg').textContent)), 14000, P.name + ' is told the server restarted');
|
||||
const msg = await A.page.evaluate(() => document.getElementById('lobbyMsg').textContent);
|
||||
assert(msg === 'The server restarted, your game was lost.', 'the message: ' + msg);
|
||||
assert(await A.page.evaluate(() => localStorage.getItem('nw.session') === null && sessionStorage.getItem('nw.room') === null), 'the dead room is forgotten (no Resume for it)');
|
||||
|
||||
// code-24: a reload that tries to slip back into a room that is gone says so
|
||||
await C.ctx.addInitScript(() => { try { if (!sessionStorage.getItem('seeded')) { sessionStorage.setItem('seeded', '1'); sessionStorage.setItem('nw.room', 'ZZZZ'); localStorage.setItem('nw.session', JSON.stringify({ pid: 'abcdefgh12345678', room: 'ZZZZ', name: 'Cee', ts: Date.now() })); } } catch (e) { /* ignore */ } });
|
||||
await C.page.goto(url);
|
||||
await until(() => C.page.evaluate(() => [...document.querySelectorAll('#toasts .toast')].some((t) => /gone/.test(t.textContent))), 5000, 'C is told the game is gone');
|
||||
const c = await C.page.evaluate(() => ({ resume: document.getElementById('btnResume').hidden, ls: localStorage.getItem('nw.session'), ss: sessionStorage.getItem('nw.room'), kind: NW.app.ctrl.kind }));
|
||||
assert(c.resume && c.ls === null && c.ss === null && c.kind === 'local', 'and the stale Resume button / saved room are gone');
|
||||
|
||||
// code-24: "Resume co-op game" for a room that is gone
|
||||
await D.ctx.addInitScript(() => { try { if (!localStorage.getItem('seeded')) { localStorage.setItem('seeded', '1'); localStorage.setItem('nw.session', JSON.stringify({ pid: 'abcdefgh87654321', room: 'YYYY', name: 'Dee', ts: Date.now() })); } } catch (e) { /* ignore */ } });
|
||||
await D.page.goto(url); await sleep(300);
|
||||
assert(await vis(D, '#btnResume'), 'D is offered Resume');
|
||||
await D.page.click('#btnResume');
|
||||
await until(() => D.page.evaluate(() => [...document.querySelectorAll('#toasts .toast')].some((t) => /gone/.test(t.textContent))), 5000, 'D is told the game is gone');
|
||||
assert(!(await vis(D, '#btnResume')), 'the stale Resume button is removed');
|
||||
|
||||
// coop-6: running out of retries does not throw the saved room away (the seat is held for a minute): Resume stays
|
||||
const room2 = await hostRoom(C, url, 'Cee');
|
||||
await C.page.evaluate(() => NW.app.ctrl._die('lost', 'Lost connection to the server.'));
|
||||
await until(() => C.page.evaluate(() => NW.app.ctrl.kind === 'local' && /Lost connection/.test(document.getElementById('lobbyMsg').textContent)), 3000, 'C is told the connection was lost');
|
||||
assert(await C.page.evaluate(([r]) => sessionStorage.getItem('nw.room') === r && !!localStorage.getItem('nw.session'), [room2]), 'the saved room is kept after "lost connection"');
|
||||
await C.page.click('#btnLobbyBack');
|
||||
assert(await vis(C, '#btnResume'), 'and Resume is offered on the menu');
|
||||
} finally { for (const P of [A, B, C, D]) await P.ctx.close(); await srv.close(); }
|
||||
}
|
||||
|
||||
module.exports = async function ({ browser }) {
|
||||
const errors = [];
|
||||
const mk = maker(browser, errors);
|
||||
const only = process.env.COOP_CHAOS || '';
|
||||
const all = { stall, freeze, endhost, lobby, stale, restart };
|
||||
for (const [name, fn] of Object.entries(all)) { if (!only || only.split(',').includes(name)) await fn(mk); }
|
||||
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
|
||||
console.log('no console errors');
|
||||
};
|
||||
110
e2e/scenarios/12-session-ui.js
Normal file
110
e2e/scenarios/12-session-ui.js
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Session / lifecycle details of the game screen that the co-op work fixed (every block fails on the old behaviour):
|
||||
* code-17 no co-op owner flags or join toasts left over after leaving a room for a solo game
|
||||
* code-18 the Reset-zoom button follows the camera however the camera was reset
|
||||
* code-20 the screen wake lock is released when the game ends and the player is back at the menu
|
||||
* code-21 Help and the Menu do not un-pause a game the player paused themselves
|
||||
* code-25 winning persists the best wave
|
||||
* code-26 first-run help once per install, and only once per page load when storage throws
|
||||
*/
|
||||
const { createServer } = require('../../server');
|
||||
|
||||
const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); };
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
async function until(fn, ms, what) { const t0 = Date.now(); for (;;) { try { const v = await fn(); if (v) return v; } catch (e) { /* retry */ } if (Date.now() - t0 > ms) throw new Error('TIMEOUT: ' + what); await sleep(40); } }
|
||||
|
||||
module.exports = async function ({ browser, url: URL }) {
|
||||
const errors = [];
|
||||
const mk = async (name, init, opts) => {
|
||||
const ctx = await browser.newContext(opts || { viewport: { width: 1100, height: 700 } });
|
||||
await ctx.addInitScript(init || (() => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } }));
|
||||
const page = await ctx.newPage();
|
||||
page.on('pageerror', (e) => errors.push('[' + name + '] pageerror: ' + e.message));
|
||||
page.on('console', (m) => { if (m.type() === 'error' && !/WebSocket|ERR_|Failed to load/.test(m.text())) errors.push('[' + name + '] console.error: ' + m.text()); });
|
||||
return { ctx, page };
|
||||
};
|
||||
const paused = (P) => P.page.evaluate(() => NW.app.ctrl.view.paused);
|
||||
const flush = (P) => P.page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); // two frames: the main loop has run
|
||||
|
||||
// ---- code-21 pause, code-18 fit, code-25 best, code-20 wake lock (one solo session with a counting wake lock)
|
||||
const wl = () => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } window.__wl = { req: 0, active: 0 }; Object.defineProperty(navigator, 'wakeLock', { configurable: true, value: { request: async () => { window.__wl.req++; window.__wl.active++; let done = false; return { release: async () => { if (!done) { done = true; window.__wl.active--; } }, addEventListener() {} }; } } }); };
|
||||
const S = await mk('solo', wl);
|
||||
try {
|
||||
const p = S.page;
|
||||
await p.goto(URL); await sleep(300);
|
||||
await p.click('#btnSolo'); await sleep(300);
|
||||
assert(await p.evaluate(() => window.__wl.active) === 1, 'code-20: the screen is held awake while playing');
|
||||
|
||||
await p.keyboard.press('p'); await flush(S);
|
||||
assert(await paused(S), 'P pauses');
|
||||
await p.keyboard.press('h'); await sleep(100);
|
||||
await p.click('#btnHelpClose'); await flush(S);
|
||||
assert(await paused(S), 'code-21: closing Help leaves a game the player paused paused');
|
||||
await p.click('#btnMenu'); await sleep(100); await p.click('#btnCloseMenu'); await flush(S);
|
||||
assert(await paused(S), 'code-21: so does opening and closing the Menu');
|
||||
await p.keyboard.press('p'); await flush(S);
|
||||
assert(!(await paused(S)), 'P resumes');
|
||||
await p.click('#btnMenu'); await flush(S);
|
||||
assert(await paused(S), 'the Menu pauses a running solo game');
|
||||
await p.click('#btnCloseMenu'); await flush(S);
|
||||
assert(!(await paused(S)), 'and closing it resumes what it paused');
|
||||
|
||||
// code-18: the Reset-zoom button follows the camera
|
||||
const box = await p.locator('#board').boundingBox();
|
||||
await p.mouse.move(box.x + 300, box.y + 200); await p.mouse.wheel(0, -400); await sleep(200);
|
||||
assert(await p.evaluate(() => !document.getElementById('btnFit').hidden && NW.app.renderer.zoom > 1.02), 'code-18: zooming in shows Reset zoom');
|
||||
await p.evaluate(() => NW.app.renderer.resetCamera()); // any code path that resets the camera (a new board, a rotation, ...)
|
||||
await flush(S);
|
||||
assert(await p.evaluate(() => document.getElementById('btnFit').hidden), 'code-18: the button is gone as soon as the camera is back at 1x');
|
||||
|
||||
// code-25: a win is a best-wave record too
|
||||
assert(await p.evaluate(() => localStorage.getItem('nw.best.open')) === null, 'no record yet');
|
||||
await p.evaluate(() => { const c = NW.app.ctrl; c.sim.winWave = 1; c.send({ c: 'wave' }); c.sim.spawnQ.length = 0; c.sim.monsters.length = 0; });
|
||||
await until(() => p.evaluate(() => !document.getElementById('end').hidden), 5000, 'the end screen after winning');
|
||||
assert(await p.evaluate(() => document.getElementById('endTitle').textContent) === 'Server secured!', 'it is a win');
|
||||
assert(await p.evaluate(() => localStorage.getItem('nw.best.open')) === '1', 'code-25: the win stored the best wave');
|
||||
|
||||
// code-20: back at the menu the lock is released
|
||||
await p.click('#btnEndMenu'); await sleep(300);
|
||||
assert(await p.evaluate(() => !NW.app.inGame && window.__wl.active) === 0, 'code-20: the wake lock is released at the menu (' + await p.evaluate(() => JSON.stringify(window.__wl)) + ')');
|
||||
} finally { await S.ctx.close(); }
|
||||
|
||||
// ---- code-26: storage that throws (some private modes): the first-run help shows once per page load, not on every solo start
|
||||
const T = await mk('throwing', () => {
|
||||
const boom = () => { throw new Error('denied'); };
|
||||
for (const k of ['getItem', 'setItem', 'removeItem']) { try { Storage.prototype[k] = boom; } catch (e) { /* ignore */ } }
|
||||
});
|
||||
try {
|
||||
const p = T.page;
|
||||
await p.goto(URL); await sleep(300);
|
||||
await p.click('#btnSolo'); await sleep(300);
|
||||
assert(await p.evaluate(() => !document.getElementById('help').hidden), 'code-26: the first solo start shows the help');
|
||||
await p.click('#btnHelpClose');
|
||||
await p.click('#btnMenu'); await p.click('#btnSolo'); await sleep(300); // "New solo game"
|
||||
assert(await p.evaluate(() => document.getElementById('help').hidden), 'code-26: the second start does not show it again');
|
||||
} finally { await T.ctx.close(); }
|
||||
|
||||
// ---- code-17: leaving a co-op room for a solo game leaves no co-op flags behind (needs a server and a partner)
|
||||
const srv = await createServer({ port: 0, host: '127.0.0.1', log: () => {}, pingMs: 0 });
|
||||
const base = 'http://127.0.0.1:' + srv.port + '/';
|
||||
const A = await mk('A'), B = await mk('B');
|
||||
try {
|
||||
await A.page.goto(base); await sleep(250);
|
||||
await A.page.click('#btnCoop'); await A.page.fill('#inName', 'Alice'); await A.page.click('#btnCreate');
|
||||
await until(() => A.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'), 5000, 'A joined');
|
||||
const room = await A.page.evaluate(() => NW.app.ctrl.room);
|
||||
await A.page.evaluate(() => { const r = NW.app.renderer, f = r.frame.bind(r); r.frame = (now, view, ui) => { window.__ui = ui; return f(now, view, ui); }; });
|
||||
await B.page.goto(base + '?room=' + room); await sleep(250);
|
||||
await B.page.fill('#inName', 'Bob'); await B.page.click('#btnJoin');
|
||||
await until(() => A.page.evaluate(() => window.__ui && window.__ui.coop === true && window.__ui.names[1] === 'Bob'), 4000, 'A draws the co-op flags with two players');
|
||||
await A.page.click('#btnMenu'); await sleep(150);
|
||||
await A.page.evaluate(() => document.querySelector('#players [data-act="leave"]').click()); await sleep(600);
|
||||
await A.page.click('#btnSolo'); await sleep(500);
|
||||
const ui = await A.page.evaluate(() => ({ coop: window.__ui.coop, names: Object.keys(window.__ui.names).length, kind: NW.app.ctrl.kind }));
|
||||
assert(ui.kind === 'local' && ui.coop === false && ui.names === 0, 'code-17: the solo game does not draw co-op owner flags');
|
||||
} finally { await A.ctx.close(); await B.ctx.close(); await srv.close(); }
|
||||
|
||||
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
|
||||
console.log('no console errors');
|
||||
};
|
||||
62
e2e/scenarios/13-uplink-price.js
Normal file
62
e2e/scenarios/13-uplink-price.js
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// The Orbital Uplink is an endgame weapon: very expensive, and each one owned makes the next dearer. The UI must show the price
|
||||
// the server will charge (palette tile, armed-tower panel, aria label) and keep it current as towers are built and sold.
|
||||
module.exports = async function ({ browser, url: URL }) {
|
||||
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 ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } });
|
||||
const page = await ctx.newPage();
|
||||
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
|
||||
page.on('console', (m) => { if (m.type() === 'error') errors.push('console.error: ' + m.text()); });
|
||||
await page.goto(URL); await sleep(300);
|
||||
await page.click('#btnSolo'); await sleep(300);
|
||||
if (await page.locator('#btnHelpClose').isVisible()) await page.click('#btnHelpClose');
|
||||
const tile = () => page.evaluate(() => { const b = document.querySelector('.tbtn[data-type="uplink"]'); return { cost: b.querySelector('.cost').textContent, label: b.getAttribute('aria-label'), poor: b.classList.contains('poor') }; });
|
||||
const base = await page.evaluate(() => TD.TOWERS.uplink.levels[0].cost);
|
||||
|
||||
let t = await tile();
|
||||
assert(t.cost === String(base) && base >= 1000, `palette shows the first Uplink at ${base} credits`);
|
||||
assert(t.poor, 'it is unaffordable with the opening credits');
|
||||
assert(/not enough credits/.test(t.label), 'and the aria label says so');
|
||||
|
||||
// a rich player builds one through the real UI, then the tile shows the dearer second one
|
||||
await page.evaluate(() => { NW.app.ctrl.sim.gold = 20000; });
|
||||
await sleep(200);
|
||||
const box = await page.locator('#board').boundingBox();
|
||||
const pt = async (cx, cy) => { const r = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: box.x + r.x, y: box.y + r.y }; };
|
||||
await page.keyboard.press('9'); await sleep(150);
|
||||
assert((await page.locator('#info').innerText()).includes(String(base) + ' credits'), 'the armed-tower panel shows the same price');
|
||||
let p = await pt(6, 5); await page.mouse.click(p.x, p.y); await sleep(250);
|
||||
const g1 = await page.evaluate(() => NW.app.ctrl.view.gold);
|
||||
assert(g1 === 20000 - base, `the first Uplink was charged ${base}`);
|
||||
t = await tile();
|
||||
const second = await page.evaluate(() => TD.priceFor('uplink', NW.app.ctrl.view.towers));
|
||||
assert(second > base * 1.2 && second < base * 1.3 && t.cost === String(second), `the tile now shows the second one at ${second} (about 25% dearer)`);
|
||||
assert((await page.locator('#info').innerText()).includes(String(second) + ' credits'), 'and so does the armed panel');
|
||||
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(250);
|
||||
assert((await page.evaluate(() => NW.app.ctrl.view.gold)) === g1 - second, `the second one was charged ${second}`);
|
||||
|
||||
// upgrades scale by the same factor: the first Uplink upgrades at the base price, the second at the same multiple it was bought at
|
||||
await page.keyboard.press('Escape');
|
||||
const upBtn = () => page.locator('#info [data-act="up"] .cost').innerText();
|
||||
p = await pt(6, 5); await page.mouse.click(p.x, p.y); await sleep(250);
|
||||
const firstUp = await page.evaluate(() => TD.TOWERS.uplink.levels[1].cost);
|
||||
assert((await upBtn()) === String(firstUp), `the first Uplink upgrades for the base ${firstUp}`);
|
||||
await page.keyboard.press('Escape');
|
||||
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(250);
|
||||
const secondUp = await page.evaluate(() => { const t = NW.app.ctrl.view.towers.filter((x) => x.type === 'uplink')[1]; return TD.upgradePrice('uplink', t.level, t.pm); });
|
||||
assert(secondUp > firstUp * 1.2 && (await upBtn()) === String(secondUp), `the second Uplink upgrades for ${secondUp} (the same 25% more)`);
|
||||
await page.keyboard.press('Escape');
|
||||
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(200);
|
||||
|
||||
// selling brings the price back down
|
||||
await page.keyboard.press('Escape');
|
||||
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(200);
|
||||
await page.click('#info [data-act="sell"]'); await sleep(250);
|
||||
t = await tile();
|
||||
assert(t.cost === String(second), 'after selling one the next costs what the second did');
|
||||
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
|
||||
console.log('no console errors');
|
||||
await ctx.close();
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue