Versus mode: attack vs defend (sim, bots, server, client)

One player defends, the other plays the Internet: earns credits over time and
spends them on packets, upgrades and sabotage. Two rounds with swapped roles,
timed (the faster fall wins). Built end to end, NOT yet QA'd or balanced.

Sim (public/js/sim.js, TD.VS table): attacker economy (income, lifetime bonus,
leak payback), spawn / stage / launch convoys, 7 tech tracks, abilities (EMP,
decoy, surge, DDoS), defender tools (scan, patch, repair, quarantine), role-checked
commands, round result, role-private state. Co-op/solo unchanged (24 scripted
games replay identically).

Bots (public/js/bot.js, tools/versus.js): defender (maze + turrets) and attacker
(budgeted spender reading the tower mix); headless bot-vs-bot runner.

Server (server/versus.js, protocol doc): versus rooms with lobby / countdown /
playing / roundover / matchover, role stamping, cross-role refusal, role-private
priv messages at 4 Hz, computer seat, freeze/forfeit rules, no pause/speed.

Client (public/js/versus.js): setup dialog (role, length, vs computer or online),
countdown, defender tools row, attacker unit shop with convoy + launch, tech and
abilities, gateway choice, round/match screens, sounds, phone-first dock rows.

Status and next steps (balance: the attacker currently wins ~100% of bot rounds;
QA with two browsers; layout matrix rerun) are in docs/NEXT.md and docs/VERSUS.md.
The full planned workflow incl. balance/QA prompts is in docs/workflows/versus-full.js.

253 unit tests pass; one smoke e2e run; no other e2e per the user's request.

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-11 10:22:29 +00:00
parent b4ae6cb57d
commit 2098d59c1f
23 changed files with 6166 additions and 90 deletions

View file

@ -26,6 +26,69 @@
const CLEAR_BONUS_PER_WAVE = 1;
function clearBonus(n) { return CLEAR_BONUS + CLEAR_BONUS_PER_WAVE * n; }
// ---------------------------------------------------------------- versus mode: every number in ONE table
// new Sim({ mode: 'versus' }) is attack-vs-defend (docs/VERSUS.md). One player defends (builds, as in co-op, with the credits in `sim.gold`),
// the other attacks (buys units with `vs.credits`). The table is exported as TD.VS and read at the moment a rule runs, never cached,
// so the balance pass edits numbers HERE and nothing else (tests and the bots derive their expectations from it).
// defender DEF_GOLD start credits (an explicit `gold` option wins), DEF_TRICKLE credits/s on top of kill rewards, a kill pays
// round(buyCost * KILL_REWARD) [no wave scaling: versus units are base stats x the attacker's tech]
// attacker ATT_CREDITS start credits; income ATT_INCOME/s + ATT_INCOME_GROWTH/s per second elapsed; every living unit pays
// buyCost * LIFE_RATE per second alive up to LIFE_CAP of its price in total; a leak pays the price back
// caps MAX_ALIVE units on the map (a release still queued counts), MAX_STAGED waiting in the convoy
// release a convoy / a multi-unit buy is let out as a stream: RELEASE_GAP s apart, but the whole stream takes at most LAUNCH_SPAN s
// tech level L (1..max) costs TECH_COST * 2^(L-1): armor +per armour, speed +per x base, health +per x base hp,
// regen +per x max hp per second, shield +per hit points, stealth: towers cannot acquire the unit for secs[L-1] s after it
// enters the map, crypt: slows (Rate Limiter, Uplink) work res[L-1] weaker. Tech applies to units that enter the map afterwards.
// abilities attacker, cost credits, cooldown cd s, effect lasts dur s; tools: defender, cost gold, same shape
const VS = {
LIMITS: [480, 720, 960], DEFAULT_LIMIT: 720, ROUNDS: 2,
ATT_CREDITS: 150, ATT_INCOME: 4, ATT_INCOME_GROWTH: 0.02, LIFE_RATE: 0.004, LIFE_CAP: 0.5,
MAX_ALIVE: 250, MAX_STAGED: 200, RELEASE_GAP: 0.5, LAUNCH_SPAN: 3,
DEF_GOLD: 250, DEF_TRICKLE: 2, KILL_REWARD: 0.4,
TECH_COST: 100,
TECH_ORDER: ['armor', 'speed', 'health', 'regen', 'shield', 'stealth', 'crypt'],
TECH: {
armor: { max: 5, per: 1 },
speed: { max: 5, per: 0.08 },
health: { max: 5, per: 0.15 },
regen: { max: 3, per: 0.01 },
shield: { max: 3, per: 40 },
stealth: { max: 3, secs: [1, 1.5, 2] },
crypt: { max: 3, res: [0.2, 0.4, 0.6] },
},
ABILITY_ORDER: ['emp', 'decoy', 'surge', 'ddos'],
ABILITIES: {
emp: { cost: 80, cd: 20, dur: 6 }, // one tower (tid) does nothing for dur s
decoy: { cost: 60, cd: 25, dur: 5 }, // a harmless, unkillable unit that every tower that can reach it prefers, for dur s
surge: { cost: 120, cd: 40, dur: 6, speed: 0.4 }, // every unit +speed x base speed
ddos: { cost: 200, cd: 70, dur: 4, slow: 0.4 }, // every tower's cooldown runs `slow` slower
},
TOOL_ORDER: ['scan', 'patch', 'repair', 'quarantine'],
TOOLS: {
scan: { cost: 40, cd: 15, radius: 4, reveal: 3 }, // at (x, y): clears EMP on towers within radius, units within radius can be targeted for reveal s
patch: { cost: 30, cd: 8 }, // tower tid is re-enabled at once
repair: { cost: 120, cd: 30, amount: 3 }, // +amount integrity, never above the maximum
quarantine: { cost: 150, cd: 60, dur: 2 }, // every unit on the board is frozen for dur s
},
// one-tap convoys for the shop UI and the attacker bot: [[kind, n], ...]
PRESETS: {
rush: [['ping', 20]],
swarm: [['spam', 60]],
siege: [['trojan', 4], ['daemon', 1]],
air: [['ghost', 10]],
boss: [['rootkit', 1]],
},
};
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
// Float credits and cooldowns drift by ~1e-12 over thousands of ticks: "can pay" and "on cooldown" tolerate EPS, and the numbers the sim
// REPORTS are rounded the careful way (credits down, cooldowns up), so a side never sees "9.00 credits" or "0 s left" and then gets a refusal.
const EPS = 1e-6;
const cooling = (x) => x > EPS;
const down2 = (x) => Math.floor((x + EPS) * 100) / 100;
const up2 = (x) => (x > EPS ? Math.ceil(x * 100) / 100 : 0);
const DEFENDER_CMDS = { place: 1, sell: 1, upgrade: 1, target: 1, tool: 1 };
const ATTACKER_CMDS = { spawn: 1, stage: 1, launch: 1, tech: 1, ability: 1 };
// ---------------------------------------------------------------- difficulty
// One row per difficulty; every number is a multiplier on the base tables below (normal is all 1, so it plays exactly the tuned base game):
// gold the starting credits (START_GOLD) lives the starting integrity (START_LIVES), at least 1
@ -614,6 +677,37 @@
this.bullets = [];
this.spawnQ = [];
this.events = [];
this.vs = null; // versus state (null in solo / co-op, which then run exactly as before)
if (opts.mode === 'versus') this.initVersus(opts);
}
// Versus: no waves, no difficulty (units are base stats x the attacker's tech), the defender's credits are `gold`, the integrity is
// `lives`; the round ends when it hits 0 (attacker wins) or `limit` seconds pass (defender wins). state: 'playing' -> 'over'.
initVersus(opts) {
this.difficulty = DEFAULT_DIFFICULTY;
this.diff = DIFFICULTIES[DEFAULT_DIFFICULTY];
this.gold = opts.gold === undefined ? VS.DEF_GOLD : opts.gold;
this.lives = opts.lives === undefined ? START_LIVES : opts.lives;
this.maxLives = this.lives;
this.winWave = Infinity;
const tech = {}, acd = {}, dcd = {};
for (const k of VS.TECH_ORDER) tech[k] = 0;
for (const k of VS.ABILITY_ORDER) acd[k] = 0;
for (const k of VS.TOOL_ORDER) dcd[k] = 0;
this.vs = {
limit: Number.isFinite(opts.limit) && opts.limit > 0 ? opts.limit : VS.DEFAULT_LIMIT,
credits: opts.credits === undefined ? VS.ATT_CREDITS : opts.credits, // the attacker's (role-private)
tech, acd, dcd,
staged: [], // the convoy: [[kind, n], ...] in the order it was bought (paid, not on the map yet)
rel: [], // units being let out: { t, kind, gate } (paid, count towards the alive cap)
surgeT: 0, ddosT: 0, freezeT: 0,
scans: [], // Scan reveal zones: { x, y, t }
trickle: 0, // the defender's fractional income (gold stays a whole number)
lost: 0, // integrity taken off in total (repairs do not give it back)
result: null, // { winner, t, integrityLost } once the round is over
stats: { spawned: 0, unitsSpent: 0, techSpent: 0, abilitySpent: 0, toolSpent: 0, earned: 0, leaked: 0, kills: 0 },
};
}
emit(e) {
@ -626,6 +720,7 @@
// ---- commands -------------------------------------------------------------------------
cmd(c) {
if (!c || typeof c !== 'object') return { ok: false, reason: 'bad_cmd' };
if (this.vs) return this.vsCmd(c);
switch (c.c) {
case 'place': return this.place(c.type, c.x, c.y, c.by | 0);
case 'sell': return this.sell(c.id);
@ -638,6 +733,189 @@
}
}
// ---- versus commands --------------------------------------------------------------------
// The command carries the issuer's `role` ('defender' | 'attacker'; the server fills it from the seat). Order of refusals, all of them
// BEFORE anything is charged or started: unknown command -> bad_cmd (waves are 'versus'), wrong or missing role -> 'role', round over
// -> 'over', then the command's own checks (bad_cmd / bad_kind / bad_target for malformed input, 'cap', 'max', 'cooldown', 'credits').
// A cooldown starts only when the command succeeded.
vsCmd(c) {
const need = hasOwn(DEFENDER_CMDS, c.c) ? 'defender' : hasOwn(ATTACKER_CMDS, c.c) ? 'attacker' : null;
if (!need) return { ok: false, reason: c.c === 'wave' || c.c === 'auto' || c.c === 'continue' ? 'versus' : 'bad_cmd' };
if (c.role !== need) return { ok: false, reason: 'role' };
if (this.state !== 'playing') return { ok: false, reason: 'over' };
let r;
switch (c.c) {
case 'place': r = this.place(c.type, c.x, c.y, c.by | 0); break;
case 'sell': r = this.sell(c.id); break;
case 'upgrade': r = this.upgrade(c.id, c.lv); break;
case 'target': r = this.setTargetMode(c.id, c.mode); break;
case 'tool': r = this.useTool(c); break;
case 'spawn': r = this.vsBuy(c, false); break;
case 'stage': r = this.vsBuy(c, true); break;
case 'launch': r = this.vsLaunch(c); break;
case 'tech': r = this.vsTech(c.id); break;
default: r = this.vsAbility(c);
}
if (r.ok && need === 'attacker') this.vsRelease(); // the first unit of a stream is on the map when the command returns
return r;
}
vsGate(g) {
if (g === undefined || g === null) return -1; // -1: round robin
return Number.isInteger(g) && g >= 0 && g < this.board.spawns.length ? g : -2;
}
vsAlive() { let n = 0; for (const m of this.monsters) if (!m.dead && !m.decoy) n++; return n + this.vs.rel.length; }
vsStaged() { let n = 0; for (const e of this.vs.staged) n += e[1]; return n; }
vsCount(c) { // units in a spawn / stage command: a positive whole number (default 1)
const n = c.n === undefined || c.n === null ? 1 : c.n;
return Number.isInteger(n) && n >= 1 && n <= VS.MAX_ALIVE ? n : 0;
}
// Queue `n` units of `kind` for release as a stream starting now (the stream's gaps: RELEASE_GAP, at most LAUNCH_SPAN s in all).
vsQueue(kind, n, gate, t0, gap) {
for (let i = 0; i < n; i++) {
const g = gate >= 0 ? gate : this.spawnRR++ % this.board.spawns.length;
this.vs.rel.push({ t: t0 + i * gap, kind, gate: g });
}
}
vsGap(n) { return n > 1 ? Math.min(VS.RELEASE_GAP, VS.LAUNCH_SPAN / n) : 0; }
// spawn (buy and release now) / stage (pay now, hold in the convoy)
vsBuy(c, stage) {
if (typeof c.kind !== 'string' || !hasOwn(ENEMIES, c.kind)) return { ok: false, reason: 'bad_kind' };
const n = this.vsCount(c);
if (!n) return { ok: false, reason: 'bad_cmd' };
const gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
const v = this.vs, cost = ENEMIES[c.kind].buyCost * n;
if (stage ? this.vsStaged() + n > VS.MAX_STAGED : this.vsAlive() + n > VS.MAX_ALIVE) return { ok: false, reason: 'cap' };
if (v.credits + EPS < cost) return { ok: false, reason: 'credits' };
v.credits -= cost; v.stats.unitsSpent += cost;
if (stage) {
const e = v.staged.find((q) => q[0] === c.kind);
if (e) e[1] += n; else v.staged.push([c.kind, n]);
return { ok: true, n, staged: this.vsStaged() };
}
this.vsQueue(c.kind, n, gate, this.time, this.vsGap(n));
return { ok: true, n };
}
// launch: let (as much as fits under the alive cap of) the convoy out as one stream
vsLaunch(c) {
const gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
const v = this.vs, total = this.vsStaged();
if (!total) return { ok: false, reason: 'empty' };
const room = VS.MAX_ALIVE - this.vsAlive();
if (room <= 0) return { ok: false, reason: 'cap' };
const k = Math.min(total, room), gap = this.vsGap(k);
let left = k, i = 0;
for (const e of v.staged) {
const take = Math.min(e[1], left);
this.vsQueue(e[0], take, gate, this.time + i * gap, gap);
e[1] -= take; left -= take; i += take;
if (!left) break;
}
v.staged = v.staged.filter((e) => e[1] > 0);
return { ok: true, n: k, staged: total - k };
}
// tech: the next level of one upgrade, TECH_COST * 2^(level now); applies to units that enter the map afterwards
vsTech(id) {
if (typeof id !== 'string' || !hasOwn(VS.TECH, id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, lv = v.tech[id];
if (lv >= VS.TECH[id].max) return { ok: false, reason: 'max' };
const cost = VS.TECH_COST * Math.pow(2, lv);
if (v.credits + EPS < cost) return { ok: false, reason: 'credits' };
v.credits -= cost; v.stats.techSpent += cost;
v.tech[id] = lv + 1;
return { ok: true, level: lv + 1 };
}
techCost(id) { const lv = this.vs.tech[id]; return lv >= VS.TECH[id].max ? null : VS.TECH_COST * Math.pow(2, lv); }
// abilities: emp (tid) / decoy (gate? tid?) / surge / ddos
vsAbility(c) {
if (typeof c.id !== 'string' || !hasOwn(VS.ABILITIES, c.id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, A = VS.ABILITIES[c.id];
let tower = null, gate = -1;
if (c.id === 'emp') {
tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null;
if (!tower || TOWERS[tower.type].role === 'wall') return { ok: false, reason: 'bad_target' }; // a Firewall does nothing to disable
} else if (c.id === 'decoy') {
gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
if (c.tid !== undefined && c.tid !== null) { tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null; if (!tower) return { ok: false, reason: 'bad_target' }; }
}
if (cooling(v.acd[c.id])) return { ok: false, reason: 'cooldown' };
if (v.credits + EPS < A.cost) return { ok: false, reason: 'credits' };
v.credits -= A.cost; v.stats.abilitySpent += A.cost; v.acd[c.id] = A.cd;
switch (c.id) {
case 'emp': tower.empT = A.dur; tower.tgt = 0; this.emit({ e: 'emp', id: tower.id, d: A.dur }); break;
case 'decoy': this.vsDecoy(gate, tower, A.dur); break;
case 'surge': v.surgeT = A.dur; this.emit({ e: 'surge', d: A.dur }); break;
default: v.ddosT = A.dur; this.emit({ e: 'ddos', d: A.dur });
}
return { ok: true };
}
// The decoy: an existing kind (a Ping) with the decoy flag, so no new wire kind. Invulnerable, harmless (leaks for nothing, pays nothing,
// earns nothing, outside the caps), gone after `dur` s. With `tower` it appears on the route cell closest to that tower, else at the gate.
vsDecoy(gate, tower, dur) {
const b = this.board, g = gate >= 0 ? gate : this.spawnRR++ % b.spawns.length;
let at = null;
if (tower) {
let bd = Infinity;
for (const cell of b.routes[g]) {
const d = (cell[0] - tower.x) * (cell[0] - tower.x) + (cell[1] - tower.y) * (cell[1] - tower.y);
if (d < bd) { bd = d; at = cell; }
}
}
const m = this.vsUnit('ping', g, at);
m.decoy = true; m.ttl = dur; m.leak = 0; m.reward = 0; m.buyCost = 0; m.stealthT = 0; m.regen = 0; m.shield = m.maxShield = 0;
this.monsters.push(m);
this.emit({ e: 'decoy', id: m.id, d: dur });
}
// defender tools: { c:'tool', id:'scan'|'patch'|'repair'|'quarantine', x?, y?, tid? }, paid with `gold`
useTool(c) {
if (typeof c.id !== 'string' || !hasOwn(VS.TOOLS, c.id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, T = VS.TOOLS[c.id], b = this.board;
let tower = null;
if (c.id === 'scan') {
if (typeof c.x !== 'number' || typeof c.y !== 'number' || !isFinite(c.x) || !isFinite(c.y) || c.x < 0 || c.y < 0 || c.x > b.cols || c.y > b.rows) return { ok: false, reason: 'bad_target' };
} else if (c.id === 'patch') {
tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null;
if (!tower || !(tower.empT > 0)) return { ok: false, reason: 'bad_target' }; // nothing to re-enable
} else if (c.id === 'repair') {
if (this.lives >= this.maxLives) return { ok: false, reason: 'max' };
}
if (cooling(v.dcd[c.id])) return { ok: false, reason: 'cooldown' };
if (this.gold < T.cost) return { ok: false, reason: 'credits' };
this.gold -= T.cost; v.stats.toolSpent += T.cost; v.dcd[c.id] = T.cd;
switch (c.id) {
case 'scan': {
const r2 = T.radius * T.radius;
for (const t of this.towers) {
const dx = t.x + 0.5 - c.x, dy = t.y + 0.5 - c.y;
if (t.empT > 0 && dx * dx + dy * dy <= r2) t.empT = 0;
}
v.scans.push({ x: c.x, y: c.y, t: T.reveal });
this.emit({ e: 'scan', x: round2(c.x), y: round2(c.y) });
break;
}
case 'patch': tower.empT = 0; break;
case 'repair': this.lives = Math.min(this.maxLives, this.lives + T.amount); this.emit({ e: 'repair' }); break;
default: v.freezeT = T.dur; this.emit({ e: 'quarantine', d: T.dur });
}
return { ok: true };
}
// A Scan zone reveals stealthed units (they can be targeted) for its `reveal` seconds.
vsRevealed(m) {
for (const z of this.vs.scans) { const dx = m.x - z.x, dy = m.y - z.y; if (dx * dx + dy * dy <= VS.TOOLS.scan.radius * VS.TOOLS.scan.radius) return true; }
return false;
}
// Cells monsters occupy or are about to enter; used to refuse placements that would trap or clip them.
monsterCells() {
const b = this.board, cols = b.cols;
@ -692,7 +970,7 @@
}
sell(id) {
if (this.state === 'lost') return { ok: false, reason: 'over' };
if (this.state === 'lost' || this.state === 'over') return { ok: false, reason: 'over' };
const t = this.towerById(id);
if (!t) return { ok: false, reason: 'no_tower' };
const def = TOWERS[t.type];
@ -736,12 +1014,14 @@
}
setAuto(v) {
if (this.vs) return { ok: false, reason: 'versus' };
this.autoWaves = v;
if (v && this.nextWaveIn < 0) this.nextWaveIn = WAVE_INTERVAL;
return { ok: true };
}
continueEndless() {
if (this.vs) return { ok: false, reason: 'versus' };
if (this.state !== 'won') return { ok: false, reason: 'not_won' };
this.state = 'playing';
this.winWave = Infinity;
@ -751,6 +1031,7 @@
// `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.vs) return { ok: false, reason: 'versus' }; // versus has no waves: the attacker brings the units
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;
@ -787,10 +1068,80 @@
this.monsters.push(m);
}
// ---- versus units ---------------------------------------------------------------------
// A unit at gate `gate` (or on the route cell `at` = [x, y]): the kind's BASE stats x the attacker's tech now. No hpScale, no difficulty.
vsUnit(kind, gate, at) {
const def = ENEMIES[kind], b = this.board, T = this.vs.tech, X = VS.TECH;
const s = at ? { x: at[0], y: at[1] } : b.spawns[gate];
const hp = Math.max(1, Math.round(def.hp * (1 + X.health.per * T.health)));
const shield = (def.shield || 0) + (T.shield ? X.shield.per * T.shield : 0);
const m = {
id: this.nid++, kind, 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 + X.armor.per * T.armor, speed: def.speed * (1 + X.speed.per * T.speed),
reward: Math.max(1, Math.round(def.buyCost * VS.KILL_REWARD)),
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
shield, maxShield: shield, shieldT: 0,
rem: 0, dead: false, wave: 0,
buyCost: def.buyCost, earned: 0, // lifetime bonus paid so far
regen: X.regen.per * T.regen, // fraction of max hp per second
crypt: T.crypt ? X.crypt.res[T.crypt - 1] : 0, // slows work this much weaker
stealthT: T.stealth ? X.stealth.secs[T.stealth - 1] : 0, // towers cannot acquire it until this runs out (or a Scan reveals it)
};
m.rem = m.air ? Math.hypot(b.core.x - s.x, b.core.y - s.y) : b.field[s.y * b.cols + s.x];
return m;
}
// Units whose release time has come enter the map (a command calls this too, so the first unit of a stream is there at once).
vsRelease() {
const rel = this.vs.rel;
let w = 0;
for (let i = 0; i < rel.length; i++) {
const q = rel[i];
if (q.t <= this.time + 1e-9) { this.monsters.push(this.vsUnit(q.kind, q.gate)); this.vs.stats.spawned++; } else rel[w++] = q;
}
rel.length = w;
}
// Start of every versus tick: income, lifetime bonus, the defender's trickle, cooldowns and effect timers, unit timers, releases.
vsBegin(dt) {
const v = this.vs;
let inc = (VS.ATT_INCOME + VS.ATT_INCOME_GROWTH * (this.time - dt / 2)) * dt; // the rate in the middle of this tick: exact for a rate that rises linearly
for (const m of this.monsters) {
if (m.dead) continue;
if (m.decoy) { m.ttl -= dt; if (m.ttl <= 0) m.dead = true; continue; }
const cap = m.buyCost * VS.LIFE_CAP;
if (m.earned < cap) { const b = Math.min(m.buyCost * VS.LIFE_RATE * dt, cap - m.earned); m.earned += b; inc += b; }
if (m.stealthT > 0) m.stealthT -= dt;
if (m.regen > 0 && m.hp < m.maxhp) m.hp = Math.min(m.maxhp, m.hp + m.maxhp * m.regen * dt);
}
v.credits += inc; v.stats.earned += inc;
v.trickle += VS.DEF_TRICKLE * dt;
const whole = Math.floor(v.trickle);
if (whole > 0) { this.gold += whole; v.trickle -= whole; }
for (const k in v.acd) if (v.acd[k] > 0) v.acd[k] = Math.max(0, v.acd[k] - dt);
for (const k in v.dcd) if (v.dcd[k] > 0) v.dcd[k] = Math.max(0, v.dcd[k] - dt);
if (v.surgeT > 0) v.surgeT = Math.max(0, v.surgeT - dt);
if (v.ddosT > 0) v.ddosT = Math.max(0, v.ddosT - dt);
if (v.freezeT > 0) v.freezeT = Math.max(0, v.freezeT - dt);
if (v.scans.length) { for (const z of v.scans) z.t -= dt; v.scans = v.scans.filter((z) => z.t > 0); }
if (v.rel.length) this.vsRelease();
}
// The round is over: `winner` is 'attacker' (integrity gone) or 'defender' (time ran out).
vsEnd(winner) {
const v = this.vs;
if (this.lives < 0) this.lives = 0;
this.state = 'over';
v.result = { winner, t: round2(this.time), integrityLost: v.lost };
this.emit({ e: 'round', winner, t: v.result.t });
}
// ---- main step ------------------------------------------------------------------------
tick(dt) {
if (this.state !== 'playing') return;
this.time += dt;
if (this.vs) this.vsBegin(dt);
if (this.autoWaves) {
this.nextWaveIn -= dt;
if (this.nextWaveIn <= 0) this.startWave();
@ -816,6 +1167,11 @@
}
this.monsters.length = w;
if (this.vs) { // versus: integrity first (the attacker wins even on the last tick), then the clock
if (this.lives <= 0) this.vsEnd('attacker');
else if (this.time >= this.vs.limit) this.vsEnd('defender');
return;
}
if (this.lives <= 0) {
this.lives = 0;
this.state = 'lost';
@ -837,9 +1193,12 @@
// ---- monsters -------------------------------------------------------------------------
moveMonster(m, dt) {
if (m.stunT > 0) return; // stunned (Sandbox): frozen in place
const vs = this.vs;
if (vs && vs.freezeT > 0) return; // Quarantine: every unit is frozen
const b = this.board;
const slowMul = 1 - Math.min(0.6, m.slow);
let remaining = m.speed * slowMul * dt;
if (vs && vs.surgeT > 0) remaining *= 1 + VS.ABILITIES.surge.speed;
if (m.air) {
const gx = b.core.x + 0.5, gy = b.core.y + 0.5;
const dx = gx - m.x, dy = gy - m.y, d = Math.hypot(dx, dy);
@ -873,13 +1232,19 @@
leak(m) {
m.dead = true; m.leaked = true;
if (m.decoy) return; // a decoy that reaches the server is harmless and silent
const v = this.vs;
if (v) { // versus: the integrity taken off is counted, the attacker gets the unit's price back
v.lost += Math.min(m.leak, Math.max(0, this.lives));
v.credits += m.buyCost; v.stats.earned += m.buyCost; v.stats.leaked++;
}
this.lives -= m.leak;
this.leaks++;
this.emit({ e: 'leak', x: m.x, y: m.y, n: m.leak });
}
damage(m, raw, src, ignoreArmor) {
if (m.dead) return;
if (m.dead || m.decoy) return; // (a decoy cannot be hurt)
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
@ -892,6 +1257,7 @@
m.dead = true;
this.gold += m.reward;
this.kills++;
if (this.vs) this.vs.stats.kills++;
if (src) src.kills++;
this.emit({ e: 'kill', x: m.x, y: m.y, k: m.kind, rw: m.reward });
}
@ -900,6 +1266,7 @@
// Shield: after shieldDelay s without damage it regrows shieldRegen of its maximum per second.
regenShield(m, dt) {
const def = ENEMIES[m.kind];
if (!def.shieldRegen) return; // a shield bought as tech on a kind that has none does not regrow
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);
@ -930,7 +1297,7 @@
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); }
for (const t of ts) { t.buff = 0; if (TOWERS[t.type].role === 'support' && !(t.empT > 0)) (sup || (sup = [])).push(t); } // (an EMPed balancer boosts nothing)
if (!sup) return;
for (const s of sup) {
const st = TOWERS[s.type].levels[s.level - 1], r2 = st.range * st.range;
@ -951,8 +1318,12 @@
if (m.air ? !def.air : !def.ground) continue;
const dx = m.x - tx, dy = m.y - ty, d2 = dx * dx + dy * dy;
if (d2 > r2) continue;
// versus: a stealthed unit cannot be ACQUIRED as a target (splash, beam and chain lightning still hit it once something else is
// shot) until its stealth runs out or a Scan reveals it; a decoy beats every other target, the nearest decoy first
if (m.stealthT > 0 && !this.vsRevealed(m)) continue;
let v;
switch (t.mode) {
if (m.decoy) v = 1e9 - d2;
else switch (t.mode) {
case 'last': v = m.rem; break;
case 'strong': v = m.hp + (m.shield || 0); break;
case 'close': v = -d2; break;
@ -964,23 +1335,25 @@
}
updateTower(t, dt) {
if (t.empT > 0) { t.empT -= dt; t.tgt = 0; return; } // versus: an EMPed tower does nothing (attack, slow, stun, boost) until it runs out
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 (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt); return; }
const dd = this.vs && this.vs.ddosT > 0 ? 1 - VS.ABILITIES.ddos.slow : 1; // DDoS: cooldowns run slower
if (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt * dd); return; }
if (def.role === 'aura') {
const r2 = st.range * st.range;
for (const m of this.monsters) {
if (m.dead) continue;
const dx = m.x - cx, dy = m.y - cy;
if (dx * dx + dy * dy > r2) continue;
const eff = st.slow * (1 - (ENEMIES[m.kind].slowRes || 0));
const eff = st.slow * (1 - (ENEMIES[m.kind].slowRes || 0)) * (1 - (m.crypt || 0));
if (eff > m.slow) m.slow = eff;
}
return;
}
t.cd -= dt * (1 + (t.buff || 0)); // a Load Balancer makes cooldowns elapse faster
t.cd -= dt * (1 + (t.buff || 0)) * dd; // 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; }
@ -1051,7 +1424,7 @@
if (dx * dx + dy * dy <= r2) blast.push(o);
}
const slowFor = (o) => {
const eff = Math.min(0.6, st.slowOnHit * (1 - (ENEMIES[o.kind].slowRes || 0)));
const eff = Math.min(0.6, st.slowOnHit * (1 - (ENEMIES[o.kind].slowRes || 0)) * (1 - (o.crypt || 0)));
if (eff >= o.slowAmt || o.slowT <= 0) o.slowAmt = eff;
o.slowT = Math.max(o.slowT, st.slowFor);
};
@ -1120,12 +1493,35 @@
// Everything a client needs to (re)build the board from scratch.
fullState() {
return {
const f = {
map: this.mapId, rev: this.rev, towers: this.towerList(),
winWave: this.winWave === Infinity ? 0 : this.winWave,
maxLives: this.maxLives,
difficulty: this.difficulty,
};
if (this.vs) { f.mode = 'versus'; f.limit = this.vs.limit; } // only versus carries these: a co-op state is exactly what it was
return f;
}
// What ONE side may know that the other may not (the shared snapshot carries only snapshot().vs). The server sends it to the seat that
// holds the role; copies, so a caller cannot reach into the sim.
// attacker { credits, income (credits per second now), tech {id: level}, staged [[kind, n]], cd {ability: seconds left}, active {surge, ddos: seconds left} }
// defender { cd {tool: seconds left} } (its credits are `gold` in the shared snapshot)
privateState(role) {
const v = this.vs;
if (!v) return null;
const left = (o) => { const r = {}; for (const k in o) r[k] = up2(o[k]); return r; };
if (role === 'defender') return { cd: left(v.dcd) };
if (role !== 'attacker') return null;
let income = VS.ATT_INCOME + VS.ATT_INCOME_GROWTH * this.time;
for (const m of this.monsters) if (!m.dead && !m.decoy && m.earned < m.buyCost * VS.LIFE_CAP) income += m.buyCost * VS.LIFE_RATE;
return {
credits: down2(v.credits), income: round2(income),
tech: Object.assign({}, v.tech),
staged: v.staged.map((e) => [e[0], e[1]]),
cd: left(v.acd),
active: { surge: up2(v.surgeT), ddos: up2(v.ddosT) },
};
}
// Compact per-tick state for the wire. Arrays, not objects, to keep it small.
@ -1134,20 +1530,23 @@
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]);
return {
const v = this.vs;
for (const t of this.towers) if (t.type !== 'wall') tt.push(v ? [t.id, t.tgt, t.kills, t.empT > 0 ? round2(t.empT) : 0] : [t.id, t.tgt, t.kills]); // versus: a 4th field, seconds left of an EMP
const snap = {
time: round2(this.time), g: this.gold, l: this.lives, w: this.wave, s: this.state,
au: this.autoWaves ? 1 : 0, nw: this.autoWaves ? round2(this.nextWaveIn) : -1,
k: this.kills, rev: this.rev, mo, bu, tt,
q: this.spawnQ.length,
};
if (v) snap.vs = { t: round2(this.time), lim: v.limit, st: this.vsStaged() }; // the SHARED part only: how big the convoy is, never what is in it
return snap;
}
}
function round2(v) { return Math.round(v * 100) / 100; }
return {
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP,
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP, VS,
DIFFICULTIES, DIFFICULTY_ORDER, DEFAULT_DIFFICULTY, isDifficulty, difficultyId,
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale, clearBonus,