Phone panels (reviewed + QA'd, matrix of 22 layouts with real taps/bounding boxes): - selected-tower action bar over the board (Upgrade/Sell/Target/close), info panel updated in place so taps are never lost, scrollable palette for 7+ towers, overlays with pinned footers (Help "Got it", Play solo, Join always visible), tappable room chip to invite, reduced-motion/contrast/forced-colors fixes, paused state, partner cursor labels, bigger level pips and owner flags - touch input rewritten around "pointerdown commits nothing": pinch never builds, 10px tap slop, palm-proof pinch, long-press pings with any tool armed, nudge arrows for precise placement, hotkey repeat guard, proportional wheel zoom - new e2e: select/sell, info-panel stability, UI states, touch precision; camera unit tests Proxy/server (reproduced against real nginx 1.26 with NPM v2.16 config): - Origin check works when the proxy drops a non-default port, TRUSTED_PROXIES for proxies on global IPv6/CGNAT addresses, service worker no longer serves nginx's 502 page, DEPLOY.md corrected (NPM default read timeout is 90 s, Advanced-tab limits, path-prefix, cookie size, per-IP cap behaviour) Content: - Orbital Uplink: 4-level endgame tower (450 + 500/800/1200 credits): piercing armour-ignoring beam, blast and lingering slow, ground+air, range 11-14; glyph, beam effect, sound, help text, unit tests - Maps: The Canyon, Archipelago, Fortress, Pinwheel (7 maps total) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
948 lines
37 KiB
JavaScript
948 lines
37 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;
|
|
|
|
// ---------------------------------------------------------------- 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
|
|
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'uplink'];
|
|
const TARGET_MODES = ['first', 'last', 'strong', 'close'];
|
|
const TOWERS = {
|
|
wall: {
|
|
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1,
|
|
desc: 'Blocks the route. Cheap: use it to build a long maze.',
|
|
levels: [{ cost: 5 }],
|
|
},
|
|
filter: {
|
|
name: 'Packet Filter', key: '2', color: '#35e0a1', air: true, ground: true,
|
|
desc: 'Fast, cheap rapid fire. Weak against armour.',
|
|
levels: [
|
|
{ cost: 25, dmg: 6, range: 3.2, rate: 3.0 },
|
|
{ cost: 30, dmg: 9, range: 3.5, rate: 3.4 },
|
|
{ cost: 55, dmg: 13, range: 3.9, rate: 4.0 },
|
|
],
|
|
bulletSpeed: 14,
|
|
},
|
|
ids: {
|
|
name: 'IDS Sniper', key: '3', color: '#b78cff', air: true, ground: true,
|
|
desc: 'Long range, hard hitting, slow. Great against armour and bosses.',
|
|
levels: [
|
|
{ cost: 60, dmg: 50, range: 6.5, rate: 0.7 },
|
|
{ cost: 70, dmg: 85, range: 7.2, rate: 0.75 },
|
|
{ cost: 110, dmg: 150, range: 8.0, rate: 0.8 },
|
|
],
|
|
},
|
|
mortar: {
|
|
name: 'Flood Mortar', key: '4', color: '#d4f04a', air: false, ground: true,
|
|
desc: 'Splash damage against ground swarms. Cannot hit flyers.',
|
|
levels: [
|
|
{ cost: 55, dmg: 28, range: 4.8, rate: 0.8, splash: 1.3 },
|
|
{ cost: 60, dmg: 45, range: 5.2, rate: 0.85, splash: 1.5 },
|
|
{ cost: 100, dmg: 75, range: 5.6, rate: 0.9, splash: 1.7 },
|
|
],
|
|
shellSpeed: 5.5,
|
|
},
|
|
throttle: {
|
|
name: 'Rate Limiter', key: '5', color: '#4de3ff', 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', air: true, ground: true,
|
|
desc: 'Chain lightning that jumps between nearby packets.',
|
|
levels: [
|
|
{ cost: 75, dmg: 16, range: 3.6, rate: 1.2, chains: 2, chainRange: 1.9, falloff: 0.7 },
|
|
{ cost: 70, dmg: 24, range: 3.8, rate: 1.25, chains: 3, chainRange: 2.0, falloff: 0.72 },
|
|
{ cost: 120, dmg: 36, range: 4.2, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
|
|
],
|
|
},
|
|
uplink: {
|
|
name: 'Orbital Uplink', key: '7', color: '#ffe27a', 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. Very expensive to build and to upgrade.',
|
|
levels: [
|
|
{ cost: 450, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
|
|
{ cost: 500, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
|
|
{ cost: 800, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
|
|
{ cost: 1200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
|
|
],
|
|
},
|
|
};
|
|
|
|
const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit'];
|
|
const ENEMIES = {
|
|
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a' },
|
|
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43' },
|
|
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b' },
|
|
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166' },
|
|
ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff' },
|
|
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', slowRes: 0.5 },
|
|
};
|
|
|
|
// 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 % 10 === 0) g.push({ k: 'rootkit', c: n / 10, gap: 3 });
|
|
return g;
|
|
}
|
|
function waveSummary(n) {
|
|
const out = [];
|
|
for (const g of waveGroups(n)) out.push({ k: g.k, c: g.c });
|
|
return out;
|
|
}
|
|
function hpScale(n) { return 1 + 0.16 * (n - 1) + 0.022 * (n - 1) * (n - 1); }
|
|
function rewardScale(n) { return 1 + 0.03 * (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;
|
|
this.gold = opts.gold === undefined ? START_GOLD : opts.gold;
|
|
this.lives = opts.lives === undefined ? START_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.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);
|
|
case 'target': return this.setTargetMode(c.id, c.mode);
|
|
case 'wave': return this.startWave();
|
|
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 = def.levels[0].cost;
|
|
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,
|
|
cd: 0, tgt: 0, kills: 0, dealt: 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) {
|
|
const lv = TOWERS[t.type].levels[t.level];
|
|
return lv ? lv.cost : null;
|
|
}
|
|
upgrade(id) {
|
|
if (this.state !== 'playing') return { ok: false, reason: 'over' };
|
|
const t = this.towerById(id);
|
|
if (!t) return { ok: false, reason: 'no_tower' };
|
|
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 };
|
|
}
|
|
|
|
startWave() {
|
|
if (this.state !== 'playing') return { ok: false, reason: 'over' };
|
|
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 hp = Math.round(def.hp * hpScale(q.wave));
|
|
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))),
|
|
leak: def.leak, slow: 0, slowT: 0, slowAmt: 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;
|
|
}
|
|
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 = 10 + 2 * 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) {
|
|
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);
|
|
m.hp -= d;
|
|
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 });
|
|
}
|
|
}
|
|
|
|
// ---- 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; 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.type === 'wall') return;
|
|
const def = TOWERS[t.type];
|
|
const st = def.levels[t.level - 1];
|
|
const cx = t.x + 0.5, cy = t.y + 0.5;
|
|
if (t.type === 'throttle') {
|
|
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;
|
|
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);
|
|
}
|
|
|
|
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.hypot(m.x - cx, m.y - cy) / def.shellSpeed;
|
|
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]);
|
|
}
|
|
|
|
// 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,
|
|
};
|
|
}
|
|
|
|
// Compact per-tick state for the wire. Arrays, not objects, to keep it small.
|
|
snapshot() {
|
|
const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp), m.maxhp, m.slow > 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,
|
|
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
|
|
waveGroups, waveSummary, hpScale, rewardScale,
|
|
buildField, nextCell, traceRoute, parseMap, Board, Sim, round2,
|
|
};
|
|
});
|