towerdef/public/js/sim.js
Claude 2098d59c1f 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
2026-10-11 10:22:29 +00:00

1555 lines
75 KiB
JavaScript

/*
* NETWALL - shared simulation core.
*
* Pure game logic, no DOM, no timers. Loaded as a classic <script> in the browser (window.TD)
* and with require() in Node (the multiplayer server runs the authoritative copy).
*
* Coordinates are in cell units; the centre of cell (i, j) is (i + 0.5, j + 0.5).
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory();
else root.TD = factory();
})(typeof self !== 'undefined' ? self : this, function () {
'use strict';
const STEP = 1 / 60;
const SQRT2 = Math.SQRT2;
const DX = [1, -1, 0, 0, 1, 1, -1, -1];
const DY = [0, 0, 1, -1, 1, -1, 1, -1];
const WAVE_INTERVAL = 28;
const START_GOLD = 140;
const START_LIVES = 20;
const SELL_RATIO = 0.7;
const WIN_WAVE = 30;
// Clearing wave n pays CLEAR_BONUS + CLEAR_BONUS_PER_WAVE * n credits on top of the kills (the same on every difficulty).
const CLEAR_BONUS = 10;
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
// hp every enemy's hit points AND its shield reward what a kill pays (a kill always pays at least 1)
// The wave clear bonus and the tower prices do not change. Nothing outside this table may hard-code a number from it: tests, the
// UI and the balance bot read the table. The ids travel on the wire (create-room option, newgame, fullState), so only ever APPEND.
// (Not to be confused with the `difficulty` 1-3 of a MAP below: that is the layout's own rating, drawn as dots on the map cards.)
const DIFFICULTY_ORDER = ['easy', 'normal', 'hard'];
const DEFAULT_DIFFICULTY = 'normal';
const DIFFICULTIES = {
easy: { id: 'easy', name: 'Easy', gold: 1.5, lives: 1.5, hp: 0.8, reward: 1.1 },
normal: { id: 'normal', name: 'Normal', gold: 1, lives: 1, hp: 1, reward: 1 },
hard: { id: 'hard', name: 'Hard', gold: 0.9, lives: 0.85, hp: 1.08, reward: 0.97 },
};
// Is `v` the id of a difficulty? (own keys only: 'toString' and '__proto__' are not difficulties)
function isDifficulty(v) { return typeof v === 'string' && Object.prototype.hasOwnProperty.call(DIFFICULTIES, v); }
// `v` if it is a difficulty, otherwise normal (what the Sim does with an unknown value; the server rejects those instead).
function difficultyId(v) { return isDifficulty(v) ? v : DEFAULT_DIFFICULTY; }
// ---------------------------------------------------------------- maps
// '.' open, '#' dead node (permanent obstacle), 'S' spawn (internet gateway), 'C' core (the server)
const MAPS = {
open: {
id: 'open', name: 'Open Field', difficulty: 1,
desc: 'One gateway, one server, wide open. Build your own maze.',
rows: [
'..........................',
'..........................',
'....##..........##........',
'....#............#........',
'..........................',
'..........................',
'..........................',
'S.........................',
'.........................C',
'..........................',
'..........................',
'..........................',
'....#............#........',
'....##..........##........',
'..........................',
'..........................',
],
},
twin: {
id: 'twin', name: 'Twin Gateways', difficulty: 2,
desc: 'Two gateways flood one server. A central pillar splits the field.',
rows: [
'S.........................',
'..........................',
'..........................',
'.........#######..........',
'..........................',
'..........................',
'..........................',
'.........................C',
'..........................',
'..........................',
'..........................',
'.........#######..........',
'..........................',
'..........................',
'..........................',
'S.........................',
],
},
hub: {
id: 'hub', name: 'The Hub', difficulty: 3,
desc: 'The server sits in the middle. Traffic arrives from three sides.',
rows: [
'............S.............',
'..........................',
'..##..................##..',
'..#....................#..',
'..........................',
'..........................',
'..........................',
'S.........................',
'.............C............',
'.........................S',
'..........................',
'..........................',
'..........................',
'..#....................#..',
'..##..................##..',
'..........................',
],
},
canyon: {
id: 'canyon', name: 'The Canyon', difficulty: 1,
desc: 'Three ridges force a natural S-bend. Great for learning where to stack turrets.',
rows: [
'.......#.........#........',
'.......#.........#........',
'.......#.........#........',
'.......#.........#........',
'.......#.........#........',
'.......#....#....#........',
'.......#....#....#........',
'S......#....#....#........',
'.......#....#....#.......C',
'.......#....#....#........',
'.......#....#....#........',
'............#.............',
'............#.............',
'............#.............',
'............#.............',
'............#.............',
],
},
archipelago: {
id: 'archipelago', name: 'Archipelago', difficulty: 2,
desc: 'Islands of dead nodes everywhere and two gateways. Mind the gaps between them.',
rows: [
'..........................',
'..........................',
'S...##........##......##..',
'....##........##......##..',
'...................##.....',
'.........##........##.....',
'.........##...............',
'..........................',
'...............##........C',
'.....##........##.........',
'.....##...................',
'..........................',
'..........##.......##.....',
'S.........##.......##.##..',
'......................##..',
'..........................',
],
},
fortress: {
id: 'fortress', name: 'Fortress', difficulty: 2,
desc: 'The server sits inside a ring with three entrances. Wall off two, defend the third.',
rows: [
'..........................',
'..........................',
'..........................',
'S.........................',
'..........................',
'..................###.###.',
'..................#.....#.',
'..................#.....#.',
'.....................C..#.',
'..................#.....#.',
'..................#.....#.',
'..................###.###.',
'S.........................',
'..........................',
'..........................',
'..........................',
],
},
pinwheel: {
id: 'pinwheel', name: 'Pinwheel', difficulty: 3,
desc: 'Four gateways, one server in the middle, bars that twist every route.',
rows: [
'.............S............',
'..........................',
'..........................',
'................#.........',
'................#.........',
'........#####...#.........',
'................#.........',
'................#........S',
'S............C............',
'.........#................',
'.........#................',
'.........#....#####.......',
'.........#................',
'.........#................',
'..........................',
'............S.............',
],
},
};
const MAP_ORDER = ['open', 'canyon', 'twin', 'archipelago', 'fortress', 'hub', 'pinwheel'];
function parseMap(m) {
const rows = m.rows.length, cols = m.rows[0].length;
const obst = new Uint8Array(cols * rows);
const spawns = [];
let core = null;
for (let y = 0; y < rows; y++) {
if (m.rows[y].length !== cols) throw new Error('map ' + m.id + ' row ' + y + ' has wrong width');
for (let x = 0; x < cols; x++) {
const ch = m.rows[y][x];
if (ch === '#') obst[y * cols + x] = 1;
else if (ch === 'S') spawns.push({ x, y });
else if (ch === 'C') core = { x, y };
}
}
if (!core || !spawns.length) throw new Error('map ' + m.id + ' needs a core and a spawn');
return { cols, rows, obst, spawns, core };
}
// ---------------------------------------------------------------- definitions
// Every tower has a 'role' so the generic code does not have to know the types:
// wall solid block, does nothing attack shoots (dmg/rate, picks a target, can be rate-boosted)
// aura continuous effect in range control periodic pulse that stuns everything in range
// support no attack of its own: boosts the 'attack' towers around it
// Hotkeys: one unique key 1-9 per tower, in palette order.
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'sandbox', 'balancer', 'uplink'];
const TARGET_MODES = ['first', 'last', 'strong', 'close'];
const UPLINK_GROWTH = 1.3; // each Orbital Uplink you own makes the next one (and its upgrades) this much dearer; was 1.25
const TOWERS = {
wall: {
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1, role: 'wall',
desc: 'Blocks the route. Cheap: use it to build a long maze.',
levels: [{ cost: 5 }],
},
filter: {
name: 'Packet Filter', key: '2', color: '#35e0a1', role: 'attack', air: true, ground: true,
desc: 'Fast, cheap rapid fire. Weak against armour.',
levels: [
{ cost: 25, dmg: 6, range: 3.5, rate: 3.0 },
{ cost: 25, dmg: 9, range: 3.8, rate: 3.4 },
{ cost: 45, dmg: 13, range: 4.2, rate: 4.0 },
],
bulletSpeed: 14,
},
ids: {
name: 'IDS Sniper', key: '3', color: '#b78cff', role: 'attack', air: true, ground: true,
desc: 'Long range, hard hitting, slow. Great against armour and bosses, poor against swarms.',
levels: [
{ cost: 70, dmg: 83, range: 6.2, rate: 0.42 },
{ cost: 80, dmg: 143, range: 6.8, rate: 0.445 },
{ cost: 130, dmg: 250, range: 7.5, rate: 0.48 },
],
},
mortar: {
name: 'Flood Mortar', key: '4', color: '#d4f04a', role: 'attack', air: false, ground: true,
desc: 'Splash damage against ground swarms. Cannot hit flyers.',
levels: [
{ cost: 55, dmg: 31, range: 4.9, rate: 0.8, splash: 1.3 },
{ cost: 60, dmg: 50, range: 5.3, rate: 0.85, splash: 1.5 },
{ cost: 95, dmg: 82, range: 5.7, rate: 0.9, splash: 1.7 },
],
shellSpeed: 5.5,
},
throttle: {
name: 'Rate Limiter', key: '5', color: '#4de3ff', role: 'aura', air: true, ground: true,
desc: 'Slows everything in range. Pair it with damage dealers.',
levels: [
{ cost: 40, range: 3.2, slow: 0.35 },
{ cost: 40, range: 3.6, slow: 0.45 },
{ cost: 70, range: 4.0, slow: 0.55 },
],
},
arc: {
name: 'Router Arc', key: '6', color: '#ff7ad9', role: 'attack', air: true, ground: true,
desc: 'Chain lightning that jumps between nearby packets.',
levels: [
{ cost: 70, dmg: 17, range: 3.8, rate: 1.2, chains: 2, chainRange: 1.9, falloff: 0.7 },
{ cost: 60, dmg: 26, range: 4.0, rate: 1.25, chains: 3, chainRange: 2.0, falloff: 0.72 },
{ cost: 105, dmg: 38, range: 4.4, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
],
},
sandbox: {
name: 'Sandbox', key: '7', color: '#ffa447', role: 'control', air: true, ground: true,
desc: 'Control tower, no damage. Every few seconds it traps every packet in range, ground and air, and freezes it for a moment. Bosses resist and are frozen for half as long.',
levels: [
{ cost: 90, range: 2.6, pulse: 5.0, stun: 1.0 },
{ cost: 80, range: 3.0, pulse: 4.5, stun: 1.3 },
{ cost: 130, range: 3.4, pulse: 4.0, stun: 1.6 },
],
},
balancer: {
name: 'Load Balancer', key: '8', color: '#d3e0ee', role: 'support',
desc: 'Support tower, no attack. Makes every turret in range fire faster. Several balancers do not stack (the best one counts) and a balancer does not boost another balancer.',
levels: [
{ cost: 70, range: 2.2, boost: 0.15 },
{ cost: 70, range: 2.6, boost: 0.25 },
{ cost: 110, range: 3.0, boost: 0.35 },
],
},
uplink: {
name: 'Orbital Uplink', key: '9', color: '#ffe27a', role: 'attack', air: true, ground: true,
desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Extremely expensive to build and to upgrade, and every Uplink you already own makes the next one ' + Math.round((UPLINK_GROWTH - 1) * 100) + '% dearer, and its upgrades too.',
priceGrowth: UPLINK_GROWTH, // the Nth Uplink costs cost * UPLINK_GROWTH^(N-1) to buy AND to upgrade (see priceMult), so kill rewards cannot buy a carpet of them
levels: [
{ cost: 1500, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
{ cost: 1200, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
{ cost: 2000, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
{ cost: 3200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
],
},
};
// ENEMY_ORDER is part of the wire format (snapshots carry the index): only ever APPEND kinds.
// buyCost is the price of one unit in the future versus mode (about 3x the kill reward).
// What building one more `type` costs right now, given the towers already on the board (an array, or a plain count).
// Most towers have a fixed price; a tower with `priceGrowth` gets dearer for every one already owned. Shared by the Sim and
// the UI so the price shown is always the price charged.
// The price multiplier a NEW tower of this type is bought at, given how many are already owned. Each tower remembers the multiplier it was
// bought at (tower.pm) and its upgrades cost the same multiple, so the Nth Uplink is dearer to buy and to upgrade by the same factor.
function priceMult(type, owned) {
const def = TOWERS[type];
if (!def || !def.priceGrowth) return 1;
let n = 0;
if (Array.isArray(owned)) { for (const t of owned) if (t.type === type) n++; } else n = owned | 0;
return Math.pow(def.priceGrowth, n);
}
const roundPrice = (v) => Math.round(v / 10) * 10;
function priceFor(type, owned) {
const def = TOWERS[type];
if (!def) return 0;
const base = def.levels[0].cost, m = priceMult(type, owned);
return m === 1 ? base : roundPrice(base * m);
}
// What upgrading a tower of `type` that is at `level` (1-based) to the next level costs, given the multiplier it was bought at (pm, default 1).
function upgradePrice(type, level, pm) {
const def = TOWERS[type], lv = def && def.levels[level];
if (!lv) return null;
return !pm || pm === 1 ? lv.cost : roundPrice(lv.cost * pm);
}
const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit', 'daemon', 'proxy', 'botnet'];
const ENEMIES = {
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a', buyCost: 10 },
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43', buyCost: 6 },
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 4, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b', buyCost: 30 },
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166', buyCost: 3 },
ghost: { name: 'Spoof', hp: 40, speed: 1.3, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff', buyCost: 15 },
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 7, reward: 60, leak: 5, air: false, r: 0.55, color: '#ff3b3b', buyCost: 180, slowRes: 0.5 },
// Healer: every HEAL_EVERY s it restores 'heal' of the max hp of every other enemy within healRange (several daemons stack up to HEAL_CAP).
daemon: { name: 'Daemon', hp: 70, speed: 1.1, armor: 0, reward: 8, leak: 1, air: false, r: 0.3, color: '#7ee08a', buyCost: 25, heal: 0.06, healRange: 2.2 },
// Shielded: 'shield' extra hit points (scaled like hp) that soak damage first and regrow shieldRegen/s of their max after shieldDelay s unhurt.
proxy: { name: 'Proxy', hp: 90, speed: 1.0, armor: 1, reward: 10, leak: 1, air: false, r: 0.34, color: '#7aa2ff', buyCost: 30, shield: 120, shieldRegen: 0.1, shieldDelay: 3 },
// Swarm flyer.
botnet: { name: 'Botnet', hp: 12, speed: 2.2, armor: 0, reward: 1, leak: 1, air: true, r: 0.14, color: '#4dd0c8', buyCost: 3 },
};
const HEAL_EVERY = 1; // seconds between daemon pulses (one global clock, so the 12%/s cap is exact)
const HEAL_CAP = 0.12; // most max-hp fraction one enemy can be healed per pulse, however many daemons are near
// Wave n (1-based). The first eight waves introduce each unit type; later ones loop with bigger numbers.
function waveGroups(n) {
const f = 1 + (n - 1) * 0.08;
const c = (b) => Math.max(1, Math.round(b * f));
let g;
switch ((n - 1) % 8) {
case 0: g = [{ k: 'ping', c: c(8), gap: 0.7 }]; break;
case 1: g = [{ k: 'worm', c: c(10), gap: 0.4 }]; break;
case 2: g = [{ k: 'ping', c: c(8), gap: 0.6 }, { k: 'trojan', c: c(1), gap: 1.4 }]; break;
case 3: g = [{ k: 'spam', c: c(24), gap: 0.18 }]; break;
case 4: g = [{ k: 'ghost', c: c(5), gap: 0.9 }, { k: 'ping', c: c(6), gap: 0.5 }]; break;
case 5: g = [{ k: 'trojan', c: c(3), gap: 1.2 }, { k: 'worm', c: c(8), gap: 0.35 }]; break;
case 6: g = [{ k: 'ghost', c: c(8), gap: 0.6 }, { k: 'spam', c: c(16), gap: 0.2 }]; break;
default: g = [{ k: 'ping', c: c(10), gap: 0.4 }, { k: 'trojan', c: c(3), gap: 1.0 }, { k: 'ghost', c: c(4), gap: 0.8 }];
}
if (n > 8) weave(g, n, c, (n - 1) % 8);
if (n % 10 === 0) g.push({ k: 'rootkit', c: n / 10, gap: 3 });
return g;
}
// From wave 9 the eight-wave cycle gets the newer kinds woven in (groups spawn one after the other, so a group
// appended behind another trails it):
// daemon the first healer rides with the pings of wave 9; from then on every trojan group has an escort that
// spawns behind it and (it is faster) catches up and heals while passing through
// proxy from wave 12 in the spam / mixed-flyer-and-trojan slots, more slots later
// botnet swarms from wave 14, more slots (and bigger) later
function weave(g, n, c, p) {
const trojans = g.find((e) => e.k === 'trojan');
if (trojans) g.push({ k: 'daemon', c: Math.max(1, Math.round(trojans.c / 2)), gap: 1.2 });
else if (n === 9) g.push({ k: 'daemon', c: 2, gap: 1.2 });
if (n >= 12) {
if (p === 3) g.push({ k: 'proxy', c: c(2), gap: 1.6 });
else if (p === 7) g.push({ k: 'proxy', c: c(2), gap: 1.4 });
else if (p === 5 && n >= 22) g.push({ k: 'proxy', c: c(2), gap: 1.4 });
else if (p === 2 && n >= 19) g.push({ k: 'proxy', c: c(1), gap: 1.6 });
else if (p === 0 && n >= 25) g.push({ k: 'proxy', c: c(1), gap: 1.6 });
}
if (n >= 14) {
if (p === 5) g.push({ k: 'botnet', c: c(8), gap: 0.12 });
else if (p === 6) g.push({ k: 'botnet', c: c(8), gap: 0.1 });
else if (p === 1 && n >= 18) g.push({ k: 'botnet', c: c(6), gap: 0.1 });
else if (p === 4 && n >= 21) g.push({ k: 'botnet', c: c(8), gap: 0.1 });
else if (p === 7 && n >= 24) g.push({ k: 'botnet', c: c(6), gap: 0.12 });
}
}
// What the wave list in the UI shows: one entry per kind (counts summed), in order of appearance, flyers flagged.
function waveSummary(n) {
const out = [], at = {};
for (const g of waveGroups(n)) {
if (at[g.k] === undefined) { at[g.k] = out.length; out.push({ k: g.k, c: 0, air: !!ENEMIES[g.k].air }); }
out[at[g.k]].c += g.c;
}
return out;
}
// Tuned numbers (docs/BALANCE.md): enemy hit points per wave and what a kill pays. Kill credits grow slower than the packets' hit points,
// so credits stay a constraint all game; bosses pay little per hit point (a rootkit is a danger, not a payday).
function hpScale(n) { return 1 + 0.145 * (n - 1) + 0.0165 * (n - 1) * (n - 1); }
function rewardScale(n) { return 1 + 0.02 * (n - 1); }
// ---------------------------------------------------------------- path finding
class MinHeap {
constructor() { this.k = []; this.v = []; }
get size() { return this.k.length; }
peekKey() { return this.k[0]; }
push(key, val) {
let i = this.k.length;
this.k.push(key); this.v.push(val);
while (i > 0) {
const p = (i - 1) >> 1;
if (this.k[p] <= key) break;
this.k[i] = this.k[p]; this.v[i] = this.v[p]; i = p;
}
this.k[i] = key; this.v[i] = val;
}
pop() {
const top = this.v[0];
const lk = this.k.pop(), lv = this.v.pop();
const n = this.k.length;
if (n > 0) {
let i = 0;
for (;;) {
let l = 2 * i + 1;
if (l >= n) break;
const r = l + 1;
if (r < n && this.k[r] < this.k[l]) l = r;
if (this.k[l] >= lk) break;
this.k[i] = this.k[l]; this.v[i] = this.v[l]; i = l;
}
this.k[i] = lk; this.v[i] = lv;
}
return top;
}
}
// Distance-to-core field. 8-way movement; diagonal steps may not cut a corner (both orthogonal
// neighbours must be free), so two walls touching diagonally still form a seal.
function buildField(cols, rows, solid, coreIdx) {
const dist = new Float64Array(cols * rows).fill(Infinity);
const heap = new MinHeap();
dist[coreIdx] = 0;
heap.push(0, coreIdx);
while (heap.size) {
const d = heap.peekKey();
const i = heap.pop();
if (d > dist[i]) continue;
const x = i % cols, y = (i / cols) | 0;
for (let k = 0; k < 8; k++) {
const nx = x + DX[k], ny = y + DY[k];
if (nx < 0 || ny < 0 || nx >= cols || ny >= rows) continue;
const ni = ny * cols + nx;
if (solid[ni]) continue;
const diag = DX[k] !== 0 && DY[k] !== 0;
if (diag && (solid[y * cols + nx] || solid[ny * cols + x])) continue;
const nd = d + (diag ? SQRT2 : 1);
if (nd < dist[ni] - 1e-6) { dist[ni] = nd; heap.push(nd, ni); }
}
}
return dist;
}
// Best neighbour of cell (x,y) towards the core, or -1 when there is none.
function nextCell(cols, rows, solid, dist, x, y) {
const here = dist[y * cols + x];
if (!isFinite(here)) return -1;
let best = -1, bv = Infinity;
for (let k = 0; k < 8; k++) {
const nx = x + DX[k], ny = y + DY[k];
if (nx < 0 || ny < 0 || nx >= cols || ny >= rows) continue;
const ni = ny * cols + nx;
if (solid[ni]) continue;
const diag = DX[k] !== 0 && DY[k] !== 0;
if (diag && (solid[y * cols + nx] || solid[ny * cols + x])) continue;
const v = dist[ni] + (diag ? SQRT2 : 1);
if (dist[ni] < here && v < bv - 1e-6) { bv = v; best = ni; }
}
return best;
}
function traceRoute(cols, rows, solid, dist, sx, sy) {
const out = [[sx, sy]];
let x = sx, y = sy;
for (let guard = cols * rows; guard > 0; guard--) {
const n = nextCell(cols, rows, solid, dist, x, y);
if (n < 0) break;
x = n % cols; y = (n / cols) | 0;
out.push([x, y]);
if (dist[n] === 0) break;
}
return out;
}
// ---------------------------------------------------------------- board (grid + pathing)
// The part of the game that is purely about the maze. The server's Sim owns one; browser clients
// keep a mirror of it so they can preview a placement (and the new route) without a round trip.
class Board {
constructor(mapId) {
const def = typeof mapId === 'object' ? mapId : MAPS[mapId || 'open'];
if (!def) throw new Error('unknown map: ' + mapId);
this.mapId = def.id;
this.def = def;
const p = parseMap(def);
this.cols = p.cols; this.rows = p.rows;
this.obst = p.obst;
this.spawns = p.spawns;
this.core = p.core;
this.coreIdx = p.core.y * p.cols + p.core.x;
this.solid = Uint8Array.from(p.obst);
this.field = null;
this.routes = [];
this.routeLen = 0;
this.recompute();
}
idx(x, y) { return y * this.cols + x; }
inBounds(x, y) { return Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0 && x < this.cols && y < this.rows; }
isSpecial(x, y) {
if (x === this.core.x && y === this.core.y) return 'core';
for (const s of this.spawns) if (s.x === x && s.y === y) return 'spawn';
return null;
}
recompute() {
this.field = buildField(this.cols, this.rows, this.solid, this.coreIdx);
this.routes = this.spawns.map((s) => traceRoute(this.cols, this.rows, this.solid, this.field, s.x, s.y));
this.routeLen = this.lengthOf(this.field);
}
lengthOf(field) {
let sum = 0;
for (const s of this.spawns) sum += field[s.y * this.cols + s.x];
return sum;
}
// Would a block at (x,y) be legal, and what would it do to the route?
// reserved: Set of cell indexes monsters are in/entering (cannot build there)
// must: cell indexes that must stay connected to the core (monster cells)
// Returns {ok, reason, before, after, routes}
trial(x, y, reserved, must, wantRoutes) {
const r = { ok: false, reason: '', before: this.routeLen, after: this.routeLen, routes: null };
if (!this.inBounds(x, y)) { r.reason = 'bounds'; return r; }
const i = this.idx(x, y);
if (this.obst[i]) { r.reason = 'obstacle'; return r; }
if (this.solid[i]) { r.reason = 'occupied'; return r; }
const sp = this.isSpecial(x, y);
if (sp) { r.reason = sp; return r; }
if (reserved && reserved.has(i)) { r.reason = 'monster'; return r; }
this.solid[i] = 1;
const f = buildField(this.cols, this.rows, this.solid, this.coreIdx);
let blocked = false;
for (const s of this.spawns) if (!isFinite(f[s.y * this.cols + s.x])) { blocked = true; break; }
if (!blocked && must) for (const c of must) if (!isFinite(f[c])) { blocked = true; break; }
if (!blocked && wantRoutes) {
r.routes = this.spawns.map((s) => traceRoute(this.cols, this.rows, this.solid, f, s.x, s.y));
}
this.solid[i] = 0;
if (blocked) { r.reason = 'blocks'; return r; }
r.ok = true;
r.after = this.lengthOf(f);
return r;
}
setSolid(x, y, v) { this.solid[y * this.cols + x] = v ? 1 : 0; }
}
// ---------------------------------------------------------------- simulation
class Sim {
constructor(opts) {
opts = opts || {};
this.board = new Board(opts.map || 'open');
this.mapId = this.board.mapId;
this.winWave = opts.winWave === undefined ? WIN_WAVE : opts.winWave;
// An explicit `gold` / `lives` (tests, the bot) is used exactly as given; the difficulty scales only the defaults.
this.difficulty = difficultyId(opts.difficulty);
this.diff = DIFFICULTIES[this.difficulty];
this.gold = opts.gold === undefined ? Math.round(START_GOLD * this.diff.gold) : opts.gold;
this.lives = opts.lives === undefined ? Math.max(1, Math.round(START_LIVES * this.diff.lives)) : opts.lives;
this.maxLives = this.lives;
this.collectEvents = opts.events !== false;
this.time = 0;
this.nid = 1;
this.rev = 0; // bumped whenever towers are added/removed/upgraded/retargeted
this.state = 'playing'; // playing | won | lost
this.wave = 0; // waves started so far
this.bonusWave = 0; // last wave that paid its clear bonus
this.kills = 0;
this.leaks = 0;
this.autoWaves = false;
this.nextWaveIn = -1;
this.spawnRR = 0;
this.healT = 0; // seconds since the last daemon pulse (one clock for all daemons)
this.towers = [];
this.towerAt = new Array(this.board.cols * this.board.rows).fill(null);
this.monsters = [];
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) {
if (!this.collectEvents) return;
this.events.push(e);
if (this.events.length > 800) this.events.splice(0, 300);
}
drainEvents() { const e = this.events; this.events = []; return e; }
// ---- 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);
case 'upgrade': return this.upgrade(c.id, c.lv);
case 'target': return this.setTargetMode(c.id, c.mode);
case 'wave': return this.startWave(c.n);
case 'auto': return this.setAuto(!!c.v);
case 'continue': return this.continueEndless();
default: return { ok: false, reason: 'bad_cmd' };
}
}
// ---- 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;
const reserved = new Set(), must = [];
for (const m of this.monsters) {
if (m.dead || m.air) continue;
const ci = m.cy * cols + m.cx;
reserved.add(ci); must.push(ci);
reserved.add(Math.floor(m.y) * cols + Math.floor(m.x));
if (m.tx >= 0) {
const ti = m.ty * cols + m.tx;
reserved.add(ti); must.push(ti);
if (m.cx !== m.tx && m.cy !== m.ty) { // diagonal step: keep both corners clear
reserved.add(m.cy * cols + m.tx);
reserved.add(m.ty * cols + m.cx);
}
}
}
return { reserved, must };
}
preview(x, y, wantRoutes) {
const mc = this.monsterCells();
return this.board.trial(x, y, mc.reserved, mc.must, wantRoutes);
}
place(type, x, y, by) {
if (this.state !== 'playing') return { ok: false, reason: 'over' };
if (typeof type !== 'string' || !Object.prototype.hasOwnProperty.call(TOWERS, type)) return { ok: false, reason: 'bad_type' };
const def = TOWERS[type];
const cost = priceFor(type, this.towers), pm = priceMult(type, this.towers);
if (this.gold < cost) return { ok: false, reason: 'gold' };
const t = this.preview(x, y, false);
if (!t.ok) return { ok: false, reason: t.reason };
const tower = {
id: this.nid++, type, x, y, level: 1, mode: 'first', spent: cost, owner: by | 0, pm,
cd: 0, tgt: 0, kills: 0, dealt: 0, buff: 0,
};
this.gold -= cost;
this.towers.push(tower);
this.towerAt[y * this.board.cols + x] = tower;
this.board.setSolid(x, y, 1);
this.board.recompute();
this.rev++;
this.emit({ e: 'place', id: tower.id, type, x, y, by: tower.owner });
return { ok: true, id: tower.id, before: t.before, after: t.after };
}
towerById(id) {
for (const t of this.towers) if (t.id === id) return t;
return null;
}
sell(id) {
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];
const refund = def.refund ? t.spent : Math.floor(t.spent * SELL_RATIO);
this.gold += refund;
this.towers.splice(this.towers.indexOf(t), 1);
this.towerAt[t.y * this.board.cols + t.x] = null;
this.board.setSolid(t.x, t.y, 0);
this.board.recompute();
this.rev++;
this.emit({ e: 'sell', id: t.id, x: t.x, y: t.y, refund });
return { ok: true, refund };
}
upgradeCost(t) { return upgradePrice(t.type, t.level, t.pm); }
// `lv` is the level the sender SAW when it pressed Upgrade (absent: no check). Two players pressing it at the same moment send the
// same command twice; the second one finds the tower already a level higher and is refused as 'stale' instead of being charged again.
upgrade(id, lv) {
if (this.state !== 'playing') return { ok: false, reason: 'over' };
const t = this.towerById(id);
if (!t) return { ok: false, reason: 'no_tower' };
if (lv !== undefined && lv !== null && lv !== t.level) return { ok: false, reason: 'stale' };
const cost = this.upgradeCost(t);
if (cost === null) return { ok: false, reason: 'max' };
if (this.gold < cost) return { ok: false, reason: 'gold' };
this.gold -= cost;
t.spent += cost;
t.level++;
this.rev++;
this.emit({ e: 'up', id: t.id, level: t.level, x: t.x, y: t.y });
return { ok: true, level: t.level };
}
setTargetMode(id, mode) {
const t = this.towerById(id);
if (!t) return { ok: false, reason: 'no_tower' };
if (TARGET_MODES.indexOf(mode) < 0) return { ok: false, reason: 'bad_mode' };
t.mode = mode;
this.rev++;
return { ok: true };
}
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;
return { ok: true };
}
// `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;
let t = this.time + 0.3;
for (const g of waveGroups(n)) {
for (let i = 0; i < g.c; i++) { this.spawnQ.push({ t, k: g.k, wave: n }); t += g.gap; }
t += 1.5;
}
this.spawnQ.sort((a, b) => a.t - b.t);
if (this.autoWaves) this.nextWaveIn = WAVE_INTERVAL;
this.emit({ e: 'wave', n, boss: n % 10 === 0 });
return { ok: true, wave: n };
}
spawnMonster(q) {
const def = ENEMIES[q.k];
const b = this.board;
const s = b.spawns[this.spawnRR++ % b.spawns.length];
const dm = this.diff; // the difficulty scales hit points and shield alike (the wire derives the shield bar from their ratio)
const hp = Math.max(1, Math.round(def.hp * hpScale(q.wave) * dm.hp));
const shield = def.shield ? Math.max(1, Math.round(def.shield * hpScale(q.wave) * dm.hp)) : 0;
const m = {
id: this.nid++, kind: q.k, 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, speed: def.speed,
reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave) * dm.reward)),
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
shield, maxShield: shield, shieldT: 0,
rem: 0, dead: false, wave: q.wave,
};
m.rem = m.air
? Math.hypot(b.core.x - s.x, b.core.y - s.y)
: b.field[s.y * b.cols + s.x];
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();
}
while (this.spawnQ.length && this.spawnQ[0].t <= this.time) this.spawnMonster(this.spawnQ.shift());
for (const m of this.monsters) { // slow = lingering slow (Orbital Uplink) unless a Rate Limiter says more
if (m.slowT > 0) { m.slow = m.slowAmt; m.slowT -= dt; } else m.slow = 0;
if (m.stunT > 0) m.stunT -= dt;
if (m.maxShield > 0) this.regenShield(m, dt);
}
this.healT += dt;
if (this.healT >= HEAL_EVERY) { this.healT -= HEAL_EVERY; this.healPulse(); }
this.updateAuras();
for (const t of this.towers) this.updateTower(t, dt);
this.updateBullets(dt);
for (const m of this.monsters) if (!m.dead) this.moveMonster(m, dt);
let w = 0;
for (let i = 0; i < this.monsters.length; i++) {
const m = this.monsters[i];
if (!m.dead) this.monsters[w++] = m;
}
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';
this.emit({ e: 'lose', wave: this.wave });
return;
}
if (this.wave > this.bonusWave && !this.monsters.length && !this.spawnQ.length) {
const bonus = clearBonus(this.wave);
this.gold += bonus;
this.bonusWave = this.wave;
this.emit({ e: 'clear', n: this.wave, bonus });
if (this.wave >= this.winWave) {
this.state = 'won';
this.emit({ e: 'win', wave: this.wave });
}
}
}
// ---- 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);
if (d <= remaining + 0.05) { this.leak(m); return; }
m.x += (dx / d) * remaining; m.y += (dy / d) * remaining;
m.rem = d - remaining;
return;
}
for (let guard = 4; remaining > 1e-6 && guard > 0; guard--) {
if (m.tx < 0) {
if (m.cx === b.core.x && m.cy === b.core.y) { this.leak(m); return; }
const n = nextCell(b.cols, b.rows, b.solid, b.field, m.cx, m.cy);
if (n < 0) break;
m.tx = n % b.cols; m.ty = (n / b.cols) | 0;
}
const gx = m.tx + 0.5, gy = m.ty + 0.5;
const dx = gx - m.x, dy = gy - m.y, d = Math.hypot(dx, dy);
if (d <= remaining) {
m.x = gx; m.y = gy; remaining -= d;
m.cx = m.tx; m.cy = m.ty; m.tx = -1; m.ty = -1;
if (m.cx === b.core.x && m.cy === b.core.y) { this.leak(m); return; }
} else {
m.x += (dx / d) * remaining; m.y += (dy / d) * remaining; remaining = 0;
}
}
const f = b.field;
m.rem = m.tx >= 0
? f[m.ty * b.cols + m.tx] + Math.hypot(m.x - (m.tx + 0.5), m.y - (m.ty + 0.5))
: f[m.cy * b.cols + m.cx];
}
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 || 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
const soak = Math.min(m.shield, d);
m.shield -= soak; hit = d - soak; m.shieldT = 0;
}
m.hp -= hit;
if (src) src.dealt += d;
if (m.hp <= 0) {
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 });
}
}
// 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);
}
// Daemon pulse, once a second on the sim's own clock: every enemy gets healed by the daemons around it (never by itself),
// together at most HEAL_CAP of its max hp, never above max. Shields are not healed.
healPulse() {
let ds = null;
for (const m of this.monsters) if (!m.dead && ENEMIES[m.kind].heal) (ds || (ds = [])).push(m);
if (!ds) return;
const did = new Set();
for (const m of this.monsters) {
if (m.dead || m.hp >= m.maxhp) continue;
let f = 0;
for (const d of ds) {
if (d === m) continue;
const def = ENEMIES[d.kind], dx = m.x - d.x, dy = m.y - d.y;
if (dx * dx + dy * dy > def.healRange * def.healRange) continue;
f += def.heal; did.add(d);
}
if (f > 0) m.hp = Math.min(m.maxhp, m.hp + Math.min(f, HEAL_CAP) * m.maxhp);
}
for (const d of did) this.emit({ e: 'heal', x: round2(d.x), y: round2(d.y), r: ENEMIES[d.kind].healRange });
}
// Load Balancer: each attack tower gets the best boost of the support towers in range (no stacking).
updateAuras() {
const ts = this.towers;
let sup = null;
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;
for (const t of ts) {
if (t.buff >= st.boost || TOWERS[t.type].role !== 'attack') continue;
const dx = t.x - s.x, dy = t.y - s.y;
if (dx * dx + dy * dy <= r2) t.buff = st.boost;
}
}
}
// ---- towers ---------------------------------------------------------------------------
findTarget(t, range, def) {
const tx = t.x + 0.5, ty = t.y + 0.5, r2 = range * range;
let best = null, bv = 0;
for (const m of this.monsters) {
if (m.dead) continue;
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;
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;
default: v = -m.rem; // 'first': smallest remaining distance wins
}
if (best === null || v > bv) { best = m; bv = v; }
}
return best;
}
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;
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)) * (1 - (m.crypt || 0));
if (eff > m.slow) m.slow = eff;
}
return;
}
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; }
if (t.cd > 0) return;
t.cd += 1 / st.rate;
this.fire(t, st, def, m, cx, cy);
}
// Sandbox: when anything is in range it stuns everything in range (ground and air) for st.stun s, then recharges st.pulse s.
// Enemies with slowRes (bosses) are stunned for (1 - slowRes) of that. Stunned enemies do not move.
pulseStun(t, st, def, cx, cy, dt) {
t.cd -= dt;
t.tgt = 0;
const r2 = st.range * st.range, hit = [];
for (const m of this.monsters) {
if (m.dead || (m.air ? !def.air : !def.ground)) continue;
const dx = m.x - cx, dy = m.y - cy;
if (dx * dx + dy * dy <= r2) hit.push(m);
}
if (!hit.length) { if (t.cd < 0) t.cd = 0; return; }
if (t.cd > 0) return;
t.cd += st.pulse;
for (const m of hit) {
const dur = st.stun * (1 - (ENEMIES[m.kind].slowRes || 0));
if (dur > m.stunT) m.stunT = dur;
}
this.emit({ e: 'stun', x: round2(cx), y: round2(cy), r: st.range, n: hit.length });
}
fire(t, st, def, m, cx, cy) {
switch (t.type) {
case 'filter':
this.bullets.push({ id: this.nid++, k: 'filter', x: cx, y: cy, sp: def.bulletSpeed, tgt: m, gx: m.x, gy: m.y, dmg: st.dmg, src: t });
this.emit({ e: 'shot', k: 'filter', x: cx, y: cy, a: Math.atan2(m.y - cy, m.x - cx) });
break;
case 'ids':
this.damage(m, st.dmg, t);
this.emit({ e: 'shot', k: 'ids', x: cx, y: cy, tx: m.x, ty: m.y });
break;
case 'mortar': {
let gx = m.x, gy = m.y;
if (m.tx >= 0) { // lead the target along its current step
const ex = m.tx + 0.5 - m.x, ey = m.ty + 0.5 - m.y, el = Math.hypot(ex, ey) || 1;
const T = Math.max(0, Math.hypot(m.x - cx, m.y - cy) / def.shellSpeed - (m.stunT > 0 ? m.stunT : 0));
const lead = Math.min(el, m.speed * (1 - Math.min(0.6, m.slow)) * T);
gx += (ex / el) * lead; gy += (ey / el) * lead;
}
this.bullets.push({ id: this.nid++, k: 'mortar', x: cx, y: cy, sp: def.shellSpeed, tgt: null, gx, gy, dmg: st.dmg, splash: st.splash, src: t });
this.emit({ e: 'shot', k: 'mortar', x: cx, y: cy, a: Math.atan2(gy - cy, gx - cx) });
break;
}
case 'uplink': {
// A beam from the tower through the target out to full range: everything in the line takes full damage
// (armour ignored), then everything near the target is blasted for half and everything hit is slowed for a moment.
const ex = m.x - cx, ey = m.y - cy, el = Math.hypot(ex, ey) || 1, ux = ex / el, uy = ey / el;
const hit = new Set();
for (const o of this.monsters) {
if (o.dead || (o.air ? !def.air : !def.ground)) continue;
const ox = o.x - cx, oy = o.y - cy, along = ox * ux + oy * uy;
if (along < 0 || along > st.range) continue;
if (Math.abs(ox * uy - oy * ux) <= st.width) hit.add(o);
}
const r2 = st.splash * st.splash;
const blast = [];
for (const o of this.monsters) {
if (o.dead || hit.has(o) || (o.air ? !def.air : !def.ground)) continue;
const dx = o.x - m.x, dy = o.y - m.y;
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)) * (1 - (o.crypt || 0)));
if (eff >= o.slowAmt || o.slowT <= 0) o.slowAmt = eff;
o.slowT = Math.max(o.slowT, st.slowFor);
};
for (const o of hit) { this.damage(o, st.dmg, t, true); slowFor(o); }
for (const o of blast) { this.damage(o, st.dmg * 0.5, t, true); slowFor(o); }
this.emit({ e: 'shot', k: 'uplink', x: cx, y: cy, tx: round2(m.x), ty: round2(m.y) });
this.emit({ e: 'beam', x: round2(cx), y: round2(cy), tx: round2(cx + ux * st.range), ty: round2(cy + uy * st.range), w: st.width, bx: round2(m.x), by: round2(m.y), br: st.splash });
break;
}
case 'arc': {
const pts = [[cx, cy], [m.x, m.y]];
const hit = new Set([m]);
let dmg = st.dmg, cur = m;
this.damage(cur, dmg, t);
for (let c = 0; c < st.chains; c++) {
let nb = null, nd = st.chainRange * st.chainRange;
for (const o of this.monsters) {
if (o.dead || hit.has(o)) continue;
if (o.air ? !def.air : !def.ground) continue;
const dx = o.x - cur.x, dy = o.y - cur.y, d2 = dx * dx + dy * dy;
if (d2 <= nd) { nd = d2; nb = o; }
}
if (!nb) break;
hit.add(nb);
dmg *= st.falloff;
this.damage(nb, dmg, t);
pts.push([nb.x, nb.y]);
cur = nb;
}
this.emit({ e: 'arc', pts: pts.map((p) => [round2(p[0]), round2(p[1])]) });
break;
}
}
}
updateBullets(dt) {
let w = 0;
for (let i = 0; i < this.bullets.length; i++) {
const b = this.bullets[i];
if (b.tgt && !b.tgt.dead) { b.gx = b.tgt.x; b.gy = b.tgt.y; }
const dx = b.gx - b.x, dy = b.gy - b.y, d = Math.hypot(dx, dy), step = b.sp * dt;
if (d <= step || d < 0.05) {
if (b.k === 'mortar') {
const r2 = b.splash * b.splash;
for (const m of this.monsters) {
if (m.dead || m.air) continue;
const ex = m.x - b.gx, ey = m.y - b.gy;
if (ex * ex + ey * ey <= r2) this.damage(m, b.dmg, b.src);
}
this.emit({ e: 'boom', x: b.gx, y: b.gy, r: b.splash });
} else if (b.tgt && !b.tgt.dead) {
this.damage(b.tgt, b.dmg, b.src);
}
continue; // bullet consumed
}
b.x += (dx / d) * step; b.y += (dy / d) * step;
this.bullets[w++] = b;
}
this.bullets.length = w;
}
// ---- views of the state ---------------------------------------------------------------
towerList() {
return this.towers.map((t) => [t.id, t.type, t.x, t.y, t.level, t.mode, t.spent, t.owner, t.pm === 1 ? 1 : round2(t.pm * 1000) / 1000]);
}
// Everything a client needs to (re)build the board from scratch.
fullState() {
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.
snapshot() {
// a shield is sent as extra hp: hp + shield out of maxhp + maxShield (the client derives the shield part from the kind's table)
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 = [];
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, 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,
buildField, nextCell, traceRoute, parseMap, Board, Sim, round2,
};
});