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:
Claude 2026-10-10 21:18:43 +00:00
parent 962189419a
commit 28502984ec
29 changed files with 3370 additions and 230 deletions

View file

@ -167,11 +167,15 @@ the trailing slash). A dedicated sub-domain is simpler.
| **Flood Mortar** | Splash damage on ground swarms. Cannot hit flyers. |
| **Rate Limiter** | Slows everything in range. Rootkits resist it. |
| **Router Arc** | Chain lightning between nearby packets. |
| **Orbital Uplink** | The endgame weapon: a piercing beam that ignores armour, hits ground and air, blasts and slows around the target and reaches across most of the map. Very expensive to buy and to upgrade (4 levels). |
| **Spoofed packets** | Fly straight over your maze: keep some anti-air. |
| **Sandbox** | Control tower, no damage: pulses a stun on every packet in range (bosses are stunned half as long). |
| **Load Balancer** | Support tower, no attack: nearby attack turrets fire 15 / 25 / 35% faster (the best balancer in range applies, they do not stack). |
| **Orbital Uplink** | The endgame weapon: a piercing beam that ignores armour, hits ground and air, blasts and slows around the target and reaches across most of the map. Extremely expensive: 1500 credits, upgrades 1200 / 2000 / 3200 (4 levels), and **every Uplink you already own makes the next one 25% dearer, to buy and to upgrade** (1500, 1880, 2340, 2930, ...), so kill rewards cannot buy a carpet of them. |
| **Spoofed packets** | Fly straight over your maze: keep some anti-air. Botnet drones are fast flying swarms. |
| **Daemons** | Healers: they restore nearby packets (up to 12% of max health per second), so kill them first. |
| **Proxies** | Shielded packets: the shield soaks damage first and regrows after 3 s without being hit. |
| **Credits** | From kills and cleared waves. Upgrade turrets (3 levels, 4 for the Uplink); selling returns 70% (walls 100%). |
Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`7` pick a tower, `Space` next wave,
Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`9` pick a tower, `Space` next wave,
`U` upgrade, `X` sell, `T` change targeting, `P` pause, `F` speed, `A` auto-waves, `M` mute, wheel zoom, Alt+click pings.
Controls, touch: tap a tower type, tap the map to preview (the new route is drawn), nudge the preview with the arrow
@ -222,7 +226,8 @@ reconnects automatically and resumes the same seat for a minute.
npm test # rules + server: placement validation, route sealing, corner cutting, targeting, waves, economy,
# protocol, rooms, reconnects, security checks, static files, dual stack
npm run e2e # real browsers: desktop, phone touch (tap-to-build, drag-paint, pinch, long-press), end screens,
# two-browser co-op incl. reconnect, and a 22-layout matrix (phones, tablets, desktop, thumb reach of every control)
# two-browser co-op incl. reconnect and chaos (stalls, half-open sockets, races), audio, keyboard / a11y, and a
# layout matrix (many phone, tablet, foldable and desktop sizes, thumb reach of every control)
```
`npm run e2e` drives Chromium through Playwright (a devDependency). Install the browser once with

View file

@ -29,13 +29,24 @@ and a check that the layout holds on **tablets and foldables**.
| Wave | Content | State |
|---|---|---|
| 1 | Phone panels/layout + touch precision (one owner of main.js/style.css), proxy/server doc fixes, QA | **done 2026-10-10** (QA passed) |
| 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave), audio + keyboard + a11y | drafted |
| 3 | Content: new towers/enemies (healer, shielded, Sandbox, Load Balancer). Done already: Orbital Uplink (sim, glyph, beam, sound, help), 4 new maps (Canyon, Archipelago, Fortress, Pinwheel) | in progress |
| 4 | Attack-vs-defend versus mode, bots for both sides | design in `docs/VERSUS.md` |
| 5 | Difficulty picker + ONE time-boxed balance pass (IDS dominance, weak Mortar/Arc, credit pile-up; maze stays strong) | after 3 and 4 |
| 1 | Phone panels/layout + touch precision, proxy/server doc fixes, QA | **done 2026-10-10** |
| 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave, restart message), audio + keyboard + a11y | **done 2026-10-10** (QA passed) |
| 3 | New enemies (Daemon healer, Proxy shielded, Botnet swarm) and towers (Sandbox stun, Load Balancer buff), glyphs/shapes, gallery e2e; Orbital Uplink (4 levels, priced 1500 + 25% per owned, upgrades scale equally); 4 new maps | **done 2026-10-10** (QA passed) |
| 4 | Difficulty picker (Easy/Normal/Hard) + ONE time-boxed balance pass (IDS dominance, weak Mortar/Arc, credit snowball and boss rewards, new content) | drafted (`wave4d`) |
| 5 | Attack-vs-defend versus mode, bots for both sides | design in `docs/VERSUS.md`, workflow drafted |
| 6 | Server leaderboard (needs `StateDirectory=netwall` + `DATA_DIR`; solo scores are client-reported) and an opt-in public room list | after 5 |
| any | Tablet/foldable viewports in the e2e matrix (near-square 690x830, 840x700, half-folded 841x400, cover 344x800) | todo |
| any | Fold/tablet real-device check; open items below | |
### Open items from wave 2 QA (all minor)
* The loser of a simultaneous Sell sees a red toast ("That tower no longer exists"); the loser of a simultaneous Keep going sees "Nothing to continue". Silence them like the stale upgrade/wave.
* A host who closes the tab (no Leave) stays host for the whole grace period (60 s), so the guest on the end screen waits that long for Play again.
* `room.js` checks the 1500-unit 'busy' cap before the sim's stale check; main.js has no wording for 'busy'.
* Any `no_room` after a successful join says "The server restarted..." even if the room merely expired (a lone sleeping phone); the tests pin the string.
* Tablet/fold polish: the co-op top bar wraps to two rows at 690x830; at 1180x820 the board letterboxes (~249 px dead band); the Players panel (Invite, Leave) is below the fold on stacked layouts; "Waiting for the host" sits flush under the Menu button.
* Test strength: the e2e 'stall' scenario passes even without the `_carryTw` fix (the sync backstop heals it; unit tests pin it); the audio fade-supersede guard is not pinned by 09-audio.
* If room codes ever get longer than 4 characters, boot's regex and the `inCode` maxlength must change together.
## Suggested order of work

View file

@ -115,7 +115,7 @@ pid for the viewer's own entry and an opaque, stable per-room alias for the othe
| message | meaning |
|---|---|
| `{t:'cmd', c:'place', type, x, y}` | build. Server calls `sim.cmd({...msg, by: slot})` (never trust a `by` from the client) |
| `{t:'cmd', c:'sell', id}` / `'upgrade'` `id` / `'target'` `id,mode` / `'wave'` / `'auto'` `v` / `'continue'` | other sim commands, same path |
| `{t:'cmd', c:'sell', id}` / `'upgrade'` `id, lv?` / `'target'` `id,mode` / `'wave'` `n?` / `'auto'` `v` / `'continue'` | other sim commands, same path. `lv` and `n` make `upgrade` and `wave` idempotent, see below |
| `{t:'ctl', c:'pause', v:bool}` / `{t:'ctl', c:'speed', v:1\|2\|3}` | room-level; reflected in `snap.pa` / `snap.sp` |
| `{t:'cursor', x, y}` | hover position in cell units (floats) or `x:null` to hide; clamp to board, round to 2 dp |
| `{t:'mark', x, y}` | map ping; at most 1 per 400 ms per player; server broadcasts `mark` (below) |
@ -124,12 +124,35 @@ pid for the viewer's own entry and an opaque, stable per-room alias for the othe
| `{t:'newgame', map}` | **host only**: replace the sim with a fresh `new Sim({map})`; resets pause/speed |
| `{t:'leave'}` | leave now |
**Idempotent `upgrade` and `wave`.** Two players who press Upgrade (or Next wave) at the same moment both send the command; without
a guard the tower would be upgraded twice and the second player charged for a level they never asked for, or two waves would start.
Both commands therefore carry what the sender *saw*: `lv` (upgrade) is the tower level on the sender's screen, `n` (wave) is the wave
number the sender expects the command to start (the wave counter they saw, plus one). The sim applies the command only if that still
holds; otherwise nothing changes and the sender gets `{ t:'reject', c, reason:'stale', id? }`. Clients treat `stale` as "your partner
was a moment faster" and show nothing. Both fields are optional (no field, no check: older clients, the balance bot and the server's
own auto-wave timer send none); when present they must be integers, anything else is a malformed message. `stale` is checked after
`over` / `no_tower` and before `max` / `gold`, so a sender who is behind is told it is stale rather than that the tower is maxed out.
Command validation is the server's job: `t:'cmd'` must carry a string `c` in the whitelist above; unknown
`c`, non-object, etc. count as malformed. A command the sim refuses (`{ok:false, reason}`) gets
`{ t:'reject', c, reason, x?, y?, id? }` sent **to the sender only** (echo `x,y`/`id` when present).
Successful commands send nothing extra; the effect arrives via `snap`.
`newgame` from a non-host -> `reject` with `reason:'not_host'`; `newgame` with a bad map -> `reject` `bad_map`.
## Client behaviour that the protocol relies on
* **Dead connections.** A joined socket gets ~20 `snap`s per second even when the game is paused, so the client treats 5 s without any
frame as a dead socket (a half-open connection after a Wi-Fi / cell switch or a NAT / proxy drop never delivers a close for a minute
or more). It shows its "reconnecting" state at once, detaches the old socket and opens a new one with the same `join` (same `pid`);
the server hands the seat to the new connection and closes the old one with 4001, which the abandoned socket ignores. A socket that
has not reached `joined` 10 s after it was opened is abandoned the same way. Retries back off up to 5 s, 14 in all.
* **Tower lists.** `tw` is sent once per `rev` change and must never be lost, whatever the render rate: a client that is stalled (hidden
tab, long frame) and gets a burst of snapshots keeps the newest undisplayed `tw` when it trims its interpolation buffer, and asks for
`sync` if `snap.rev` and the rev of the last applied list ever disagree.
* **"No such room" after a reconnect** (`error` / `no_room` in answer to a `join` for the room the client was in) means the server
restarted (rooms live in memory only) or the room expired. The client says so ("The server restarted, your game was lost.") and
forgets the saved room; after a plain connection failure it keeps the saved room, because the seat is held for `graceMs`.
## Server -> client
```
@ -148,6 +171,15 @@ Successful commands send nothing extra; the effect arrives via `snap`.
* Snapshots are sent every `1000/snapshotHz` ms **whether or not** the sim advanced (paused rooms still send, so
cursors keep moving) but only to online players, and only if at least one player is online.
* `ev` events are drained from the sim once per snapshot, so every client sees every event exactly once.
* **Tower rows** (`tw`, `state.towers`) are `[id, type, x, y, level, mode, spent, owner, pm]`; `pm` is the price multiplier the tower was bought at (1 for
almost every tower; the Orbital Uplink gets dearer for every one owned, and its upgrades cost the same multiple). Clients that ignore the ninth
field still work; the UI uses it to show the same upgrade price the sim will charge.
* **Monster entries** in `snap.mo` are `[id, kindIndex, x, y, hp, maxhp, slow]`. `kindIndex` indexes `TD.ENEMY_ORDER` (append-only, so
old and new clients agree). Two encodings keep the format fixed: a **shielded** enemy (the Proxy) sends `hp = hp + shield` and
`maxhp = maxhp + maxShield` (the client derives the shield part from the kind's base hp : shield ratio); and the `slow` flag is `1`
while the enemy is slowed **or stunned** (a stunned enemy simply stops moving, the client infers the stun from that).
* New events: `stun {x, y, r, n}` (a Sandbox pulse: centre, radius, number of enemies hit) and `heal {x, y, r}` (a Daemon pulse), besides
the Orbital Uplink's `beam {x, y, tx, ty, w, bx, by, br}`.
* Because WebSocket is reliable and ordered, `tw` deltas cannot be lost; `snap.rev` lets a client detect a
bug/desync (`rev` differs from the `rev` it last applied and no `tw` came along) and ask for `sync`.

View file

@ -23,7 +23,7 @@ opponent for either side so it can be played alone.
| Base income | 4 credits/s, rising slowly (+0.02/s per second of the round) |
| **Lifetime bonus** | every living attacker unit earns `cost x 0.004` credits per second alive, capped at 50% of its cost in total |
| Leak bonus | a unit that reaches the server pays back its full cost (and damages integrity) |
| Unit shop | every enemy kind has a `buyCost` (pinger 10, worm 14, spam pack 20, ghost 40, trojan 60, healer 70, rootkit 400, ...) |
| Unit shop | every enemy kind has a `buyCost` in the sim's `ENEMIES` table (currently ping 10, worm 6, spam 3, ghost 15, trojan 30, daemon 25, proxy 30, botnet 3, rootkit 300; about 3x the kill reward, to be tuned by the versus balance pass) |
| Caps | at most 250 units alive, 200 staged (performance) |
**Save up and launch.** Units can be bought instantly (`spawn`) or **staged** (`stage`): the price is paid now, the units wait in

View file

@ -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');
};

View file

@ -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);

View file

@ -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') || ''));

View file

@ -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
View 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
View 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');
};

View 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
View 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(' | '));
};

View 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');
};

View 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');
};

View 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();
};

View file

@ -12,6 +12,8 @@ name them in `tracks.json`:
* Formats: mp3, ogg, m4a or wav. Anything left `null` keeps the synth version.
* Loops are played with the browser's `loop` flag, so crop the track to a whole number of bars for a clean seam.
* Keep files small (a few MB) so phones start playing quickly.
* A track that is not playing 5 s after it was asked for (slow connection, missing or broken file) is replaced by the synth melody for that moment and tried again the next time it is wanted. `win` and `lose` are fetched in the background once the first `battle` track plays, `boss` a wave or two before the first boss wave (Data Saver and 2G/3G skip that).
* Browsers that refuse to start audio without a tap (iOS / iPadOS Safari, Chrome on Android) get the music at the first tap. The `volume` of an audio element is read-only on iOS, so the fades there are instant and the music plays at full file volume: master the files accordingly.
## Suno prompts

View file

@ -265,7 +265,10 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(
.wv .e i.sh-ping, .wv .e i.sh-worm { border-radius: 50%; }
.wv .e i.sh-trojan { clip-path: polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0 50%); }
.wv .e i.sh-spam { clip-path: polygon(0 20%, 60% 20%, 60% 0, 100% 50%, 60% 100%, 60% 80%, 0 80%); }
.wv .e i.sh-spoof { clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); }
.wv .e i.sh-spoof, .wv .e i.sh-ghost { clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); } /* (the kind key is "ghost": this used to be a plain square) */
.wv .e i.sh-daemon { clip-path: polygon(34% 0, 66% 0, 66% 34%, 100% 34%, 100% 66%, 66% 66%, 66% 100%, 34% 100%, 34% 66%, 0 66%, 0 34%, 34% 34%); } /* healer: a plus */
.wv .e i.sh-proxy { clip-path: polygon(0 4%, 100% 4%, 100% 58%, 50% 100%, 0 58%); } /* shielded: a shield */
.wv .e i.sh-botnet { clip-path: polygon(18% 0, 50% 32%, 82% 0, 100% 18%, 68% 50%, 100% 82%, 82% 100%, 50% 68%, 18% 100%, 0 82%, 32% 50%, 0 18%); } /* swarm drone: an X */
.wv .e i.sh-rootkit { clip-path: polygon(30% 0, 70% 0, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0 70%, 0 30%); width: 14px; height: 14px; }
.wv .tag { padding: 1px 6px; border-radius: 6px; font-size: 11px; border: 1px solid; }
.wv .tag.air { color: #e29bff; border-color: #5b3a73; }

View file

@ -51,9 +51,9 @@
<div class="spacer"></div>
<button id="btnWave" class="primary" aria-label="Start next wave"><svg class="ic"><use href="#i-play"/></svg><span id="btnWaveText">Wave 1</span></button>
<button id="btnAuto" class="icon toggle" aria-pressed="false" aria-label="Automatic waves" title="Automatic waves (A)"><span>AUTO</span></button>
<button id="btnSpeed" class="icon" aria-label="Game speed" title="Speed (F)"><span id="speedText">1×</span></button>
<button id="btnSpeed" class="icon" aria-label="Game speed 1×" title="Speed (F)"><span id="speedText">1×</span></button>
<button id="btnPause" class="icon" aria-label="Pause" aria-pressed="false" title="Pause (P)"><svg class="ic"><use href="#i-pause"/></svg></button>
<button id="btnSound" class="icon" aria-label="Sound" title="Sound (M)"><svg class="ic"><use href="#i-sound"/></svg></button>
<button id="btnSound" class="icon" aria-label="Mute sound" title="Sound (M)"><svg class="ic"><use href="#i-sound"/></svg></button>
</header>
<main id="stage">
@ -85,10 +85,10 @@
</aside>
<!-- ===== main menu: .card-body scrolls, .card-foot (the primary buttons) is always visible ===== -->
<div id="menu" class="overlay">
<div id="menu" class="overlay" role="dialog" aria-modal="true" aria-labelledby="menuTitle">
<div class="card">
<div class="card-body">
<div class="logo"><span class="logo-mark" aria-hidden="true"></span><h1>NETWALL</h1></div>
<div class="logo"><span class="logo-mark" aria-hidden="true"></span><h1 id="menuTitle">NETWALL</h1></div>
<p class="tag">Build the firewall. Stretch the route. Protect the server.</p>
<div id="mapPick" class="maps" role="radiogroup" aria-label="Map"></div>
<p id="mapDesc" class="mapdesc"></p>
@ -103,6 +103,7 @@
<div class="row small">
<button id="btnHelp" class="link">How to play</button>
<button id="btnFullscreen" class="link" hidden>Fullscreen</button>
<button id="btnMenuSound" class="link">Sound: on</button>
<button id="btnCloseMenu" class="link" hidden>Back to game</button>
</div>
</div>
@ -110,10 +111,10 @@
</div>
<!-- ===== co-op lobby ===== -->
<div id="lobby" class="overlay" hidden>
<div id="lobby" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="lobbyTitle">
<div class="card">
<div class="card-body">
<h2>Co-op online</h2>
<h2 id="lobbyTitle">Co-op online</h2>
<p class="muted lead">Two players, one base, one pool of credits. Create a room and send the link, or enter a friend's code.</p>
<label class="field"><span>Your name</span><input id="inName" maxlength="16" autocomplete="nickname" autocapitalize="words" spellcheck="false" placeholder="Player"></label>
<div class="split">
@ -140,16 +141,16 @@
</div>
<!-- ===== help ===== -->
<div id="help" class="overlay" hidden>
<div id="help" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="helpTitle">
<div class="card wide">
<div class="card-body">
<h2>How to play</h2>
<h2 id="helpTitle">How to play</h2>
<ul class="howto">
<li><b>Goal.</b> Packets pour in from the gateways (red). Don't let them reach the <b>server</b>. Each leak costs integrity (&hearts;).</li>
<li><b>Maze.</b> The map is open: <b>Firewalls</b> are cheap walls. Packets always take the shortest open route, so walls make them walk further, past your turrets. You can lengthen the route but never seal it off completely. <span class="kbd-only">Hover</span><span class="touch-only">Tap</span> to preview the new route.</li>
<li><b>Turrets.</b> Filter (fast), IDS Sniper (long range, armour-piercing), Mortar (splash), Rate Limiter (slows), Router Arc (chain lightning), and the very expensive late-game <b>Orbital Uplink</b> (a piercing beam that ignores armour, hits flyers and slows what it touches). <b>Spoofed packets fly</b> over your maze, so keep some anti-air. Mortars can't hit flyers.</li>
<li><b>Credits.</b> Earned from kills and every cleared wave. Upgrade turrets up to level 3. Sell for 70% back (walls refund in full).</li>
<li><b>Controls.</b> <span class="kbd-only">Click to build, drag to paint walls, right-click to cancel. Keys <span id="helpKeys">1&ndash;6</span> pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, wheel zooms.</span>
<li><b>Controls.</b> <span class="kbd-only">Click to build, drag to paint walls, right-click to cancel. Keys <span id="helpKeys">1&ndash;6</span> pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, M mutes, wheel zooms.</span>
<span class="touch-only">Tap a tower type, then tap the map to preview; nudge the cell with the arrows and tap &#10003; to build. Walls paint as you drag. Pinch to zoom, two fingers to pan, long-press to ping your partner.</span></li>
<li><b>Co-op.</b> Both players share everything and can build, sell and upgrade at the same time. You see each other's cursors; long-press / Alt-click pings the map.</li>
</ul>
@ -159,7 +160,7 @@
</div>
<!-- ===== game over / victory ===== -->
<div id="end" class="overlay" hidden>
<div id="end" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="endTitle" aria-describedby="endText">
<div class="card">
<div class="card-body">
<h2 id="endTitle">Breach!</h2>
@ -173,6 +174,7 @@
<button id="btnEndMenu" class="big">Menu</button>
</div>
<p id="endWait" class="msg" hidden>Waiting for the host to start a new game&hellip;</p>
<div class="row small"><button id="btnEndSound" class="link">Sound: on</button></div>
</div>
</div>
</div>

View file

@ -17,9 +17,7 @@
let unlocked = false;
let wanted = null; // music track the game currently wants ('theme' | 'battle' | 'boss' | null)
let current = null; // { name, kind:'file'|'synth', el?, stop() }
const fileState = {}; // name -> 'unknown' | 'ok' | 'missing'
const lastPlay = {};
const files = {}; // name -> HTMLAudioElement
try {
const s = JSON.parse(localStorage.getItem(STORE) || '{}');
@ -200,46 +198,115 @@
// ---------------------------------------------------------------- file music
// assets/music/tracks.json maps track names to file names, e.g. {"battle": "my-song.mp3"}; null = use the synth.
// Reading one small manifest (instead of probing for files) keeps the console free of 404s.
let manifestP = null;
function manifest() {
if (!manifestP) {
manifestP = (typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))
? fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' }).then((r) => (r.ok ? r.json() : {})).catch(() => ({}))
: Promise.resolve({});
}
//
// Rules that keep the sound right when the game asks for music faster than a file loads or a fade finishes:
// * every track has ONE element for the whole session, created the first time it is asked for (not when it can play), so
// rapid music() calls share one download (code-16);
// * a fade belongs to its element and any newer fade or restart cancels it, so a stale fade-out can never pause a track that
// was started again (code-7); the stinger has its own supersede token (code-12);
// * a file that is not playable within timing.load ms (stalled, or broken) is replaced by the synth at once, and the file is
// tried again the next time that track is wanted (code-15);
// * a play() the browser refuses (iOS / Safari autoplay rules) is retried inside the next tap, click or key press (code-14).
const timing = { load: 5000, sting: 2500, retry: 15000 }; // ms: wait for a music file / for a stinger / before retrying a file that errored
let manifestData = null, manifestP = null, manifestTried = -1e9;
function manifest() { // resolves to the manifest, or null when it could not be read (never latched: it is asked again later)
if (manifestData) return Promise.resolve(manifestData);
if (manifestP) return manifestP;
if (!(typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))) { manifestData = {}; return Promise.resolve(manifestData); }
if (Date.now() - manifestTried < timing.retry) return Promise.resolve(null);
manifestTried = Date.now();
manifestP = fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' })
.then((r) => (r.ok ? r.json() : r.status === 404 ? {} : null)) // no manifest at all = no files: synth for good; a server error is asked again later
.catch(() => null)
.then((m) => { manifestP = null; if (m && typeof m === 'object') manifestData = m; return manifestData; });
return manifestP;
}
function fileFor(name, cb) {
if (fileState[name] === 'missing') { cb(null); return; }
if (files[name]) { cb(files[name]); return; }
manifest().then((m) => {
const f = m && typeof m[name] === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(m[name]) ? m[name] : null;
if (!f) { fileState[name] = 'missing'; cb(null); return; }
const el = new Audio();
el.preload = 'auto';
el.loop = name !== 'win' && name !== 'lose';
el.addEventListener('canplay', () => { fileState[name] = 'ok'; files[name] = el; cb(el); }, { once: true });
el.addEventListener('error', () => { fileState[name] = 'missing'; cb(null); }, { once: true });
el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
el.load();
});
manifest(); // (read it up front: the first tap can then create the element and call play() inside the gesture, which iOS insists on)
function fileName(name) {
const f = manifestData && manifestData[name];
return typeof f === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(f) ? f : null;
}
const tracks = {}; // name -> { el, state: 'loading' | 'ready' | 'failed', failedAt }
// The element of a track; null when the manifest names no file for it. A failed one is tried again after timing.retry.
function track(name) {
let t = tracks[name];
if (t && t.state === 'failed' && Date.now() - t.failedAt > timing.retry) { try { t.el.removeAttribute('src'); t.el.load(); } catch (e) { /* ignore */ } t = tracks[name] = null; }
if (t) return t;
const f = fileName(name);
if (!f) return null;
const el = new Audio();
t = tracks[name] = { name, el, state: 'loading', failedAt: 0 };
el.preload = 'auto';
el.loop = name !== 'win' && name !== 'lose';
el.addEventListener('canplay', () => { if (t.state === 'loading') t.state = 'ready'; });
el.addEventListener('error', () => { if (tracks[name] === t) { t.state = 'failed'; t.failedAt = Date.now(); } });
el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
return t;
}
// Starts a track the player is not listening to yet (the boss theme before the boss, the stingers before the end). Cheap files only
// unless the connection allows it: Data Saver and 2G/3G skip it.
function preload(name) {
const c = root.navigator && root.navigator.connection;
if (c && (c.saveData || /(^|-)[23]g$/.test(c.effectiveType || ''))) return;
manifest().then(() => { if (manifestData) track(name); });
}
const fades = new WeakMap(); // element -> the fade running on it (a token object)
function cancelFade(el) { fades.delete(el); }
function fadeEl(el, to, ms, done) {
const mine = {}; fades.set(el, mine);
const from = el.volume, t0 = performance.now();
const step = () => {
const k = Math.min(1, (performance.now() - t0) / ms);
if (fades.get(el) !== mine) return; // superseded: a newer fade or a restart owns the element now
const k = ms > 0 ? Math.min(1, (performance.now() - t0) / ms) : 1;
try { el.volume = Math.max(0, Math.min(1, from + (to - from) * k)); } catch (e) { /* ignore */ }
if (k < 1) requestAnimationFrame(step); else if (done) done();
if (k < 1) setTimeout(step, 33); else { fades.delete(el); if (done) done(); } // (a timer, not rAF: a hidden tab must still finish its fade-out)
};
step();
}
const pauseEl = (el) => { try { el.pause(); } catch (e) { /* ignore */ } };
let blocked = false; // the browser refused play(): the next gesture retries (code-14)
let stingersLoaded = false; // the end-screen stingers are fetched once, after the first battle track plays
function stopCurrent(fade) {
const c = current; current = null;
if (!c || c.kind === 'pending') return;
if (!c) return;
clearTimeout(c.timer);
if (c.kind === 'synth') c.stop(fade);
else fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { try { c.el.pause(); } catch (e) { /* ignore */ } });
else if (c.el) fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { if (!(current && current.el === c.el)) pauseEl(c.el); });
}
// The generative melody stands in for a track whose file is missing, broken or too slow.
function useSynth(tok) {
clearTimeout(tok.timer);
if (current !== tok) return;
if (tok.el) { cancelFade(tok.el); pauseEl(tok.el); } // the file may still arrive: it must not start on top of the synth
const c = ensureCtx();
current = c ? startSynth(tok.name) : null;
if (current) current.name = tok.name;
}
function playFile(t, tok, keepPos) {
const el = t.el;
tok.el = el;
cancelFade(el);
if (el.paused && !keepPos) { try { el.currentTime = 0; } catch (e) { /* not seekable yet */ } el.volume = 0; } // (a track still playing, e.g. a mute undone during its fade-out, carries on)
let pr;
try { pr = el.play(); } catch (e) { pr = Promise.reject(e); }
const ok = () => {
if (current !== tok) return;
clearTimeout(tok.timer);
tok.kind = 'file';
fadeEl(el, 0.8 * musicVol, 1200);
if (tok.name === 'battle' && !stingersLoaded) { stingersLoaded = true; setTimeout(() => { preload('lose'); preload('win'); }, 1500); }
};
const bad = (err) => {
if (current !== tok) return;
const why = err && err.name;
if (why === 'AbortError') return; // paused or reloaded under it (tab hidden): the visible handler starts it again
if (why === 'NotAllowedError') { clearTimeout(tok.timer); pauseEl(el); current = null; blocked = true; return; }
t.state = 'failed'; t.failedAt = Date.now();
useSynth(tok);
};
if (pr && pr.then) pr.then(ok, bad); else ok();
}
function applyMusic() {
@ -249,57 +316,61 @@
if (current && current.name === wanted) return;
const name = wanted;
stopCurrent(0.9);
// placeholder so that rapid calls do not stack
const token = current = { name, kind: 'pending', stop() {} };
fileFor(name, (el) => {
if (current !== token) return; // superseded while loading
if (el) {
el.currentTime = 0; el.volume = 0;
const pr = el.play();
if (pr && pr.catch) pr.catch(() => { /* blocked: will retry on next gesture */ current = null; });
current = { name, kind: 'file', el, stop() {} };
fadeEl(el, 0.8 * musicVol, 1200);
} else {
const c = ensureCtx();
current = c ? startSynth(name) : null;
if (current) current.name = name;
}
});
const tok = current = { name, kind: 'pending', stop() {}, el: null, timer: 0 }; // placeholder: rapid calls do not stack, a late answer is ignored
tok.timer = setTimeout(() => { if (current === tok) useSynth(tok); }, timing.load);
const go = () => {
const t = track(name);
if (!t || t.state === 'failed') useSynth(tok); else playFile(t, tok);
};
if (manifestData) { go(); return; } // (synchronously, so that play() is still inside the tap)
manifest().then(() => { if (current === tok) go(); });
}
let stingEl = null;
let stingEl = null, stingTok = 0;
function stopStinger(fade) {
stingTok++;
const el = stingEl; stingEl = null;
if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { try { el.pause(); } catch (e) { /* ignore */ } });
if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { if (stingEl !== el) pauseEl(el); });
}
function jingle(name) { // the synth stinger, also what plays when the file is missing, late or refused
if (muted || !ctx) return;
if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
}
function stinger(name) {
if (muted || !unlocked) return;
fileFor(name, (el) => {
if (el) { try { stopStinger(0.2); stingEl = el; el.currentTime = 0; el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol)); el.play().catch(() => {}); } catch (e) { /* ignore */ } return; }
if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
});
stopStinger(0.2);
const tok = stingTok, t = manifestData ? track(name) : null;
if (!t || t.state === 'failed') { jingle(name); return; }
const el = t.el;
stingEl = el; cancelFade(el);
try { el.currentTime = 0; } catch (e) { /* not seekable yet */ }
el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol));
const fail = () => { if (tok !== stingTok) return; stingEl = null; cancelFade(el); pauseEl(el); jingle(name); };
const timer = setTimeout(fail, timing.sting); // not playing yet after this long: the synth jingle stands in, the file is dropped
let pr;
try { pr = el.play(); } catch (e) { pr = Promise.reject(e); }
if (pr && pr.then) pr.then(() => clearTimeout(timer), (err) => { clearTimeout(timer); if (!(err && err.name === 'AbortError')) fail(); });
}
// ---------------------------------------------------------------- public
function unlock() {
if (unlocked) return;
const c = ensureCtx();
if (c && c.state === 'suspended') c.resume();
unlocked = true;
applyMusic();
if (c && c.state !== 'running' && c.state !== 'closed') { try { const p = c.resume(); if (p && p.catch) p.catch(() => {}); } catch (e) { /* ignore */ } }
if (!unlocked) { unlocked = true; applyMusic(); return; }
if (blocked) { blocked = false; applyMusic(); } // a refused play() is retried at every gesture until it is allowed (code-14)
}
root.addEventListener('pointerdown', unlock, { passive: true });
root.addEventListener('keydown', unlock, { passive: true });
// Every kind of gesture, in the capture phase: pointerdown alone is no gesture for a finger (touch needs pointerup / touchend / click).
for (const ev of ['pointerdown', 'pointerup', 'touchend', 'click', 'keydown']) root.addEventListener(ev, unlock, { passive: true, capture: true });
document.addEventListener('visibilitychange', () => {
if (!ctx) return;
if (document.hidden) {
ctx.suspend && ctx.suspend();
if (current && current.kind === 'file') current.el.pause();
if (ctx && ctx.suspend) ctx.suspend();
if (current && current.el) pauseEl(current.el);
if (stingEl) pauseEl(stingEl);
} else {
ctx.resume && ctx.resume();
if (current && current.kind === 'file' && !muted) current.el.play().catch(() => {});
if (ctx && ctx.resume) ctx.resume();
if (current && current.el && !muted) { const t = tracks[current.name]; if (t && t.el === current.el) playFile(t, current, true); }
}
});
@ -307,12 +378,15 @@
sfx,
unlock,
stinger,
preload,
timing, // tunable for tests
get muted() { return muted; },
get now() { return current ? { name: current.name, kind: current.kind } : null; }, // for tests / debugging
get blocked() { return blocked; },
setMuted(m) {
muted = !!m; save();
if (master) master.gain.value = muted ? 0 : 0.9;
if (muted) stopCurrent(0.2); else applyMusic();
if (muted) { stopCurrent(0.2); stopStinger(0.2); } else applyMusic();
},
toggleMuted() { this.setMuted(!muted); return muted; },
// Which music the game wants right now: 'theme' | 'battle' | 'boss' | null
@ -321,7 +395,7 @@
setMusicVolume(v) {
musicVol = Math.min(1, Math.max(0, v)); save();
if (musBus) musBus.gain.value = 0.3 * musicVol;
if (current && current.kind === 'file') current.el.volume = 0.8 * musicVol;
if (current && current.kind === 'file') { cancelFade(current.el); current.el.volume = 0.8 * musicVol; }
},
};
})(typeof self !== 'undefined' ? self : this);

View file

@ -8,7 +8,9 @@
* gold lives maxLives wave state auto nextWaveIn kills winWave rev queued speed paused
* towers[{id,type,x,y,level,mode,spent,owner,tgt,kills}]
* monsters[{id,kind,x,y,hp,maxhp,slow,air}] bullets[{id,k,x,y}] cursors[{slot,x,y}]
* ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue
* ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue. An upgrade carries the level the player saw (lv)
* and a wave carries the wave it expects to start (n), filled in here from the view: a second player who
* pressed the same button at the same moment is refused as 'stale' (see sim.js) instead of paying twice.
* ctrl.ctl(c, v) 'pause' | 'speed'
* ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route?
* events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt'
@ -18,6 +20,9 @@
const NW = root.NW = root.NW || {};
const TD = root.TD;
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const WATCHDOG_MS = 5000; // a joined socket that has been silent this long is dead (snapshots arrive at 20 Hz)
const CONNECT_MS = 10000; // a socket that is not joined this long after it was opened is abandoned
const BUF_MAX = 10; // snapshots kept for interpolation
class Emitter {
constructor() { this._h = {}; }
@ -29,6 +34,13 @@
}
}
// What the player SAW when pressing the button (the view they were looking at), so the sim can tell a stale command from a fresh one.
function stampCmd(c, view) {
if (c.c === 'upgrade' && c.lv === undefined) { const t = view.towers.find((x) => x.id === c.id); if (t) c.lv = t.level; }
else if (c.c === 'wave' && c.n === undefined) c.n = view.wave + 1;
return c;
}
// ws(s)://<same host>/ws, relative to the page so it also works under a proxy path prefix
function wsUrl() {
const u = new URL('ws', root.location.href);
@ -80,7 +92,7 @@
if (ev.length) this.emit('events', ev);
}
send(cmd) {
const res = this.sim.cmd(Object.assign({}, cmd, { by: 0 }));
const res = this.sim.cmd(stampCmd(Object.assign({}, cmd, { by: 0 }), this.view));
if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id });
return res;
}
@ -110,6 +122,9 @@
this.ws = null; this.players = []; this.you = null; this.board = null;
this.buf = []; this.delay = 120;
this.rev = -1; this.recvRev = -1; this.towers = [];
this._carryTw = null; // the newest tower list that was pushed out of the buffer before it was displayed (coop-1)
this.resume = !!opts.resume; // rejoining a game we left (reload / Resume button): "no such room" then means it is gone
this.everJoined = false;
this.monCache = new Map(); this.bulCache = new Map(); this._gen = 0;
this.rtt = 0;
this.retry = 0; this.intentional = false; this.fatal = false;
@ -124,6 +139,11 @@
root.addEventListener('online', this._onVis);
this._timers = [];
}
// The document / window listeners must not outlive the controller (code-19): called when it dies and when it is closed.
_dispose() {
document.removeEventListener('visibilitychange', this._onVis);
root.removeEventListener('online', this._onVis);
}
connect() {
if (this.intentional || this.fatal) return;
@ -140,6 +160,23 @@
ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); };
ws.onclose = (e) => { if (this.ws === ws) this._onClose(e); };
ws.onerror = () => { /* onclose follows */ };
// A connect over a dead path can hang for minutes: give up on this socket and try again (or report it) after CONNECT_MS.
clearTimeout(this._connT);
this._connT = setTimeout(() => { if (this.ws === ws && this.status !== 'joined') this._abandon(); }, CONNECT_MS);
}
// The socket is presumed dead: no frame for WATCHDOG_MS, or the page woke up after a stall. A half-open connection (Wi-Fi / cell
// switch, NAT or proxy drop) never delivers a close for 47 to 65 s, so we do not wait for one (coop-2): forget the socket, show
// "reconnecting" now and open a fresh one. The server swaps the old connection out by pid. Handlers are detached first, so the
// dead socket's eventual close (or the server's 4001 "replaced") cannot be mistaken for the new connection's.
_abandon() {
const ws = this.ws;
this.ws = null;
clearTimeout(this._connT);
this._stopRtt();
if (ws) { ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null; try { ws.close(); } catch (e) { /* ignore */ } }
if (this.status === 'joined') { this._setStatus('reconnecting'); this.connect(); } // it was alive a moment ago: straight back in
else this._failed(); // never got in: count it, back off, give up eventually
}
_setStatus(s) { if (this.status !== s) { this.status = s; this.emit('status', s); } }
@ -155,11 +192,12 @@
}
_die(code, msg) {
this.fatal = true; this._setStatus('closed');
this._stopTimers();
this._stopTimers(); this._dispose();
this.emit('fatal', { code, msg });
}
_onClose(e) {
this.ws = null;
clearTimeout(this._connT);
this._stopRtt();
if (this.intentional || this.fatal) { this._setStatus('closed'); return; }
if (e && e.code === 4001) { this._die('replaced', 'This game was opened in another tab or device.'); return; }
@ -170,27 +208,30 @@
if (this.intentional || this.fatal || this.status === 'connecting') return;
const stale = performance.now() - this.lastMsg > 2500;
if (!this.ws || this.ws.readyState > 1) { this.retry = 0; this.connect(); }
else if (this.status === 'joined' && stale) { try { this.ws.close(); } catch (e) { /* ignore */ } }
else if (this.status === 'joined' && stale) this._abandon();
}
_stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; this._stopRtt(); }
_stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; clearTimeout(this._connT); this._stopRtt(); }
_stopRtt() { if (this._rttT) { clearInterval(this._rttT); this._rttT = 0; } if (this._wdT) { clearInterval(this._wdT); this._wdT = 0; } }
_startRtt() {
this._stopRtt();
this._rttT = setInterval(() => this._send({ t: 'rtt', ts: performance.now() }), 2000);
this._wdT = setInterval(() => { // snapshots flow at 20 Hz even when paused: silence means a dead socket
if (this.status === 'joined' && this.ws && performance.now() - this.lastMsg > 5000) { try { this.ws.close(); } catch (e) { /* ignore */ } }
if (this.status === 'joined' && this.ws && performance.now() - this.lastMsg > WATCHDOG_MS) this._abandon();
}, 1000);
}
_send(o) { if (this.ws && this.ws.readyState === 1) this.ws.send(JSON.stringify(o)); }
_onMsg(raw) {
if (this.intentional || this.fatal) return; // closed on purpose: nothing may reach the UI any more (code-3)
let m;
try { m = JSON.parse(raw); } catch (e) { return; }
if (!m || typeof m.t !== 'string') return;
switch (m.t) {
case 'snap': this._onSnap(m); break;
case 'joined':
clearTimeout(this._connT);
this.room = m.room; this.you = m.you; this.players = m.players || [];
this.everJoined = true;
this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused;
this._applyState(m.state, m.snap);
this._setStatus('joined');
@ -214,6 +255,11 @@
{ const s = performance.now() - m.ts; this.rtt = this.rtt ? Math.round(this.rtt * 0.7 + s * 0.3) : Math.round(s); this.emit('rtt', this.rtt); }
break;
case 'error': {
// "no such room" while rejoining means the server lost it: it restarted (coop-6). The code says so, the text spells it out.
if (m.code === 'no_room' && (this.everJoined || this.resume)) {
this._die('restarted', this.everJoined ? 'The server restarted, your game was lost.' : 'That co-op game is gone: the server restarted or the room timed out.');
break;
}
const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.' };
this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.');
break;
@ -227,7 +273,7 @@
b.solid.set(b.obst);
this.towers = list.map((a) => {
b.setSolid(a[2], a[3], 1);
return { id: a[0], type: a[1], x: a[2], y: a[3], level: a[4], mode: a[5], spent: a[6], owner: a[7], tgt: 0, kills: 0 };
return { id: a[0], type: a[1], x: a[2], y: a[3], level: a[4], mode: a[5], spent: a[6], owner: a[7], pm: a[8] || 1, tgt: 0, kills: 0 };
});
b.recompute();
}
@ -236,7 +282,7 @@
this._setTowers(state.towers);
this.rev = this.recvRev = state.rev;
this.maxLives = state.maxLives; this.winWave = state.winWave;
this.buf.length = 0; this.monCache.clear(); this.bulCache.clear();
this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear();
if (snap) this._push(snap, true);
}
_push(snap, first) {
@ -246,7 +292,12 @@
for (const a of snap.tt || []) tt.set(a[0], a);
const e = { t: performance.now(), snap, mo, bu, tt, rel: !!first };
this.buf.push(e);
if (this.buf.length > 10) this.buf.shift();
while (this.buf.length > BUF_MAX) {
const old = this.buf.shift();
// A stalled page (hidden tab, a long frame) gets a burst of snapshots. The server sends a tower list exactly once, so an entry
// that carries one and was never displayed must not simply vanish (coop-1): its list rides along to the next update (the newest wins).
if (old.snap.tw && !old.twDone) this._carryTw = old.snap;
}
}
// Towers ride along with the snapshot that changed them and are applied when that snapshot is *displayed*
// (see update), so a new tower and the credits it cost appear on screen together.
@ -272,10 +323,13 @@
let i = buf.length - 1;
while (i > 0 && buf[i].t > rt) i--;
const a = buf[i], b = buf[Math.min(i + 1, buf.length - 1)];
const alpha = a === b ? 1 : clamp((rt - a.t) / (b.t - a.t), 0, 1);
let lastTw = null;
for (let k = 0; k <= i; k++) { if (buf[k].snap.tw && !buf[k].twDone) { lastTw = buf[k]; } buf[k].twDone = true; }
if (lastTw) { this._setTowers(lastTw.snap.tw); this.rev = lastTw.snap.rev; }
const alpha = a === b ? 1 : clamp((rt - a.t) / Math.max(1e-3, b.t - a.t), 0, 1); // (a burst after a stall has equal arrival times)
let lastTw = this._carryTw; this._carryTw = null;
for (let k = 0; k <= i; k++) { if (buf[k].snap.tw && !buf[k].twDone) { lastTw = buf[k].snap; } buf[k].twDone = true; }
if (lastTw) { this._setTowers(lastTw.tw); this.rev = lastTw.rev; }
// Backstop: every tower list that arrived has been applied or is still waiting in the buffer. If the revisions still differ, a list
// was lost somehow: ask for the full state instead of showing a wrong maze until somebody builds again.
else if (this.rev !== this.recvRev && !buf.some((x) => x.snap.tw && !x.twDone)) this.requestSync();
const s = a.snap, v = this.view;
v.gold = s.g; v.lives = s.l; v.wave = s.w; v.state = s.s; v.auto = !!s.au; v.nextWaveIn = s.nw; v.kills = s.k;
v.rev = s.rev; v.queued = s.q || 0; v.time = s.time;
@ -319,6 +373,7 @@
send(cmd) {
const c = Object.assign({}, cmd); delete c.by;
stampCmd(c, this.view);
this._send(Object.assign({ t: 'cmd' }, c));
return { ok: true, pending: true };
}
@ -339,13 +394,20 @@
this._send({ t: 'cursor', x: x === null ? null : Math.round(x * 100) / 100, y: y === null ? null : Math.round(y * 100) / 100 });
}
sendMark(x, y) { this._send({ t: 'mark', x: Math.round(x * 100) / 100, y: Math.round(y * 100) / 100 }); }
// Leaves the room (a deliberate leave frees the seat at once) and detaches from the UI for good: after this nothing is emitted, so
// a controller that was still connecting cannot take over a game that was started meanwhile (code-3).
close() {
if (this.intentional) return;
this.intentional = true;
this._stopTimers();
document.removeEventListener('visibilitychange', this._onVis);
root.removeEventListener('online', this._onVis);
if (this.ws) { try { this._send({ t: 'leave' }); this.ws.close(); } catch (e) { /* ignore */ } }
this._stopTimers(); this._dispose();
const ws = this.ws; this.ws = null;
if (ws) {
try { if (ws.readyState === 1) ws.send(JSON.stringify({ t: 'leave' })); } catch (e) { /* ignore */ }
ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
try { ws.close(); } catch (e) { /* ignore */ }
}
this._setStatus('closed');
this._h = {};
}
}

View file

@ -6,6 +6,9 @@
const TD = root.TD, NW = root.NW, Audio = NW.Audio;
const $ = (id) => document.getElementById(id);
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
// Anything that came from the server and goes into innerHTML is escaped; colours are looked up in our own table (code-28).
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const slotColor = (slot) => (Number.isInteger(slot) && NW.SLOT_COLORS[slot]) || '#9db4d8';
// ------------------------------------------------------------------ storage (every access guarded)
const store = {
@ -89,7 +92,45 @@
const wasHidden = o.hidden; o.hidden = o.id !== id;
if (wasHidden && !o.hidden) { const body = o.querySelector('.card-body'); if (body) body.scrollTop = 0; }
}
syncModal();
}
// ------------------------------------------------------------------ dialogs (menu, lobby, help, end are role=dialog)
// While one is open the page behind it is inert (not focusable, not clickable, hidden from screen readers), focus moves into the
// dialog onto its primary button, Tab stays inside it, and focus goes back to where it was when the dialog closes (code-8).
// Overlays are also hidden and shown directly (`$('end').hidden = true`), so a MutationObserver keeps this in step.
const modal = { open: null, opener: null, guard: 0 };
const isShown = (el) => el.getClientRects().length > 0 && !el.disabled;
function syncModal() {
const ov = document.querySelector('.overlay:not([hidden])');
if (ov === modal.open) return;
const was = modal.open;
modal.open = ov;
if (ov && !was) { const a = document.activeElement; modal.opener = a && a !== document.body && a.isConnected ? a : null; } // (before the page behind it goes inert and drops focus)
for (const id of ['topbar', 'stage', 'side']) { const el = $(id); if (el) el.toggleAttribute('inert', !!ov); }
if (ov) {
const btns = [...ov.querySelectorAll('button')].filter(isShown);
const first = btns.find((b) => b.classList.contains('primary')) || btns[0]; // never a text field: on a phone that would raise the keyboard
if (ov.id === 'end') modal.guard = performance.now() + 600; // (see the click guard below)
if (first) first.focus({ preventScroll: true });
} else if (was) {
const o = modal.opener; modal.opener = null;
if (o && o.isConnected && isShown(o) && !o.closest('[inert]')) o.focus({ preventScroll: true });
}
}
root.addEventListener('keydown', (e) => { // Tab wraps inside the open dialog (browsers without `inert` would let it out)
if (e.key !== 'Tab' || !modal.open) return;
const items = [...modal.open.querySelectorAll('button, input, a[href]')].filter(isShown);
if (!items.length) { e.preventDefault(); return; }
const first = items[0], last = items[items.length - 1], a = document.activeElement;
if (!modal.open.contains(a)) { e.preventDefault(); first.focus(); }
else if (e.shiftKey && a === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && a === last) { e.preventDefault(); first.focus(); }
});
{ const mo = new MutationObserver(syncModal); for (const o of document.querySelectorAll('.overlay')) mo.observe(o, { attributes: true, attributeFilter: ['hidden'] }); }
// The game-over dialog takes focus the moment the game ends, and a player who was tapping Space / Enter to start waves would
// press its focused "Play again" with the next key and never see the result. For the first 0.6 s only a pointer can press its buttons.
$('end').addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true);
function setScreen(name) {
app.screen = name;
$('app').dataset.screen = name;
@ -99,11 +140,16 @@
function useController(ctrl) {
if (app.ctrl && app.ctrl !== ctrl && app.ctrl.kind === 'remote') { /* closed by caller */ }
app.ctrl = ctrl;
app.menuPaused = false;
if (ctrl.kind !== 'remote') { ui.coop = false; ui.names = {}; app.prevPlayers = null; } // no co-op owner flags / join toasts left over in a solo game (code-17)
ctrl.on('events', onEvents);
ctrl.on('reject', onReject);
ctrl.on('mark', (m) => { renderer.addMark(m.x, m.y, m.slot); Audio.sfx('ping'); });
ctrl.on('players', onPlayers);
ctrl.on('newgame', () => { resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true; });
ctrl.on('newgame', () => {
resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true;
app.bossMusic = false; if (app.inGame) Audio.music('battle'); // a new game starts its music on every client, not only on the one that pressed Play again (code-5)
});
adoptBoard(true);
}
function adoptBoard(force) {
@ -122,6 +168,7 @@
}
function startSolo(mapId) {
cancelPending(); // a co-op join that is still connecting must not take this game over (code-3)
leaveRemote(true);
app.mapId = mapId; store.set('nw.map', mapId);
const c = new NW.LocalController({ map: mapId });
@ -130,8 +177,14 @@
resetSelection(); setScreen('playing'); showOverlay(null);
$('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true;
renderInfo(true);
Audio.music('battle');
app.bossMusic = false; Audio.music('battle');
requestWakeLock();
firstRunHelp();
}
// The first-run help opens once per install (storage) and at most once per page load, so a browser whose storage throws does not get it on every start (code-26).
function firstRunHelp() {
if (app.helpSeen) return;
app.helpSeen = true;
if (!store.get('nw.helped', false)) { store.set('nw.helped', true); showOverlay('help'); }
}
function previewMap(mapId) {
@ -139,13 +192,14 @@
c.paused = true;
useController(c);
app.inGame = false;
releaseWakeLock(); // nobody is playing: the screen may sleep again (code-20)
}
function leaveRemote(silent) {
// keep: the connection was lost, not left on purpose, so the saved room stays and a reload or "Resume" can still try (coop-6)
function leaveRemote(silent, keep) {
const c = app.ctrl;
if (c && c.kind === 'remote') { c.close(); }
sess.del('nw.room'); store.del('nw.session');
clearRoomFromUrl();
if (!keep) { sess.del('nw.room'); store.del('nw.session'); clearRoomFromUrl(); }
if (!silent) { /* caller handles screens */ }
}
function clearRoomFromUrl() {
@ -173,6 +227,7 @@
}
let errSfxAt = -1e9;
function onReject(r) {
if (r.reason === 'stale') return; // the partner pressed the same Upgrade / Next wave an instant earlier: it already happened, say nothing (coop-5)
toast(REASONS[r.reason] || ('Not possible: ' + r.reason), 'bad');
// One buzzer per wall stroke (a stroke can reject dozens of cells), and never a burst: co-op rejects arrive after the finger has lifted (touch-16)
const now = performance.now();
@ -181,6 +236,8 @@
}
// ------------------------------------------------------------------ palette + info panel
// What building one more of this tower costs right now (the Orbital Uplink gets dearer for every one owned): same function the sim charges with
function priceOf(type) { return TD.priceFor(type, app.ctrl && app.ctrl.view ? app.ctrl.view.towers : 0); }
function buildPalette() {
const pal = $('palette');
pal.textContent = '';
@ -189,10 +246,10 @@
const def = TD.TOWERS[type];
const b = document.createElement('button');
b.className = 'tbtn'; b.dataset.type = type; b.type = 'button';
b.setAttribute('aria-label', def.name + ', ' + def.levels[0].cost + ' credits');
b.setAttribute('aria-label', def.name + ', ' + priceOf(type) + ' credits');
b.innerHTML = '<span class="key">' + def.key + '</span><canvas></canvas><span class="nm"></span><span class="cost"></span>';
b.querySelector('.nm').textContent = def.name;
b.querySelector('.cost').textContent = String(def.levels[0].cost);
b.querySelector('.cost').textContent = String(priceOf(type));
b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); });
pal.appendChild(b);
}
@ -245,12 +302,16 @@
if (L.rate) out.push(['Fire rate', L.rate.toFixed(1) + '/s']);
if (L.dmg && L.rate) out.push(['DPS', String(Math.round(L.dmg * L.rate))]);
if (L.range) out.push(['Range', L.range.toFixed(1)]);
if (L.stun) out.push(['Stun', L.stun.toFixed(1) + ' s']); // Sandbox
if (L.pulse) out.push(['Pulse', 'every ' + L.pulse.toFixed(1) + ' s']);
if (L.boost) out.push(['Fire rate', '+' + Math.round(L.boost * 100) + '%']); // Load Balancer: the bonus it gives the turrets in range
if (L.splash) out.push(['Splash', L.splash.toFixed(1)]);
if (L.slow) out.push(['Slows', Math.round(L.slow * 100) + '%']);
if (L.chains) out.push(['Chains', String(L.chains)]);
return out;
}
function targetsText(def) { return def.ground && def.air ? 'ground + air' : def.ground ? 'ground only' : 'none'; }
function aimsAtTargets(def) { return def.role !== 'wall' && def.role !== 'control' && def.role !== 'support'; } // has a Target mode and can get kills
// The info panel is built ONCE per selection (tower id + owner, or armed build type) and then updated in place, so a
// button is never replaced under a finger: partner actions bump view.rev constantly in co-op (code-2). A rebuild that
@ -267,21 +328,21 @@
if (tower) {
if (ctrl.kind === 'remote' && ctrl.players.length > 1) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
shape = 't' + tower.id + tower.type + ':' + (ownerP ? ownerP.slot + ownerP.name : '');
} else if (app.selType) shape = 'b' + app.selType;
} else if (app.selType) shape = 'b' + app.selType + ':' + priceOf(app.selType); // the price can change while armed (Orbital Uplink)
if (!force && shape === info.shape) { if (tower) syncInfo(); return; }
if (info.pressed) { info.dirty = true; return; } // never replace a node while a pointer is down on it
info.shape = shape; info.sig = ''; info.lv = 0; info.dirty = false;
if (!shape) { box.textContent = ''; return; }
if (tower) {
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall';
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', aim = aimsAtTargets(def);
box.innerHTML =
'<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div>' +
'<div class="desc"></div><div class="kv"></div><div class="actions">' +
(wall ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') +
'<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>' +
(wall ? '' : '<button type="button" data-act="mode" title="Which packet to shoot"><svg class="ic"><use href="#i-target"/></svg><span class="w">Target:</span><span class="mv"></span></button>') +
(aim ? '<button type="button" data-act="mode" title="Which packet to shoot"><svg class="ic"><use href="#i-target"/></svg><span class="w">Target:</span><span class="mv"></span></button>' : '') +
'<button type="button" data-act="close" class="icon" aria-label="Close" title="Close"><svg class="ic"><use href="#i-x"/></svg></button></div>' +
'<div class="byline">' + (wall ? '' : '<span id="infoKills"></span>') + (ownerP ? '<span class="dot" style="background:' + NW.SLOT_COLORS[ownerP.slot] + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
'<div class="byline">' + (aim ? '<span id="infoKills"></span>' : '') + (ownerP ? '<span class="dot" style="background:' + slotColor(ownerP.slot) + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
box.querySelector('.nm').textContent = def.name;
box.querySelector('.desc').textContent = def.desc;
if (ownerP) box.querySelector('#infoOwner').textContent = 'Built by ' + ownerP.name;
@ -293,7 +354,7 @@
if (app.selType !== 'wall') kv += '<div class="kvp"><span>Targets</span><span>' + targetsText(def) + '</span></div>';
box.innerHTML = '<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div><div class="desc"></div><div class="kv">' + kv + '</div></div>';
box.querySelector('.nm').textContent = def.name;
box.querySelector('.lv').textContent = def.levels[0].cost + ' credits';
box.querySelector('.lv').textContent = priceOf(app.selType) + ' credits';
box.querySelector('.desc').textContent = def.desc;
NW.drawIcon(box.querySelector('canvas'), app.selType, 1);
}
@ -304,7 +365,7 @@
const box = $('info'), view = app.ctrl.view, t = view.towers.find((x) => x.id === app.selTower);
if (!t || !box.firstChild) return;
const def = TD.TOWERS[t.type], wall = t.type === 'wall', i = t.level - 1;
const canUp = t.level < def.levels.length, upCost = canUp ? def.levels[t.level].cost : 0;
const canUp = t.level < def.levels.length, upCost = canUp ? TD.upgradePrice(t.type, t.level, t.pm) : 0;
const affordable = canUp && view.gold >= upCost;
const sellVal = def.refund ? t.spent : Math.floor(t.spent * TD.SELL_RATIO);
const sig = t.level + ':' + t.mode + ':' + sellVal + ':' + t.kills + ':' + (affordable ? 1 : 0);
@ -372,6 +433,7 @@
app.last.waveKey = key;
const box = $('nextwave');
if (view.state !== 'playing') { box.textContent = ''; return; }
if (n % 10 === 9 || n % 10 === 0) Audio.preload('boss'); // the boss theme is fetched a wave or two ahead, so it starts with the boss instead of seconds later (code-12)
const sum = TD.waveSummary(n);
let html = '<div class="panel"><h4>Next &middot; wave ' + n + '</h4><div class="wv">';
let air = false;
@ -399,14 +461,15 @@
app.prevPlayers = list.map((p) => Object.assign({}, p));
renderPlayers();
if (ctrl.kind === 'remote') renderInfo(false); // the shape includes the owner, so only a changed roster rebuilds
if (!$('end').hidden) syncEndButtons(); // the host left while the end screen is up: the promoted guest gets "Play again" (coop-3, code-11)
}
function renderPlayers() {
const ctrl = app.ctrl, box = $('players');
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
box.hidden = false;
let html = '<div class="panel"><h4>Room ' + (ctrl.room || '') + ' <span id="plPing" class="muted"></span></h4>';
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + ' <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
for (const p of ctrl.players) {
html += '<div class="pl"><span class="dot" style="background:' + NW.SLOT_COLORS[p.slot] + '"></span><span class="pn"></span>' +
html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' +
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>';
}
if (ctrl.players.length < 2) html += '<div class="muted small">Waiting for a partner&hellip; share the invite link.</div>';
@ -420,7 +483,7 @@
if (b.dataset.act === 'invite') invite();
if (b.dataset.act === 'leave') { leaveToMenu(); }
});
function inviteUrl() { return root.location.origin + root.location.pathname + '?room=' + app.ctrl.room; }
function inviteUrl() { return root.location.origin + root.location.pathname + '?room=' + encodeURIComponent(app.ctrl.room); }
function invite() {
const url = inviteUrl(), text = 'Join my Netwall game (room ' + app.ctrl.room + ')';
if (root.navigator.share) { root.navigator.share({ title: 'Netwall', text, url }).catch(() => {}); return; }
@ -448,19 +511,24 @@
const attn = idle && view.wave === 0 && view.state === 'playing';
if (L.attn !== attn) { L.attn = attn; $('btnWave').classList.toggle('attn', attn); }
if (L.auto !== view.auto) { L.auto = view.auto; $('btnAuto').setAttribute('aria-pressed', view.auto ? 'true' : 'false'); }
if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; }
if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; $('btnSpeed').setAttribute('aria-label', 'Game speed ' + view.speed + '×'); } // (the name carries the value: a screen reader hears the speed, not just "Game speed")
if (L.paused !== view.paused) { // paused: dimmed board, a resume pill, and an amber pressed pause button (not a second play triangle)
L.paused = view.paused; $('pausedTag').hidden = !view.paused; $('stage').classList.toggle('paused', !!view.paused);
$('btnPause').setAttribute('aria-pressed', view.paused ? 'true' : 'false'); $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
$('btnPause').setAttribute('aria-pressed', view.paused ? 'true' : 'false'); // a toggle keeps its name ("Pause") and announces "pressed" while paused
}
const offline = !$('reconnect').hidden;
if (L.offline !== offline) { L.offline = offline; $('app').classList.toggle('offline', offline); }
if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = '<svg class="ic"><use href="#i-' + (Audio.muted ? 'mute' : 'sound') + '"/></svg>'; }
// palette affordability
const gold = view.gold;
if (L.palGold !== gold) {
L.palGold = gold;
for (const b of $('palette').children) b.classList.toggle('poor', gold < TD.TOWERS[b.dataset.type].levels[0].cost);
const palKey = gold + ':' + view.towers.length; // prices can change when the tower count does (Orbital Uplink)
if (L.palGold !== palKey) {
L.palGold = palKey;
for (const b of $('palette').children) {
const def = TD.TOWERS[b.dataset.type], price = priceOf(b.dataset.type), poor = gold < price;
b.classList.toggle('poor', poor);
const c = b.querySelector('.cost'); if (c && c.textContent !== String(price)) c.textContent = String(price);
b.setAttribute('aria-label', def.name + ', ' + price + ' credits' + (poor ? ', not enough credits' : ''));
}
}
if (ctrl.kind === 'remote') {
const chip = $('netChip');
@ -484,17 +552,21 @@
$('endTitle').textContent = won ? 'Server secured!' : 'Breach!';
$('endTitle').style.color = won ? 'var(--green)' : 'var(--red)';
const best = store.get('nw.best.' + ctrl.board.mapId, 0);
if (!won && view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave);
if (view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave); // a win counts too (code-25)
$('endText').textContent = won ? 'You held the line through wave ' + view.wave + '. Every packet was filtered.' : 'The server fell on wave ' + view.wave + '.';
const walls = view.towers.filter((t) => t.type === 'wall').length;
const rows = [['Wave', view.wave], ['Packets killed', view.kills], ['Turrets', view.towers.length - walls], ['Firewalls', walls], ['Integrity left', view.lives], ['Best (map)', Math.max(best, view.wave)]];
$('endStats').innerHTML = rows.map((r) => '<div><span>' + r[0] + '</span><b>' + r[1] + '</b></div>').join('');
const remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
$('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
$('endStats').innerHTML = rows.map((r) => '<div><span>' + r[0] + '</span><b>' + esc(r[1]) + '</b></div>').join(''); // (in co-op these numbers come from the server)
syncEndButtons();
$('btnContinue').hidden = !won;
showOverlay('end');
Audio.music(null); Audio.stinger(won ? 'win' : 'lose');
}
// Only the host of a co-op room starts the next game: the others wait. Called when the end screen opens and whenever the roster changes.
function syncEndButtons() {
const ctrl = app.ctrl, remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
$('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
}
// ------------------------------------------------------------------ placement + previews
function cellFromEvent(e) {
@ -504,7 +576,7 @@
function placeAt(cell) {
const ctrl = app.ctrl;
if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) return false;
const cost = TD.TOWERS[app.selType].levels[0].cost;
const cost = priceOf(app.selType);
if (ctrl.view.gold < cost) { onReject({ reason: 'gold' }); return false; }
ctrl.send({ c: 'place', type: app.selType, x: cell.x, y: cell.y });
app.previewDirty = true;
@ -521,7 +593,7 @@
if (!force && !app.previewDirty && now - app.lastPreviewAt < 250) return;
app.previewDirty = false; app.lastPreviewAt = now;
const pv = ctrl.preview(cell.x, cell.y, true);
const cost = TD.TOWERS[app.selType].levels[0].cost;
const cost = priceOf(app.selType);
const poor = ctrl.view.gold < cost;
ui.preview = pv; ui.valid = pv.ok && !poor;
if (!pv.ok) hint('✕ ' + (REASONS[pv.reason] || pv.reason), 'bad');
@ -537,7 +609,7 @@
function updateConfirm() {
const show = !!(app.pending && app.selType && app.selType !== 'wall');
$('confirm').hidden = !show;
if (show) { const cost = TD.TOWERS[app.selType].levels[0].cost; $('confirmText').textContent = 'Build · ' + cost; $('btnConfirmBuild').setAttribute('aria-label', 'Build for ' + cost + ' credits'); hint(hintText, hintKind); }
if (show) { const cost = priceOf(app.selType); $('confirmText').textContent = 'Build · ' + cost; $('btnConfirmBuild').setAttribute('aria-label', 'Build for ' + cost + ' credits'); hint(hintText, hintKind); }
else if (!ptrs.size) clearCursor(); // (no pending cell, no finger down: the partner's view of our touch cursor goes)
layoutBars(true);
}
@ -837,8 +909,9 @@
if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
if (e.ctrlKey || e.metaKey) return;
if (e.repeat) return; // holding a key is one press: Space must not start 20 waves (code-6)
if (e.key && e.key.toLowerCase() === 'm' && !e.altKey) { Audio.toggleMuted(); return; } // M mutes anywhere: in the menu, behind a dialog, on the end screen (code-13)
if (!app.inGame) return;
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape') { closeOverlayToGame(); } return; }
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9)
const ctrl = app.ctrl, view = ctrl.view;
const k = e.key.toLowerCase();
// Space / Enter on a focused button or link press THAT control (keyboard users), not the next-wave hotkey (code-8)
@ -851,7 +924,6 @@
case 'p': ctrl.ctl('pause', !view.paused); break;
case 'f': ctrl.ctl('speed', view.speed % 3 + 1); break;
case 'a': ctrl.send({ c: 'auto', v: !view.auto }); break;
case 'm': Audio.toggleMuted(); break;
case 'u': if (app.selTower) $('info').querySelector('[data-act="up"]') && $('info').querySelector('[data-act="up"]').click(); break;
case 'x': case 'delete': case 'backspace': if (app.selTower) { $('info').querySelector('[data-act="sell"]') && $('info').querySelector('[data-act="sell"]').click(); e.preventDefault(); } break;
case 't': if (app.selTower) $('info').querySelector('[data-act="mode"]') && $('info').querySelector('[data-act="mode"]').click(); break;
@ -867,7 +939,21 @@
$('btnAuto').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.send({ c: 'auto', v: !app.ctrl.view.auto }); });
$('btnSpeed').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('speed', app.ctrl.view.speed % 3 + 1); });
$('btnPause').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', !app.ctrl.view.paused); });
$('btnSound').addEventListener('click', () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); });
// The sound switch exists three times: the top bar, and a text button in the menu and the end dialog (the top bar is behind a dialog). One function keeps them in step.
let soundShown = null;
function syncSound() {
const m = Audio.muted;
if (soundShown === m) return;
soundShown = m;
const b = $('btnSound');
b.innerHTML = '<svg class="ic"><use href="#i-' + (m ? 'mute' : 'sound') + '"/></svg>';
b.setAttribute('aria-label', m ? 'Unmute sound' : 'Mute sound'); // the name says what a press does; the icon shows what is the case
b.title = (m ? 'Sound is off' : 'Sound is on') + ' (M)';
for (const id of ['btnMenuSound', 'btnEndSound']) { const x = $(id); if (x) x.textContent = 'Sound: ' + (m ? 'off' : 'on'); }
}
const toggleSound = () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); syncSound(); };
for (const id of ['btnSound', 'btnMenuSound', 'btnEndSound']) $(id).addEventListener('click', toggleSound);
syncSound();
$('btnMenu').addEventListener('click', () => { Audio.sfx('click'); openMenu(); });
$('pausedTag').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', false); });
$('netChip').addEventListener('click', () => { if (app.ctrl && app.ctrl.kind === 'remote') { Audio.sfx('click'); invite(); } }); // room code chip: tap to invite
@ -905,7 +991,8 @@
}
function openMenu() {
if (app.inGame && app.ctrl.kind === 'local') app.ctrl.ctl('pause', true);
// The menu pauses a solo game, and only the menu un-pauses it again: a game the player paused themselves stays paused (code-21).
if (app.inGame && app.ctrl.kind === 'local' && !app.ctrl.view.paused) { app.ctrl.ctl('pause', true); app.menuPaused = true; }
setScreen(app.inGame ? 'playing' : 'menu');
$('btnCloseMenu').hidden = !app.inGame;
$('btnSolo').lastChild.textContent = app.inGame ? 'New solo game' : 'Play solo';
@ -915,11 +1002,13 @@
}
function closeOverlayToGame() {
if (!app.inGame) return;
if (!$('lobby').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3)
showOverlay(null);
if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false);
if (app.menuPaused) { app.menuPaused = false; if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); }
}
function leaveToMenu() {
leaveRemote(true);
function leaveToMenu(keep) {
cancelPending();
leaveRemote(true, keep);
app.prevPlayers = null;
app.inGame = false;
$('reconnect').hidden = true; $('players').hidden = true; $('netChip').hidden = true;
@ -950,11 +1039,11 @@
function openLobby(code) {
showOverlay('lobby'); setScreen(app.inGame ? 'playing' : 'menu');
$('inName').value = store.get('nw.name', '') || '';
if (code) $('inCode').value = code;
if (code) { $('inCode').value = code; $('btnJoin').focus({ preventScroll: true }); } // an invite link: Enter must join that room, not create a new one (the dialog's first button is Create room)
lobbyMsg(root.location.protocol === 'file:' ? 'Co-op needs the Netwall server: run "npm start" and open its address (the page is currently opened as a file).' : '', root.location.protocol === 'file:');
}
$('btnCoop').addEventListener('click', () => { Audio.unlock(); openLobby(); });
$('btnLobbyBack').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else openMenu(); });
$('btnLobbyBack').addEventListener('click', () => { cancelPending(); lobbyMsg(''); if (app.inGame) closeOverlayToGame(); else openMenu(); });
$('inCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
$('btnCreate').addEventListener('click', () => connectRemote({ room: null, map: app.mapId }));
$('btnJoin').addEventListener('click', () => {
@ -964,34 +1053,64 @@
});
$('inCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('btnJoin').click(); });
// The co-op controller whose join is in progress. It becomes app.ctrl only once it has joined, so a failed join (wrong code, full room)
// leaves the game that is running untouched (coop-4), Back / Play solo can cancel it (code-3), and only one attempt runs at a time (code-4).
let pendingRc = null;
const KEEP_SESSION = { connect: 1, lost: 1, replaced: 1 }; // after these the saved room is still worth another try; any other failure means it is gone
function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume']) $(id).disabled = b; }
function cancelPending() {
const rc = pendingRc; pendingRc = null;
if (rc) rc.close();
setLobbyBusy(false);
}
// opts: { room, map, resume }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist".
function connectRemote(opts) {
if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; }
if (pendingRc) return; // a double click must not open two rooms and an orphan socket
const live = app.inGame && app.ctrl && app.ctrl.kind === 'remote' ? app.ctrl : null;
if (live && opts.room && live.room === opts.room) { closeOverlayToGame(); return; } // that is the room we are in
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
store.set('nw.name', name);
if (app.ctrl && app.ctrl.kind === 'remote') app.ctrl.close();
lobbyMsg('Connecting…');
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map });
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, resume: !!opts.resume });
pendingRc = rc; setLobbyBusy(true);
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); };
let first = true;
rc.on('joined', () => {
sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() });
if (first && pendingRc !== rc) { rc.close(); return; } // cancelled while connecting: never take anything over
saveSession();
$('reconnect').hidden = true;
if (first) {
first = false;
first = false; pendingRc = null; setLobbyBusy(false);
const old = app.ctrl; if (old && old !== rc && old.kind === 'remote') old.close(); // the room we were in is left only now that the new one is ours
useController(rc);
app.inGame = true; app.started = true; app.last = {}; app.endShown = false; app.prevPlayers = null;
resetSelection(); setScreen('playing'); showOverlay(null);
onPlayers(rc.players);
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + rc.room); } catch (e) { /* ignore */ }
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
toast('Room ' + rc.room + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good');
Audio.music('battle'); requestWakeLock();
firstRunHelp(); // an invited player is new to the game too (code-26)
} else { toast('Reconnected', 'good'); adoptBoard(); }
lobbyMsg('');
});
rc.on('status', (s) => { if (app.ctrl === rc && app.inGame) $('reconnect').hidden = s !== 'reconnecting'; });
rc.on('status', (s) => {
if (app.ctrl !== rc || !app.inGame) return;
$('reconnect').hidden = s !== 'reconnecting';
if (s === 'reconnecting') saveSession(); // the 15 minutes of "Resume" count from the last time we were in the room
});
rc.on('fatal', (f) => {
sess.del('nw.room'); store.del('nw.session');
if (app.ctrl === rc && app.inGame) { toast(f.msg, 'bad'); leaveToMenu(); openLobby(); lobbyMsg(f.msg, true); }
else lobbyMsg(f.msg, true);
if (pendingRc === rc) { pendingRc = null; setLobbyBusy(false); }
const keep = !!KEEP_SESSION[f.code];
if (app.ctrl === rc && app.inGame) { // the game we were playing is gone
if (!keep) { sess.del('nw.room'); store.del('nw.session'); }
toast(f.msg, 'bad'); leaveToMenu(keep); openLobby(); lobbyMsg(f.msg, true);
return;
}
if (opts.resume && !keep) { sess.del('nw.room'); store.del('nw.session'); } // the saved game cannot be rejoined: forget it
lobbyMsg(f.msg, true);
if ($('lobby').hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24)
updateResumeButton();
});
rc.connect();
}
@ -1006,13 +1125,26 @@
const s = store.get('nw.session', null); if (!s) return;
sess.set('nw.pid', s.pid);
$('inName').value = s.name || '';
connectRemote({ room: s.room });
connectRemote({ room: s.room, resume: true });
});
// ------------------------------------------------------------------ misc platform bits
let wakeLock = null;
let wakeLock = null, wakeAsk = false;
function requestWakeLock() {
try { if (navigator.wakeLock && !wakeLock) navigator.wakeLock.request('screen').then((l) => { wakeLock = l; l.addEventListener('release', () => { wakeLock = null; }); }).catch(() => {}); } catch (e) { /* ignore */ }
if (wakeLock || wakeAsk) return;
try {
if (!navigator.wakeLock) return;
wakeAsk = true;
navigator.wakeLock.request('screen').then((l) => {
wakeAsk = false;
if (!app.inGame) { l.release().catch(() => {}); return; } // the game ended while the request was in flight
wakeLock = l; l.addEventListener('release', () => { if (wakeLock === l) wakeLock = null; });
}).catch(() => { wakeAsk = false; });
} catch (e) { wakeAsk = false; }
}
function releaseWakeLock() { // back at the menu the screen may sleep again (code-20)
const l = wakeLock; wakeLock = null;
if (l) { try { l.release().catch(() => {}); } catch (e) { /* ignore */ } }
}
document.addEventListener('visibilitychange', () => { if (!document.hidden && app.inGame) requestWakeLock(); });
@ -1066,20 +1198,25 @@
const ctrl = app.ctrl; if (!ctrl) return;
ctrl.update(now);
const view = ctrl.view;
syncSound(); // (M, the top bar, the menu and the end dialog can all flip it)
if (app.inGame) {
if (app.last.state !== view.state) {
app.last.state = view.state;
if (view.state === 'won' || view.state === 'lost') { if (!app.endShown) { app.endShown = true; endScreen(view); } }
else if (app.endShown) { app.endShown = false; $('end').hidden = true; }
else if (app.endShown) { // the game went on without this player pressing anything (the host's Keep going / Play again): its music starts here too (code-5)
app.endShown = false; $('end').hidden = true;
app.bossMusic = view.monsters.some((m) => m.kind === 'rootkit'); Audio.music(app.bossMusic ? 'boss' : 'battle');
}
}
if (app.selTower && !view.towers.some((t) => t.id === app.selTower)) { app.selTower = 0; renderInfo(true); }
if (app.pending && pendFree) { // the partner built on the cell being previewed: drop it and say so (coop-7)
const t = towerAtCell(app.pending);
if (t) { setPending(null); toast(((ui.names && ui.names[t.owner]) || 'Someone') + ' just built there', 'bad'); }
}
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower) renderInfo(false); }
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower || app.selType) renderInfo(false); }
updateHud(view);
layoutBars(false);
updateFit(); // the Reset-zoom button always follows the camera, however it was reset (code-18, coop-8)
if (now - app.lastBossCheck > 600 && view.state === 'playing') {
app.lastBossCheck = now;
const boss = view.monsters.some((m) => m.kind === 'rootkit');
@ -1108,7 +1245,7 @@
if (savedRoom && /^[A-Z0-9]{4}$/.test(savedRoom) && root.location.protocol !== 'file:' && (!codeParam || codeParam === savedRoom)) {
// page reload in the same tab: slip straight back into the room
$('inName').value = store.get('nw.name', '') || '';
connectRemote({ room: savedRoom });
connectRemote({ room: savedRoom, resume: true });
} else if (/^[A-Z0-9]{4}$/.test(codeParam)) {
openLobby(codeParam);
lobbyMsg('Enter your name and press Join.');

View file

@ -37,8 +37,8 @@
}
// ------------------------------------------------------------------ tower glyphs (also used for UI icons)
// S = tile size, (cx,cy) = centre, ang = barrel angle (radians), t = seconds (animation)
function drawGlyph(ctx, type, level, cx, cy, S, ang, t, alpha, rot) {
// S = tile size, (cx,cy) = centre, ang = barrel angle (radians), t = seconds (animation), fx = 0..1 flash right after a Sandbox pulse
function drawGlyph(ctx, type, level, cx, cy, S, ang, t, alpha, rot, fx) {
const def = TD.TOWERS[type]; if (!def) return;
const col = def.color;
ctx.save();
@ -117,6 +117,43 @@
}
break;
}
case 'sandbox': {
// containment cell: four corner brackets round a core that hums, held by thin tethers; it flashes when it pulses
const g = fx || 0, p = 0.5 + 0.5 * Math.sin(t * 3), a = S * 0.22, k = S * 0.11;
ctx.save(); ctx.translate(0, -S * 0.04);
ctx.strokeStyle = rgba(col, 0.45); ctx.lineWidth = S * 0.03;
ctx.beginPath();
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * S * 0.09, sy * S * 0.09); ctx.lineTo(sx * (a - k * 0.35), sy * (a - k * 0.35)); }
ctx.stroke();
ctx.strokeStyle = col; ctx.lineWidth = S * 0.06;
ctx.beginPath();
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * a, sy * (a - k)); ctx.lineTo(sx * a, sy * a); ctx.lineTo(sx * (a - k), sy * a); }
ctx.stroke();
const c = S * (0.095 + 0.015 * p + 0.05 * g);
ctx.beginPath(); ctx.moveTo(0, -c); ctx.lineTo(c, 0); ctx.lineTo(0, c); ctx.lineTo(-c, 0); ctx.closePath();
ctx.fillStyle = g > 0 ? '#fff3dd' : rgba(col, 0.55 + 0.3 * p); ctx.fill();
ctx.lineWidth = S * 0.035; ctx.stroke();
ctx.restore();
break;
}
case 'balancer': {
// scales: post, a gently rocking beam and two hanging pans
const dy = S * 0.27 * Math.sin(Math.sin(t * 1.4) * 0.07), ex = S * 0.27, top = -S * 0.21;
ctx.save(); ctx.translate(0, -S * 0.02);
ctx.lineWidth = S * 0.05; ctx.strokeStyle = col;
ctx.beginPath(); ctx.moveTo(0, top); ctx.lineTo(0, S * 0.14); ctx.moveTo(-S * 0.12, S * 0.15); ctx.lineTo(S * 0.12, S * 0.15); ctx.stroke();
ctx.beginPath(); ctx.moveTo(-ex, top - dy); ctx.lineTo(ex, top + dy); ctx.stroke();
for (const sx of [-1, 1]) {
const px = sx * ex, py = top + sx * dy, w = S * 0.1, d = S * 0.14;
ctx.lineWidth = S * 0.03;
ctx.beginPath(); ctx.moveTo(px - w, py + d); ctx.lineTo(px, py); ctx.lineTo(px + w, py + d); ctx.stroke();
ctx.fillStyle = rgba(col, 0.55); ctx.beginPath(); ctx.arc(px, py + d, w, 0, Math.PI); ctx.closePath(); ctx.fill();
ctx.lineWidth = S * 0.04; ctx.beginPath(); ctx.arc(px, py + d, w, 0, Math.PI); ctx.stroke();
}
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, top, S * 0.05, 0, TAU); ctx.fill();
ctx.restore();
break;
}
default: break;
}
// level pips: big enough to read at 14 px cells, with a dark halo so they show on any tile colour
@ -129,8 +166,26 @@
}
// ------------------------------------------------------------------ monsters
function drawMonster(ctx, m, ang, t, flash, rot) {
// Hit points and shield of one enemy, from either kind of view object. Solo hands the sim's monsters over (hp and shield apart:
// m.shield / m.maxShield); co-op gets hp + shield out of maxhp + maxShield from the wire, and the split follows the kind's table
// (the shield soaks first, so what is above the hit point part of the total is shield). Result is a shared scratch object.
const VIT = { hp: 0, mh: 1, sh: 0, ms: 0 };
function vitals(m, def) {
if (!def.shield) { VIT.hp = m.hp; VIT.mh = m.maxhp; VIT.sh = 0; VIT.ms = 0; }
else if (m.maxShield !== undefined) { VIT.hp = m.hp; VIT.mh = m.maxhp; VIT.sh = m.shield; VIT.ms = m.maxShield; }
else {
const mh = m.maxhp * def.hp / (def.hp + def.shield);
VIT.mh = mh; VIT.ms = m.maxhp - mh; VIT.hp = Math.min(m.hp, mh); VIT.sh = Math.max(0, m.hp - mh);
}
return VIT;
}
const SWARM = { botnet: 1 }; // swarm units die in a hit or two: no bar, no ground shadow, few particles (there can be 100+)
// stun: true while the enemy is frozen by a Sandbox (the caller knows: the sim's stunT in solo, "slow flag and not moving" in co-op)
function drawMonster(ctx, m, ang, t, flash, rot, stun) {
const def = TD.ENEMIES[m.kind], r = def.r * C, col = def.color;
const v = vitals(m, def), sf = v.ms > 0 ? clamp(v.sh / v.ms, 0, 1) : 0;
const lift = m.kind === 'ghost' ? -7 : 0;
ctx.save();
ctx.translate(m.x * C, m.y * C);
if (rot) { ctx.rotate(-rot); ang += rot; }
@ -187,20 +242,72 @@
ctx.fillStyle = rgba('#ff3b3b', 0.55 + Math.sin(t * 4) * 0.3); ctx.beginPath(); ctx.arc(0, 0, r * 0.45, 0, TAU); ctx.fill();
break;
}
case 'daemon': {
// healer: an upright plus (a medic cross), its core breathing in time with the heal pulse
const a = r * 1.3, w = r * 0.38, br = 0.5 + 0.5 * Math.sin(t * 5 + m.id);
ctx.beginPath();
ctx.moveTo(-w, -a); ctx.lineTo(w, -a); ctx.lineTo(w, -w); ctx.lineTo(a, -w); ctx.lineTo(a, w); ctx.lineTo(w, w);
ctx.lineTo(w, a); ctx.lineTo(-w, a); ctx.lineTo(-w, w); ctx.lineTo(-a, w); ctx.lineTo(-a, -w); ctx.lineTo(-w, -w); ctx.closePath();
ctx.fillStyle = '#0d2b17'; ctx.fill(); ctx.lineWidth = 2.8; ctx.strokeStyle = col; ctx.stroke();
ctx.fillStyle = rgba('#d6ffe0', 0.5 + 0.4 * br);
ctx.fillRect(-w * 0.45, -a * 0.62, w * 0.9, a * 1.24); ctx.fillRect(-a * 0.62, -w * 0.45, a * 1.24, w * 0.9);
break;
}
case 'proxy': {
// shielded relay: a heater-shield badge (never a hexagon: the Trojan is one) inside a bubble that thins as the shield goes
if (sf > 0.01) {
ctx.fillStyle = rgba('#7ab8ff', 0.07 + 0.2 * sf); ctx.beginPath(); ctx.arc(0, 0, r * 1.55, 0, TAU); ctx.fill();
ctx.lineWidth = 0.9 + 2.3 * sf; ctx.strokeStyle = rgba('#b9dcff', 0.3 + 0.65 * sf); ctx.stroke();
}
ctx.beginPath();
ctx.moveTo(-r * 0.92, -r * 0.8); ctx.lineTo(r * 0.92, -r * 0.8); ctx.lineTo(r * 0.92, r * 0.12); ctx.lineTo(0, r * 1.05); ctx.lineTo(-r * 0.92, r * 0.12); ctx.closePath();
ctx.fillStyle = '#0d1a3a'; ctx.fill(); ctx.lineWidth = 2.8; ctx.strokeStyle = col; ctx.stroke();
ctx.fillStyle = rgba(col, 0.9); ctx.beginPath(); ctx.arc(0, -r * 0.12, r * 0.3, 0, TAU); ctx.fill();
ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(0, r * 0.2); ctx.lineTo(0, r * 0.72); ctx.stroke();
break;
}
case 'botnet': {
// a drone of a swarm: spinning X of two struts with a rotor at each tip, wobbling about its path
const a = Math.max(r * 1.7, 8), wb = 2.5;
ctx.translate(Math.sin(t * 6 + m.id * 1.9) * wb, Math.cos(t * 5 + m.id * 2.3) * wb);
ctx.rotate(t * 7 + m.id);
ctx.lineWidth = 3; ctx.strokeStyle = col;
ctx.beginPath(); ctx.moveTo(-a, -a); ctx.lineTo(a, a); ctx.moveTo(a, -a); ctx.lineTo(-a, a); ctx.stroke();
ctx.fillStyle = '#a6f2ea';
ctx.beginPath();
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * a + 2.6, sy * a); ctx.arc(sx * a, sy * a, 2.6, 0, TAU); }
ctx.fill();
ctx.fillStyle = '#e8fffd'; ctx.beginPath(); ctx.arc(0, 0, r * 0.6, 0, TAU); ctx.fill();
break;
}
default:
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, r, 0, TAU); ctx.fill();
}
if (flash > 0) { ctx.globalAlpha = Math.min(0.85, flash * 9); ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r * 1.05, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; }
if (m.slow > 0) { ctx.lineWidth = 1.6; ctx.strokeStyle = 'rgba(77,227,255,.85)'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r + 3.5, 0, TAU); ctx.stroke(); }
if (flash > 0) { ctx.globalAlpha = Math.min(0.85, flash * 9); ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(0, lift, r * 1.05, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; }
if (stun) {
// frozen by a Sandbox: an ice shell with crackling crystal spikes (the cyan ring below is only a slow)
const swarm = SWARM[m.kind], s = swarm ? 7 : Math.max(r * 1.3, 7) + 2;
ctx.fillStyle = 'rgba(200,240,255,.24)'; ctx.beginPath(); ctx.arc(0, lift, s, 0, TAU); ctx.fill();
ctx.lineWidth = swarm ? 1.4 : 2; ctx.strokeStyle = '#eefbff'; ctx.stroke();
if (!swarm) {
ctx.lineWidth = 2.2; ctx.beginPath();
for (let i = 0; i < 6; i++) {
const a = i * TAU / 6 + 0.5, len = s + (Math.sin(t * 31 + i * 2.1 + m.id) > 0 ? 6 : 3.5);
ctx.moveTo(Math.cos(a) * s, lift + Math.sin(a) * s); ctx.lineTo(Math.cos(a) * len, lift + Math.sin(a) * len);
}
ctx.stroke();
}
} else if (m.slow > 0) { ctx.lineWidth = 1.6; ctx.strokeStyle = 'rgba(77,227,255,.85)'; ctx.beginPath(); ctx.arc(0, lift, r + 3.5, 0, TAU); ctx.stroke(); }
ctx.restore();
// health bar
if (m.hp < m.maxhp) {
const w = Math.max(15, r * 2.3), y = -r - (m.kind === 'ghost' ? 16 : 9), x = -w / 2;
const f = clamp(m.hp / m.maxhp, 0, 1);
// health bar (a blue shield strip above it for shielded kinds)
if (!SWARM[m.kind] && (v.hp < v.mh || v.sh < v.ms)) {
const w = Math.max(15, r * 2.3), y = -r * (sf > 0.01 ? 1.55 : 1) - (m.kind === 'ghost' ? 16 : 9), x = -w / 2;
const f = clamp(v.hp / v.mh, 0, 1);
ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot);
ctx.fillStyle = 'rgba(0,0,0,.65)'; ctx.fillRect(x - 1, y - 1, w + 2, 5);
ctx.fillStyle = 'rgba(0,0,0,.65)'; ctx.fillRect(x - 1, y - 1, w + 2, v.ms > 0 ? 8 : 5);
ctx.fillStyle = f > 0.5 ? '#35e0a1' : f > 0.25 ? '#ffd24d' : '#ff5c7a';
ctx.fillRect(x, y, w * f, 3);
ctx.fillRect(x, y + (v.ms > 0 ? 3 : 0), w * f, 3);
if (v.ms > 0) { ctx.fillStyle = '#6fb4ff'; ctx.fillRect(x, y, w * sf, 2); }
ctx.restore();
}
}
@ -214,6 +321,8 @@
this.cam = { zoom: 1, px: 0, py: 0 };
this.board = null;
this.parts = []; this.rings = []; this.lines = []; this.texts = []; this.marks = [];
this.pulses = []; // heal / stun pulses: their own small pool, so a swarm of daemons can never starve the leak and boom rings
this.glow = new Map(); // Sandbox cell index -> seconds of flash left after its pulse
this.aim = new Map(); this.trk = new Map();
this.wallGrid = null;
this.shake = 0; this.flashCore = 0; this.lastNow = 0;
@ -225,8 +334,8 @@
setBoard(board) {
this.board = board;
this.wallGrid = new Uint8Array(board.cols * board.rows);
this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0;
this.aim.clear(); this.trk.clear();
this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0; this.pulses.length = 0;
this.aim.clear(); this.trk.clear(); this.glow.clear();
this.resetCamera();
}
resize(w, h, dpr) {
@ -296,6 +405,7 @@
}
}
_ring(x, y, r0, r1, col, life, w) { if (this.rings.length < 40) this.rings.push({ x, y, r0, r1, col, life, max: life, w: w || 2 }); }
_pulse(x, y, r0, r1, col, life, w, fill) { if (this.pulses.length < 24) this.pulses.push({ x, y, r0, r1, col, life, max: life, w, fill }); }
_text(x, y, txt, col) { if (this.texts.length < 24) this.texts.push({ x, y, txt, col, life: 0.9, max: 0.9 }); }
addMark(x, y, slot) { this.marks.push({ x, y, slot: slot | 0, life: 1.6, max: 1.6 }); if (this.marks.length > 12) this.marks.shift(); }
addEvents(evs) {
@ -303,7 +413,7 @@
switch (e.e) {
case 'kill': {
const d = TD.ENEMIES[e.k];
this._burst(e.x * C, e.y * C, d ? d.color : '#fff', e.k === 'rootkit' ? 26 : 6, 90, 0.5);
this._burst(e.x * C, e.y * C, d ? d.color : '#fff', e.k === 'rootkit' ? 26 : SWARM[e.k] ? 2 : 6, 90, 0.5);
if (e.rw >= 3) this._text(e.x * C, e.y * C - 8, '+' + e.rw, '#ffd24d');
break;
}
@ -334,6 +444,15 @@
case 'place': { const d = TD.TOWERS[e.type]; this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 34, d ? d.color : '#fff', 0.35, 2.5); this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, d ? d.color : '#fff', 5, 60, 0.35); break; }
case 'sell': this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, '#9db4d8', 6, 70, 0.35); break;
case 'up': this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 38, '#ffffff', 0.4, 2.5); break;
case 'stun': { // Sandbox pulse: an amber wave out to its range, a white one inside it, and the glyph flashes
const d = TD.TOWERS.sandbox, col = d ? d.color : '#ffa447', b = this.board;
const rg = (e.r || 3) * C;
this._pulse(e.x * C, e.y * C, 10, rg, col, 0.55, 3.5, 0.13);
this._pulse(e.x * C, e.y * C, 8, rg * 0.6, '#fff3dd', 0.35, 2, 0);
if (b) this.glow.set(Math.floor(e.y) * b.cols + Math.floor(e.x), 0.4);
break;
}
case 'heal': this._pulse(e.x * C, e.y * C, 10, (e.r || 2.2) * C, '#7ee08a', 0.7, 2.2, 0.07); break; // soft green wave out to the daemon's range
default: break;
}
}
@ -413,6 +532,9 @@
const monById = new Map();
for (let i = 0; i < view.monsters.length; i++) monById.set(view.monsters[i].id, view.monsters[i]);
if (this.glow.size) for (const [k, g] of this.glow) { if (g - dt <= 0) this.glow.delete(k); else this.glow.set(k, g - dt); }
this._drawLinks(ctx, towers, ui, t);
const coop = ui.coop;
for (let i = 0; i < towers.length; i++) {
const tw = towers[i];
@ -421,7 +543,8 @@
const tg = tw.tgt ? monById.get(tw.tgt) : null;
if (tg) { ang = lerpAngle(ang, Math.atan2(tg.y - (tw.y + 0.5), tg.x - (tw.x + 0.5)), 0.35); this.aim.set(tw.id, ang); }
const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C;
drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot);
const gl = tw.type === 'sandbox' && this.glow.size ? this.glow.get(tw.y * cols + tw.x) : 0;
drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot, gl ? Math.min(1, gl / 0.25) : 0);
if (coop && tw.type !== 'wall') { // owner corner flag: at least ~5 CSS px, dark outline so it shows on a tile of the same colour
const k = Math.max(12, 5.5 / sc), x0 = cx - C * 0.46, y0 = cy - C * 0.46;
ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + k, y0); ctx.lineTo(x0, y0 + k); ctx.closePath();
@ -502,6 +625,47 @@
if (labels.length) this._cursorLabels(ctx, labels);
}
// Load Balancer links: dashed lines (flowing towards the turret) and an outline on every attack tower it boosts, only for the balancer that is
// selected, hovered or about to be built, so a busy board stays calm. Same rule as the sim's updateAuras: attack role, centre to centre
// within range. (The wire has no per-tower buff flag, so this is worked out here from the tower list.)
_drawLinks(ctx, towers, ui, t) {
let src = null;
if (ui.selTower) { const st = towers.find((x) => x.id === ui.selTower); if (st) src = st; }
if (!src && ui.hover) {
for (let i = 0; i < towers.length; i++) if (towers[i].x === ui.hover.x && towers[i].y === ui.hover.y) { src = towers[i]; break; }
if (!src && ui.selType && !ui.noGhost) src = { type: ui.selType, level: 1, x: ui.hover.x, y: ui.hover.y };
}
const def = src && TD.TOWERS[src.type];
if (!def || def.role !== 'support') return;
const lv = def.levels[src.level - 1] || def.levels[0], r2 = (lv.range || 0) * (lv.range || 0);
const bx = (src.x + 0.5) * C, by = (src.y + 0.5) * C;
let lines = null;
for (let i = 0; i < towers.length; i++) {
const tw = towers[i], d = TD.TOWERS[tw.type];
if (!d || d.role !== 'attack' || tw === src) continue;
const dx = tw.x - src.x, dy = tw.y - src.y;
if (dx * dx + dy * dy > r2) continue;
(lines || (lines = [])).push(tw);
}
if (!lines) return;
const u = Math.max(1, 0.55 / this.scale), lw = Math.max(2, 1.2 / this.scale); // keep the dashes and arrowheads readable when the cells are small
ctx.save();
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
ctx.strokeStyle = rgba(def.color, 0.75); ctx.lineWidth = lw; ctx.setLineDash([6 * u, 5 * u]); ctx.lineDashOffset = -t * 16;
ctx.beginPath();
for (const tw of lines) { ctx.moveTo(bx, by); ctx.lineTo((tw.x + 0.5) * C, (tw.y + 0.5) * C); }
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = rgba(def.color, 0.95); ctx.lineWidth = lw;
for (const tw of lines) { // an arrowhead just outside the tile, and a frame round it
const tx = (tw.x + 0.5) * C, ty = (tw.y + 0.5) * C, a = Math.atan2(ty - by, tx - bx), d = C * 0.62 + 4 * u;
const ax = tx - Math.cos(a) * d, ay = ty - Math.sin(a) * d, ca = Math.cos(a), sa = Math.sin(a);
ctx.beginPath(); ctx.moveTo(ax + ca * 6 * u, ay + sa * 6 * u); ctx.lineTo(ax - ca * 3 * u - sa * 5 * u, ay - sa * 3 * u + ca * 5 * u); ctx.lineTo(ax - ca * 3 * u + sa * 5 * u, ay - sa * 3 * u - ca * 5 * u); ctx.closePath(); ctx.fill();
rr(ctx, tw.x * C + 1.5, tw.y * C + 1.5, C - 3, C - 3, 6); ctx.stroke();
}
ctx.restore();
}
_rangeRing(ctx, cx, cy, r, col) {
ctx.fillStyle = rgba(col, 0.07); ctx.beginPath(); ctx.arc(cx, cy, r, 0, TAU); ctx.fill();
ctx.strokeStyle = rgba(col, 0.55); ctx.lineWidth = 1.5; ctx.stroke();
@ -559,17 +723,33 @@
_drawMonsters(ctx, view, t, dt, air, rot) {
const trk = this.trk;
if (!air) { // a Daemon's heal range, faint, all in one stroke
let any = false;
for (const m of view.monsters) {
const d = TD.ENEMIES[m.kind];
if (!d.healRange) continue;
if (!any) { any = true; ctx.beginPath(); }
ctx.moveTo(m.x * C + d.healRange * C, m.y * C); ctx.arc(m.x * C, m.y * C, d.healRange * C, 0, TAU);
}
if (any) { ctx.strokeStyle = rgba(TD.ENEMIES.daemon.color, 0.15); ctx.lineWidth = 1.5; ctx.stroke(); }
}
for (const m of view.monsters) {
if (!!m.air !== air) continue;
const def = TD.ENEMIES[m.kind];
let k = trk.get(m.id);
if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0 }; trk.set(m.id, k); }
if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0, still: 0, sv: null }; trk.set(m.id, k); }
const dm = def.shield && m.maxShield === undefined ? this._shieldView(k, m, def, dt) : m; // co-op: tell hp and shield apart (see there)
const v = vitals(dm, def), cur = v.hp + v.sh;
const dx = m.x - k.x, dy = m.y - k.y;
if (dx * dx + dy * dy > 1e-6) k.ang = lerpAngle(k.ang, Math.atan2(dy, dx), 0.35);
k.still = dx * dx + dy * dy < 1e-8 ? k.still + dt : 0;
k.x = m.x; k.y = m.y;
if (m.hp < k.hp) k.flash = 0.1;
k.hp = m.hp; k.flash = Math.max(0, k.flash - dt);
if (air) { const er = TD.ENEMIES[m.kind].r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
drawMonster(ctx, m, k.ang, t, k.flash, rot);
if (cur < k.hp) k.flash = 0.1;
k.hp = cur; k.flash = Math.max(0, k.flash - dt);
// stunned: solo knows (stunT); in co-op the wire only says "slowed or stunned", and a slowed packet still moves, so a flagged packet that stands still is stunned
const stun = m.stunT !== undefined ? m.stunT > 0 : m.slow > 0 && k.still > 0.2 && !view.paused;
if (air && !SWARM[m.kind]) { const er = def.r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
drawMonster(ctx, dm, k.ang, t, k.flash, rot, stun);
}
if (air && trk.size > view.monsters.length + 60) { // drop stale trackers
const live = new Set(view.monsters.map((x) => x.id));
@ -577,6 +757,27 @@
}
}
// Co-op sends a shielded enemy as hp + shield out of maxhp + maxShield. A shield soaks first, so most of the time the split is plain from the
// total, but once the hp is hurt and the shield has regrown the total alone is ambiguous (hp 20 + shield 120 looks like hp 90 + shield 50).
// So the split is followed over time: a drop in the total hits the shield first, a rise after shieldDelay seconds without a hit refills the
// shield, any other rise is a heal. Returns a solo-style view object (hp and shield apart) kept in the tracker entry.
_shieldView(k, m, def, dt) {
const mh = m.maxhp * def.hp / (def.hp + def.shield), ms = m.maxhp - mh;
let s = k.sv;
if (!s) s = k.sv = { id: m.id, kind: m.kind, air: m.air, x: 0, y: 0, hp: 0, maxhp: mh, shield: clamp(m.hp - mh, 0, ms), maxShield: ms, slow: 0, tot: m.hp, idle: 0 };
else {
const d = m.hp - s.tot;
if (d < -0.5) { s.shield -= Math.min(s.shield, -d); s.idle = 0; }
else if (d > 0.5 && s.idle >= def.shieldDelay - 0.25 && s.shield < ms) s.shield = Math.min(ms, s.shield + d);
s.tot = m.hp; s.idle += dt;
}
s.maxhp = mh; s.maxShield = ms;
if (m.hp - s.shield > mh) s.shield = clamp(m.hp - mh, 0, ms); // more than the hp part can hold: the rest is shield
s.hp = clamp(m.hp - s.shield, 0, mh);
s.x = m.x; s.y = m.y; s.slow = m.slow; s.air = m.air;
return s;
}
_drawFx(ctx, dt, sc, rot) {
// lines (tracers, arcs)
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
@ -600,6 +801,15 @@
ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU); ctx.stroke();
}
ctx.globalAlpha = 1;
for (let i = this.pulses.length - 1; i >= 0; i--) {
const r = this.pulses[i]; r.life -= dt;
if (r.life <= 0) { this.pulses.splice(i, 1); continue; }
const k = 1 - r.life / r.max;
ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU);
if (r.fill) { ctx.globalAlpha = (1 - k) * r.fill; ctx.fillStyle = r.col; ctx.fill(); }
ctx.globalAlpha = 1 - k; ctx.strokeStyle = r.col; ctx.lineWidth = r.w; ctx.stroke();
}
ctx.globalAlpha = 1;
for (let i = this.parts.length - 1; i >= 0; i--) {
const p = this.parts[i]; p.life -= dt;
if (p.life <= 0) { this.parts.splice(i, 1); continue; }
@ -651,6 +861,7 @@
NW.Renderer = Renderer;
NW.drawIcon = drawIcon;
NW.drawGlyph = drawGlyph;
NW.drawMonster = drawMonster;
NW.SLOT_COLORS = SLOT_COLORS;
NW.CELL = C;
NW.BOARD_MARGIN = MARGIN;

View file

@ -201,16 +201,21 @@
}
// ---------------------------------------------------------------- definitions
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'uplink'];
// Every tower has a 'role' so the generic code does not have to know the types:
// wall solid block, does nothing attack shoots (dmg/rate, picks a target, can be rate-boosted)
// aura continuous effect in range control periodic pulse that stuns everything in range
// support no attack of its own: boosts the 'attack' towers around it
// Hotkeys: one unique key 1-9 per tower, in palette order.
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'sandbox', 'balancer', 'uplink'];
const TARGET_MODES = ['first', 'last', 'strong', 'close'];
const TOWERS = {
wall: {
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1,
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1, role: 'wall',
desc: 'Blocks the route. Cheap: use it to build a long maze.',
levels: [{ cost: 5 }],
},
filter: {
name: 'Packet Filter', key: '2', color: '#35e0a1', air: true, ground: true,
name: 'Packet Filter', key: '2', color: '#35e0a1', role: 'attack', air: true, ground: true,
desc: 'Fast, cheap rapid fire. Weak against armour.',
levels: [
{ cost: 25, dmg: 6, range: 3.2, rate: 3.0 },
@ -220,7 +225,7 @@
bulletSpeed: 14,
},
ids: {
name: 'IDS Sniper', key: '3', color: '#b78cff', air: true, ground: true,
name: 'IDS Sniper', key: '3', color: '#b78cff', role: 'attack', air: true, ground: true,
desc: 'Long range, hard hitting, slow. Great against armour and bosses.',
levels: [
{ cost: 60, dmg: 50, range: 6.5, rate: 0.7 },
@ -229,7 +234,7 @@
],
},
mortar: {
name: 'Flood Mortar', key: '4', color: '#d4f04a', air: false, ground: true,
name: 'Flood Mortar', key: '4', color: '#d4f04a', role: 'attack', air: false, ground: true,
desc: 'Splash damage against ground swarms. Cannot hit flyers.',
levels: [
{ cost: 55, dmg: 28, range: 4.8, rate: 0.8, splash: 1.3 },
@ -239,7 +244,7 @@
shellSpeed: 5.5,
},
throttle: {
name: 'Rate Limiter', key: '5', color: '#4de3ff', air: true, ground: true,
name: 'Rate Limiter', key: '5', color: '#4de3ff', role: 'aura', air: true, ground: true,
desc: 'Slows everything in range. Pair it with damage dealers.',
levels: [
{ cost: 40, range: 3.2, slow: 0.35 },
@ -248,7 +253,7 @@
],
},
arc: {
name: 'Router Arc', key: '6', color: '#ff7ad9', air: true, ground: true,
name: 'Router Arc', key: '6', color: '#ff7ad9', role: 'attack', air: true, ground: true,
desc: 'Chain lightning that jumps between nearby packets.',
levels: [
{ cost: 75, dmg: 16, range: 3.6, rate: 1.2, chains: 2, chainRange: 1.9, falloff: 0.7 },
@ -256,27 +261,82 @@
{ cost: 120, dmg: 36, range: 4.2, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
],
},
uplink: {
name: 'Orbital Uplink', key: '7', color: '#ffe27a', air: true, ground: true,
desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Very expensive to build and to upgrade.',
sandbox: {
name: 'Sandbox', key: '7', color: '#ffa447', role: 'control', air: true, ground: true,
desc: 'Control tower, no damage. Every few seconds it traps every packet in range, ground and air, and freezes it for a moment. Bosses resist and are frozen for half as long.',
levels: [
{ cost: 450, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
{ cost: 500, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
{ cost: 800, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
{ cost: 1200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
{ cost: 90, range: 2.6, pulse: 5.0, stun: 1.0 },
{ cost: 80, range: 3.0, pulse: 4.5, stun: 1.3 },
{ cost: 130, range: 3.4, pulse: 4.0, stun: 1.6 },
],
},
balancer: {
name: 'Load Balancer', key: '8', color: '#d3e0ee', role: 'support',
desc: 'Support tower, no attack. Makes every turret in range fire faster. Several balancers do not stack (the best one counts) and a balancer does not boost another balancer.',
levels: [
{ cost: 70, range: 2.2, boost: 0.15 },
{ cost: 70, range: 2.6, boost: 0.25 },
{ cost: 110, range: 3.0, boost: 0.35 },
],
},
uplink: {
name: 'Orbital Uplink', key: '9', color: '#ffe27a', role: 'attack', air: true, ground: true,
desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Extremely expensive to build and to upgrade, and every Uplink you already own makes the next one 25% dearer, and its upgrades too.',
priceGrowth: 1.25, // the Nth Uplink costs cost * 1.25^(N-1) to buy AND to upgrade (see priceMult), so kill rewards cannot buy a carpet of them
levels: [
{ cost: 1500, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
{ cost: 1200, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
{ cost: 2000, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
{ cost: 3200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
],
},
};
const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit'];
// ENEMY_ORDER is part of the wire format (snapshots carry the index): only ever APPEND kinds.
// buyCost is the price of one unit in the future versus mode (about 3x the kill reward).
// What building one more `type` costs right now, given the towers already on the board (an array, or a plain count).
// Most towers have a fixed price; a tower with `priceGrowth` gets dearer for every one already owned. Shared by the Sim and
// the UI so the price shown is always the price charged.
// The price multiplier a NEW tower of this type is bought at, given how many are already owned. Each tower remembers the multiplier it was
// bought at (tower.pm) and its upgrades cost the same multiple, so the Nth Uplink is dearer to buy and to upgrade by the same factor.
function priceMult(type, owned) {
const def = TOWERS[type];
if (!def || !def.priceGrowth) return 1;
let n = 0;
if (Array.isArray(owned)) { for (const t of owned) if (t.type === type) n++; } else n = owned | 0;
return Math.pow(def.priceGrowth, n);
}
const roundPrice = (v) => Math.round(v / 10) * 10;
function priceFor(type, owned) {
const def = TOWERS[type];
if (!def) return 0;
const base = def.levels[0].cost, m = priceMult(type, owned);
return m === 1 ? base : roundPrice(base * m);
}
// What upgrading a tower of `type` that is at `level` (1-based) to the next level costs, given the multiplier it was bought at (pm, default 1).
function upgradePrice(type, level, pm) {
const def = TOWERS[type], lv = def && def.levels[level];
if (!lv) return null;
return !pm || pm === 1 ? lv.cost : roundPrice(lv.cost * pm);
}
const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit', 'daemon', 'proxy', 'botnet'];
const ENEMIES = {
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a' },
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43' },
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b' },
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166' },
ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff' },
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', slowRes: 0.5 },
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a', buyCost: 10 },
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43', buyCost: 6 },
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b', buyCost: 30 },
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166', buyCost: 3 },
ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff', buyCost: 15 },
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', buyCost: 300, slowRes: 0.5 },
// Healer: every HEAL_EVERY s it restores 'heal' of the max hp of every other enemy within healRange (several daemons stack up to HEAL_CAP).
daemon: { name: 'Daemon', hp: 70, speed: 1.1, armor: 0, reward: 8, leak: 1, air: false, r: 0.3, color: '#7ee08a', buyCost: 25, heal: 0.06, healRange: 2.2 },
// Shielded: 'shield' extra hit points (scaled like hp) that soak damage first and regrow shieldRegen/s of their max after shieldDelay s unhurt.
proxy: { name: 'Proxy', hp: 90, speed: 1.0, armor: 1, reward: 10, leak: 1, air: false, r: 0.34, color: '#7aa2ff', buyCost: 30, shield: 120, shieldRegen: 0.1, shieldDelay: 3 },
// Swarm flyer.
botnet: { name: 'Botnet', hp: 12, speed: 2.6, armor: 0, reward: 1, leak: 1, air: true, r: 0.14, color: '#4dd0c8', buyCost: 3 },
};
const HEAL_EVERY = 1; // seconds between daemon pulses (one global clock, so the 12%/s cap is exact)
const HEAL_CAP = 0.12; // most max-hp fraction one enemy can be healed per pulse, however many daemons are near
// Wave n (1-based). The first eight waves introduce each unit type; later ones loop with bigger numbers.
function waveGroups(n) {
@ -293,12 +353,42 @@
case 6: g = [{ k: 'ghost', c: c(8), gap: 0.6 }, { k: 'spam', c: c(16), gap: 0.2 }]; break;
default: g = [{ k: 'ping', c: c(10), gap: 0.4 }, { k: 'trojan', c: c(3), gap: 1.0 }, { k: 'ghost', c: c(4), gap: 0.8 }];
}
if (n > 8) weave(g, n, c, (n - 1) % 8);
if (n % 10 === 0) g.push({ k: 'rootkit', c: n / 10, gap: 3 });
return g;
}
// From wave 9 the eight-wave cycle gets the newer kinds woven in (groups spawn one after the other, so a group
// appended behind another trails it):
// daemon the first healer rides with the pings of wave 9; from then on every trojan group has an escort that
// spawns behind it and (it is faster) catches up and heals while passing through
// proxy from wave 12 in the spam / mixed-flyer-and-trojan slots, more slots later
// botnet swarms from wave 14, more slots (and bigger) later
function weave(g, n, c, p) {
const trojans = g.find((e) => e.k === 'trojan');
if (trojans) g.push({ k: 'daemon', c: Math.max(1, Math.round(trojans.c / 2)), gap: 1.2 });
else if (n === 9) g.push({ k: 'daemon', c: 2, gap: 1.2 });
if (n >= 12) {
if (p === 3) g.push({ k: 'proxy', c: c(2), gap: 1.6 });
else if (p === 7) g.push({ k: 'proxy', c: c(2), gap: 1.4 });
else if (p === 5 && n >= 22) g.push({ k: 'proxy', c: c(2), gap: 1.4 });
else if (p === 2 && n >= 19) g.push({ k: 'proxy', c: c(1), gap: 1.6 });
else if (p === 0 && n >= 25) g.push({ k: 'proxy', c: c(1), gap: 1.6 });
}
if (n >= 14) {
if (p === 5) g.push({ k: 'botnet', c: c(8), gap: 0.12 });
else if (p === 6) g.push({ k: 'botnet', c: c(8), gap: 0.1 });
else if (p === 1 && n >= 18) g.push({ k: 'botnet', c: c(6), gap: 0.1 });
else if (p === 4 && n >= 21) g.push({ k: 'botnet', c: c(8), gap: 0.1 });
else if (p === 7 && n >= 24) g.push({ k: 'botnet', c: c(6), gap: 0.12 });
}
}
// What the wave list in the UI shows: one entry per kind (counts summed), in order of appearance, flyers flagged.
function waveSummary(n) {
const out = [];
for (const g of waveGroups(n)) out.push({ k: g.k, c: g.c });
const out = [], at = {};
for (const g of waveGroups(n)) {
if (at[g.k] === undefined) { at[g.k] = out.length; out.push({ k: g.k, c: 0, air: !!ENEMIES[g.k].air }); }
out[at[g.k]].c += g.c;
}
return out;
}
function hpScale(n) { return 1 + 0.16 * (n - 1) + 0.022 * (n - 1) * (n - 1); }
@ -487,6 +577,7 @@
this.autoWaves = false;
this.nextWaveIn = -1;
this.spawnRR = 0;
this.healT = 0; // seconds since the last daemon pulse (one clock for all daemons)
this.towers = [];
this.towerAt = new Array(this.board.cols * this.board.rows).fill(null);
@ -509,9 +600,9 @@
switch (c.c) {
case 'place': return this.place(c.type, c.x, c.y, c.by | 0);
case 'sell': return this.sell(c.id);
case 'upgrade': return this.upgrade(c.id);
case 'upgrade': return this.upgrade(c.id, c.lv);
case 'target': return this.setTargetMode(c.id, c.mode);
case 'wave': return this.startWave();
case 'wave': return this.startWave(c.n);
case 'auto': return this.setAuto(!!c.v);
case 'continue': return this.continueEndless();
default: return { ok: false, reason: 'bad_cmd' };
@ -548,13 +639,13 @@
if (this.state !== 'playing') return { ok: false, reason: 'over' };
if (typeof type !== 'string' || !Object.prototype.hasOwnProperty.call(TOWERS, type)) return { ok: false, reason: 'bad_type' };
const def = TOWERS[type];
const cost = def.levels[0].cost;
const cost = priceFor(type, this.towers), pm = priceMult(type, this.towers);
if (this.gold < cost) return { ok: false, reason: 'gold' };
const t = this.preview(x, y, false);
if (!t.ok) return { ok: false, reason: t.reason };
const tower = {
id: this.nid++, type, x, y, level: 1, mode: 'first', spent: cost, owner: by | 0,
cd: 0, tgt: 0, kills: 0, dealt: 0,
id: this.nid++, type, x, y, level: 1, mode: 'first', spent: cost, owner: by | 0, pm,
cd: 0, tgt: 0, kills: 0, dealt: 0, buff: 0,
};
this.gold -= cost;
this.towers.push(tower);
@ -587,14 +678,14 @@
return { ok: true, refund };
}
upgradeCost(t) {
const lv = TOWERS[t.type].levels[t.level];
return lv ? lv.cost : null;
}
upgrade(id) {
upgradeCost(t) { return upgradePrice(t.type, t.level, t.pm); }
// `lv` is the level the sender SAW when it pressed Upgrade (absent: no check). Two players pressing it at the same moment send the
// same command twice; the second one finds the tower already a level higher and is refused as 'stale' instead of being charged again.
upgrade(id, lv) {
if (this.state !== 'playing') return { ok: false, reason: 'over' };
const t = this.towerById(id);
if (!t) return { ok: false, reason: 'no_tower' };
if (lv !== undefined && lv !== null && lv !== t.level) return { ok: false, reason: 'stale' };
const cost = this.upgradeCost(t);
if (cost === null) return { ok: false, reason: 'max' };
if (this.gold < cost) return { ok: false, reason: 'gold' };
@ -628,8 +719,11 @@
return { ok: true };
}
startWave() {
// `expect` is the wave number the sender expects this command to start (the wave it saw + 1; absent: no check; the auto-wave timer
// never passes one). A second "Next wave" pressed at the same moment by the other player is refused as 'stale', not started twice.
startWave(expect) {
if (this.state !== 'playing') return { ok: false, reason: 'over' };
if (expect !== undefined && expect !== null && expect !== this.wave + 1) return { ok: false, reason: 'stale' };
const n = ++this.wave;
let t = this.time + 0.3;
for (const g of waveGroups(n)) {
@ -647,12 +741,15 @@
const b = this.board;
const s = b.spawns[this.spawnRR++ % b.spawns.length];
const hp = Math.round(def.hp * hpScale(q.wave));
const shield = def.shield ? Math.round(def.shield * hpScale(q.wave)) : 0;
const m = {
id: this.nid++, kind: q.k, air: !!def.air,
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1,
hp, maxhp: hp, armor: def.armor, speed: def.speed,
reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave))),
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, rem: 0, dead: false, wave: q.wave,
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
shield, maxShield: shield, shieldT: 0,
rem: 0, dead: false, wave: q.wave,
};
m.rem = m.air
? Math.hypot(b.core.x - s.x, b.core.y - s.y)
@ -672,7 +769,12 @@
for (const m of this.monsters) { // slow = lingering slow (Orbital Uplink) unless a Rate Limiter says more
if (m.slowT > 0) { m.slow = m.slowAmt; m.slowT -= dt; } else m.slow = 0;
if (m.stunT > 0) m.stunT -= dt;
if (m.maxShield > 0) this.regenShield(m, dt);
}
this.healT += dt;
if (this.healT >= HEAL_EVERY) { this.healT -= HEAL_EVERY; this.healPulse(); }
this.updateAuras();
for (const t of this.towers) this.updateTower(t, dt);
this.updateBullets(dt);
for (const m of this.monsters) if (!m.dead) this.moveMonster(m, dt);
@ -704,6 +806,7 @@
// ---- monsters -------------------------------------------------------------------------
moveMonster(m, dt) {
if (m.stunT > 0) return; // stunned (Sandbox): frozen in place
const b = this.board;
const slowMul = 1 - Math.min(0.6, m.slow);
let remaining = m.speed * slowMul * dt;
@ -747,8 +850,13 @@
damage(m, raw, src, ignoreArmor) {
if (m.dead) return;
const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25);
m.hp -= d;
const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25); // armour applies once, to the damage dealt
let hit = d;
if (m.maxShield > 0) { // a shield soaks first, any damage restarts its regrow timer
const soak = Math.min(m.shield, d);
m.shield -= soak; hit = d - soak; m.shieldT = 0;
}
m.hp -= hit;
if (src) src.dealt += d;
if (m.hp <= 0) {
m.dead = true;
@ -759,6 +867,51 @@
}
}
// Shield: after shieldDelay s without damage it regrows shieldRegen of its maximum per second.
regenShield(m, dt) {
const def = ENEMIES[m.kind];
m.shieldT += dt;
const over = Math.min(dt, m.shieldT - def.shieldDelay);
if (over > 0 && m.shield < m.maxShield) m.shield = Math.min(m.maxShield, m.shield + m.maxShield * def.shieldRegen * over);
}
// Daemon pulse, once a second on the sim's own clock: every enemy gets healed by the daemons around it (never by itself),
// together at most HEAL_CAP of its max hp, never above max. Shields are not healed.
healPulse() {
let ds = null;
for (const m of this.monsters) if (!m.dead && ENEMIES[m.kind].heal) (ds || (ds = [])).push(m);
if (!ds) return;
const did = new Set();
for (const m of this.monsters) {
if (m.dead || m.hp >= m.maxhp) continue;
let f = 0;
for (const d of ds) {
if (d === m) continue;
const def = ENEMIES[d.kind], dx = m.x - d.x, dy = m.y - d.y;
if (dx * dx + dy * dy > def.healRange * def.healRange) continue;
f += def.heal; did.add(d);
}
if (f > 0) m.hp = Math.min(m.maxhp, m.hp + Math.min(f, HEAL_CAP) * m.maxhp);
}
for (const d of did) this.emit({ e: 'heal', x: round2(d.x), y: round2(d.y), r: ENEMIES[d.kind].healRange });
}
// Load Balancer: each attack tower gets the best boost of the support towers in range (no stacking).
updateAuras() {
const ts = this.towers;
let sup = null;
for (const t of ts) { t.buff = 0; if (TOWERS[t.type].role === 'support') (sup || (sup = [])).push(t); }
if (!sup) return;
for (const s of sup) {
const st = TOWERS[s.type].levels[s.level - 1], r2 = st.range * st.range;
for (const t of ts) {
if (t.buff >= st.boost || TOWERS[t.type].role !== 'attack') continue;
const dx = t.x - s.x, dy = t.y - s.y;
if (dx * dx + dy * dy <= r2) t.buff = st.boost;
}
}
}
// ---- towers ---------------------------------------------------------------------------
findTarget(t, range, def) {
const tx = t.x + 0.5, ty = t.y + 0.5, r2 = range * range;
@ -771,7 +924,7 @@
let v;
switch (t.mode) {
case 'last': v = m.rem; break;
case 'strong': v = m.hp; break;
case 'strong': v = m.hp + (m.shield || 0); break;
case 'close': v = -d2; break;
default: v = -m.rem; // 'first': smallest remaining distance wins
}
@ -781,11 +934,12 @@
}
updateTower(t, dt) {
if (t.type === 'wall') return;
const def = TOWERS[t.type];
if (def.role === 'wall' || def.role === 'support') return;
const st = def.levels[t.level - 1];
const cx = t.x + 0.5, cy = t.y + 0.5;
if (t.type === 'throttle') {
if (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt); return; }
if (def.role === 'aura') {
const r2 = st.range * st.range;
for (const m of this.monsters) {
if (m.dead) continue;
@ -796,7 +950,7 @@
}
return;
}
t.cd -= dt;
t.cd -= dt * (1 + (t.buff || 0)); // a Load Balancer makes cooldowns elapse faster
const m = this.findTarget(t, st.range, def);
t.tgt = m ? m.id : 0;
if (!m) { if (t.cd < 0) t.cd = 0; return; }
@ -805,6 +959,27 @@
this.fire(t, st, def, m, cx, cy);
}
// Sandbox: when anything is in range it stuns everything in range (ground and air) for st.stun s, then recharges st.pulse s.
// Enemies with slowRes (bosses) are stunned for (1 - slowRes) of that. Stunned enemies do not move.
pulseStun(t, st, def, cx, cy, dt) {
t.cd -= dt;
t.tgt = 0;
const r2 = st.range * st.range, hit = [];
for (const m of this.monsters) {
if (m.dead || (m.air ? !def.air : !def.ground)) continue;
const dx = m.x - cx, dy = m.y - cy;
if (dx * dx + dy * dy <= r2) hit.push(m);
}
if (!hit.length) { if (t.cd < 0) t.cd = 0; return; }
if (t.cd > 0) return;
t.cd += st.pulse;
for (const m of hit) {
const dur = st.stun * (1 - (ENEMIES[m.kind].slowRes || 0));
if (dur > m.stunT) m.stunT = dur;
}
this.emit({ e: 'stun', x: round2(cx), y: round2(cy), r: st.range, n: hit.length });
}
fire(t, st, def, m, cx, cy) {
switch (t.type) {
case 'filter':
@ -819,7 +994,7 @@
let gx = m.x, gy = m.y;
if (m.tx >= 0) { // lead the target along its current step
const ex = m.tx + 0.5 - m.x, ey = m.ty + 0.5 - m.y, el = Math.hypot(ex, ey) || 1;
const T = Math.hypot(m.x - cx, m.y - cy) / def.shellSpeed;
const T = Math.max(0, Math.hypot(m.x - cx, m.y - cy) / def.shellSpeed - (m.stunT > 0 ? m.stunT : 0));
const lead = Math.min(el, m.speed * (1 - Math.min(0.6, m.slow)) * T);
gx += (ex / el) * lead; gy += (ey / el) * lead;
}
@ -910,7 +1085,7 @@
// ---- views of the state ---------------------------------------------------------------
towerList() {
return this.towers.map((t) => [t.id, t.type, t.x, t.y, t.level, t.mode, t.spent, t.owner]);
return this.towers.map((t) => [t.id, t.type, t.x, t.y, t.level, t.mode, t.spent, t.owner, t.pm === 1 ? 1 : round2(t.pm * 1000) / 1000]);
}
// Everything a client needs to (re)build the board from scratch.
@ -924,7 +1099,8 @@
// Compact per-tick state for the wire. Arrays, not objects, to keep it small.
snapshot() {
const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp), m.maxhp, m.slow > 0 ? 1 : 0]);
// a shield is sent as extra hp: hp + shield out of maxhp + maxShield (the client derives the shield part from the kind's table)
const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp + (m.shield || 0)), m.maxhp + (m.maxShield || 0), m.slow > 0 || m.stunT > 0 ? 1 : 0]);
const bu = this.bullets.map((b) => [b.id, b.k === 'mortar' ? 1 : 0, round2(b.x), round2(b.y)]);
const tt = [];
for (const t of this.towers) if (t.type !== 'wall') tt.push([t.id, t.tgt, t.kills]);
@ -940,9 +1116,9 @@
function round2(v) { return Math.round(v * 100) / 100; }
return {
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE,
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP,
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
waveGroups, waveSummary, hpScale, rewardScale,
priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale,
buildField, nextCell, traceRoute, parseMap, Board, Sim, round2,
};
});

View file

@ -205,8 +205,11 @@ class Room {
this.reject(p, c, 'busy', msg);
return true;
}
// `lv` (upgrade: the level the sender saw) and `n` (wave: the wave number it expects to start) make a command idempotent: the sim
// answers 'stale' when the premise no longer holds. Optional, but when present they must be integers.
for (const k of ['lv', 'n']) if (msg[k] !== undefined && msg[k] !== null && !Number.isInteger(msg[k])) return false;
// Whitelisted fields only; `by` always comes from the socket's slot, never from the client.
const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, by: p.slot };
const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, lv: msg.lv, n: msg.n, by: p.slot };
let r;
try { r = sim.cmd(cmd); } catch (e) { this.log('sim.cmd threw: ' + (e && e.stack || e)); r = { ok: false, reason: 'error' }; }
if (!r || !r.ok) this.reject(p, c, (r && r.reason) || 'error', msg);

251
test/controllers.test.js Normal file
View file

@ -0,0 +1,251 @@
'use strict';
/*
* RemoteController / LocalController without a browser: public/js/controllers.js runs in a vm context with a fake WebSocket, a fake
* document/window and a manual clock (timers and performance.now() advance only when the test says so).
*/
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const vm = require('node:vm');
const TD = require('../public/js/sim.js');
const SRC = fs.readFileSync(path.join(__dirname, '..', 'public', 'js', 'controllers.js'), 'utf8');
function harness() {
const H = { now: 1000, timers: [], seq: 0, sockets: [], docAdded: 0, docRemoved: 0, winAdded: 0, winRemoved: 0 };
const timer = (fn, ms, repeat) => { const t = { id: ++H.seq, at: H.now + ms, fn, ms, repeat }; H.timers.push(t); return t.id; };
class FakeWS {
constructor(url) { this.url = url; this.readyState = 0; this.sent = []; this.closeCalls = 0; H.sockets.push(this); }
send(s) { this.sent.push(JSON.parse(s)); }
close() { this.closeCalls++; this.readyState = 2; } // a half-open socket: no close event follows
open() { this.readyState = 1; if (this.onopen) this.onopen(); }
recv(o) { if (this.onmessage) this.onmessage({ data: JSON.stringify(o) }); }
serverClose(code) { this.readyState = 3; if (this.onclose) this.onclose({ code }); }
}
const sandbox = {
TD, console, URL, FakeWS,
WebSocket: FakeWS,
document: { hidden: false, addEventListener() { H.docAdded++; }, removeEventListener() { H.docRemoved++; } },
performance: { now: () => H.now },
location: { href: 'http://localhost/index.html' },
addEventListener() { H.winAdded++; }, removeEventListener() { H.winRemoved++; },
setTimeout: (fn, ms) => timer(fn, ms, false), clearTimeout: (id) => { H.timers = H.timers.filter((t) => t.id !== id); },
setInterval: (fn, ms) => timer(fn, ms, true), clearInterval: (id) => { H.timers = H.timers.filter((t) => t.id !== id); },
};
sandbox.self = sandbox;
vm.runInNewContext(SRC, sandbox, { filename: 'controllers.js' });
H.NW = sandbox.NW;
H.advance = (ms) => { // runs the timers that fall due, in order, moving the clock along
const end = H.now + ms;
for (;;) {
const due = H.timers.filter((t) => t.at <= end).sort((a, b) => a.at - b.at || a.id - b.id)[0];
if (!due) break;
H.now = Math.max(H.now, due.at);
if (due.repeat) due.at += due.ms; else H.timers = H.timers.filter((t) => t !== due);
due.fn();
}
H.now = end;
};
return H;
}
// What the server would send for a sim in its current state.
function joinedMsg(sim, extra) {
return Object.assign({
t: 'joined', room: 'ABCD', resumed: false, you: { pid: 'pidpidpid1', slot: 1, host: false },
players: [{ pid: 'pidpidpid1', slot: 1, name: 'Bob', host: false, online: true }, { pid: 'aliasaliasalias', slot: 0, name: 'Alice', host: true, online: true }],
state: sim.fullState(), snap: sim.snapshot(), speed: 1, paused: false,
}, extra);
}
let seq = 0;
function snapMsg(sim, tw) {
const m = Object.assign({ t: 'snap', seq: ++seq }, sim.snapshot(), { ev: [], cur: [], pa: 0, sp: 1 });
if (tw) m.tw = sim.towerList();
return m;
}
function connected(opts) {
const H = harness();
const sim = new TD.Sim({ map: 'open' });
const rc = new H.NW.RemoteController(Object.assign({ pid: 'pidpidpid1', name: 'Bob', room: 'ABCD', url: 'ws://x/ws' }, opts));
rc.connect();
const ws = H.sockets[0];
ws.open();
ws.recv(joinedMsg(sim));
return { H, sim, rc, ws };
}
test('coop-1: a burst of snapshots larger than the buffer does not lose the partner\'s tower change', () => {
const { H, sim, rc, ws } = connected();
assert.equal(rc.status, 'joined');
ws.recv(snapMsg(sim)); // quiet snapshots, then the partner builds...
sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 });
ws.recv(snapMsg(sim, true)); // ...this one carries the tower list (sent exactly once)
for (let i = 0; i < 14; i++) ws.recv(snapMsg(sim)); // the page was stalled: 14 more arrive before it renders again
assert.ok(rc.buf.length <= 10, 'the buffer is still bounded');
H.advance(500);
rc.update(H.now);
assert.equal(rc.towers.length, 1, 'the tower is there');
assert.equal(rc.view.towers.length, 1);
assert.equal(rc.rev, sim.rev, 'and so is the revision');
assert.ok(rc.board.solid[5 * rc.board.cols + 12], 'the mirror board knows the new wall (route previews are right)');
assert.equal(ws.sent.filter((m) => m.t === 'sync').length, 0, 'no resync was needed');
});
test('coop-1: the NEWEST of several dropped tower lists wins; an older one is never applied over it', () => {
const { H, sim, rc, ws } = connected();
sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 });
ws.recv(snapMsg(sim, true));
sim.cmd({ c: 'place', type: 'wall', x: 12, y: 6, by: 1 });
ws.recv(snapMsg(sim, true));
sim.cmd({ c: 'sell', id: 1 });
ws.recv(snapMsg(sim, true)); // list 3: wall 2 only
for (let i = 0; i < 20; i++) ws.recv(snapMsg(sim));
H.advance(500);
rc.update(H.now);
assert.deepEqual([...rc.towers.map((t) => t.id)], [2]);
assert.equal(rc.rev, sim.rev);
});
test('coop-1: a tower list that never arrives is noticed (revision mismatch) and the full state is requested', () => {
const { H, sim, rc, ws } = connected();
sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 });
ws.recv(snapMsg(sim, true));
rc.buf.length = 0; ws.recv(snapMsg(sim)); // (simulate the list being lost on the way)
H.advance(500);
rc.update(H.now);
assert.equal(ws.sent.filter((m) => m.t === 'sync').length, 1);
});
test('coop-2: a joined socket that goes silent is abandoned after 5 s: reconnecting at once and a fresh socket, without waiting for a close', () => {
const { H, rc, ws } = connected();
const states = [];
rc.on('status', (s) => states.push(s));
H.advance(4000);
assert.equal(rc.status, 'joined', 'still fine after 4 s of silence');
assert.equal(H.sockets.length, 1);
H.advance(2500);
assert.equal(rc.status, 'reconnecting', 'the watchdog shows it immediately');
assert.equal(H.sockets.length, 2, 'a new socket was opened without waiting for the dead one to close');
assert.equal(ws.closeCalls, 1, 'the dead one was closed');
assert.equal(ws.onclose, null, 'its handlers are detached: a late close / the server\'s 4001 cannot be mistaken for the new connection');
assert.deepEqual(states, ['reconnecting']);
const ws2 = H.sockets[1];
ws2.open();
assert.equal(ws2.sent[0].t, 'join'); assert.equal(ws2.sent[0].room, 'ABCD'); assert.equal(ws2.sent[0].pid, 'pidpidpid1');
ws2.recv(joinedMsg(new TD.Sim({ map: 'open' }), { resumed: true }));
assert.equal(rc.status, 'joined');
ws.serverClose(1006); // the old socket finally dies: nothing changes
assert.equal(rc.status, 'joined');
assert.equal(H.sockets.length, 2);
});
test('coop-2: waking up after a stall abandons a socket that has been silent for 2.5 s', () => {
const { H, rc } = connected();
H.now += 3000; // the page was frozen; timers have not run
rc._wake();
assert.equal(rc.status, 'reconnecting');
assert.equal(H.sockets.length, 2);
});
test('coop-2: a connection attempt that hangs is abandoned after 10 s and retried', () => {
const { H, rc } = connected();
H.advance(6000); // watchdog: socket 2 is opened and then hangs (never opens)
assert.equal(H.sockets.length, 2);
H.advance(10100);
assert.equal(rc.status, 'reconnecting');
assert.equal(H.sockets[1].closeCalls, 1, 'the attempt that went nowhere was dropped');
H.advance(500);
assert.equal(H.sockets.length, 3, 'and another attempt was made');
});
test('coop-6: "no such room" after a reconnect says the server restarted; on a resume it says the game is gone; a plain join says so', () => {
const a = connected();
const fatal = []; a.rc.on('fatal', (f) => fatal.push(f));
a.ws.serverClose(1006); // the server went away...
a.H.advance(500);
const ws2 = a.H.sockets[1]; ws2.open();
ws2.recv({ t: 'error', code: 'no_room', msg: 'no such room' }); // ...and came back without the room
assert.equal(fatal.length, 1);
assert.equal(fatal[0].code, 'restarted');
assert.match(fatal[0].msg, /server restarted, your game was lost/);
const H = harness();
const resume = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ZZZZ', url: 'ws://x/ws', resume: true });
const f2 = []; resume.on('fatal', (f) => f2.push(f));
resume.connect(); H.sockets[0].open(); H.sockets[0].recv({ t: 'error', code: 'no_room', msg: 'no such room' });
assert.equal(f2[0].code, 'restarted'); assert.match(f2[0].msg, /gone/);
const plain = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ZZZZ', url: 'ws://x/ws' });
const f3 = []; plain.on('fatal', (f) => f3.push(f));
plain.connect(); H.sockets[1].open(); H.sockets[1].recv({ t: 'error', code: 'no_room', msg: 'no such room' });
assert.equal(f3[0].code, 'no_room'); assert.match(f3[0].msg, /does not exist/);
});
test('code-19: listeners are removed when the controller dies and when it is closed', () => {
const { H, rc, ws } = connected();
assert.equal(H.docAdded, 1); assert.equal(H.winAdded, 1);
ws.recv({ t: 'error', code: 'full', msg: 'x' }); // fatal
assert.equal(H.docRemoved, 1); assert.equal(H.winRemoved, 1);
const c2 = new H.NW.RemoteController({ pid: 'pidpidpid2', name: 'x', room: 'ABCD', url: 'ws://x/ws' });
c2.close();
assert.equal(H.docRemoved, 2); assert.equal(H.winRemoved, 2);
c2.close(); // idempotent
assert.equal(H.docRemoved, 2);
assert.equal(rc.status, 'closed');
});
test('code-3: a controller that was closed while connecting never emits again (a late "joined" cannot take over a game)', () => {
const H = harness();
const rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: null, map: 'open', url: 'ws://x/ws' });
const events = [];
for (const e of ['joined', 'players', 'status', 'fatal', 'events']) rc.on(e, () => events.push(e));
rc.connect();
const ws = H.sockets[0];
ws.open();
assert.equal(ws.sent[0].t, 'join');
rc.close(); // (the user pressed Back / Play solo)
assert.deepEqual(ws.sent.map((m) => m.t), ['join', 'leave'], 'the room that is being created is left again at once');
events.length = 0;
ws.recv(joinedMsg(new TD.Sim({ map: 'open' }))); // the server's answer arrives anyway
rc._onMsg(JSON.stringify(joinedMsg(new TD.Sim({ map: 'open' })))); // (even if the browser still delivered a frame already queued)
ws.serverClose(1000);
assert.deepEqual(events, []);
assert.equal(rc.status, 'closed');
});
test('coop-5: Upgrade carries the level that is on screen, Next wave the wave it expects to start; explicit values are kept', () => {
const { sim, rc, ws, H } = connected();
sim.gold = 5000;
sim.cmd({ c: 'place', type: 'filter', x: 10, y: 8, by: 0 });
sim.cmd({ c: 'upgrade', id: 1 });
ws.recv(snapMsg(sim, true));
H.advance(500); rc.update(H.now);
assert.equal(rc.view.towers[0].level, 2);
rc.send({ c: 'upgrade', id: 1 });
rc.send({ c: 'wave' });
rc.send({ c: 'upgrade', id: 1, lv: 7 });
rc.send({ c: 'place', type: 'wall', x: 3, y: 3 });
rc.send({ c: 'upgrade', id: 99 }); // a tower this client does not know: no level to carry
const cmds = ws.sent.filter((m) => m.t === 'cmd');
assert.deepEqual(cmds[0], { t: 'cmd', c: 'upgrade', id: 1, lv: 2 });
assert.deepEqual(cmds[1], { t: 'cmd', c: 'wave', n: rc.view.wave + 1 });
assert.equal(cmds[2].lv, 7);
assert.equal(cmds[3].lv, undefined); assert.equal(cmds[3].n, undefined);
assert.equal(cmds[4].lv, undefined);
});
test('coop-5: solo too: a second "Next wave" in the same frame (a double tap) is stale, the next frame\'s is not', () => {
const H = harness();
const lc = new H.NW.LocalController({ map: 'open' });
const rejects = [];
lc.on('reject', (r) => rejects.push(r));
lc.update(1000);
assert.equal(lc.send({ c: 'wave' }).ok, true);
assert.equal(lc.send({ c: 'wave' }).reason, 'stale');
assert.equal(lc.sim.wave, 1);
assert.deepEqual(rejects.map((r) => r.reason), ['stale']);
lc.update(1016);
assert.equal(lc.send({ c: 'wave' }).ok, true);
assert.equal(lc.sim.wave, 2);
});

View file

@ -460,6 +460,67 @@ test('upgrade / target / sell / auto / continue go through the same path', async
});
});
test('simultaneous Upgrade from both players: applied once, the second is rejected as stale (sender only), charged once (coop-5)', async () => {
await withServer({}, async (S) => {
const { a, b, room } = await S.pair();
const sim = S.srv.rooms.get(room).sim;
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 4 });
await a.c.snap((m) => m.tw && m.tw.length === 1);
await b.c.snap((m) => m.tw && m.tw.length === 1);
const gold = sim.gold, cost = TD.TOWERS.filter.levels[1].cost;
// both saw level 1 and pressed Upgrade at the same moment
a.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 1 });
b.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 1 });
await a.c.barrier(); await b.c.barrier();
assert.equal(sim.towers[0].level, 2, 'level 2, not 3');
assert.equal(sim.gold, gold - cost, 'charged once');
const rejects = [...a.c.of('reject'), ...b.c.of('reject')];
assert.equal(rejects.length, 1, 'exactly one of them was refused');
assert.deepEqual(rejects[0], { t: 'reject', c: 'upgrade', reason: 'stale', id: 1 });
// a client that saw level 2 may continue; a command without lv is still applied (older clients)
a.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 2 });
await a.c.snap((m) => m.tw && m.tw[0][4] === 3);
sim.gold = 1000;
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 6, y: 4 });
await a.c.snap((m) => m.tw && m.tw.length === 2);
a.c.send({ t: 'cmd', c: 'upgrade', id: 2 });
await a.c.snap((m) => m.tw && m.tw[1][4] === 2);
});
});
test('simultaneous Next wave from both players starts one wave; the other is stale (coop-5)', async () => {
await withServer({}, async (S) => {
const { a, b, room } = await S.pair();
const sim = S.srv.rooms.get(room).sim;
a.c.send({ t: 'cmd', c: 'wave', n: 1 });
b.c.send({ t: 'cmd', c: 'wave', n: 1 });
await a.c.barrier(); await b.c.barrier();
assert.equal(sim.wave, 1, 'one wave, not two');
const rejects = [...a.c.of('reject'), ...b.c.of('reject')];
assert.equal(rejects.length, 1);
assert.deepEqual(rejects[0], { t: 'reject', c: 'wave', reason: 'stale' });
b.c.send({ t: 'cmd', c: 'wave', n: 2 });
await b.c.snap((m) => m.w === 2);
a.c.send({ t: 'cmd', c: 'wave' }); // no number: always the next wave
await a.c.snap((m) => m.w === 3);
});
});
test('"lv" and "n" must be integers when present: anything else is a malformed command, never "stale"', async () => {
await withServer({}, async (S) => {
const { a, room } = await S.pair();
const sim = S.srv.rooms.get(room).sim;
a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 4 });
await a.c.snap((m) => m.tw && m.tw.length === 1);
for (const bad of [{ c: 'upgrade', id: 1, lv: '1' }, { c: 'upgrade', id: 1, lv: 1.5 }, { c: 'wave', n: 'x' }, { c: 'wave', n: {} }]) a.c.send(Object.assign({ t: 'cmd' }, bad));
await a.c.barrier();
assert.equal(sim.towers[0].level, 1); assert.equal(sim.wave, 0);
assert.equal(a.c.of('reject').length, 0, 'not rejected by the sim: dropped as malformed');
for (let i = 0; i < 17; i++) a.c.send({ t: 'cmd', c: 'wave', n: 'x' }); // 4 + 17 = 21 malformed messages
assert.equal((await a.c.closed()).code, 4400);
});
});
test('wave command spawns monsters that appear in snapshots; refused beyond the load cap', async () => {
await withServer({}, async (S) => {
const { a, room } = await S.pair();

87
test/sim-commands.test.js Normal file
View file

@ -0,0 +1,87 @@
'use strict';
/*
* Idempotent commands (coop-5): two players who press Upgrade / Next wave at the same moment send the same
* command twice. Each carries what its sender saw (`lv`: the tower level, `n`: the wave it expects to start);
* the sim applies the first and rejects the second with reason 'stale' instead of charging or launching twice.
* A command without the field is applied as before (auto waves, the balance bot, older clients).
*/
const test = require('node:test');
const assert = require('node:assert/strict');
const TD = require('../public/js/sim.js');
const { Sim, TOWERS } = TD;
function withTower(type = 'filter') {
const s = new Sim({ map: 'open', gold: 5000 });
const r = s.cmd({ c: 'place', type, x: 10, y: 8, by: 0 });
assert.ok(r.ok, 'place ' + type);
return { s, id: r.id };
}
test('upgrade carrying the level the sender saw is applied once; the same command again is stale and costs nothing', () => {
const { s, id } = withTower();
const g0 = s.gold, cost = TOWERS.filter.levels[1].cost;
const a = s.cmd({ c: 'upgrade', id, lv: 1, by: 0 });
assert.deepEqual([a.ok, a.level], [true, 2]);
assert.equal(s.gold, g0 - cost);
const rev = s.rev;
const b = s.cmd({ c: 'upgrade', id, lv: 1, by: 1 });
assert.deepEqual([b.ok, b.reason], [false, 'stale']);
assert.equal(s.towerById(id).level, 2, 'still level 2, not 3');
assert.equal(s.gold, g0 - cost, 'charged once');
assert.equal(s.rev, rev, 'a rejected command changes nothing');
assert.equal(s.cmd({ c: 'upgrade', id, lv: 2, by: 1 }).ok, true, 'a sender who saw level 2 may go on to 3');
assert.equal(s.towerById(id).level, 3);
});
test('upgrade without a level (older client, bot, console) keeps working; a stale level never matches a later level either', () => {
const { s, id } = withTower();
assert.equal(s.cmd({ c: 'upgrade', id }).ok, true);
assert.equal(s.towerById(id).level, 2);
assert.equal(s.cmd({ c: 'upgrade', id, lv: null }).ok, true);
assert.equal(s.towerById(id).level, 3);
assert.equal(s.cmd({ c: 'upgrade', id, lv: 2 }).reason, 'stale');
assert.equal(s.cmd({ c: 'upgrade', id, lv: '3' }).reason, 'stale', 'a level of the wrong type is never "the level I saw"');
assert.equal(s.towerById(id).level, 3);
});
test('stale beats max / gold: a sender who saw an older level is told it is stale, not that the tower is maxed out', () => {
const { s, id } = withTower();
const top = TOWERS.filter.levels.length;
for (let lv = 1; lv < top; lv++) assert.ok(s.cmd({ c: 'upgrade', id, lv }).ok);
assert.equal(s.towerById(id).level, top);
assert.equal(s.cmd({ c: 'upgrade', id, lv: top - 1 }).reason, 'stale');
assert.equal(s.cmd({ c: 'upgrade', id, lv: top }).reason, 'max', 'a sender who saw the top level still gets the real reason');
const poor = new Sim({ map: 'open', gold: TOWERS.filter.levels[0].cost });
const p = poor.cmd({ c: 'place', type: 'filter', x: 10, y: 8 });
assert.equal(poor.cmd({ c: 'upgrade', id: p.id, lv: 1 }).reason, 'gold');
assert.equal(poor.cmd({ c: 'upgrade', id: 999, lv: 1 }).reason, 'no_tower');
s.state = 'lost'; // and a finished game answers "over" before it says "stale"
assert.equal(s.cmd({ c: 'upgrade', id, lv: 7 }).reason, 'over');
assert.equal(s.cmd({ c: 'wave', n: 7 }).reason, 'over');
});
test('wave carrying the number it expects to start: the first starts it, a second sender who saw the same wave is stale', () => {
const s = new Sim({ map: 'open' });
const a = s.cmd({ c: 'wave', n: 1, by: 0 });
assert.deepEqual([a.ok, a.wave], [true, 1]);
const queued = s.spawnQ.length;
const b = s.cmd({ c: 'wave', n: 1, by: 1 });
assert.deepEqual([b.ok, b.reason], [false, 'stale']);
assert.equal(s.wave, 1, 'one wave started, not two');
assert.equal(s.spawnQ.length, queued, 'nothing was queued by the rejected command');
assert.equal(s.cmd({ c: 'wave', n: 2 }).ok, true, 'a sender who saw wave 1 may start wave 2');
assert.equal(s.wave, 2);
assert.equal(s.cmd({ c: 'wave', n: 9 }).reason, 'stale', 'a number from the future is stale too');
});
test('wave without a number still starts the next wave; auto waves never need one', () => {
const s = new Sim({ map: 'open' });
assert.equal(s.cmd({ c: 'wave' }).wave, 1);
assert.equal(s.cmd({ c: 'wave', n: null }).wave, 2);
s.cmd({ c: 'auto', v: true });
s.nextWaveIn = 0.01;
s.tick(TD.STEP * 2);
assert.equal(s.wave, 3, 'the timer starts a wave on its own');
assert.equal(s.cmd({ c: 'wave', n: 3 }).reason, 'stale', 'and a click that saw the old wave number is now stale');
});

View file

@ -313,19 +313,27 @@ test('fuzz: garbage commands never throw', () => {
});
test('balance tables keep the shape the client and server rely on', () => {
assert.deepEqual(TD.TOWER_ORDER, ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'uplink']);
assert.deepEqual(TD.ENEMY_ORDER, ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit']);
assert.deepEqual(TD.TOWER_ORDER, ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'sandbox', 'balancer', 'uplink']);
assert.deepEqual(TD.ENEMY_ORDER, ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit', 'daemon', 'proxy', 'botnet']);
assert.equal(Object.keys(TOWERS).length, TD.TOWER_ORDER.length, 'every tower is in the palette order');
assert.equal(Object.keys(ENEMIES).length, TD.ENEMY_ORDER.length, 'every enemy is in the wire order');
assert.equal(TOWERS.wall.levels.length, 1);
assert.ok(TOWERS.wall.refund, 'walls refund in full');
const ROLES = ['wall', 'attack', 'aura', 'control', 'support'];
for (const k of TD.TOWER_ORDER) {
const t = TOWERS[k];
assert.ok(t.name && t.color && t.key && t.desc, k + ' has display fields');
assert.ok(ROLES.includes(t.role), k + ' has a known role');
if (k === 'wall') continue;
assert.equal(t.levels.length, k === 'uplink' ? 4 : 3, k + ' has the expected number of levels');
t.levels.forEach((lv, i) => {
assert.ok(lv.cost > 0 && lv.range > 0, k + ' L' + (i + 1) + ' cost/range');
if (k === 'throttle') assert.ok(lv.slow > 0 && lv.slow <= 0.6, 'slow is capped at 0.6 by the sim');
else if (k === 'sandbox') assert.ok(lv.pulse > 0 && lv.stun > 0 && lv.stun < lv.pulse, 'sandbox pulses and stuns for less than the recharge');
else if (k === 'balancer') assert.ok(lv.boost > 0 && lv.boost <= 1, 'balancer boosts the fire rate');
else assert.ok(lv.dmg > 0 && lv.rate > 0, k + ' L' + (i + 1) + ' dmg/rate');
if (t.role === 'attack') assert.ok(lv.dmg > 0 && lv.rate > 0, k + ' attack towers have dmg and rate');
else assert.ok(!lv.dmg && !lv.rate, k + ' deals no damage of its own');
if (k === 'mortar') assert.ok(lv.splash > 0);
if (k === 'arc') assert.ok(lv.chains >= 1 && lv.chainRange > 0 && lv.falloff > 0 && lv.falloff < 1);
if (k === 'uplink') assert.ok(lv.width > 0 && lv.splash > 0 && lv.slowOnHit > 0 && lv.slowOnHit <= 0.6 && lv.slowFor > 0);
@ -335,6 +343,8 @@ test('balance tables keep the shape the client and server rely on', () => {
for (const k of TD.ENEMY_ORDER) {
const e = ENEMIES[k];
assert.ok(e.name && e.color && e.hp > 0 && e.speed > 0 && e.reward > 0 && e.leak > 0 && e.armor >= 0 && e.r > 0, k);
assert.equal(typeof e.air, 'boolean', k + ' says whether it flies');
assert.ok(Number.isInteger(e.buyCost) && e.buyCost > 0, k + ' has a versus buyCost');
}
assert.ok(TD.START_GOLD >= TOWERS.filter.levels[0].cost * 2, 'the opening credits buy at least two turrets');
assert.ok(TD.SELL_RATIO > 0 && TD.SELL_RATIO < 1, 'selling a turret always loses credits');
@ -384,3 +394,476 @@ test('Orbital Uplink: expensive endgame beam that pierces, ignores armour, blast
const g = s.gold; s.sell(t.id);
assert.equal(s.gold, g + Math.floor(upTotal * TD.SELL_RATIO));
});
// ---------------------------------------------------------------------------------------------------- new content
// A real monster (spawned through the sim so it has every field) moved to (x, y) and, by default, held still.
function put(s, kind, x, y, wave) {
s.spawnMonster({ k: kind, wave: wave || 1 });
const m = s.monsters[s.monsters.length - 1];
m.x = x; m.y = y; m.cx = Math.floor(x); m.cy = Math.floor(y); m.tx = -1; m.ty = -1;
m.speed = 0;
return m;
}
const tick = (s, seconds) => { const n = Math.round(seconds / STEP); for (let i = 0; i < n; i++) s.tick(STEP); };
test('hotkeys: one unique key 1-9 per tower, in palette order; enemy kinds are only ever appended', () => {
const keys = TD.TOWER_ORDER.map((k) => TOWERS[k].key);
assert.deepEqual(keys, ['1', '2', '3', '4', '5', '6', '7', '8', '9']);
assert.equal(new Set(keys).size, keys.length);
assert.equal(TOWERS.wall.key, '1');
assert.equal(TOWERS.sandbox.key, '7');
assert.equal(TOWERS.balancer.key, '8');
assert.equal(TOWERS.uplink.key, '9');
// the first six indexes are on the wire already (snapshot kindIndex)
assert.deepEqual(TD.ENEMY_ORDER.slice(0, 6), ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit']);
assert.deepEqual(TD.ENEMY_ORDER.slice(6), ['daemon', 'proxy', 'botnet']);
});
test('buyCost: every enemy has one, about three times its kill reward', () => {
for (const k of TD.ENEMY_ORDER) {
const e = ENEMIES[k];
assert.ok(Number.isInteger(e.buyCost) && e.buyCost > 0, k);
const ratio = e.buyCost / e.reward;
assert.ok(ratio >= 2.5 && ratio <= 3.5, k + ' buyCost/reward = ' + ratio.toFixed(2));
}
assert.ok(ENEMIES.daemon.air === false && ENEMIES.proxy.air === false && ENEMIES.botnet.air === true);
});
test('every tower can be built, upgraded through all its levels, and sold (solid blocks like the others)', () => {
const s = new Sim({ map: 'open', gold: 100000 });
let x = 3;
for (const type of TD.TOWER_ORDER) {
const def = TOWERS[type];
const r = s.place(type, x, 10);
assert.ok(r.ok, type + ' can be placed');
assert.equal(s.board.solid[10 * s.board.cols + x], 1, type + ' is a solid block');
assert.equal(s.place(type, x, 10).reason, 'occupied');
const t = s.towerById(r.id);
for (let lv = 1; lv < def.levels.length; lv++) assert.ok(s.upgrade(t.id).ok, type + ' upgrade to level ' + (lv + 1));
assert.equal(s.upgrade(t.id).reason, 'max', type);
assert.equal(t.level, def.levels.length);
assert.equal(t.spent, def.levels.reduce((a, l) => a + l.cost, 0));
assert.ok(s.setTargetMode(t.id, 'close').ok);
const g = s.gold, sold = s.sell(t.id);
assert.equal(sold.refund, def.refund ? t.spent : Math.floor(t.spent * TD.SELL_RATIO));
assert.equal(s.gold, g + sold.refund);
assert.equal(s.board.solid[10 * s.board.cols + x], 0, type + ' sold: the cell is free again');
x++;
}
assert.equal(s.towers.length, 0);
// a Sandbox or Load Balancer cannot seal the route either
const tiny = new Sim({ map: mini(['S....', '.....', '.....', '.....', '....C']), gold: 1000 });
assert.ok(tiny.place('sandbox', 3, 4).ok);
assert.equal(tiny.place('balancer', 4, 3).reason, 'blocks');
assert.equal(tiny.place('sandbox', 5, 5).reason, 'bounds');
});
test('Daemon heals every other enemy within 2.2 cells for 6% of max hp, never itself, never above max', () => {
const s = new Sim({ map: 'open', gold: 0 });
const d = put(s, 'daemon', 10.5, 5.5);
const near = put(s, 'trojan', 12.5, 5.5), far = put(s, 'trojan', 13.0, 5.5); // 2.0 and 2.5 cells away
const air = put(s, 'botnet', 10.5, 7.5); // 2.0 cells away, a flyer
const full = put(s, 'ping', 10.5, 4.0);
const dead = put(s, 'trojan', 10.5, 6.0);
for (const m of [near, far, d, air]) m.hp = m.maxhp / 2;
air.maxhp = air.hp = 100; air.hp = 50;
dead.hp = 1; dead.dead = true;
const per = (m) => 0.06 * m.maxhp;
const n0 = near.hp, f0 = far.hp, d0 = d.hp, a0 = air.hp;
s.healPulse();
assert.ok(Math.abs(near.hp - (n0 + per(near))) < 1e-9, 'a trojan 2.0 cells away is healed by 6% of its max');
assert.equal(far.hp, f0, 'one 2.5 cells away is not');
assert.equal(d.hp, d0, 'a daemon never heals itself');
assert.ok(Math.abs(air.hp - (a0 + per(air))) < 1e-9, 'flyers are healed too');
assert.equal(full.hp, full.maxhp);
assert.equal(dead.hp, 1, 'dead enemies are not healed');
near.hp = near.maxhp - 1;
s.healPulse();
assert.equal(near.hp, near.maxhp, 'never above max');
// two daemons heal each other, a lone one does not
const d2 = put(s, 'daemon', 10.5, 6.5);
d.hp = d.maxhp / 2; d2.hp = d2.maxhp / 2;
s.healPulse();
assert.ok(d.hp > d.maxhp / 2 && d2.hp > d2.maxhp / 2);
assert.equal(d.hp, d.maxhp / 2 + per(d), 'the healing came from the other daemon only (6%, not 12%)');
});
test('several daemons never heal one enemy for more than 12% of its max hp per second', () => {
const s = new Sim({ map: 'open', gold: 0 });
const t = put(s, 'trojan', 10.5, 5.5);
for (let i = 0; i < 5; i++) put(s, 'daemon', 10.5 + 0.3 * i, 6.0);
t.hp = t.maxhp * 0.1;
s.healPulse();
assert.ok(Math.abs(t.hp - t.maxhp * 0.22) < 1e-9, 'five daemons heal 12%, not 30%: ' + (t.hp / t.maxhp));
// two daemons already give the full 12%; one gives 6%
const s1 = new Sim({ map: 'open', gold: 0 });
const t1 = put(s1, 'trojan', 10.5, 5.5); put(s1, 'daemon', 11.0, 5.5); t1.hp = 0;
s1.healPulse();
assert.ok(Math.abs(t1.hp - 0.06 * t1.maxhp) < 1e-9);
});
test('daemons pulse once a second on one clock; heals scale with wave hp (max hp, not base hp)', () => {
const s = new Sim({ map: 'open', gold: 0 });
const d = put(s, 'daemon', 10.5, 5.5, 10), t = put(s, 'trojan', 11.5, 5.5, 10);
t.hp = 100;
assert.equal(t.maxhp, Math.round(ENEMIES.trojan.hp * TD.hpScale(10)));
tick(s, 0.9);
assert.equal(t.hp, 100, 'no heal before the first second is up');
tick(s, 0.2);
assert.ok(Math.abs(t.hp - (100 + 0.06 * t.maxhp)) < 1e-6, 'one pulse after a second');
tick(s, 1.0);
assert.ok(Math.abs(t.hp - (100 + 2 * 0.06 * t.maxhp)) < 1e-6, 'one more pulse a second later');
const ev = s.drainEvents().filter((e) => e.e === 'heal');
assert.equal(ev.length, 2, 'each pulse tells the client where the daemon healed');
assert.ok(ev[0].r === ENEMIES.daemon.healRange && Number.isFinite(ev[0].x));
s.monsters.splice(s.monsters.indexOf(d), 1);
const before = t.hp;
tick(s, 2.5);
assert.equal(t.hp, before, 'no daemon, no healing');
});
test('Proxy: the shield soaks damage first, armour applies once, overflow hurts hp, the snapshot carries hp + shield', () => {
const s = new Sim({ map: 'open', gold: 0 });
const m = put(s, 'proxy', 10.5, 5.5);
const E = ENEMIES.proxy;
assert.equal(m.hp, E.hp); assert.equal(m.shield, E.shield); assert.equal(m.maxShield, E.shield);
s.damage(m, 10); // armour 1: 9 get through to the shield
assert.equal(m.shield, E.shield - 9);
assert.equal(m.hp, E.hp, 'hp untouched while the shield holds');
const snap1 = s.snapshot().mo[0];
assert.equal(snap1[4], E.hp + E.shield - 9, 'hp field = hp + shield');
assert.equal(snap1[5], E.hp + E.shield, 'maxhp field = maxhp + maxShield');
assert.equal(snap1.length, 7);
s.damage(m, 150); // 149 after armour: 111 left in the shield, 38 into hp (armour NOT applied a second time)
assert.equal(m.shield, 0);
assert.equal(m.hp, E.hp - (149 - (E.shield - 9)));
assert.equal(s.snapshot().mo[0][4], m.hp);
assert.equal(m.dead, false);
s.damage(m, 1e6);
assert.equal(m.dead, true);
assert.equal(s.kills, 1);
// the whole pool (shield + hp) must be dealt before it dies; armour-ignoring damage also hits the shield first
const m2 = put(s, 'proxy', 10.5, 5.5);
s.damage(m2, E.shield + E.hp - 1, null, true);
assert.equal(m2.dead, false);
s.damage(m2, 1, null, true);
assert.equal(m2.dead, true);
});
test('Proxy shield is scaled with the wave like hp, regrows 10%/s after 3 s without damage, and the timer restarts on every hit', () => {
const s = new Sim({ map: 'open', gold: 0 });
const m = put(s, 'proxy', 10.5, 5.5, 12);
const sh = Math.round(ENEMIES.proxy.shield * TD.hpScale(12));
assert.equal(m.maxShield, sh);
assert.equal(m.maxhp, Math.round(ENEMIES.proxy.hp * TD.hpScale(12)));
s.damage(m, 400, null, true);
const left = sh - 400;
assert.equal(m.shield, left);
tick(s, 2.8);
assert.equal(m.shield, left, 'nothing regrows during the 3 s delay');
tick(s, 1.2); // 4.0 s since the hit: one second of regrow
assert.ok(Math.abs(m.shield - (left + 0.1 * sh)) < 0.5, 'regrew 10% of max in the first second after the delay: ' + (m.shield - left) + ' vs ' + 0.1 * sh);
s.damage(m, 5, null, true);
const after = m.shield;
tick(s, 2.9);
assert.equal(m.shield, after, 'a hit restarts the delay');
tick(s, 60);
assert.equal(m.shield, sh, 'regrows to the maximum and not beyond');
assert.equal(m.hp, m.maxhp, 'the shield regrows, hp is not touched');
// a daemon never tops up a shield, only hp
s.damage(m, sh + 40, null, true);
const d = put(s, 'daemon', 11.0, 5.5, 12);
s.healPulse();
assert.equal(m.shield, 0);
assert.ok(Math.abs(m.hp - (m.maxhp - 40 + 0.06 * m.maxhp)) < 1e-6 || m.hp === m.maxhp);
assert.ok(d.hp > 0);
});
test('Botnet: a fast, tiny flyer that goes straight for the core and is hit by anti-air only', () => {
const s = new Sim({ map: 'open', gold: 1000 });
const E = ENEMIES.botnet;
assert.ok(E.air && E.hp <= 15 && E.speed > ENEMIES.ghost.speed && E.reward === 1);
const m = put(s, 'botnet', 12.5, 7.5);
s.place('mortar', 12, 6);
tick(s, 1);
assert.equal(m.dead, false, 'a mortar cannot hit flyers');
s.place('filter', 11, 6);
tick(s, 1);
assert.ok(m.dead || m.hp < m.maxhp, 'a filter can');
// and it flies straight at the core at its own speed
const s2 = new Sim({ map: 'open', gold: 0 });
const f = put(s2, 'botnet', 0.5, 7.5);
f.speed = E.speed;
tick(s2, 2);
assert.ok(Math.abs(f.x - (0.5 + 2 * E.speed * Math.cos(Math.atan2(8 - 7.5, 25.5 - 0.5)))) < 0.1, 'x=' + f.x);
});
test('Sandbox stuns everything in range (ground and air), not what is outside, and stunned enemies do not move', () => {
const s = new Sim({ map: 'open', gold: 1000 });
s.place('sandbox', 2, 6); // centre (2.5, 6.5), range 2.6
const L = TOWERS.sandbox.levels[0];
const ground = put(s, 'ping', 0.5, 7.5), air = put(s, 'ghost', 3.5, 7.5), out = put(s, 'ping', 8.5, 7.5);
for (const m of [ground, air, out]) m.speed = ENEMIES[m.kind].speed;
const gx = ground.x, ax = air.x, ox = out.x;
tick(s, L.stun * 0.9);
assert.ok(ground.stunT > 0 && air.stunT > 0, 'ground and air are stunned');
assert.equal(out.stunT, 0, 'out of range: untouched');
assert.equal(ground.x, gx, 'stunned ground unit stands still');
assert.equal(air.x, ax, 'stunned flyer stands still');
assert.ok(out.x > ox, 'the unit outside keeps moving');
assert.equal(s.snapshot().mo.find((e) => e[0] === ground.id)[6], 1, 'stunned units are flagged in the snapshot (the 0/1 slow flag)');
tick(s, L.stun * 0.3);
assert.ok(ground.x > gx, 'moves again once the stun is over');
const ev = s.drainEvents().filter((e) => e.e === 'stun');
assert.equal(ev.length, 1);
assert.equal(ev[0].n, 2);
});
test('Sandbox: pulse cadence by level, only pulses when something is in range, stun does not stack, bosses get half', () => {
const s = new Sim({ map: 'open', gold: 10000 });
const r = s.place('sandbox', 5, 5), t = s.towerById(r.id);
tick(s, 12);
assert.equal(s.drainEvents().filter((e) => e.e === 'stun').length, 0, 'nothing in range: no pulse and the charge is kept');
assert.equal(t.cd, 0);
const boss = put(s, 'rootkit', 6.5, 6.5, 10), ping = put(s, 'ping', 5.5, 7.0);
const L1 = TOWERS.sandbox.levels[0];
tick(s, 0.1);
assert.ok(Math.abs(ping.stunT - (L1.stun - 0.1 + STEP)) < 0.05, 'a ping is stunned for the full time');
assert.ok(Math.abs(boss.stunT - (L1.stun * (1 - ENEMIES.rootkit.slowRes) - 0.1 + STEP)) < 0.05, 'a boss for half');
assert.ok(boss.stunT < ping.stunT);
tick(s, 8.8); // 8.9 s: pulses at 0 and 5
assert.equal(s.drainEvents().filter((e) => e.e === 'stun').length, 2);
// level 3 pulses faster and stuns longer; a second pulse never adds to a running stun, it only refreshes it
s.upgrade(t.id); s.upgrade(t.id);
const L3 = TOWERS.sandbox.levels[2];
assert.ok(L3.pulse < L1.pulse && L3.stun > L1.stun && L3.range > L1.range);
s.drainEvents();
t.cd = 0; ping.stunT = 0.5;
tick(s, 0.05);
assert.ok(Math.abs(ping.stunT - (L3.stun - 0.05 + STEP)) < 0.05 && ping.stunT <= L3.stun, 'stun is set to the pulse stun, not added');
t.cd = 0; ping.stunT = L3.stun * 2; // an already longer stun stays
s.tick(STEP);
assert.ok(ping.stunT > L3.stun, 'a shorter stun never cuts a longer one');
s.drainEvents();
tick(s, 12.1);
assert.equal(s.drainEvents().filter((e) => e.e === 'stun').length, 3, 'level 3 recharges every ' + L3.pulse + ' s');
});
test('Load Balancer: boosts attack towers in range, best boost only, not itself, not control/aura towers, ends when sold', () => {
const s = new Sim({ map: 'open', gold: 100000 });
const f1 = s.towerById(s.place('filter', 10, 5).id); // 1 cell from the balancer at (11,5)
const fFar = s.towerById(s.place('filter', 14, 5).id); // 3 cells: outside the level 1 and 2 range, exactly inside level 3
const sb = s.towerById(s.place('sandbox', 10, 6).id);
const th = s.towerById(s.place('throttle', 9, 5).id);
const wl = s.towerById(s.place('wall', 11, 6).id);
const b1 = s.towerById(s.place('balancer', 11, 5).id);
const B = TOWERS.balancer.levels;
s.updateAuras();
assert.equal(f1.buff, B[0].boost);
assert.equal(fFar.buff, 0, 'out of range');
for (const t of [sb, th, wl, b1]) assert.equal(t.buff, 0, t.type + ' is not an attack tower');
// upgrading makes it stronger; a second, weaker balancer never adds to it
s.upgrade(b1.id);
s.updateAuras();
assert.equal(f1.buff, B[1].boost);
assert.equal(fFar.buff, 0);
const b2 = s.towerById(s.place('balancer', 10, 4).id);
s.updateAuras();
assert.equal(f1.buff, B[1].boost, 'the best boost applies, they do not stack (not 0.15 + 0.25)');
assert.equal(b1.buff, 0, 'a balancer does not boost another balancer'); assert.equal(b2.buff, 0);
s.upgrade(b1.id);
s.updateAuras();
assert.equal(f1.buff, B[2].boost);
assert.equal(fFar.buff, B[2].boost, 'level 3 reaches 3 cells');
// selling the strong one drops back to the weak one, selling the last ends the boost
s.sell(b1.id);
s.updateAuras();
assert.equal(f1.buff, B[0].boost);
assert.equal(fFar.buff, 0);
s.sell(b2.id);
s.tick(STEP);
assert.equal(f1.buff, 0, 'selling the last balancer ends the boost');
});
test('Load Balancer: cooldowns really elapse faster, so a boosted tower fires more often', () => {
const mk = (withBalancer) => {
const s = new Sim({ map: 'open', gold: 10000 });
const t = s.towerById(s.place('ids', 10, 5).id);
if (withBalancer) s.place('balancer', 11, 5);
const target = put(s, 'trojan', 10.5, 7.5, 1);
target.hp = target.maxhp = 1e12; target.armor = 0;
return { s, t, target };
};
const a = mk(false), b = mk(true);
a.t.cd = b.t.cd = 1;
a.s.tick(0.1); b.s.tick(0.1);
assert.ok(Math.abs(a.t.cd - 0.9) < 1e-9);
assert.ok(Math.abs(b.t.cd - (1 - 0.1 * (1 + TOWERS.balancer.levels[0].boost))) < 1e-9, 'cooldown ran 15% faster');
const shots = (x) => { tick(x.s, 40); return x.s.drainEvents().filter((e) => e.e === 'shot' && e.k === 'ids').length; };
const na = shots(a), nb = shots(b);
assert.ok(na >= 25, 'baseline fires ~28 shots in 40 s: ' + na);
assert.ok(nb > na * 1.1 && nb < na * 1.2, 'boosted ' + nb + ' vs ' + na);
});
test('waves 1-8 are exactly the original introduction', () => {
const W = [
[{ k: 'ping', c: 8, gap: 0.7 }],
[{ k: 'worm', c: 11, gap: 0.4 }],
[{ k: 'ping', c: 9, gap: 0.6 }, { k: 'trojan', c: 1, gap: 1.4 }],
[{ k: 'spam', c: 30, gap: 0.18 }],
[{ k: 'ghost', c: 7, gap: 0.9 }, { k: 'ping', c: 8, gap: 0.5 }],
[{ k: 'trojan', c: 4, gap: 1.2 }, { k: 'worm', c: 11, gap: 0.35 }],
[{ k: 'ghost', c: 12, gap: 0.6 }, { k: 'spam', c: 24, gap: 0.2 }],
[{ k: 'ping', c: 16, gap: 0.4 }, { k: 'trojan', c: 5, gap: 1 }, { k: 'ghost', c: 6, gap: 0.8 }],
];
for (let n = 1; n <= 8; n++) assert.deepEqual(TD.waveGroups(n), W[n - 1], 'wave ' + n);
for (let n = 1; n <= 8; n++) assert.ok(!TD.waveGroups(n).some((g) => ['daemon', 'proxy', 'botnet'].includes(g.k)));
});
test('new kinds are woven into the waves from 9 on: daemons with trojans, proxies from 12, botnets from 14', () => {
const first = {};
for (let n = 1; n <= 60; n++) {
const g = TD.waveGroups(n);
for (const e of g) {
assert.ok(ENEMIES[e.k], 'wave ' + n + ' kind ' + e.k);
assert.ok(Number.isInteger(e.c) && e.c >= 1 && e.gap > 0, 'wave ' + n);
if (first[e.k] === undefined) first[e.k] = n;
}
assert.ok(g.length <= 8, 'wave ' + n + ' has a sane number of groups');
const t = g.reduce((a, e) => a + e.c * e.gap + 1.5, 0);
assert.ok(t < 120, 'wave ' + n + ' finishes spawning within two minutes (' + t.toFixed(0) + ' s)');
if (n >= 9 && g.some((e) => e.k === 'trojan')) {
const tr = g.find((e) => e.k === 'trojan'), dm = g.find((e) => e.k === 'daemon');
assert.ok(dm && dm.c >= 1, 'wave ' + n + ' has a daemon escort');
assert.ok(g.indexOf(dm) > g.indexOf(tr), 'the escort spawns behind the trojans');
assert.ok(dm.c <= tr.c, 'the escort is not bigger than the trojan group');
}
}
assert.equal(first.daemon, 9);
assert.equal(first.proxy, 12);
assert.equal(first.botnet, 14);
for (const k of TD.ENEMY_ORDER) assert.ok(first[k] !== undefined, k + ' appears somewhere in waves 1-60');
for (let n = 9; n <= 60; n++) {
const kinds = TD.waveGroups(n).map((e) => e.k);
if (n < 12) assert.ok(!kinds.includes('proxy'), 'no proxy before 12');
if (n < 14) assert.ok(!kinds.includes('botnet'), 'no botnet before 14');
}
// the late waves combine them
assert.ok(['daemon', 'proxy', 'botnet'].every((k) => TD.waveGroups(30).some((e) => e.k === k)), 'wave 30 has all three');
assert.ok(TD.waveGroups(20).some((e) => e.k === 'rootkit') && TD.waveGroups(20).some((e) => e.k === 'proxy'));
// the loop keeps growing: the same slot gets more units later
const cnt = (n, k) => TD.waveGroups(n).filter((e) => e.k === k).reduce((a, e) => a + e.c, 0);
assert.ok(cnt(22, 'botnet') > cnt(14, 'botnet') && cnt(36, 'proxy') > cnt(12, 'proxy'));
});
test('waveSummary lists one entry per kind with counts and flags flyers', () => {
for (let n = 1; n <= 60; n++) {
const sum = TD.waveSummary(n), groups = TD.waveGroups(n);
assert.equal(new Set(sum.map((e) => e.k)).size, sum.length, 'one entry per kind in wave ' + n);
for (const e of sum) {
assert.equal(e.air, !!ENEMIES[e.k].air, 'wave ' + n + ' ' + e.k + ' air flag');
assert.equal(e.c, groups.filter((g) => g.k === e.k).reduce((a, g) => a + g.c, 0));
}
assert.equal(sum.reduce((a, e) => a + e.c, 0), groups.reduce((a, g) => a + g.c, 0));
}
assert.deepEqual(TD.waveSummary(5), [{ k: 'ghost', c: 7, air: true }, { k: 'ping', c: 8, air: false }]);
assert.ok(TD.waveSummary(14).some((e) => e.k === 'botnet' && e.air === true));
assert.ok(TD.waveSummary(7).some((e) => e.k === 'ghost' && e.air));
});
test('the new waves run end to end and the snapshot (incl. daemon, proxy, botnet) survives JSON', () => {
const s = new Sim({ map: 'twin', gold: 0, lives: 1000 });
s.wave = 14; // every new kind in the queue at once
s.spawnQ.push({ t: 0, k: 'daemon', wave: 14 }, { t: 0, k: 'proxy', wave: 14 }, { t: 0, k: 'botnet', wave: 14 }, { t: 0, k: 'trojan', wave: 14 });
s.spawnQ.push(...TD.waveGroups(14).flatMap((g, gi) => Array.from({ length: g.c }, (_, i) => ({ t: gi * 5 + i * g.gap, k: g.k, wave: 14 }))));
s.spawnQ.sort((a, b) => a.t - b.t);
let sawNew = false, sawShield = false;
for (let i = 0; i < 60 * 25 && s.state === 'playing'; i++) {
s.tick(STEP);
if (i % 30 === 0) {
const snap = JSON.parse(JSON.stringify(s.snapshot()));
assert.deepEqual(snap, JSON.parse(JSON.stringify(snap)));
for (const e of snap.mo) {
assert.equal(e.length, 7);
assert.ok(Number.isInteger(e[1]) && e[1] >= 0 && e[1] < TD.ENEMY_ORDER.length, 'kindIndex indexes ENEMY_ORDER');
assert.ok(e[4] > 0 && e[4] <= e[5], 'hp (incl. shield) within maxhp (incl. maxShield)');
if (e[1] >= 6) sawNew = true;
if (TD.ENEMY_ORDER[e[1]] === 'proxy') { sawShield = true; assert.ok(e[5] > ENEMIES.proxy.hp * TD.hpScale(14), 'proxy maxhp includes the shield'); }
}
}
}
assert.ok(sawNew && sawShield);
assert.ok(s.leaks > 0, 'undefended waves leak');
assert.equal(JSON.stringify(s.fullState()).includes('null'), false);
});
test('Orbital Uplink pricing: very expensive, and every one you own makes the next dearer', () => { // (25% per owned one, for buying and for upgrading)
const base = TOWERS.uplink.levels[0].cost;
assert.ok(base >= 8 * TD.START_GOLD, 'the first Uplink costs many times the opening credits');
assert.ok(base >= 20 * TOWERS.ids.levels[0].cost, 'and a lot more than an IDS Sniper');
// the shared helper: arrays of towers and plain counts agree; other towers have a flat price
assert.equal(TD.priceFor('uplink', 0), base);
assert.equal(TD.priceFor('uplink', [{ type: 'uplink' }, { type: 'filter' }, { type: 'uplink' }]), TD.priceFor('uplink', 2));
assert.equal(TD.priceFor('filter', 50), TOWERS.filter.levels[0].cost, 'a Packet Filter never gets dearer');
assert.equal(TD.priceFor('wall', [{ type: 'wall' }, { type: 'wall' }]), TOWERS.wall.levels[0].cost);
for (let n = 1; n < 6; n++) assert.ok(TD.priceFor('uplink', n) >= 1.2 * TD.priceFor('uplink', n - 1), 'each Uplink is about 25% dearer than the one before');
const s = new Sim({ map: 'open', gold: 1e6 });
const ids = [];
let prev = 0;
for (let i = 0; i < 4; i++) {
const want = TD.priceFor('uplink', s.towers);
assert.ok(want > prev, 'price keeps rising');
prev = want;
const g = s.gold;
const r = s.place('uplink', 4 + 2 * i, 6);
assert.ok(r.ok);
assert.equal(g - s.gold, want, 'the sim charges exactly the price the UI shows');
assert.equal(s.towerById(r.id).spent, want, 'spent records what was actually paid');
ids.push(r.id);
}
// refunds follow what each one cost, and selling brings the price back down
const before = TD.priceFor('uplink', s.towers);
const g0 = s.gold, t0 = s.towerById(ids[0]);
const refund = s.sell(ids[0]).refund;
assert.equal(refund, Math.floor(t0.spent * TD.SELL_RATIO));
assert.equal(s.gold, g0 + refund);
assert.ok(TD.priceFor('uplink', s.towers) < before, 'owning fewer makes the next one cheaper again');
// not enough credits for the dearer one: refused without charging
const poor = new Sim({ map: 'open', gold: base });
assert.ok(poor.place('uplink', 5, 5).ok);
poor.gold = TD.priceFor('uplink', poor.towers) - 10;
const gp = poor.gold;
assert.equal(poor.place('uplink', 8, 5).reason, 'gold');
assert.equal(poor.gold, gp);
});
test('Orbital Uplink upgrades get dearer by the same factor as the tower they belong to', () => {
const s = new Sim({ map: 'open', gold: 1e7 });
const a = s.towerById(s.place('uplink', 4, 6).id), b = s.towerById(s.place('uplink', 8, 6).id), c = s.towerById(s.place('uplink', 12, 6).id);
assert.equal(a.pm, 1);
assert.ok(Math.abs(b.pm - TOWERS.uplink.priceGrowth) < 1e-9 && Math.abs(c.pm - TOWERS.uplink.priceGrowth ** 2) < 1e-9, 'each remembers the multiplier it was bought at');
for (const t of [a, b, c]) {
const m = t.pm;
const g0 = s.gold, up1 = TD.upgradePrice('uplink', 1, m);
assert.equal(s.upgradeCost(t), up1, 'the sim and the shared helper agree');
assert.ok(Math.abs(up1 / TOWERS.uplink.levels[1].cost - m) < 0.01 * m + 0.01, 'level 2 costs the base upgrade times the multiplier');
assert.ok(s.upgrade(t.id).ok);
assert.equal(g0 - s.gold, up1);
assert.equal(t.spent, TD.priceFor('uplink', t.pm === 1 ? 0 : Math.round(Math.log(t.pm) / Math.log(TOWERS.uplink.priceGrowth))) + up1);
}
assert.ok(TD.upgradePrice('uplink', 3, c.pm) > TD.upgradePrice('uplink', 3, a.pm) * 1.5, 'the third Uplink is much dearer to upgrade than the first');
// flat-price towers are untouched
const f = s.towerById(s.place('filter', 6, 10).id);
assert.equal(f.pm, 1);
assert.equal(TD.upgradePrice('filter', 1, f.pm), TOWERS.filter.levels[1].cost);
// a tower bought after another was sold gets the lower multiplier back
s.sell(a.id);
const d = s.towerById(s.place('uplink', 16, 6).id);
assert.ok(d.pm < c.pm * 1.0001 && d.pm >= b.pm - 1e-9, 'owning fewer when you buy lowers the multiplier again');
// the multiplier travels in the tower list so a co-op client can show the same upgrade price
const row = s.towerList().find((r) => r[0] === c.id);
assert.equal(row.length, 9);
assert.ok(Math.abs(row[8] - c.pm) < 0.002);
assert.equal(s.towerList().find((r) => r[0] === f.id)[8], 1);
});

View file

@ -194,7 +194,8 @@ class Bot {
let gs = 0, gn = 0;
for (const g of groups) if (g.k === q.k) { gs += g.gap * g.c; gn += g.c; }
const g = (gn ? gs / gn : 1) * nSp; // seconds between consecutive packets on ONE route
const h = Math.round(TD.ENEMIES[q.k].hp * TD.hpScale(w));
const ed = TD.ENEMIES[q.k];
const h = Math.round((ed.hp + (ed.shield || 0)) * TD.hpScale(w)); // a shield is extra hit points
out.push({ ki, N: q.c, Nr: Math.max(1, q.c / nSp), h, leak: K.leak, v: K.v, armor: K.armor, air: K.air, g, spacing: Math.max(0.2, K.v * g), w: weight });
}
};
@ -230,6 +231,7 @@ class Bot {
capSpec(sp, e, slow, G) {
if (sp.type === 'throttle') return 0;
const TD = this.TD, td = TD.TOWERS[sp.type], st = sp.st;
if (!(st.dmg > 0)) return 0; // support / control towers (Load Balancer, Sandbox) deal no damage; the bot never builds them
if (e.air ? !td.air : !td.ground) return 0;
const hit0 = Math.min(perHit(st.dmg, e.armor), e.h); // no credit for overkill
let dps = hit0 * st.rate, M = 1;