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

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

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

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

386 lines
18 KiB
JavaScript

'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const TD = require('../public/js/sim.js');
const { Sim, Board, MAPS, TOWERS, ENEMIES, STEP } = TD;
function run(sim, seconds) {
const n = Math.round(seconds / STEP);
for (let i = 0; i < n && sim.state === 'playing'; i++) sim.tick(STEP);
}
// Tiny hand-made maps for edge cases.
function mini(rows) { return { id: 'mini', name: 'mini', rows }; }
test('all built-in maps parse and have a route from every spawn to the core', () => {
for (const id of TD.MAP_ORDER) {
const b = new Board(id);
assert.ok(b.cols > 0 && b.rows > 0);
for (const s of b.spawns) assert.ok(isFinite(b.field[b.idx(s.x, s.y)]), id + ' spawn unreachable');
assert.ok(b.routes.every((r) => r.length > 1));
assert.equal(MAPS[id].rows.length, b.rows);
}
});
test('placement validation: bounds, special cells, obstacles, occupancy, gold', () => {
const s = new Sim({ map: 'open', gold: 100 });
const b = s.board;
assert.equal(s.place('wall', -1, 0).reason, 'bounds');
assert.equal(s.place('wall', b.cols, 0).reason, 'bounds');
assert.equal(s.place('wall', 1.5, 2).reason, 'bounds');
assert.equal(s.place('wall', NaN, 2).reason, 'bounds');
assert.equal(s.place('wall', b.spawns[0].x, b.spawns[0].y).reason, 'spawn');
assert.equal(s.place('wall', b.core.x, b.core.y).reason, 'core');
assert.equal(s.place('wall', 4, 2).reason, 'obstacle');
assert.equal(s.place('nope', 5, 5).reason, 'bad_type');
assert.equal(s.place('__proto__', 5, 5).reason, 'bad_type');
assert.equal(s.place('constructor', 5, 5).reason, 'bad_type');
assert.equal(s.place({}, 5, 5).reason, 'bad_type');
assert.ok(s.place('wall', 5, 5).ok);
assert.equal(s.place('wall', 5, 5).reason, 'occupied');
assert.equal(s.gold, 100 - TOWERS.wall.levels[0].cost);
s.gold = TOWERS.wall.levels[0].cost - 1;
assert.equal(s.place('wall', 6, 5).reason, 'gold');
assert.equal(s.place('ids', 6, 5).reason, 'gold');
});
test('a placement that would seal the core off is rejected (corner cannot be cut)', () => {
// core in the corner of an open 5x5 room. Its only neighbours are (3,4), (4,3) and (3,3); the diagonal step
// (3,3)->(4,4) needs both (3,4) and (4,3) free, so walls on those two already seal it.
const s = new Sim({ map: mini(['S....', '.....', '.....', '.....', '....C']), gold: 1000 });
assert.ok(s.place('wall', 3, 4).ok);
const r = s.place('wall', 4, 3);
assert.equal(r.ok, false);
assert.equal(r.reason, 'blocks');
assert.equal(s.towers.length, 1);
});
test('diagonal corner cutting is impossible: a diagonal staircase of walls is a seal', () => {
const s = new Sim({ map: mini(['S....', '.....', '.....', '.....', '....C']), gold: 1000 });
// staircase from (0,3) to (3,0) separates S (0,0) from C (4,4) once the last step is placed
assert.ok(s.place('wall', 0, 3).ok);
assert.ok(s.place('wall', 1, 2).ok);
assert.ok(s.place('wall', 2, 1).ok);
const r = s.place('wall', 3, 0);
assert.equal(r.ok, false, 'last step would seal the spawn off');
assert.equal(r.reason, 'blocks');
});
test('sealing the spawn behind a diagonal staircase is refused at the final cell', () => {
const s = new Sim({ map: mini(['S....', '.....', '.....', '.....', '....C']), gold: 1000 });
// S at (0,0). Seal with walls at (1,0),(0,1) and (1,1) is not needed: diagonal (0,0)->(1,1) needs both (1,0),(0,1) free.
assert.ok(s.place('wall', 1, 0).ok);
const r = s.place('wall', 0, 1);
assert.equal(r.ok, false);
assert.equal(r.reason, 'blocks');
});
test('route length grows when a wall forces a detour, and sells restore it', () => {
const s = new Sim({ map: 'open', gold: 1000 });
const before = s.board.routeLen;
// wall off a vertical line, leaving a gap at the bottom
for (let y = 0; y < 14; y++) assert.ok(s.place('wall', 12, y).ok, 'wall ' + y);
assert.ok(s.board.routeLen > before + 3, 'route should lengthen: ' + before + ' -> ' + s.board.routeLen);
// closing the last gap must be refused (gap rows 14 and 15)
assert.ok(s.place('wall', 12, 14).ok);
assert.equal(s.place('wall', 12, 15).reason, 'blocks');
const before2 = s.board.routeLen;
const wall0 = s.towerAt[7 * s.board.cols + 12]; // the wall straight in front of the spawn
s.sell(wall0.id);
assert.ok(s.board.routeLen < before2, 'selling a wall shortens the route');
for (const t of s.towers.slice()) s.sell(t.id);
assert.equal(s.board.routeLen, before);
assert.equal(s.gold, 1000, 'walls refund 100%');
});
test('preview reports the route delta and the new routes without mutating state', () => {
const s = new Sim({ map: 'open', gold: 100 });
const solidBefore = Uint8Array.from(s.board.solid);
const p = s.preview(12, 7, true);
assert.ok(p.ok);
assert.ok(p.after >= p.before);
assert.ok(Array.isArray(p.routes) && p.routes.length === 1);
assert.deepEqual(Array.from(s.board.solid), Array.from(solidBefore));
assert.equal(s.board.routeLen, p.before);
});
test('monsters walk to the core and cost lives; flyers go straight', () => {
const s = new Sim({ map: 'open', gold: 0, lives: 20 });
s.spawnQ.push({ t: 0, k: 'ping', wave: 1 });
s.spawnQ.push({ t: 0, k: 'ghost', wave: 1 });
s.wave = 1;
run(s, 40);
assert.equal(s.lives, 20 - ENEMIES.ping.leak - ENEMIES.ghost.leak, 'ping + ghost leaked');
assert.equal(s.monsters.length, 0);
});
test('monster speed: a ping covers roughly route length / speed seconds', () => {
const s = new Sim({ map: 'open', gold: 0 });
s.wave = 1;
s.spawnQ.push({ t: 0, k: 'ping', wave: 1 });
const expected = s.board.routeLen / ENEMIES.ping.speed;
let t = 0;
while (s.lives === 20 && t < 120) { s.tick(STEP); t += STEP; }
assert.ok(Math.abs(t - expected) < 1.0, `took ${t.toFixed(2)}s expected ~${expected.toFixed(2)}s`);
});
test('cells monsters occupy cannot be built on, and they never get trapped', () => {
const s = new Sim({ map: 'open', gold: 5000 });
s.wave = 1;
for (let i = 0; i < 6; i++) s.spawnQ.push({ t: i * 0.6, k: 'ping', wave: 1 });
let rejectedMonster = 0;
const rnd = (() => { let a = 12345; return () => (a = (a * 1664525 + 1013904223) >>> 0) / 4294967296; })();
for (let step = 0; step < 60 * 40 && s.state === 'playing'; step++) {
s.tick(STEP);
if (step % 5 === 0) {
const x = Math.floor(rnd() * s.board.cols), y = Math.floor(rnd() * s.board.rows);
const r = s.place('wall', x, y);
if (r.reason === 'monster') rejectedMonster++;
}
// invariant: every living ground monster can always reach the core
for (const m of s.monsters) {
assert.ok(isFinite(s.board.field[m.cy * s.board.cols + m.cx]), 'monster stranded at ' + m.cx + ',' + m.cy);
assert.equal(s.board.solid[m.cy * s.board.cols + m.cx], 0, 'monster inside a wall');
if (m.tx >= 0) assert.equal(s.board.solid[m.ty * s.board.cols + m.tx], 0, 'monster target is a wall');
}
}
assert.ok(s.towers.length > 20, 'random walls were placed');
assert.ok(rejectedMonster > 0, 'some placements were refused because a monster was on that cell');
});
test('hammering random walls never lets a spawn be sealed', () => {
for (const id of TD.MAP_ORDER) {
const s = new Sim({ map: id, gold: 1e6 });
let seed = 7;
const rnd = () => (seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296;
for (let i = 0; i < 600; i++) {
s.place('wall', Math.floor(rnd() * s.board.cols), Math.floor(rnd() * s.board.rows));
for (const sp of s.board.spawns) assert.ok(isFinite(s.board.field[sp.y * s.board.cols + sp.x]), id + ' sealed');
}
assert.ok(s.board.routeLen > 0);
}
});
test('selling and upgrading', () => {
const s = new Sim({ map: 'open', gold: 1000 });
const r = s.place('filter', 10, 3);
assert.ok(r.ok);
const t = s.towerById(r.id);
assert.equal(t.level, 1);
assert.ok(s.upgrade(t.id).ok);
assert.ok(s.upgrade(t.id).ok);
assert.equal(s.upgrade(t.id).reason, 'max');
assert.equal(t.level, 3);
const lv = TOWERS.filter.levels;
assert.equal(lv.length, 3);
assert.equal(t.spent, lv[0].cost + lv[1].cost + lv[2].cost);
const g = s.gold;
const sold = s.sell(t.id);
assert.equal(sold.refund, Math.floor(t.spent * TD.SELL_RATIO));
assert.equal(s.gold, g + sold.refund);
assert.equal(s.towers.length, 0);
assert.equal(s.sell(t.id).reason, 'no_tower');
assert.equal(s.board.solid[3 * s.board.cols + 10], 0);
});
test('targeting modes pick the intended monster', () => {
const s = new Sim({ map: 'open', gold: 1000 });
const r = s.place('ids', 12, 6);
const t = s.towerById(r.id);
const def = TOWERS.ids;
const mk = (id, x, y, hp, rem) => ({ id, kind: 'ping', air: false, x, y, cx: 0, cy: 0, tx: -1, ty: -1, hp, maxhp: hp, armor: 0, speed: 1, slow: 0, rem, dead: false });
s.monsters = [mk(101, 10, 7, 10, 20), mk(102, 13, 7, 99, 5), mk(103, 12.6, 6.6, 50, 12)];
const range = def.levels[0].range;
t.mode = 'first'; assert.equal(s.findTarget(t, range, def).id, 102);
t.mode = 'last'; assert.equal(s.findTarget(t, range, def).id, 101);
t.mode = 'strong'; assert.equal(s.findTarget(t, range, def).id, 102);
t.mode = 'close'; assert.equal(s.findTarget(t, range, def).id, 103);
assert.ok(s.setTargetMode(t.id, 'close').ok);
assert.equal(s.setTargetMode(t.id, 'bogus').reason, 'bad_mode');
});
test('towers kill monsters and pay out; mortar cannot hit flyers', () => {
const s = new Sim({ map: 'open', gold: 1000 });
const route = s.board.routes[0];
const mid = route[8];
// put a few filters beside the route
for (const [dx, dy] of [[0, 1], [1, 1], [0, -1], [1, -1]]) s.place('filter', mid[0] + dx, mid[1] + dy);
const g0 = s.gold;
s.wave = 1;
for (let i = 0; i < 5; i++) s.spawnQ.push({ t: i * 0.5, k: 'ping', wave: 1 });
run(s, 30);
assert.ok(s.kills >= 4, 'kills=' + s.kills);
assert.ok(s.gold > g0);
const s2 = new Sim({ map: 'open', gold: 1000 });
const mid2 = s2.board.routes[0][8];
s2.place('mortar', mid2[0], mid2[1] + 1);
s2.wave = 1;
s2.spawnQ.push({ t: 0, k: 'ghost', wave: 1 });
run(s2, 20);
assert.equal(s2.kills, 0);
assert.equal(s2.lives, 20 - ENEMIES.ghost.leak);
});
test('throttle slows monsters; rootkit is partly resistant', () => {
const s = new Sim({ map: 'open', gold: 1000 });
s.place('throttle', 5, 6);
const mk = (kind, x, y) => ({ id: s.nid++, kind, air: false, x, y, cx: 5, cy: 7, tx: -1, ty: -1, hp: 100, maxhp: 100, armor: 0, speed: 1, slow: 0, rem: 10, dead: false });
const a = mk('ping', 5.5, 7.5), b = mk('rootkit', 5.5, 7.5);
s.monsters = [a, b];
s.updateTower(s.towers[0], STEP);
const slow1 = TOWERS.throttle.levels[0].slow;
assert.ok(Math.abs(a.slow - slow1) < 1e-9);
assert.ok(Math.abs(b.slow - slow1 * (1 - ENEMIES.rootkit.slowRes)) < 1e-9);
assert.ok(b.slow < a.slow);
});
test('waves: queue, clear bonus, win and lose states, auto waves', () => {
const s = new Sim({ map: 'open', gold: 0, winWave: 1 });
assert.ok(s.startWave().ok);
assert.ok(s.spawnQ.length > 0);
run(s, 60);
assert.equal(s.state, 'won');
const clear = s.drainEvents().find((e) => e.e === 'clear');
assert.ok(clear && clear.bonus > 0 && clear.n === 1, 'a clear event with a positive bonus');
assert.equal(s.gold, clear.bonus, 'the wave clear bonus is the only income of an undefended wave');
assert.ok(s.continueEndless().ok);
assert.equal(s.state, 'playing');
assert.ok(s.startWave().ok);
const s2 = new Sim({ map: 'open', gold: 0, lives: 1 });
s2.startWave();
run(s2, 60);
assert.equal(s2.state, 'lost');
assert.equal(s2.lives, 0);
assert.equal(s2.place('wall', 5, 5).reason, 'over');
const s3 = new Sim({ map: 'open', gold: 0 });
s3.setAuto(true);
run(s3, TD.WAVE_INTERVAL + 1);
assert.equal(s3.wave, 1);
s3.setAuto(false);
});
test('wave definitions are sane for 60 waves', () => {
let prev = 0;
for (let n = 1; n <= 60; n++) {
const g = TD.waveGroups(n);
assert.ok(g.length > 0);
for (const e of g) { assert.ok(ENEMIES[e.k]); assert.ok(e.c >= 1 && e.gap > 0); }
assert.ok(TD.hpScale(n) >= prev); prev = TD.hpScale(n);
}
assert.ok(TD.waveGroups(10).some((e) => e.k === 'rootkit'));
});
test('snapshot / fullState are JSON round-trippable and compact', () => {
const s = new Sim({ map: 'twin', gold: 1000 });
s.place('filter', 5, 5, 1);
s.startWave();
run(s, 5);
const snap = JSON.parse(JSON.stringify(s.snapshot()));
assert.equal(snap.s, 'playing');
assert.ok(Array.isArray(snap.mo) && snap.mo.length > 0);
assert.equal(snap.mo[0].length, 7);
const full = JSON.parse(JSON.stringify(s.fullState()));
assert.equal(full.map, 'twin');
assert.deepEqual(full.towers[0].slice(0, 4).length, 4);
assert.equal(full.towers[0][7], 1, 'owner slot is carried');
});
test('a client-side Board mirror predicts the server route exactly', () => {
const s = new Sim({ map: 'hub', gold: 1000 });
const mirror = new Board('hub');
for (const [x, y] of [[5, 5], [6, 6], [7, 7], [8, 8], [9, 4]]) {
const r = s.place('wall', x, y);
assert.ok(r.ok);
}
for (const t of s.fullState().towers) mirror.setSolid(t[2], t[3], 1);
mirror.recompute();
assert.equal(mirror.routeLen, s.board.routeLen);
const pm = mirror.trial(10, 10, null, null, true);
const ps = s.preview(10, 10, true);
assert.equal(pm.after, ps.after);
});
test('fuzz: garbage commands never throw', () => {
const s = new Sim({ map: 'open', gold: 100 });
const junk = [null, undefined, 1, 'x', [], {}, { c: 'place' }, { c: 'place', type: 'wall' }, { c: 'sell', id: 'a' },
{ c: 'upgrade', id: {} }, { c: 'target', id: 1, mode: 5 }, { c: '__proto__' }, { c: 'place', type: 'wall', x: Infinity, y: -0 },
{ c: 'place', type: 'wall', x: '5', y: '5' }, { c: 'auto' }, { c: 'continue' }, { c: 'wave' }];
for (const j of junk) assert.doesNotThrow(() => s.cmd(j));
assert.equal(s.towers.length, 0);
});
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.equal(TOWERS.wall.levels.length, 1);
assert.ok(TOWERS.wall.refund, 'walls refund in full');
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');
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 assert.ok(lv.dmg > 0 && lv.rate > 0, k + ' L' + (i + 1) + ' dmg/rate');
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);
if (i > 0) assert.ok(lv.range >= t.levels[i - 1].range, 'range never shrinks on upgrade');
});
}
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.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');
// no way to turn credits into more credits by buying, upgrading and selling
for (const k of TD.TOWER_ORDER) {
if (k === 'wall') continue;
const spent = TOWERS[k].levels.reduce((a, l) => a + l.cost, 0);
assert.ok(Math.floor(spent * TD.SELL_RATIO) < spent);
}
// the opening waves are survivable with the opening credits and wave pressure never decreases
for (let n = 2; n <= 60; n++) assert.ok(TD.hpScale(n) > TD.hpScale(n - 1));
for (let n = 2; n <= 60; n++) assert.ok(TD.rewardScale(n) >= TD.rewardScale(n - 1));
});
test('Orbital Uplink: expensive endgame beam that pierces, ignores armour, blasts, slows and hits flyers', () => {
const s = new Sim({ map: 'open', gold: 100000 });
const r = s.place('uplink', 5, 7);
assert.ok(r.ok);
const t = s.towerById(r.id), st = TOWERS.uplink.levels[0];
const idsTotal = TOWERS.ids.levels.reduce((a, l) => a + l.cost, 0);
const upTotal = TOWERS.uplink.levels.reduce((a, l) => a + l.cost, 0);
assert.ok(TOWERS.uplink.levels[0].cost >= 5 * TOWERS.ids.levels[0].cost, 'buying it costs several times an IDS Sniper');
assert.ok(upTotal >= 8 * idsTotal, 'a fully upgraded Uplink costs many times a fully upgraded IDS');
assert.ok(st.range > TOWERS.ids.levels[2].range, 'it out-ranges even a level 3 IDS');
assert.ok(st.dmg > TOWERS.ids.levels[2].dmg, 'and hits harder than a level 3 IDS from the start');
const mk = (id, x, y, extra) => Object.assign({ id, kind: 'trojan', air: false, x, y, cx: 0, cy: 0, tx: -1, ty: -1, hp: 5000, maxhp: 5000, armor: 50, speed: 1, slow: 0, slowT: 0, slowAmt: 0, rem: 10, dead: false }, extra);
// tower centre is (5.5, 7.5): three monsters on the horizontal line, one flyer on it, one far off the line, one beside the first target
const a = mk(201, 8.5, 7.5), b = mk(202, 11.5, 7.5), c = mk(203, 14.5, 7.5), air = mk(204, 12.5, 7.5, { air: true, kind: 'ghost' });
const off = mk(205, 9.5, 12.5), near = mk(206, 8.5, 8.6);
s.monsters = [a, b, c, air, off, near];
t.mode = 'close'; t.cd = 0;
s.updateTower(t, TD.STEP);
for (const o of [a, b, c, air]) assert.equal(o.hp, 5000 - st.dmg, 'on-line monster took full beam damage ignoring armour (armour 50)');
assert.equal(off.hp, 5000, 'a monster off the line is untouched');
assert.equal(near.hp, 5000 - st.dmg * 0.5, 'a monster beside the target takes half from the blast, also ignoring armour');
assert.ok(a.slowT > 0 && a.slowAmt > 0, 'hit monsters are slowed');
assert.equal(off.slowT, 0);
// slow lingers after the shot and then wears off
t.cd = 1e9; // stop it re-firing so we can watch the slow wear off
s.tick(TD.STEP); assert.ok(a.slow > 0, 'slow is applied on the next tick');
for (let i = 0; i < 60 * 3; i++) s.tick(TD.STEP);
assert.equal(a.slow, 0, 'slow wears off after a couple of seconds');
// upgrades to level 4 and refunds 70% of everything spent
assert.ok(s.upgrade(t.id).ok); assert.ok(s.upgrade(t.id).ok); assert.ok(s.upgrade(t.id).ok);
assert.equal(s.upgrade(t.id).reason, 'max');
assert.equal(t.level, 4);
const g = s.gold; s.sell(t.id);
assert.equal(s.gold, g + Math.floor(upTotal * TD.SELL_RATIO));
});