Difficulty: - TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated create-room / newgame option, state carries it; solo menu picker and co-op lobby picker (44px segmented control, reachable on every layout), HUD/room/end-screen labels, best-wave record per map AND difficulty (Normal keeps the legacy key), Play again keeps the running game's difficulty for host and guest Balance (12 bot runs, deterministic, 48/48 games replay identically in QA): - Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open - credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at wave 30: 1309 -> 335 - IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only dies by wave 7); Mortar, Arc and Filter buffed - Orbital Uplink price step per owned unit 30% (buy and upgrade) - remaining imbalances documented in docs/BALANCE.md Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix reachability of the picker. 156 unit tests, 17 e2e scenarios. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
1156 lines
52 KiB
JavaScript
1156 lines
52 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; }
|
|
|
|
// ---------------------------------------------------------------- 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 = [];
|
|
}
|
|
|
|
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' };
|
|
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' };
|
|
}
|
|
}
|
|
|
|
// 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') 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) {
|
|
this.autoWaves = v;
|
|
if (v && this.nextWaveIn < 0) this.nextWaveIn = WAVE_INTERVAL;
|
|
return { ok: true };
|
|
}
|
|
|
|
continueEndless() {
|
|
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.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);
|
|
}
|
|
|
|
// ---- main step ------------------------------------------------------------------------
|
|
tick(dt) {
|
|
if (this.state !== 'playing') return;
|
|
this.time += 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.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 b = this.board;
|
|
const slowMul = 1 - Math.min(0.6, m.slow);
|
|
let remaining = m.speed * slowMul * dt;
|
|
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;
|
|
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;
|
|
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 (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];
|
|
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') (sup || (sup = [])).push(t); }
|
|
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;
|
|
let v;
|
|
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) {
|
|
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; }
|
|
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));
|
|
if (eff > m.slow) m.slow = eff;
|
|
}
|
|
return;
|
|
}
|
|
t.cd -= dt * (1 + (t.buff || 0)); // 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)));
|
|
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() {
|
|
return {
|
|
map: this.mapId, rev: this.rev, towers: this.towerList(),
|
|
winWave: this.winWave === Infinity ? 0 : this.winWave,
|
|
maxLives: this.maxLives,
|
|
difficulty: this.difficulty,
|
|
};
|
|
}
|
|
|
|
// 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 = [];
|
|
for (const t of this.towers) if (t.type !== 'wall') tt.push([t.id, t.tgt, t.kills]);
|
|
return {
|
|
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,
|
|
};
|
|
}
|
|
}
|
|
|
|
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,
|
|
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,
|
|
};
|
|
});
|