Files
Robot-Clash/tests/sim.test.js
2026-11-19 00:55:39 +01:00

482 lines
26 KiB
JavaScript

// Node test for the game logic (no browser): node tests/sim.test.js
'use strict';
const path = require('path');
const g = p => require(path.join(__dirname, '..', 'game', p));
g('parts.js'); g('robot.js'); g('combat.js'); g('ai.js'); g('progress.js'); g('tourney.js'); g('live.js'); g('ltourney.js'); g('cloudsave.js'); g('ranking.js'); g('missions.js');
const RC = globalThis.RC;
let fails = 0;
const ok = (c, msg) => { if (!c) { fails++; console.log('FAIL', msg); } };
// workshop rules
ok(RC.validate(RC.STARTER).ok, 'starter build valid');
ok(!RC.validate({ ...RC.STARTER, chassis: null }).ok, 'chassis required');
ok(RC.validate({ chassis: 'scarab', motor: 'comet', wheels: 'tracks', battery: 'lipo', armour: 'hardox', weapon: 'spinner', tower: 'rockets' }).errors.includes('overweight'), 'overweight detected');
ok(RC.validate({ chassis: 'crate', motor: 'comet', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'spinner', tower: null }).errors.includes('no_power'), 'power detected');
ok(RC.validate({ ...RC.STARTER, motor: 'lead' }).errors.includes('bad_motor'), 'wrong slot detected');
// every weight class: all eight builds must fit the class limit and its own power budget
for (const c of RC.CLASSES) {
RC.setClass(c.id);
for (const o of RC.LEAGUE) {
const v = RC.validate(o.build);
ok(v.ok, `${c.id} build ${o.id}: ${v.errors} (${v.weight} kg, ${v.power}/${v.supply})`);
ok(v.weight <= c.max, `${c.id} build ${o.id} stays under ${c.max} kg (${v.weight})`);
}
const names = RC.LEAGUE.map(o => o.name);
ok(new Set(names).size === names.length, `${c.id}: no duplicate names`);
const rising = RC.LEAGUE.every((o, i) => i === 0 || o.prize > RC.LEAGUE[i - 1].prize);
ok(rising, `${c.id}: prize money goes up through the league`);
}
RC.setClass('medium');
ok(RC.WEIGHT_LIMIT === 100 && RC.LEAGUE === RC.LEAGUES.medium, 'setClass swaps limit and roster');
RC.setClass('light');
ok(RC.WEIGHT_LIMIT === 60, 'the light class really lowers the limit');
ok(!RC.validate({ ...RC.STARTER, chassis: 'plough', armour: 'hardox' }).ok, 'a heavy build is refused in the light class');
RC.setClass('medium');
{ const v = RC.validate(RC.DUMMY.build); ok(v.ok, `dummy build: ${v.errors}`); }
// fights: every league robot vs every other, AI on both sides
function fight(a, b, seed) {
const s = RC.Combat.create({ robots: [RC.stats(a.build), RC.stats(b.build)], seed, names: [a.name, b.name] });
const ba = RC.AI.create({ style: a.style, skill: a.skill, seed }), bb = RC.AI.create({ style: b.style, skill: b.skill, seed: seed + 9 });
const dt = 1 / 60;
for (let i = 0; i < 60 * 130 && !(s.result && s.endIn <= 0); i++) {
const [p, q] = s.robots;
RC.Combat.step(s, dt, [ba.think(s, p, q, dt), bb.think(s, q, p, dt)]);
s.events.length = 0;
for (const r of s.robots) if (![r.x, r.z, r.a, r.hp, r.y].every(Number.isFinite)) { ok(false, `NaN in ${a.id} vs ${b.id}`); return s; }
}
return s;
}
const durs = [];
const reasons = { ko: 0, pit: 0, time: 0 }, wins = {};
for (const o of RC.LEAGUE) wins[o.id] = 0;
for (const a of RC.LEAGUE) for (const b of RC.LEAGUE) {
if (a === b) continue;
const s = fight(a, b, 3 + a.prize + b.prize);
ok(s.result, `${a.id} vs ${b.id} ended`);
if (!s.result) continue;
reasons[s.result.reason]++; durs.push(Math.round(s.t));
if (s.result.winner === 0) wins[a.id]++; else if (s.result.winner === 1) wins[b.id]++;
}
console.log('end reasons', reasons, 'seconds', durs.sort((x, y) => x - y).join(' '));
console.log('wins (of 14)', wins);
ok(reasons.ko + reasons.pit > 0, 'some fights end early');
ok(wins.overlord >= wins.rustbucket, 'top robot beats bottom robot more often');
// pit: robot standing on the open pit falls in and loses
{
const s = RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: 1 });
s.t = RC.ARENA.duration - RC.ARENA.pitOpensAt; s.pitOpen = 1; s.pitAlarm = true;
s.robots[0].x = RC.ARENA.pit.x; s.robots[0].z = RC.ARENA.pit.z;
RC.Combat.step(s, 1 / 60, [{}, {}]);
ok(s.result && s.result.winner === 1 && s.result.reason === 'pit', 'pit = loss');
}
// weapon mount direction: a weapon reaches where it is bolted on (front/back/sides)
{
const zone = (build, ex, ez) => {
const s = RC.Combat.create({ robots: [RC.stats(build), RC.stats(RC.STARTER)], seed: 3, names: ['a', 'b'] });
const me = s.robots[0], e = s.robots[1];
me.x = 0; me.z = 0; me.a = 0; me.out = false; e.x = ex; e.z = ez; e.out = false;
return RC.Combat.inZone(s, me, e);
};
const W = s => ({ ...RC.STARTER, weapon: 'spinner', mount: { weapon: { side: s, up: 0 } } });
const front = { ...RC.STARTER, weapon: 'spinner' }; // no mount = front, like every old build
ok(RC.stats(front).mountA === 0, 'default mount is front (angle 0)');
ok(zone(front, 1.0, 0) && !zone(front, -1.0, 0), 'front weapon reaches ahead, not behind');
ok(zone(W('back'), -1.0, 0) && !zone(W('back'), 1.0, 0), 'back-mounted weapon reaches behind, not ahead');
ok(zone(W('left'), 0, 0.8) !== zone(W('left'), 0, -0.8), 'side mount reaches one side only');
ok(zone(W('left'), 0, 0.8) === !zone(W('right'), 0, 0.8), 'left and right are opposite sides');
// a full fight with a rear-mounted weapon still ends and never goes NaN
const s = fight({ id: 'rear', name: 'Rear', build: W('back'), style: 'brawler', skill: 0.6 },
{ id: 'foe', name: 'Foe', build: RC.STARTER, style: 'brawler', skill: 0.5 }, 42);
ok(s.result, 'fight with a rear-mounted weapon ends');
}
// multiple weapons: up to 3, same id allowed, each counts and fights
{
const two = { ...RC.STARTER, weapons: [{ id: 'spinner', side: 'front' }, { id: 'spinner', side: 'back' }] };
const one = { ...RC.STARTER, weapons: [{ id: 'spinner', side: 'front' }] };
ok(RC.stats(two).weapons.length === 2, 'two weapons mounted');
ok(RC.validate(two).weight > RC.validate(one).weight, 'a second (same) weapon adds weight');
ok(RC.validate(two).power > RC.validate(one).power, 'a second weapon adds power draw');
const four = { ...RC.STARTER, weapons: [{ id: 'spinner' }, { id: 'spinner' }, { id: 'spinner' }, { id: 'spinner' }] };
ok(RC.validate(four).errors.includes('too_many_weapons'), 'more than 3 weapons is refused');
ok(RC.stats(four).weapons.length === 3, 'stats caps the weapon list at 3');
// a full fight with three weapons on three sides ends and never goes NaN
const r = fight({ id: 'multi', name: 'Multi', build: { ...RC.STARTER, weapons: [{ id: 'spinner', side: 'front' }, { id: 'hammer', side: 'back' }, { id: 'saw', side: 'left' }] }, style: 'brawler', skill: 0.6 },
{ id: 'foe2', name: 'Foe', build: RC.STARTER, style: 'brawler', skill: 0.5 }, 11);
ok(r.result, 'a fight with three weapons ends');
}
// cloud save: which copy wins (by ts)
{
const N = RC.CloudSave.newer;
ok(N({ ts: 20 }, { ts: 10 }) === true, 'newer cloud wins');
ok(N({ ts: 10 }, { ts: 20 }) === false, 'older cloud loses');
ok(N({ ts: 10 }, { ts: 10 }) === true, 'equal ts takes the cloud (shared copy)');
ok(N(null, { ts: 5 }) === false, 'no cloud -> keep local (first migration)');
ok(N({ money: 5 }, { ts: 5 }) === false, 'cloud without ts never overwrites a timed local');
}
// ranking: dedupe/sort/cap (pure)
{
const R = RC.Ranking.rank;
const data = { a: { name: 'A', fame: 50, ts: 1 }, b: { name: 'B', fame: 90, ts: 2 }, c: { name: 'C', fame: 90, ts: 9 }, d: { bad: 1 }, e: { name: 'E', fame: 'x' } };
const rows = R(data);
ok(rows.length === 3, 'ranking drops malformed rows');
ok(rows[0].key === 'c' && rows[1].key === 'b', 'ranking sorts by fame desc, newer first on tie');
ok(rows[2].name === 'A', 'ranking keeps the rest ordered');
ok(R(data, 2).length === 2, 'ranking caps to n');
ok(R(null).length === 0, 'ranking handles empty');
}
// missions: roll / reset / progress
{
const M = RC.Missions;
const now = 1_700_000_000_000, save = {};
M.ensure(save, now, 12345);
ok(save.missions.daily.length === 3, 'missions: 3 daily');
ok(save.missions.weekly.length === 1, 'missions: 1 weekly');
const ids = save.missions.daily.map(m => m.id);
ok(new Set(ids).size === 3, 'missions: daily are distinct');
// deterministic for the same seed + day
const s2 = {}; M.ensure(s2, now, 12345);
ok(s2.missions.daily.map(m => m.id).join() === ids.join(), 'missions: deterministic roll');
// same day re-ensure keeps progress
save.missions.daily[0].prog = 1; M.ensure(save, now + 1000, 12345);
ok(save.missions.daily[0].prog === 1, 'missions: same day keeps progress');
// next day re-rolls daily
M.ensure(save, now + 86400000, 12345);
ok(save.missions.daily[0].prog === 0, 'missions: new day resets daily');
// progress: a win mission
const wm = { id: 'x', type: 'win', goal: 2, prog: 0, done: false };
ok(M.apply(wm, { won: false }) === false && wm.prog === 0, 'missions: loss does not advance win');
ok(M.apply(wm, { won: true }) === false && wm.prog === 1, 'missions: win advances');
ok(M.apply(wm, { won: true }) === true && wm.done, 'missions: completes at goal');
ok(M.apply(wm, { won: true }) === false, 'missions: done stays done');
// damage accumulates and caps
const dm = { id: 'd', type: 'damage', goal: 500, prog: 0, done: false };
M.apply(dm, { dealt: 300 }); ok(dm.prog === 300, 'missions: damage adds');
const c = M.apply(dm, { dealt: 999 }); ok(dm.prog === 500 && c === true, 'missions: damage caps + completes');
// typed wins
ok(M.gain('arena:foundry', { won: true, arenaId: 'foundry' }) === 1, 'missions: arena win counts');
ok(M.gain('arena:foundry', { won: true, arenaId: 'crucible' }) === 0, 'missions: wrong arena no count');
ok(M.gain('weapon:spinner', { won: true, weaponType: 'spinner' }) === 1, 'missions: weapon win counts');
}
// gadgets
ok(RC.validate({ ...RC.STARTER, gadget: 'turbo' }).ok, 'gadget build valid');
ok(RC.stats({ ...RC.STARTER, gadget: 'emp' }).gadget.type === 'emp', 'gadget in stats');
{
// repair kit heals and spends a charge
const s = RC.Combat.create({ robots: [RC.stats({ ...RC.STARTER, gadget: 'repair' }), RC.stats(RC.STARTER)], seed: 2 });
const r = s.robots[0]; r.hp = r.maxHp * 0.3; const before = r.hp, uses = r.gUses;
RC.Combat.step(s, 1 / 60, [{ fire3: true }, {}]);
ok(r.hp > before && r.gUses === uses - 1, 'repair heals + spends charge');
}
{
// shield cuts incoming damage
const base = RC.stats(RC.STARTER), s = RC.Combat.create({ robots: [RC.stats({ ...RC.STARTER, gadget: 'shield' }), base], seed: 3 });
const r = s.robots[0];
RC.Combat.step(s, 1 / 60, [{ fire3: true }, {}]);
ok(r.shield > 0, 'shield active after use');
}
{
// emp stuns a nearby enemy
const s = RC.Combat.create({ robots: [RC.stats({ ...RC.STARTER, gadget: 'emp' }), RC.stats(RC.STARTER)], seed: 4 });
const a = s.robots[0], b = s.robots[1]; b.x = a.x + 1; b.z = a.z;
RC.Combat.step(s, 1 / 60, [{ fire3: true }, {}]);
ok(b.stun > 0, 'emp stuns nearby enemy');
}
{
// self-righter flips a toppled robot back
const s = RC.Combat.create({ robots: [RC.stats({ ...RC.STARTER, gadget: 'righter' }), RC.stats(RC.STARTER)], seed: 5 });
const r = s.robots[0]; r.flipped = 2;
RC.Combat.step(s, 1 / 60, [{ fire3: true }, {}]);
ok(r.flipped === 0, 'self-righter clears flipped');
}
// cooldown readout for the fight HUD
{
const s = RC.Combat.create({ robots: [RC.stats({ ...RC.STARTER, weapon: 'hammer', tower: 'rockets', gadget: 'repair' }), RC.stats(RC.STARTER)], seed: 6 });
const r = s.robots[0];
let cd = RC.Combat.cooldowns(r);
ok(cd.length === 3 && cd.map(c => c.slot).join() === 'weapon,tower,gadget', 'cooldowns: one entry per fitted slot');
ok(cd.every(c => c.p === 0), 'cooldowns: everything ready at the start');
ok(cd[2].n === 2, 'cooldowns: repair kit reports its charges');
r.hp = r.maxHp * 0.5;
RC.Combat.step(s, 1 / 60, [{ fire: true, fire2: true, fire3: true }, {}]);
cd = RC.Combat.cooldowns(r);
ok(cd[0].p > 0.9 && cd[1].p > 0.9 && cd[2].p > 0.9, 'cooldowns: full right after use');
ok(cd[2].n === 1, 'cooldowns: repair charge was spent');
for (let i = 0; i < 60 * 12; i++) RC.Combat.step(s, 1 / 60, [{}, {}]);
ok(RC.Combat.cooldowns(r).every(c => c.p === 0), 'cooldowns: back to zero when they ran out');
}
// battle damage: parts tear off at fixed shares of health
{
const s = RC.Combat.create({ robots: [RC.stats({ ...RC.STARTER, armour: 'steel', weapon: 'hammer' }), RC.stats(RC.STARTER)], seed: 7 });
const r = s.robots[0], A = s.arena;
r.x = A.saws[0].x; r.z = A.saws[0].z; // park him on a floor saw so he keeps taking hits
r.hp = r.maxHp * 0.61;
const broke = [];
for (let i = 0; i < 60 * 2 && !s.result; i++) {
RC.Combat.step(s, 1 / 60, [{}, {}]);
for (const e of s.events) if (e.type === 'broke') broke.push(e.part);
s.events.length = 0;
}
ok(r.hp < r.maxHp * 0.6, 'the saw actually did damage');
ok(broke.includes('armour'), 'armour tears off below 60% health');
ok(r.lost.armour === true, 'the robot remembers the lost armour');
}
{
const s = RC.Combat.create({ robots: [RC.stats({ ...RC.STARTER, weapon: 'hammer' }), RC.stats(RC.STARTER)], seed: 8 });
const r = s.robots[0];
r.lostW[0] = true;
RC.Combat.step(s, 1 / 60, [{ fire: true }, {}]);
ok(r.W[0].swing === 0 && r.W[0].cd === 0, 'a torn-off weapon cannot be fired any more');
ok(RC.Combat.cooldowns(r)[0].broke === true, 'the HUD is told the weapon is gone');
}
{
const speed = lost => {
const s = RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: 9 });
const r = s.robots[0];
if (lost) r.lost.wheels = true;
for (let i = 0; i < 120; i++) RC.Combat.step(s, 1 / 60, [{ throttle: 1 }, {}]);
return Math.hypot(r.vx, r.vz);
};
ok(speed(true) < speed(false) * 0.95, 'a burst wheel slows the robot down');
}
// --- arena furniture: cover, belts, oil, and the new outlines ---
const arenaById = id => RC.ARENAS.find(a => a.id === id);
function drive(arenaId, place, input, secs) {
const s = RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: 11, arena: arenaId });
const r = s.robots[0];
Object.assign(r, place);
for (let i = 0; i < 60 * secs && !s.result; i++) { RC.Combat.step(s, 1 / 60, [input, {}]); s.events.length = 0; }
return { s, r };
}
{
// every arena must be built sanely: nothing outside the outline, nothing buried in a block
const rad = RC.stats(RC.STARTER).rad * 0.9;
let bad = [];
for (const A of RC.ARENAS) {
const out = [];
for (const p of A.starts) if (RC.wallPush(A, p.x, p.z, rad) || RC.inBlock(A, p.x, p.z, rad)) out.push('start');
if (RC.wallPush(A, A.pit.x, A.pit.z, A.pit.hw) || RC.inBlock(A, A.pit.x, A.pit.z, 0)) out.push('pit');
for (const g of [A.press, A.crane]) if (RC.wallPush(A, g.x, g.z, g.hw)) out.push('guardian');
for (const h of A.saws) if (RC.wallPush(A, h.x, h.z, h.r)) out.push('saw');
for (const h of A.flames) if (RC.wallPush(A, h.x, h.z, h.hw)) out.push('flame');
for (const b of A.blocks) if (RC.wallPush(A, b.x, b.z, Math.max(b.hw, b.hd))) out.push('block');
if (out.length) bad.push(A.id + ':' + out.join('/'));
}
ok(bad.length === 0, 'every arena fits inside its own outline (' + bad.join(' ') + ')');
}
{
// a pillar is solid: driving at it does not get you through
const A = arenaById('crucible'), b = A.blocks[0];
const { r } = drive('crucible', { x: 0, z: -5, a: Math.PI / 2 }, { throttle: 1 }, 4);
ok(r.z < b.z - b.hd, 'a solid block stops the robot (z=' + r.z.toFixed(2) + ')');
}
{
// conveyor belt drags a robot that is not even driving
const A = arenaById('colosseum'), bl = A.belts[0];
const { r } = drive('colosseum', { x: bl.x, z: bl.z - 1, a: 0 }, {}, 1.2);
ok(r.z > bl.z - 1 + 0.4, 'the belt drags an idle robot along (dz=' + (r.z - bl.z + 1).toFixed(2) + ')');
}
{
// oil makes steering mushy
const turn = place => Math.abs(drive('scrapyard', place, { throttle: 1, turn: 1 }, 0.6).r.av);
const dry = turn({ x: 7.5, z: -1, a: 0 }), wet = turn({ x: -2.4, z: 1, a: 0 });
ok(wet < dry * 0.85, 'oil cuts the turn rate (dry ' + dry.toFixed(2) + ' vs oil ' + wet.toFixed(2) + ')');
}
for (const id of ['crucible', 'colosseum', 'foundry', 'arena64']) {
// round and octagon walls must hold the robot in
const A = arenaById(id), rad = RC.stats(RC.STARTER).rad * 0.9;
let worst = 0;
for (const dir of [0, 1, 2, 3, 4, 5, 6, 7]) {
const a = dir / 8 * Math.PI * 2;
const { r } = drive(id, { x: 0, z: 0, a, vx: 0, vz: 0 }, { throttle: 1 }, 6);
if (RC.wallPush(A, r.x, r.z, rad * 0.98)) worst++;
}
ok(worst === 0, `${A.shape} wall of ${id} keeps the robot inside`);
}
// mine layer: drop one, it arms, anyone driving over it gets launched - including the owner later on
{
const mk = () => {
const s = RC.Combat.create({ robots: [RC.stats({ ...RC.STARTER, gadget: 'mines' }), RC.stats(RC.STARTER)], seed: 5 });
s.robots[0].x = 0; s.robots[0].z = 0; s.robots[0].a = 0;
s.robots[1].x = 9; s.robots[1].z = 9;
return s;
};
let s = mk();
RC.Combat.step(s, 1 / 60, [{ fire3: true }, {}]);
ok(s.mines.length === 1 && s.robots[0].gUses === 2, 'mine is dropped and costs a charge');
for (let i = 0; i < 120; i++) RC.Combat.step(s, 1 / 60, [{}, {}]);
ok(s.mines.length === 1 && s.mines[0].arm <= 0, 'it arms without blowing up the robot that laid it');
const b = s.robots[1], mn = s.mines[0], hp0 = b.hp, dealt0 = s.robots[0].dealt;
b.x = mn.x; b.z = mn.z; b.y = 0;
RC.Combat.step(s, 1 / 60, [{}, {}]);
ok(hp0 - b.hp > 10 && b.vy > 4 && s.mines.length === 0, 'driving over it hurts and throws the robot up');
ok(s.robots[0].dealt - dealt0 > 10, 'the damage counts for whoever laid the mine');
s = mk();
RC.Combat.step(s, 1 / 60, [{ fire3: true }, {}]);
for (let i = 0; i < 60 * 4; i++) RC.Combat.step(s, 1 / 60, [{}, {}]);
const a2 = s.robots[0], m2 = s.mines[0], h0 = a2.hp;
a2.x = m2.x; a2.z = m2.z; a2.y = 0;
RC.Combat.step(s, 1 / 60, [{}, {}]);
ok(h0 - a2.hp > 10, 'once the grace time is over your own mine gets you too');
}
// ranks and achievements
{
const P = RC.Progress;
ok(P.rankOf(0).key === P.RANKS[0].key, 'no fame = lowest rank');
ok(P.rankOf(149).key === 'scrap' && P.rankOf(150).key === 'rookie', 'rank flips exactly at the threshold');
ok(P.rankOf(1e9).next === null && P.rankOf(1e9).pct === 1, 'top rank has nothing above it');
let last = -1, rising = true;
for (const r of P.RANKS) { if (r.at <= last) rising = false; last = r.at; }
ok(rising, 'rank thresholds go up');
const save = { money: 0, fame: 0, games: 0, owned: [], robots: [], paint: {}, ach: {} };
let got = P.check(save, { won: true, reason: 'ko', hpPct: 0.5, dealt: 100, lost: 1 });
const ids = got.map(a => a.id);
ok(ids.includes('first_win') && ids.includes('ko'), 'winning by knockout earns both the first win and the KO');
ok(!ids.includes('pit') && !ids.includes('flawless'), 'nothing is handed out that was not done');
ok(got.every(a => a.reward > 0), 'every achievement pays something');
got = P.check(save, { won: true, reason: 'ko', hpPct: 0.5, dealt: 100, lost: 1 });
ok(got.length === 0, 'the same achievement is never earned twice');
save.money = 5000;
ok(P.check(save, {}).map(a => a.id).includes('rich'), 'save-only achievements work without a fight');
ok(P.earned(save) === 3 && P.total === P.ACHIEVEMENTS.length, 'the counter matches what was earned');
const dup = P.ACHIEVEMENTS.map(a => a.id).filter((v, i, arr) => arr.indexOf(v) !== i);
ok(dup.length === 0, 'achievement ids are unique');
}
// knockout tournament
{
const T = RC.Tourney;
const me = () => ({ name: 'Me', build: RC.STARTER, paint: { body: 1, accent: 2 } });
let st = T.create({ me: me(), seed: 42 });
ok(st.field.length === T.SIZE, 'the bracket starts with eight robots');
ok(st.field.filter(e => e.player).length === 1, 'you are in it exactly once');
const names = st.field.map(e => e.name);
ok(new Set(names).size === names.length, 'no robot appears twice');
const p = T.pair(st);
ok(p && p[0].player && p[1] && !p[1].player, 'your first match is you against someone else');
// losing ends the run straight away
let lost = T.create({ me: me(), seed: 7 });
T.simOthers(lost);
T.advance(lost, false);
ok(lost.done && lost.out && !lost.won, 'a defeat knocks you out');
// winning everything takes three rounds and halves the field each time
st = T.create({ me: me(), seed: 42 });
const sizes = [];
let guard = 0;
while (!st.done && guard++ < 6) {
sizes.push(st.field.length);
T.simOthers(st);
T.advance(st, true);
}
ok(st.won && st.round === 3, 'three wins take the trophy');
ok(sizes.join() === '8,4,2', 'the field halves every round');
ok(st.prize === T.ROUND_PRIZE.reduce((a, b) => a + b, 0), 'every round prize is paid');
ok(st.log.filter(l => l.mine).length === 3, 'your three matches are in the log');
ok(st.log.filter(l => !l.mine).length === 4, 'the other matches were fought out too');
}
// live settings from the backend
{
const L = RC.Live, NOW = 1000000;
const ev = { id: 'e1', type: 'prize', prizeMul: 2, from: NOW - 100, to: NOW + 100 };
let r = L.parse(null, NOW, '20261115.1200');
ok(r.event === null && !r.onlineOff && !r.needsReload, 'no config = nothing special running');
ok(!r.locked('parts', 'wedge'), 'without a config every part stays available');
r = L.parse({ event: ev }, NOW, '');
ok(r.event && r.event.prizeMul === 2, 'an event inside its window is live');
ok(L.parse({ event: ev }, NOW + 500, '').event === null, 'after its end it is over');
ok(L.parse({ event: ev }, NOW - 500, '').event === null, 'before it starts it is not on yet');
ok(L.parse({ event: { id: 'x' } }, NOW, '').event !== null, 'an event without times runs all the time');
ok(L.parse({ event: { id: 'x', prizeMul: 99 } }, NOW, '').event.prizeMul === 5, 'a silly prize factor is capped');
r = L.parse({ unlock: { parts: ['wedge', 'saw'] } }, NOW, '');
ok(!r.locked('parts', 'wedge') && r.locked('parts', 'spinner'), 'only released parts are available');
ok(!r.locked('arenas', 'foundry'), 'a list that was not set locks nothing');
ok(!L.parse({ unlock: { parts: [] } }, NOW, '').locked('parts', 'spinner'), 'an empty list means everything is free');
ok(L.parse({ flags: { onlineOff: true } }, NOW, '').onlineOff, 'the kill switch comes through');
ok(L.parse({ flags: { tournament: true } }, NOW, '').tournament, 'the tournament switch opens the tournament');
ok(!L.parse({}, NOW, '').tournament, 'without the switch the tournament stays closed');
ok(L.parse({ event: { id: 't', tournament: true } }, NOW, '').tournament, 'an event can open the tournament too');
ok(L.parse({ build: { min: '20261115.1800' } }, NOW, '20261115.1200').needsReload, 'an older copy is asked to reload');
ok(!L.parse({ build: { min: '20261115.1800' } }, NOW, '20261115.1900').needsReload, 'a newer copy is left alone');
ok(!L.parse({ build: { min: '20261115.1800' } }, NOW, '').needsReload, 'without a build stamp we never nag');
for (const junk of ['nonsense', 42, [], { event: 'no object' }, { unlock: 5 }]) {
const p = L.parse(junk, NOW, '');
ok(p && p.event === null && typeof p.locked === 'function', 'broken config does not break the game: ' + JSON.stringify(junk));
}
}
// live multiplayer bracket
{
const LT = RC.LTourney;
ok(LT.order(['a','b'], 1).length === 2, '2 players = bracket of 2');
ok(LT.order(['a','b','c'], 1).length === 4, '3 players pad to 4 (one bye)');
ok(LT.order(['a','b','c','d','e'], 1).length === 8, '5 players pad to 8');
ok(LT.order(['a','b','c'], 1).filter(x => x === null).length === 1, 'exactly one bye for 3 players');
const o = LT.order(['bob','amy'], 1); // sorted-ish; host = lower uid
const m = LT.myMatch(o, {}, 'amy');
ok(m && m.round === 0 && m.opp === 'bob', 'first match is against the other player');
ok(LT.myMatch(o, {}, 'amy').host === ('amy' < 'bob'), 'lower uid hosts');
// a bye advances on its own, no match to play
const ob = LT.order(['x','y','z'], 2);
const bye = ob.indexOf(null) === 1 ? ob[0] : null; // the player paired with the null
// winner reported -> loser is out, winner is champion (2-player)
const win = o[0];
ok(LT.myMatch(o, { 0: { 0: win } }, win).done === true, 'the reported winner is done (champion)');
ok(LT.myMatch(o, { 0: { 0: win } }, o[1]) === null, 'the loser drops out');
// full 8: play it through, there is always one champion
const u = ['u0','u1','u2','u3','u4','u5','u6','u7'], O = LT.order(u, 9);
const R = {};
for (let r = 0; r < 3; r++) { const rows = LT.rounds(O, R)[r]; R[r] = {}; for (let i = 0; i < rows.length; i += 2) R[r][i/2] = rows[i] || rows[i+1]; }
const champ = LT.myMatch(O, R, O[0]);
ok(RC.LTourney.rounds(O, R).length === 4, 'an 8-player bracket has four columns');
ok(u.indexOf(champ.champion) >= 0, 'the champion is one of the players');
}
// body proportions designer
{
const base = { ...RC.STARTER };
const big = { ...base, body: { hx: 1.6, wx: 1.4, lx: 1.3 } };
const small = { ...base, body: { hx: 0.7, wx: 0.8, lx: 0.8 } };
const s0 = RC.stats(base), sb = RC.stats(big), ss = RC.stats(small);
ok(sb.h > s0.h && sb.len > s0.len && sb.wid > s0.wid, 'bigger body = bigger dimensions');
ok(ss.h < s0.h && ss.len < s0.len, 'smaller body = smaller dimensions');
ok(RC.validate(big).weight > RC.validate(base).weight, 'bigger body weighs more');
ok(sb.hp > s0.hp && ss.hp < s0.hp, 'size changes hit points');
ok(sb.top < s0.top, 'a heavy big build is slower');
ok(sb.topHeavy > 1 && RC.stats({ ...base, body: { hx: 0.8, wx: 1.4, lx: 1.3 } }).topHeavy < 1, 'tall = top-heavy, flat = stable');
ok(RC.bodyOf({ body: { hx: 9, wx: 9, lx: 9 } }).hx === 1.6, 'absurd values are clamped');
ok([sb.hp, sb.len, sb.mass, sb.top].every(Number.isFinite), 'no NaN at the extreme');
// a big heavy build can bust the class limit
RC.setClass('light');
ok(RC.validate({ ...RC.STARTER, body: { hx: 1.6, wx: 1.4, lx: 1.3 } }).weight > RC.validate(RC.STARTER).weight, 'body weight counts toward the limit');
RC.setClass('medium');
// builds without a body are unchanged
ok(RC.validate(RC.STARTER).weight === RC.validate({ ...RC.STARTER, body: { hx: 1, wx: 1, lx: 1 } }).weight, 'default body = no change');
}
console.log(fails ? `${fails} failure(s)` : 'all ok');
process.exit(fails ? 1 : 0);