Add Netwall solo client, shared simulation core and protocol spec

- public/js/sim.js: pure game rules shared by browser and server (flow-field
  pathing with no corner cutting, placement validation that can never seal the
  route, towers, enemies, waves, economy, snapshots)
- Responsive canvas client: desktop, landscape and portrait phones (board
  rotates 90 degrees in portrait), mouse + touch input, pinch zoom/pan,
  tap-to-preview placement, route preview, effects, synth sfx + music
- Local and Remote controllers behind one interface (remote: snapshot
  interpolation, auto-reconnect, seat resume)
- docs/PROTOCOL.md: co-op wire protocol and server requirements
- README, PWA manifest and icons, 20 sim unit tests

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-09 19:14:35 +00:00
commit 107ef60ec6
20 changed files with 4100 additions and 0 deletions

307
test/sim.test.js Normal file
View file

@ -0,0 +1,307 @@
'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, 95);
s.gold = 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, 18, 'ping 1 + ghost 1 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);
assert.equal(t.spent, 25 + 30 + 55);
const g = s.gold;
const sold = s.sell(t.id);
assert.equal(sold.refund, Math.floor(110 * 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, 19);
});
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);
assert.ok(Math.abs(a.slow - 0.35) < 1e-9);
assert.ok(Math.abs(b.slow - 0.175) < 1e-9);
});
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');
assert.equal(s.gold, 12, 'wave clear bonus 10 + 2*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);
});