towerdef/test/difficulty.test.js
Claude b4ae6cb57d Difficulty picker (Easy/Normal/Hard) and a balance pass
Difficulty:
- TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated
  create-room / newgame option, state carries it; solo menu picker and co-op lobby
  picker (44px segmented control, reachable on every layout), HUD/room/end-screen
  labels, best-wave record per map AND difficulty (Normal keeps the legacy key),
  Play again keeps the running game's difficulty for host and guest

Balance (12 bot runs, deterministic, 48/48 games replay identically in QA):
- Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open
- credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling
  eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at
  wave 30: 1309 -> 335
- IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only
  dies by wave 7); Mortar, Arc and Filter buffed
- Orbital Uplink price step per owned unit 30% (buy and upgrade)
- remaining imbalances documented in docs/BALANCE.md

Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix
reachability of the picker. 156 unit tests, 17 e2e scenarios.

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

493 lines
27 KiB
JavaScript

'use strict';
/*
* Difficulty (Easy / Normal / Hard): the rules in sim.js, the create-room / newgame option on the server, and the two controllers.
* Expected numbers are derived from TD.DIFFICULTIES (the balance pass retunes the table), only the relationships between the rows
* (easy is more generous than normal, normal than hard) and "normal is the base tables with every multiplier at 1" are pinned.
*/
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 WebSocket = require('ws');
const TD = require('../public/js/sim.js');
const { createServer } = require('../server');
const { Sim, ENEMIES, STEP, DIFFICULTIES } = TD;
const NOT_DIFFICULTIES = ['nope', '', 'EASY', ' hard', 'toString', '__proto__', 'constructor', 'hasOwnProperty', 42, true, {}, []];
// ---------------------------------------------------------------- the table
test('DIFFICULTIES: easy, normal and hard, in that order; normal is the base game (all multipliers 1); the others lean the right way', () => {
assert.deepEqual(TD.DIFFICULTY_ORDER.slice(0, 3), ['easy', 'normal', 'hard']);
assert.equal(TD.DEFAULT_DIFFICULTY, 'normal');
assert.deepEqual(Object.keys(DIFFICULTIES).sort(), TD.DIFFICULTY_ORDER.slice().sort(), 'the order lists exactly the table\'s rows');
for (const id of TD.DIFFICULTY_ORDER) {
const d = DIFFICULTIES[id];
assert.equal(d.id, id);
assert.ok(typeof d.name === 'string' && d.name.length > 0, id + ' has a name');
for (const k of ['gold', 'lives', 'hp', 'reward']) assert.ok(Number.isFinite(d[k]) && d[k] > 0, id + '.' + k + ' is a positive multiplier');
}
for (const k of ['gold', 'lives', 'hp', 'reward']) assert.equal(DIFFICULTIES.normal[k], 1, 'normal.' + k + ' is 1: normal plays the base tables as they are');
const E = DIFFICULTIES.easy, N = DIFFICULTIES.normal, H = DIFFICULTIES.hard;
for (const k of ['gold', 'lives', 'reward']) assert.ok(E[k] >= N[k] && N[k] >= H[k] && E[k] > H[k], k + ': easy gives more than normal, normal more than hard');
assert.ok(E.hp <= N.hp && N.hp <= H.hp && E.hp < H.hp, 'hp: easy packets are weaker than normal, hard ones tougher');
});
test('isDifficulty / difficultyId only accept the table\'s own ids', () => {
for (const id of TD.DIFFICULTY_ORDER) { assert.equal(TD.isDifficulty(id), true); assert.equal(TD.difficultyId(id), id); }
for (const v of NOT_DIFFICULTIES.concat([undefined, null])) {
assert.equal(TD.isDifficulty(v), false, JSON.stringify(v));
assert.equal(TD.difficultyId(v), 'normal', 'anything else is normal: ' + JSON.stringify(v));
}
});
// ---------------------------------------------------------------- the sim
test('a Sim without a difficulty, or with an unknown one, is a normal game', () => {
const plain = new Sim({ map: 'open' });
assert.equal(plain.difficulty, 'normal');
assert.equal(plain.gold, TD.START_GOLD);
assert.equal(plain.lives, TD.START_LIVES);
assert.equal(new Sim().difficulty, 'normal', 'no options at all');
for (const v of NOT_DIFFICULTIES.concat([undefined, null])) {
const s = new Sim({ map: 'open', difficulty: v });
assert.equal(s.difficulty, 'normal', JSON.stringify(v));
assert.equal(s.gold, plain.gold); assert.equal(s.lives, plain.lives); assert.equal(s.maxLives, plain.maxLives);
assert.equal(s.fullState().difficulty, 'normal');
}
});
test('starting credits and lives follow the table; an explicit gold / lives is used as given', () => {
for (const id of TD.DIFFICULTY_ORDER) {
const d = DIFFICULTIES[id], s = new Sim({ map: 'open', difficulty: id });
assert.equal(s.difficulty, id);
assert.equal(s.gold, Math.round(TD.START_GOLD * d.gold), id + ' credits');
assert.equal(s.lives, Math.max(1, Math.round(TD.START_LIVES * d.lives)), id + ' lives');
assert.equal(s.maxLives, s.lives, id + ': the integrity bar is full at the start');
assert.equal(s.snapshot().g, s.gold); assert.equal(s.snapshot().l, s.lives);
const given = new Sim({ map: 'open', difficulty: id, gold: 1234, lives: 7 });
assert.equal(given.gold, 1234); assert.equal(given.lives, 7); assert.equal(given.maxLives, 7);
assert.equal(given.difficulty, id, 'the difficulty still applies to the packets');
}
const [e, n, h] = ['easy', 'normal', 'hard'].map((id) => new Sim({ map: 'open', difficulty: id }));
assert.ok(e.gold > n.gold && n.gold > h.gold, 'more credits on easy than on normal than on hard');
assert.ok(e.lives > n.lives && n.lives > h.lives, 'and more lives');
});
test('the table drives everything: a made-up row with tiny multipliers still leaves one life, a hit point and a credit per kill', () => {
DIFFICULTIES.tiny = { id: 'tiny', name: 'Tiny', gold: 0.001, lives: 0.001, hp: 0.001, reward: 0.001 };
try {
assert.equal(TD.isDifficulty('tiny'), true);
const s = new Sim({ map: 'open', difficulty: 'tiny' });
assert.equal(s.lives, 1, 'a game always starts with at least one life');
assert.equal(s.maxLives, 1);
assert.equal(s.gold, 0);
s.spawnMonster({ k: 'spam', wave: 1 });
assert.ok(s.monsters[0].hp >= 1 && s.monsters[0].reward >= 1, 'a packet always has hit points and pays at least one credit');
} finally { delete DIFFICULTIES.tiny; }
assert.equal(TD.isDifficulty('tiny'), false);
});
// A packet of `kind` on wave `wave`, as the sim spawns it.
function spawned(difficulty, kind, wave) {
const s = new Sim({ map: 'open', difficulty });
s.spawnMonster({ k: kind, wave });
return s.monsters[0];
}
test('normal packets are exactly the base tables (hp, shield and reward: the multiplier is 1)', () => {
for (const kind of TD.ENEMY_ORDER) {
for (const wave of [1, 7, 20, 45]) {
const def = ENEMIES[kind], m = spawned('normal', kind, wave), dflt = spawned(undefined, kind, wave);
assert.equal(m.maxhp, Math.round(def.hp * TD.hpScale(wave)), kind + ' hp on wave ' + wave);
assert.equal(m.maxShield, def.shield ? Math.round(def.shield * TD.hpScale(wave)) : 0, kind + ' shield');
assert.equal(m.reward, Math.max(1, Math.round(def.reward * TD.rewardScale(wave))), kind + ' reward');
assert.deepEqual([dflt.maxhp, dflt.maxShield, dflt.reward], [m.maxhp, m.maxShield, m.reward], 'no difficulty is normal');
}
}
});
test('enemy hit points and shields scale with the difficulty\'s hp multiplier', () => {
for (const id of TD.DIFFICULTY_ORDER) {
const d = DIFFICULTIES[id];
for (const kind of ['ping', 'trojan', 'rootkit', 'proxy']) {
for (const wave of [1, 12, 30]) {
const def = ENEMIES[kind], m = spawned(id, kind, wave);
assert.equal(m.maxhp, Math.max(1, Math.round(def.hp * TD.hpScale(wave) * d.hp)), id + ' ' + kind + ' hp, wave ' + wave);
assert.equal(m.hp, m.maxhp);
assert.equal(m.maxShield, def.shield ? Math.round(def.shield * TD.hpScale(wave) * d.hp) : 0, id + ' ' + kind + ' shield');
assert.equal(m.shield, m.maxShield);
}
}
}
const [e, n, h] = ['easy', 'normal', 'hard'].map((id) => spawned(id, 'trojan', 10));
assert.ok(e.maxhp < n.maxhp && n.maxhp < h.maxhp, 'a Trojan is softer on easy and tougher on hard');
// the wire sends hp + shield out of maxhp + maxShield and the client splits it by the kind's base ratio: scaling both keeps the split
for (const id of TD.DIFFICULTY_ORDER) {
const m = spawned(id, 'proxy', 20), def = ENEMIES.proxy;
assert.ok(Math.abs(m.maxShield / (m.maxhp + m.maxShield) - def.shield / (def.hp + def.shield)) < 0.01, id + ': the shield keeps its share of the total');
}
// other stats are not touched
for (const id of TD.DIFFICULTY_ORDER) { const m = spawned(id, 'rootkit', 10); assert.equal(m.speed, ENEMIES.rootkit.speed); assert.equal(m.armor, ENEMIES.rootkit.armor); assert.equal(m.leak, ENEMIES.rootkit.leak); }
});
test('a kill pays the reward multiplier of the difficulty (checked on kinds that pay more than a credit)', () => {
for (const id of TD.DIFFICULTY_ORDER) {
const d = DIFFICULTIES[id];
for (const kind of ['rootkit', 'trojan', 'proxy']) {
for (const wave of [10, 25]) {
const def = ENEMIES[kind], m = spawned(id, kind, wave);
assert.equal(m.reward, Math.max(1, Math.round(def.reward * TD.rewardScale(wave) * d.reward)), id + ' ' + kind + ' reward, wave ' + wave);
}
}
}
const [e, n, h] = ['easy', 'normal', 'hard'].map((id) => spawned(id, 'rootkit', 10).reward);
assert.ok(e > n && n > h, `a boss pays ${e} / ${n} / ${h} credits on easy / normal / hard`);
// the credits really arrive when it dies
for (const id of TD.DIFFICULTY_ORDER) {
const s = new Sim({ map: 'open', difficulty: id, gold: 0 });
s.spawnMonster({ k: 'rootkit', wave: 10 });
const m = s.monsters[0], want = m.reward;
s.damage(m, 1e9, null, true);
assert.equal(s.gold, want, id + ': the kill paid the packet\'s reward');
}
// the wave clear bonus is the same on every difficulty
const bonus = [];
for (const id of TD.DIFFICULTY_ORDER) {
const s = new Sim({ map: 'open', difficulty: id, gold: 0 });
s.startWave(); s.spawnQ.length = 0;
s.tick(STEP);
bonus.push(s.gold);
}
assert.equal(new Set(bonus).size, 1, 'the clear bonus does not depend on the difficulty: ' + bonus);
});
test('a whole wave of the real game: the same packets come, with the difficulty\'s hit points', () => {
const hp = {};
for (const id of TD.DIFFICULTY_ORDER) {
const s = new Sim({ map: 'open', difficulty: id });
s.cmd({ c: 'wave' });
for (let i = 0; i < 60 * 8 && s.spawnQ.length; i++) s.tick(STEP); // 8 s: the first group of pings is out
assert.ok(s.monsters.length > 0 || s.leaks > 0);
const m = s.monsters.find((x) => x.kind === 'ping') || s.monsters[0];
assert.ok(m, id + ' has a packet on the board');
hp[id] = m.maxhp;
assert.equal(m.maxhp, Math.round(ENEMIES[m.kind].hp * TD.hpScale(1) * DIFFICULTIES[id].hp));
}
assert.ok(hp.easy < hp.normal && hp.normal < hp.hard);
});
test('fullState carries the difficulty (additively), the snapshot keeps its shape, and both survive JSON', () => {
for (const id of TD.DIFFICULTY_ORDER) {
const s = new Sim({ map: 'twin', difficulty: id });
const fs1 = s.fullState();
assert.equal(fs1.difficulty, id);
for (const k of ['map', 'rev', 'towers', 'winWave', 'maxLives']) assert.ok(k in fs1, 'the old field ' + k + ' is still there');
assert.equal(fs1.maxLives, s.maxLives);
assert.deepEqual(JSON.parse(JSON.stringify(fs1)), fs1);
assert.ok(!('difficulty' in s.snapshot()), 'the per-tick snapshot does not repeat it');
s.cmd({ c: 'wave' }); for (let i = 0; i < 200; i++) s.tick(STEP);
assert.equal(s.fullState().difficulty, id, 'it never changes during a game');
JSON.stringify(s.snapshot());
}
});
// ---------------------------------------------------------------- Orbital Uplink price growth (the user's request: slightly dearer per unit owned)
test('Orbital Uplink: each one you own makes the next a little dearer than it used to (more than 25%, still modest), upgrades by the same factor', () => {
const up = TD.TOWERS.uplink;
assert.ok(up.priceGrowth > 1.25, 'the growth per Uplink owned went up from 25%');
assert.ok(up.priceGrowth <= 1.4, 'but it is a slight increase');
assert.ok(up.desc.includes(Math.round((up.priceGrowth - 1) * 100) + '%'), 'the description quotes the real percentage: ' + up.desc);
assert.ok(!/25%/.test(up.desc), 'and not the old one');
const base = up.levels[0].cost;
for (let n = 1; n <= 5; n++) {
const price = TD.priceFor('uplink', n), prev = TD.priceFor('uplink', n - 1);
assert.ok(price / prev > 1.25, 'Uplink number ' + (n + 1) + ' costs more than 25% over the one before (' + prev + ' -> ' + price + ')');
assert.ok(Math.abs(price - Math.round(base * Math.pow(up.priceGrowth, n) / 10) * 10) <= 10, 'it follows the growth rate');
}
// the buying price and the upgrade price rise by the SAME factor, in the sim as well as in the helpers
const s = new Sim({ map: 'open', gold: 1e7 });
const towers = [4, 8, 12].map((x) => s.towerById(s.place('uplink', x, 6).id));
towers.forEach((t, i) => {
assert.ok(Math.abs(t.pm - Math.pow(up.priceGrowth, i)) < 1e-9);
for (let lv = 1; lv < up.levels.length; lv++) {
const got = TD.upgradePrice('uplink', lv, t.pm), want = up.levels[lv].cost * Math.pow(up.priceGrowth, i);
assert.ok(Math.abs(got - want) <= 5 + 1e-9, `upgrade ${lv} of Uplink ${i + 1} costs ${got}, expected about ${want}`);
}
});
const buyRatio = TD.priceFor('uplink', 2) / TD.priceFor('uplink', 0), upRatio = TD.upgradePrice('uplink', 1, towers[2].pm) / TD.upgradePrice('uplink', 1, towers[0].pm);
assert.ok(Math.abs(buyRatio - upRatio) < 0.01, 'buying and upgrading get dearer by the same factor: ' + buyRatio + ' vs ' + upRatio);
});
// ---------------------------------------------------------------- the server
const noop = () => {};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let pidN = 0;
const newPid = () => 'diffpid' + String(++pidN).padStart(6, '0');
async function until(fn, ms = 3000, label = 'condition') {
const end = Date.now() + ms;
for (;;) { const v = fn(); if (v) return v; if (Date.now() > end) throw new Error('timed out waiting for ' + label); await sleep(4); }
}
class Client {
constructor(url) {
this.msgs = []; this.pos = 0; this.closeInfo = null; this.opened = false;
const ws = this.ws = new WebSocket(url);
ws.on('open', () => { this.opened = true; });
ws.on('message', (d) => { this.msgs.push(JSON.parse(d.toString())); });
ws.on('close', (code) => { this.closeInfo = { code }; });
ws.on('error', noop);
}
async open() { await until(() => this.opened || this.closeInfo, 3000, 'open'); return this; }
send(o) { this.ws.send(JSON.stringify(o)); }
next(pred, ms = 3000, label = 'message') {
return until(() => { for (let i = this.pos; i < this.msgs.length; i++) if (pred(this.msgs[i])) { this.pos = i + 1; return this.msgs[i]; } return null; }, ms, label);
}
type(t) { return this.next((m) => m.t === t, 3000, t); }
async barrier() { const ts = Math.random(); this.send({ t: 'rtt', ts }); await this.next((m) => m.t === 'rtt' && m.ts === ts, 3000, 'barrier'); }
}
async function withServer(fn) {
const srv = await createServer({ port: 0, host: '127.0.0.1', log: noop, graceMs: 400, pingMs: 0 });
const clients = [];
const S = {
srv,
async join(extra) {
const c = new Client('ws://127.0.0.1:' + srv.port + '/ws'); clients.push(c);
await c.open();
c.send(Object.assign({ t: 'join', pid: newPid(), name: 'P' }, extra));
const r = await c.next((m) => m.t === 'joined' || m.t === 'error', 3000, 'joined');
return { c, r };
},
};
try { return await fn(S); } finally { for (const c of clients) { try { c.ws.terminate(); } catch (e) { /* ignore */ } } await srv.close(); }
}
test('server: create-room takes a difficulty (default normal) and tells everyone in the state', async () => {
await withServer(async (S) => {
const none = await S.join({});
assert.equal(none.r.state.difficulty, 'normal', 'no option: normal');
assert.equal(S.srv.rooms.get(none.r.room).sim.difficulty, 'normal');
const nul = await S.join({ difficulty: null });
assert.equal(nul.r.state.difficulty, 'normal', 'null is "not given"');
for (const id of TD.DIFFICULTY_ORDER) {
const d = DIFFICULTIES[id];
const host = await S.join({ map: 'twin', difficulty: id });
assert.equal(host.r.t, 'joined', id);
assert.equal(host.r.state.difficulty, id);
assert.equal(host.r.state.map, 'twin', 'the map option is untouched');
assert.equal(host.r.snap.g, Math.round(TD.START_GOLD * d.gold), id + ' credits in the first snapshot');
assert.equal(host.r.snap.l, Math.max(1, Math.round(TD.START_LIVES * d.lives)), id + ' lives');
assert.equal(host.r.state.maxLives, host.r.snap.l);
assert.equal(S.srv.rooms.get(host.r.room).sim.difficulty, id);
// a joiner gets the room's difficulty in its own joined message
const guest = await S.join({ room: host.r.room });
assert.equal(guest.r.state.difficulty, id, id + ': the guest sees the host\'s choice');
assert.equal(guest.r.snap.g, host.r.snap.g);
// ... and in a sync
guest.c.send({ t: 'sync' });
assert.equal((await guest.c.type('state')).state.difficulty, id);
}
});
});
test('server: a bad difficulty is refused like a bad map (bad_difficulty, closed, no room left behind)', async () => {
await withServer(async (S) => {
for (const bad of NOT_DIFFICULTIES) {
const { c, r } = await S.join({ difficulty: bad });
assert.equal(r.t, 'error', JSON.stringify(bad));
assert.equal(r.code, 'bad_difficulty', JSON.stringify(bad));
assert.equal(typeof r.msg, 'string');
assert.ok((await until(() => c.closeInfo, 3000, 'close')).code >= 4000);
}
assert.equal(S.srv.rooms.size, 0, 'a refused create leaves no room');
const both = await S.join({ map: 'nope', difficulty: 'nope' });
assert.equal(both.r.code, 'bad_map', 'the map is checked first');
});
});
test('server: only a creating join carries a difficulty; joining a room takes the room\'s', async () => {
await withServer(async (S) => {
const host = await S.join({ difficulty: 'hard' });
const guest = await S.join({ room: host.r.room, difficulty: 'easy' });
assert.equal(guest.r.t, 'joined');
assert.equal(guest.r.state.difficulty, 'hard');
assert.equal(S.srv.rooms.get(host.r.room).sim.difficulty, 'hard');
const odd = await S.join({ room: host.r.room, difficulty: 'nope' }); // (the room is full, but a bogus field must not matter first)
assert.notEqual(odd.r.code, 'bad_difficulty');
// a reconnect (same pid) gets the room's difficulty again
const pid = newPid();
const first = await S.join({ pid, difficulty: 'easy' });
first.c.ws.terminate();
await until(() => S.srv.rooms.get(first.r.room).players[0].conn === null, 2000, 'the socket is gone');
const back = await S.join({ pid, room: first.r.room });
assert.equal(back.r.resumed, true);
assert.equal(back.r.state.difficulty, 'easy');
});
});
test('server: the host\'s newgame may carry a difficulty; none keeps the room\'s; a bad one is rejected and changes nothing', async () => {
await withServer(async (S) => {
const a = await S.join({ name: 'Alice', difficulty: 'easy' });
const b = await S.join({ name: 'Bob', room: a.r.room });
await a.c.next((m) => m.t === 'players' && m.players.length === 2, 3000, 'two players');
const room = S.srv.rooms.get(a.r.room);
a.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 2, y: 2 });
await a.c.next((m) => m.t === 'snap' && m.rev === 1, 3000, 'a wall');
// a non-host cannot, whatever it asks for
b.c.send({ t: 'newgame', difficulty: 'hard' });
assert.deepEqual(await b.c.type('reject'), { t: 'reject', c: 'newgame', reason: 'not_host' });
assert.equal(room.sim.difficulty, 'easy');
// a bad value: rejected, the running game is untouched, nobody gets a new state
for (const bad of ['nope', 7, '__proto__', {}]) {
a.c.send({ t: 'newgame', difficulty: bad });
assert.deepEqual(await a.c.type('reject'), { t: 'reject', c: 'newgame', reason: 'bad_difficulty' }, JSON.stringify(bad));
}
a.c.send({ t: 'newgame', map: 'nope', difficulty: 'hard' });
assert.equal((await a.c.type('reject')).reason, 'bad_map', 'the map is checked first');
await a.c.barrier();
assert.equal(room.sim.difficulty, 'easy'); assert.equal(room.sim.rev, 1, 'the wall is still there');
assert.equal(a.c.msgs.filter((m) => m.t === 'state').length, 0);
// switch to hard: both players get the new state, with the table's credits and lives
const hard = DIFFICULTIES.hard;
a.c.send({ t: 'newgame', difficulty: 'hard' });
for (const c of [a.c, b.c]) {
const st = await c.type('state');
assert.equal(st.newgame, true);
assert.equal(st.state.difficulty, 'hard');
assert.equal(st.state.map, 'open', 'the map stays when only the difficulty is given');
assert.deepEqual(st.state.towers, []);
assert.equal(st.snap.g, Math.round(TD.START_GOLD * hard.gold));
assert.equal(st.snap.l, Math.max(1, Math.round(TD.START_LIVES * hard.lives)));
assert.equal(st.state.maxLives, st.snap.l);
}
assert.equal(room.sim.difficulty, 'hard');
// no difficulty (Play again): it stays hard; a map change alone keeps it too
a.c.send({ t: 'newgame' });
assert.equal((await b.c.type('state')).state.difficulty, 'hard');
a.c.send({ t: 'newgame', map: 'hub' });
const st = await b.c.type('state');
assert.equal(st.state.map, 'hub'); assert.equal(st.state.difficulty, 'hard');
a.c.send({ t: 'newgame', map: 'hub', difficulty: 'normal' });
assert.equal((await b.c.type('state')).state.difficulty, 'normal');
assert.equal(room.sim.gold, TD.START_GOLD);
});
});
test('server: the hard packets really are tougher in a running room', async () => {
await withServer(async (S) => {
const out = {};
for (const id of ['easy', 'hard']) {
const host = await S.join({ difficulty: id });
host.c.send({ t: 'cmd', c: 'wave' });
const snap = await host.c.next((m) => m.t === 'snap' && m.mo.length > 0, 5000, 'a packet on the board');
out[id] = snap.mo[0][5]; // maxhp of the first packet
}
assert.ok(out.easy < out.hard, `maxhp ${out.easy} on easy, ${out.hard} on hard`);
});
});
// ---------------------------------------------------------------- the controllers (browser code, run in a vm with a fake socket)
const CTRL_SRC = fs.readFileSync(path.join(__dirname, '..', 'public', 'js', 'controllers.js'), 'utf8');
function controllers() {
const sockets = [];
class FakeWS {
constructor(url) { this.url = url; this.readyState = 0; this.sent = []; sockets.push(this); }
send(s) { this.sent.push(JSON.parse(s)); }
close() { this.readyState = 3; }
open() { this.readyState = 1; if (this.onopen) this.onopen(); }
recv(o) { if (this.onmessage) this.onmessage({ data: JSON.stringify(o) }); }
}
const sb = {
TD, console, URL, WebSocket: FakeWS, document: { hidden: false, addEventListener() {}, removeEventListener() {} },
performance: { now: () => 1000 }, location: { href: 'http://localhost/index.html' }, addEventListener() {}, removeEventListener() {},
setTimeout: () => 1, clearTimeout() {}, setInterval: () => 1, clearInterval() {},
};
sb.self = sb;
vm.runInNewContext(CTRL_SRC, sb, { filename: 'controllers.js' });
return { NW: sb.NW, sockets };
}
function joined(sim, extra) {
return Object.assign({
t: 'joined', room: 'ABCD', resumed: false, you: { pid: 'pidpidpid1', slot: 0, host: true },
players: [{ pid: 'pidpidpid1', slot: 0, name: 'A', host: true, online: true }], state: sim.fullState(), snap: sim.snapshot(), speed: 1, paused: false,
}, extra);
}
test('LocalController: starts on the chosen difficulty, keeps it for "Play again", changes it when asked', () => {
const { NW } = controllers();
const dflt = new NW.LocalController({ map: 'open' });
assert.equal(dflt.difficulty, 'normal'); assert.equal(dflt.view.difficulty, 'normal');
assert.equal(dflt.view.gold, TD.START_GOLD);
assert.equal(new NW.LocalController({ map: 'open', difficulty: 'bogus' }).difficulty, 'normal');
for (const id of TD.DIFFICULTY_ORDER) {
const d = DIFFICULTIES[id], c = new NW.LocalController({ map: 'twin', difficulty: id });
assert.equal(c.sim.difficulty, id);
assert.equal(c.view.difficulty, id);
assert.equal(c.view.gold, Math.round(TD.START_GOLD * d.gold));
assert.equal(c.view.lives, Math.max(1, Math.round(TD.START_LIVES * d.lives)));
assert.equal(c.view.maxLives, c.view.lives);
c.sim.gold = 1; c.sim.lives = 1;
let fired = 0; c.on('newgame', () => fired++);
c.newGame(c.mapId); // Play again
assert.equal(fired, 1);
assert.equal(c.difficulty, id, id + ' survives Play again'); assert.equal(c.view.difficulty, id);
assert.equal(c.view.gold, Math.round(TD.START_GOLD * d.gold), 'a fresh game: the credits are back');
c.newGame('open', id);
assert.equal(c.sim.difficulty, id);
}
const c = new NW.LocalController({ map: 'open', difficulty: 'hard' });
c.newGame('open', 'easy');
assert.equal(c.sim.difficulty, 'easy'); assert.equal(c.view.difficulty, 'easy'); assert.equal(c.view.lives, Math.round(TD.START_LIVES * DIFFICULTIES.easy.lives));
c.newGame('open', 'nonsense');
assert.equal(c.sim.difficulty, 'normal', 'an unknown one is normal, like the sim says');
});
test('RemoteController: a creating join asks for the difficulty, a joining one does not; the state decides what the view shows', () => {
const { NW, sockets } = controllers();
const create = new NW.RemoteController({ pid: 'pidpidpid1', name: 'A', room: null, map: 'hub', difficulty: 'hard', url: 'ws://x/ws' });
create.connect(); sockets[0].open();
assert.deepEqual(sockets[0].sent[0], { t: 'join', pid: 'pidpidpid1', name: 'A', map: 'hub', difficulty: 'hard' });
const defaulted = new NW.RemoteController({ pid: 'pidpidpid2', name: 'A', room: null, map: 'open', url: 'ws://x/ws' });
defaulted.connect(); sockets[1].open();
assert.equal(sockets[1].sent[0].difficulty, 'normal');
const join = new NW.RemoteController({ pid: 'pidpidpid3', name: 'B', room: 'ABCD', difficulty: 'hard', url: 'ws://x/ws' });
join.connect(); sockets[2].open();
assert.deepEqual(sockets[2].sent[0], { t: 'join', pid: 'pidpidpid3', name: 'B', room: 'ABCD' }, 'no map, no difficulty when joining');
// the server's state is the truth (the guest asked for nothing, the room is easy)
const sim = new TD.Sim({ map: 'open', difficulty: 'easy' });
sockets[2].recv(joined(sim));
assert.equal(join.difficulty, 'easy'); assert.equal(join.view.difficulty, 'easy');
assert.equal(join.maxLives, sim.maxLives);
// a new game on another difficulty arrives as a state message
const sim2 = new TD.Sim({ map: 'open', difficulty: 'hard' });
let newgames = 0; join.on('newgame', () => newgames++);
sockets[2].recv({ t: 'state', state: sim2.fullState(), snap: sim2.snapshot(), speed: 1, paused: false, newgame: true });
assert.equal(newgames, 1); assert.equal(join.view.difficulty, 'hard'); assert.equal(join.maxLives, sim2.maxLives);
// an older server sends no difficulty: normal
const old = sim.fullState(); delete old.difficulty;
sockets[2].recv({ t: 'state', state: old, snap: sim.snapshot(), speed: 1, paused: false });
assert.equal(join.view.difficulty, 'normal');
// a reconnect of the creator no longer carries the options (it has a room by then)
sockets[0].recv(joined(sim, { room: 'WXYZ' }));
assert.equal(create.room, 'WXYZ');
});
test('RemoteController: newGame sends the difficulty only when one is given; bad_difficulty has a message', () => {
const { NW, sockets } = controllers();
const rc = new NW.RemoteController({ pid: 'pidpidpid1', name: 'A', room: 'ABCD', url: 'ws://x/ws' });
rc.connect(); sockets[0].open();
sockets[0].recv(joined(new TD.Sim({ map: 'open' })));
rc.newGame('hub');
rc.newGame('hub', 'hard');
const ng = sockets[0].sent.filter((m) => m.t === 'newgame');
assert.deepEqual(ng[0], { t: 'newgame', map: 'hub' }, 'no difficulty: the server keeps the room\'s');
assert.deepEqual(ng[1], { t: 'newgame', map: 'hub', difficulty: 'hard' });
const rc2 = new NW.RemoteController({ pid: 'pidpidpid5', name: 'A', room: null, url: 'ws://x/ws' });
let fatal = null; rc2.on('fatal', (f) => { fatal = f; });
rc2.connect(); sockets[1].open();
sockets[1].recv({ t: 'error', code: 'bad_difficulty', msg: 'unknown difficulty' });
assert.equal(fatal.code, 'bad_difficulty'); assert.match(fatal.msg, /difficulty/i);
});