Difficulty: - TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated create-room / newgame option, state carries it; solo menu picker and co-op lobby picker (44px segmented control, reachable on every layout), HUD/room/end-screen labels, best-wave record per map AND difficulty (Normal keeps the legacy key), Play again keeps the running game's difficulty for host and guest Balance (12 bot runs, deterministic, 48/48 games replay identically in QA): - Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open - credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at wave 30: 1309 -> 335 - IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only dies by wave 7); Mortar, Arc and Filter buffed - Orbital Uplink price step per owned unit 30% (buy and upgrade) - remaining imbalances documented in docs/BALANCE.md Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix reachability of the picker. 156 unit tests, 17 e2e scenarios. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
211 lines
18 KiB
JavaScript
211 lines
18 KiB
JavaScript
// Easy / Normal / Hard. Solo: the picker in the menu (every difficulty, remembered, validated), what each one does to the real game
|
|
// (credits, lives, packet hit points, shown next to the next-wave list), Play again keeps it, the end screen names it, and the best wave
|
|
// is per map AND difficulty (a record from before difficulties existed counts as normal). Co-op: the host picks it in the lobby when
|
|
// creating the room, the guest's own screen shows the host's choice, and Play again keeps it for both. Expected numbers come from
|
|
// TD.DIFFICULTIES in the page, so a retune of the table does not break this.
|
|
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(50); } }
|
|
|
|
module.exports = async function ({ browser, url: URL, out: OUT }) {
|
|
const errors = [];
|
|
const mk = async (name, opts, init) => {
|
|
const ctx = await browser.newContext(opts);
|
|
await ctx.addInitScript(() => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } }); // no first-run help in the way
|
|
if (init) await ctx.addInitScript(init);
|
|
const page = await ctx.newPage();
|
|
page.on('pageerror', (e) => errors.push(`[${name}] pageerror: ${e.message}`));
|
|
page.on('console', (m) => { if (m.type() === 'error') errors.push(`[${name}] console.error: ${m.text()}`); });
|
|
return { ctx, page };
|
|
};
|
|
const table = (page) => page.evaluate(() => ({ order: TD.DIFFICULTY_ORDER.slice(), d: JSON.parse(JSON.stringify(TD.DIFFICULTIES)), gold: TD.START_GOLD, lives: TD.START_LIVES }));
|
|
const startGold = (T, id) => Math.round(T.gold * T.d[id].gold);
|
|
const startLives = (T, id) => Math.max(1, Math.round(T.lives * T.d[id].lives));
|
|
const checked = (page, box) => page.evaluate((b) => [...document.querySelectorAll(b + ' button')].filter((x) => x.getAttribute('aria-checked') === 'true').map((x) => x.dataset.diff), box);
|
|
const hud = (page) => page.evaluate(() => ({
|
|
gold: document.getElementById('vGold').textContent, lives: document.getElementById('vLives').textContent,
|
|
tag: (document.querySelector('#nextwave .dtag') || {}).textContent || null, tagD: (document.querySelector('#nextwave .dtag') || { dataset: {} }).dataset.d || null,
|
|
view: NW.app.ctrl.view.difficulty,
|
|
}));
|
|
const endRows = (page) => page.evaluate(() => Object.fromEntries([...document.querySelectorAll('#endStats > div')].map((d) => [d.firstChild.textContent, d.lastChild.textContent])));
|
|
// The HUD catches up with a new game a frame or two later (more on a loaded machine): wait for it instead of sleeping and hoping.
|
|
let T = null;
|
|
const waitHud = async (page, id, what) => {
|
|
let h = null;
|
|
try { await until(async () => { h = await hud(page); return h.view === id && h.gold === String(startGold(T, id)) && h.lives === String(startLives(T, id)) && h.tag === T.d[id].name; }, 6000, what); } catch (e) { throw new Error(`${e.message} (last HUD: ${JSON.stringify(h)})`); }
|
|
return h;
|
|
};
|
|
const loseNow = (page, wave) => page.evaluate((w) => { const s = NW.app.ctrl.sim; s.wave = w; s.lives = 0; s.state = 'lost'; }, wave);
|
|
|
|
// ================================================================ solo
|
|
const S = await mk('solo', { viewport: { width: 1100, height: 760 } });
|
|
const p = S.page;
|
|
await p.goto(URL); await sleep(300);
|
|
T = await table(p);
|
|
assert(T.order.length >= 3 && T.order[0] === 'easy' && T.order.includes('normal') && T.order.includes('hard'), `the table has ${T.order.join(', ')}`);
|
|
|
|
// the picker: one radio per difficulty, normal checked on a first visit, 44px targets, and it does not steal the dialog's focus
|
|
const seg = await p.evaluate(() => {
|
|
const box = document.getElementById('diffPick'), bs = [...box.querySelectorAll('button')];
|
|
return { role: box.getAttribute('role'), label: box.getAttribute('aria-label'), ids: bs.map((b) => b.dataset.diff), roles: bs.map((b) => b.getAttribute('role')), h: Math.min(...bs.map((b) => b.getBoundingClientRect().height)), primary: bs.some((b) => b.classList.contains('primary')), active: document.activeElement.id, text: bs.map((b) => b.textContent) };
|
|
});
|
|
assert(seg.role === 'radiogroup' && /difficulty/i.test(seg.label) && seg.roles.every((r) => r === 'radio'), 'the picker is a labelled radiogroup of radios');
|
|
assert(JSON.stringify(seg.ids) === JSON.stringify(T.order), 'one segment per difficulty, in table order: ' + seg.ids);
|
|
assert(seg.text.every((t, i) => t === T.d[T.order[i]].name), 'labelled with the table\'s names: ' + seg.text);
|
|
assert(seg.h >= 43.5, 'every segment is at least 44px high (' + seg.h + ')');
|
|
assert(!seg.primary && seg.active === 'btnSolo', 'no segment is .primary, so the menu still focuses Play solo (' + seg.active + ')');
|
|
assert(JSON.stringify(await checked(p, '#diffPick')) === '["normal"]', 'normal is picked on a first visit');
|
|
assert(/standard/i.test(await p.textContent('#diffNote')), 'and the note says it is the standard game');
|
|
|
|
// every difficulty: pick it, play, and the game on the screen is that game
|
|
const startedGold = {};
|
|
for (const id of T.order) {
|
|
const inGame = await p.evaluate(() => NW.app.inGame);
|
|
if (inGame) { await p.click('#btnMenu'); await sleep(150); }
|
|
await p.click(`#diffPick [data-diff="${id}"]`);
|
|
assert(JSON.stringify(await checked(p, '#diffPick')) === JSON.stringify([id]), `picking ${id} checks only ${id}`);
|
|
assert((await p.evaluate(() => localStorage.getItem('nw.difficulty'))) === JSON.stringify(id), `${id} is remembered`);
|
|
const note = await p.textContent('#diffNote');
|
|
assert(inGame ? /^This game: /.test(note) && note.includes('next game: ' + T.d[id].name) : note.length > 5, `the note under the picker: "${note}"`);
|
|
await p.click('#btnSolo');
|
|
const h = await waitHud(p, id, `${id}: the new game's HUD`);
|
|
assert(h.gold === String(startGold(T, id)) && h.lives === String(startLives(T, id)), `${id}: the HUD shows ${startGold(T, id)} credits and ${startLives(T, id)} integrity (${h.gold} / ${h.lives})`);
|
|
assert(h.view === id && h.tag === T.d[id].name && h.tagD === id, `${id}: the next-wave panel names it ("${h.tag}")`);
|
|
assert(await p.evaluate(() => NW.app.ctrl.sim.difficulty) === id, `${id}: the local sim runs it`);
|
|
startedGold[id] = startGold(T, id);
|
|
// a real packet has the difficulty's hit points
|
|
await p.evaluate(() => { NW.app.ctrl.send({ c: 'wave' }); });
|
|
await until(() => p.evaluate(() => NW.app.ctrl.sim.monsters.length > 0), 5000, 'a packet spawns');
|
|
const mon = await p.evaluate(() => { const m = NW.app.ctrl.sim.monsters[0]; return { kind: m.kind, maxhp: m.maxhp, reward: m.reward }; });
|
|
const want = await p.evaluate(([k, id2]) => Math.round(TD.ENEMIES[k].hp * TD.hpScale(1) * TD.DIFFICULTIES[id2].hp), [mon.kind, id]);
|
|
assert(mon.maxhp === want, `${id}: a ${mon.kind} has ${mon.maxhp} hit points (table says ${want})`);
|
|
}
|
|
assert(startedGold.easy > startedGold.normal && startedGold.normal > startedGold.hard, 'more credits on easy than on normal than on hard: ' + JSON.stringify(startedGold));
|
|
|
|
// the pick survives a reload; a stored value that is not a difficulty is normal (and 'toString' is not one)
|
|
await p.reload(); await sleep(400);
|
|
const last = await p.evaluate(() => JSON.parse(localStorage.getItem('nw.difficulty')));
|
|
assert(last === T.order[T.order.length - 1], `the last pick (${last}) was stored`);
|
|
assert(JSON.stringify(await checked(p, '#diffPick')) === JSON.stringify([last]), `after a reload the picker shows it: ${JSON.stringify(await checked(p, '#diffPick'))}`);
|
|
for (const junk of ['"toString"', '"__proto__"', '17', 'not json', '"EASY"']) {
|
|
await p.evaluate((j) => localStorage.setItem('nw.difficulty', j), junk); await p.reload(); await sleep(300);
|
|
assert(JSON.stringify(await checked(p, '#diffPick')) === '["normal"]', `a stored ${junk} falls back to normal`);
|
|
}
|
|
|
|
// the menu pick is for the NEXT game: Play again and the end screen belong to the game that was played
|
|
await p.click('#diffPick [data-diff="easy"]'); await p.click('#btnSolo'); await sleep(300);
|
|
await p.click('#btnMenu'); await sleep(150);
|
|
await p.click('#diffPick [data-diff="hard"]');
|
|
const liveNote = await p.textContent('#diffNote');
|
|
assert(/This game: Easy/.test(liveNote) && /next game: Hard/.test(liveNote), 'the menu of a running game says which game it is and what the pick is for: "' + liveNote + '"');
|
|
await p.click('#btnCloseMenu'); await sleep(200);
|
|
assert((await hud(p)).view === 'easy', 'closing the menu leaves the running game on easy');
|
|
await p.evaluate(() => { localStorage.removeItem('nw.best.open'); localStorage.removeItem('nw.best.open.easy'); });
|
|
await loseNow(p, 3);
|
|
await until(() => p.evaluate(() => !document.getElementById('end').hidden), 5000, 'the end screen');
|
|
let rows = await endRows(p);
|
|
assert(rows.Difficulty === T.d.easy.name, 'the end screen names the difficulty of the game that ended: ' + JSON.stringify(rows));
|
|
assert(rows['Best on ' + T.d.easy.name] === '3', 'and the best wave on it: ' + JSON.stringify(rows));
|
|
assert((await p.evaluate(() => localStorage.getItem('nw.best.open.easy'))) === '3' && (await p.evaluate(() => localStorage.getItem('nw.best.open'))) === null, 'the record went to the easy key, not to the normal one');
|
|
await p.screenshot({ path: OUT + 'difficulty-end-easy.png' });
|
|
await p.click('#btnAgain');
|
|
const again = await waitHud(p, 'easy', 'Play again: the HUD of a fresh easy game');
|
|
assert(again.view === 'easy' && again.gold === String(startGold(T, 'easy')) && again.lives === String(startLives(T, 'easy')) && again.tag === T.d.easy.name, 'Play again keeps easy, not the menu\'s hard: ' + JSON.stringify(again));
|
|
assert(JSON.stringify(await checked(p, '#diffPick')) === '["hard"]', 'the menu pick is still hard for the next new game');
|
|
await S.ctx.close();
|
|
|
|
// ---- best wave per map AND difficulty; a record from before difficulties existed is the normal one
|
|
const M = await mk('migrate', { viewport: { width: 1100, height: 760 } }, () => { try { if (localStorage.getItem('nw.best.open') === null) localStorage.setItem('nw.best.open', '7'); } catch (e) { /* ignore */ } });
|
|
const m = M.page;
|
|
await m.goto(URL); await sleep(300);
|
|
await m.click('#btnSolo'); await sleep(300);
|
|
await loseNow(m, 2);
|
|
await until(() => m.evaluate(() => !document.getElementById('end').hidden), 5000, 'normal end screen');
|
|
rows = await endRows(m);
|
|
assert(rows['Best on Normal'] === '7' && rows.Difficulty === 'Normal', 'the old record (7) is the normal best, nothing was lost: ' + JSON.stringify(rows));
|
|
assert((await m.evaluate(() => localStorage.getItem('nw.best.open'))) === '7', 'and the old key is still there, untouched');
|
|
await m.click('#btnEndMenu'); await sleep(300);
|
|
await m.click('#diffPick [data-diff="hard"]'); await m.click('#btnSolo'); await sleep(300);
|
|
await loseNow(m, 2);
|
|
await until(() => m.evaluate(() => !document.getElementById('end').hidden), 5000, 'hard end screen');
|
|
rows = await endRows(m);
|
|
assert(rows['Best on Hard'] === '2' && rows.Difficulty === 'Hard', 'hard has its own record (2), the 7 is not shown there: ' + JSON.stringify(rows));
|
|
const keys = await m.evaluate(() => ({ normal: localStorage.getItem('nw.best.open'), hard: localStorage.getItem('nw.best.open.hard'), easy: localStorage.getItem('nw.best.open.easy') }));
|
|
assert(keys.normal === '7' && keys.hard === '2' && keys.easy === null, 'the keys are per map and difficulty: ' + JSON.stringify(keys));
|
|
await m.click('#btnEndMenu'); await sleep(300);
|
|
await m.click('.mapcard[data-map="twin"]');
|
|
await m.click('#btnSolo'); await sleep(300); // another map on hard: its own (empty) record
|
|
await loseNow(m, 1);
|
|
await until(() => m.evaluate(() => !document.getElementById('end').hidden), 5000, 'twin end screen');
|
|
rows = await endRows(m);
|
|
assert(rows['Best on Hard'] === '1', 'another map has its own record: ' + JSON.stringify(rows));
|
|
await M.ctx.close();
|
|
|
|
// ================================================================ co-op: the host picks it in the lobby, the guest sees it
|
|
const A = await mk('host', { viewport: { width: 1280, height: 800 } });
|
|
const B = await mk('guest', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
|
|
await A.page.goto(URL); await sleep(300);
|
|
await A.page.click('#btnCoop'); await sleep(150);
|
|
assert(JSON.stringify(await checked(A.page, '#lobbyDiff')) === '["normal"]', 'the lobby\'s picker starts on normal');
|
|
const lobbySeg = await A.page.evaluate(() => [...document.querySelectorAll('#lobbyDiff button')].map((b) => [b.dataset.diff, Math.round(b.getBoundingClientRect().height), b.getAttribute('role')]));
|
|
assert(lobbySeg.length === T.order.length && lobbySeg.every((x) => x[1] >= 44 && x[2] === 'radio'), 'one 44px radio per difficulty in the lobby: ' + JSON.stringify(lobbySeg));
|
|
assert(await A.page.evaluate(() => document.activeElement.id) === 'btnCreate', 'the lobby still focuses Create room');
|
|
await A.page.click('#lobbyDiff [data-diff="hard"]');
|
|
assert(JSON.stringify(await checked(A.page, '#lobbyDiff')) === '["hard"]' && JSON.stringify(await checked(A.page, '#diffPick')) === '["hard"]', 'picking hard in the lobby checks it there and in the menu\'s picker (one setting)');
|
|
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, 'host joined');
|
|
const room = await A.page.evaluate(() => NW.app.ctrl.room);
|
|
const ah = await waitHud(A.page, 'hard', 'the host\'s HUD shows the hard room');
|
|
assert(ah.view === 'hard' && ah.gold === String(startGold(T, 'hard')) && ah.lives === String(startLives(T, 'hard')), `the host's room is hard: ${startGold(T, 'hard')} credits, ${startLives(T, 'hard')} integrity (${JSON.stringify(ah)})`);
|
|
assert(ah.tag === T.d.hard.name, 'the host sees it next to the wave list');
|
|
assert(await A.page.evaluate(() => document.querySelector('#players .dtag').textContent) === T.d.hard.name, 'and in the room panel');
|
|
assert(/Hard/.test(await A.page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|'))), 'the host\'s join toast names it');
|
|
|
|
await B.page.goto(URL + '?room=' + room); await sleep(300);
|
|
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');
|
|
const bh = await waitHud(B.page, 'hard', 'the guest\'s HUD shows the host\'s hard room');
|
|
assert(bh.view === 'hard', 'the guest\'s controller is on the host\'s difficulty: ' + bh.view);
|
|
assert(bh.gold === String(startGold(T, 'hard')) && bh.lives === String(startLives(T, 'hard')), `the guest's screen shows the hard game's credits and integrity (${bh.gold} / ${bh.lives})`);
|
|
assert(bh.tag === T.d.hard.name && bh.tagD === 'hard', 'the guest\'s next-wave panel says Hard');
|
|
assert(await B.page.evaluate(() => document.querySelector('#players .dtag').textContent) === T.d.hard.name, 'and so does the guest\'s room panel');
|
|
assert(/Hard/.test(await B.page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|'))), 'the guest is told on joining');
|
|
assert((await B.page.evaluate(() => localStorage.getItem('nw.difficulty'))) === null, 'the guest\'s own pick was not touched by joining');
|
|
await B.page.tap('#btnMenu'); await sleep(200);
|
|
const gnote = await B.page.textContent('#diffNote');
|
|
assert(/This game: Hard/.test(gnote), 'the guest\'s menu says which game this is: "' + gnote + '"');
|
|
await B.page.tap('#btnCloseMenu'); await sleep(200);
|
|
await A.page.screenshot({ path: OUT + 'difficulty-coop-host.png' });
|
|
await B.page.screenshot({ path: OUT + 'difficulty-coop-guest.png' });
|
|
|
|
// the host's menu pick is for the host's NEXT solo game only: with Easy picked there, Play again in this Hard room must still repeat Hard
|
|
// (without this the host's pick and the room are both Hard, and a Play again that sent the menu's pick would pass unnoticed)
|
|
await A.page.click('#btnMenu'); await sleep(150);
|
|
await A.page.click('#diffPick [data-diff="easy"]');
|
|
assert(JSON.stringify(await checked(A.page, '#diffPick')) === '["easy"]' && /This game: Hard/.test(await A.page.textContent('#diffNote')), 'the host picked Easy for a later game while the room runs Hard: "' + await A.page.textContent('#diffNote') + '"');
|
|
await A.page.click('#btnCloseMenu'); await sleep(150);
|
|
|
|
// lose fast (three waves at once, speed 3, nothing built): the end screen names it and Play again keeps it for both
|
|
await A.page.evaluate(() => { NW.app.ctrl.ctl('speed', 3); for (const n of [1, 2, 3]) NW.app.ctrl.send({ c: 'wave', n }); });
|
|
await until(() => A.page.evaluate(() => !document.getElementById('end').hidden), 120000, 'the host\'s end screen');
|
|
await until(() => B.page.evaluate(() => !document.getElementById('end').hidden), 20000, 'the guest\'s end screen');
|
|
for (const [name, X] of [['host', A], ['guest', B]]) {
|
|
const r = await endRows(X.page);
|
|
assert(r.Difficulty === T.d.hard.name && ('Best on ' + T.d.hard.name) in r, `the ${name}'s end screen names the difficulty: ${JSON.stringify(r)}`);
|
|
}
|
|
assert(await B.page.evaluate(() => document.getElementById('btnAgain').hidden), 'only the host can start the next game');
|
|
await A.page.click('#btnAgain');
|
|
await until(() => B.page.evaluate(() => document.getElementById('end').hidden && NW.app.ctrl.view.state === 'playing' && NW.app.ctrl.view.wave === 0), 8000, 'the guest is in the new game');
|
|
await until(() => A.page.evaluate(() => document.getElementById('end').hidden && NW.app.ctrl.view.state === 'playing'), 8000, 'the host is in the new game');
|
|
for (const [name, X] of [['host', A], ['guest', B]]) {
|
|
const h = await waitHud(X.page, 'hard', `${name}: a fresh hard game`);
|
|
assert(h.view === 'hard' && h.tag === T.d.hard.name && h.gold === String(startGold(T, 'hard')), `Play again keeps hard on the ${name}'s screen (${JSON.stringify(h)})`);
|
|
}
|
|
|
|
await A.page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } });
|
|
await B.page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } });
|
|
await A.ctx.close(); await B.ctx.close();
|
|
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
|
|
console.log('no console errors');
|
|
};
|