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
520 lines
30 KiB
JavaScript
520 lines
30 KiB
JavaScript
/*
|
|
* NETWALL versus bots: a computer opponent for either side (docs/VERSUS.md).
|
|
*
|
|
* const bot = NWBot.create(sim, 'defender' | 'attacker', { seed, skill, by });
|
|
* bot.think(dt); // call it with the sim seconds that passed (every tick is fine); it decides about once per sim second
|
|
*
|
|
* Loaded as a classic <script> in the browser (window.NWBot, needs window.TD from sim.js first) and with require() in Node (the server and
|
|
* tools/versus.js). It drives the game ONLY the way a human does: sim.cmd({ role, by, ... }) for every action, sim.preview / the public
|
|
* board and tower list to look, and sim.privateState(its own role) for what only its own side may see. The defender never looks at the
|
|
* attacker's convoy, tech or credits; the attacker never looks at the defender's cooldowns. All randomness is a seeded PRNG (no
|
|
* Math.random: the same seed plays the same game). `skill` 0..1 (default 1) slows its decisions, adds noise and drops the clever parts
|
|
* (maze, tools, tech, abilities) for the weakest settings. Every command is checked against affordability and cooldowns first, so a bot
|
|
* never sends a command the sim would refuse for a reason a human's UI would have prevented (it can still meet 'monster' / 'blocks' /
|
|
* 'occupied' when the board changes under a wall or turret placement, exactly like a human).
|
|
*/
|
|
(function (root, factory) {
|
|
if (typeof module === 'object' && module.exports) module.exports = factory(require('./sim.js'));
|
|
else root.NWBot = factory(root.TD);
|
|
})(typeof self !== 'undefined' ? self : this, function (TD) {
|
|
'use strict';
|
|
|
|
const { VS, TOWERS, ENEMIES, ENEMY_ORDER } = TD;
|
|
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
|
const perHit = (d, armor) => Math.max(d - armor, d * 0.25);
|
|
|
|
function prng(seed) { // mulberry32
|
|
let a = seed >>> 0;
|
|
return function () {
|
|
a = (a + 0x6D2B79F5) >>> 0;
|
|
let t = a;
|
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
};
|
|
}
|
|
|
|
class Base {
|
|
constructor(sim, role, o) {
|
|
o = o || {};
|
|
this.sim = sim; this.role = role;
|
|
this.by = o.by | 0;
|
|
this.skill = clamp(o.skill === undefined || o.skill === null ? 1 : +o.skill, 0, 1);
|
|
this.rng = prng((o.seed === undefined ? 1 : o.seed) * 7919 + (role === 'defender' ? 13 : 29));
|
|
this.interval = 1 + (1 - this.skill) * 3; // sim seconds between decisions
|
|
this.clock = this.rng() * this.interval; // two bots do not wake on the same tick
|
|
this.refused = []; // the last few refusals (for the tools that watch the bots)
|
|
}
|
|
// the one door to the sim: carries the role and the seat
|
|
cmd(c) {
|
|
const r = this.sim.cmd(Object.assign({ role: this.role, by: this.by }, c));
|
|
if (!r.ok && this.refused.length < 20) this.refused.push({ c: c.c, id: c.id || c.type || c.kind, reason: r.reason });
|
|
return r;
|
|
}
|
|
think(dt) {
|
|
if (this.sim.state !== 'playing') return;
|
|
this.clock += dt;
|
|
if (this.clock < this.interval) return;
|
|
this.clock = 0;
|
|
this.act();
|
|
}
|
|
}
|
|
|
|
// ====================================================================================================================
|
|
// The defender: turrets where the route is, a maze of wall lines, upgrades, and the counter-tools.
|
|
// ====================================================================================================================
|
|
const TURRETS = TD.TOWER_ORDER.filter((t) => TOWERS[t].role !== 'wall'); // whatever the table holds (a new tower type is simply another candidate)
|
|
const DIRS = [[1, 0], [-1, 0], [0, 1], [0, -1]];
|
|
|
|
// Until it has a few turrets the defender does not know what is coming; a crowd (ground or air) at the very start is what loses a round
|
|
// fastest, and cheap rapid fire stops that best per credit. After the opening the scores below follow what it has actually seen.
|
|
const OPENING = { filter: 3, arc: 1.2, throttle: 0.6, mortar: 0.5, ids: 0.4, sandbox: 0.3, balancer: 0.1, uplink: 0.1 };
|
|
|
|
class Defender extends Base {
|
|
constructor(sim, o) {
|
|
super(sim, 'defender', o);
|
|
const r = this.rng, s = this.skill;
|
|
this.share = (0.12 + 0.2 * r()) * (s < 0.3 ? 0 : s); // the share of all the credits it has seen that may go into walls
|
|
this.openN = 7 + Math.floor(r() * 4); // turrets that count as the opening (and come before the first wall)
|
|
this.jitter = 0.1 + (1 - s) * 0.5; // relative noise on every score
|
|
this.fav = {}; // every player has favourites
|
|
for (const t of TURRETS) this.fav[t] = 0.85 + 0.3 * r();
|
|
this.types = TURRETS.filter((t) => s > 0.5 || (TOWERS[t].role !== 'control' && TOWERS[t].role !== 'support')); // the fiddly ones are for the better players
|
|
this.plan = []; // wall cells still to place
|
|
this.spentWalls = 0; this.spentOther = 0;
|
|
this.nextSeg = 0; this.noSegRev = -1;
|
|
this.th = { air: 0.15, armor: 0.1, swarm: 0.5 }; // what it has been seeing (moving averages); the start is a guess: expect a crowd, mostly on the ground
|
|
this.clock = this.interval; // the defender builds at once: a round starts with the attacker's credits in hand
|
|
this.geo = null; this.tables = {};
|
|
this.badUntil = new Map(); // cells where a turret just failed to go up (a packet in the way): not again for a while
|
|
}
|
|
|
|
act() {
|
|
this.observe();
|
|
if (this.skill >= 0.3) this.tools();
|
|
for (let n = 0; n < 10; n++) if (!this.step()) break; // (the opening spends the whole start purse in one go)
|
|
}
|
|
|
|
// ---- what is coming: the share of flyers / armoured / tiny units among what is on the board (judged by kind and hit points, as the screen shows them)
|
|
observe() {
|
|
const ms = this.sim.monsters.filter((m) => !m.dead);
|
|
if (!ms.length) return;
|
|
let air = 0, armor = 0, small = 0;
|
|
for (const m of ms) {
|
|
const d = ENEMIES[m.kind];
|
|
if (d.air) air++;
|
|
if (d.armor >= 3 || d.shield || m.maxhp >= 300) armor++;
|
|
if (m.maxhp <= 20) small++;
|
|
}
|
|
const a = 0.25, n = ms.length;
|
|
this.th.air += a * (air / n - this.th.air);
|
|
this.th.armor += a * (armor / n - this.th.armor);
|
|
this.th.swarm += a * (Math.min(1, (small + Math.max(0, n - 12)) / n) - this.th.swarm);
|
|
}
|
|
|
|
// ---- counter-tools: patch / scan EMPed towers, scan stealth, repair, quarantine
|
|
tools() {
|
|
const sim = this.sim, T = VS.TOOLS, cd = sim.privateState('defender').cd, rng = this.rng;
|
|
const can = (id) => cd[id] <= 0 && sim.gold >= T[id].cost;
|
|
const awake = rng() < 0.45 + 0.55 * this.skill; // a slower player reacts a decision later
|
|
const emped = sim.towers.filter((t) => t.empT > 0);
|
|
if (emped.length && awake) {
|
|
const r2 = T.scan.radius * T.scan.radius, near = (a, b) => (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) <= r2 * 0.5;
|
|
const group = emped.filter((t) => near(t, emped[0]));
|
|
if (group.length >= 2 && can('scan')) {
|
|
const cx = group.reduce((s, t) => s + t.x + 0.5, 0) / group.length, cy = group.reduce((s, t) => s + t.y + 0.5, 0) / group.length;
|
|
this.cmd({ c: 'tool', id: 'scan', x: cx, y: cy });
|
|
} else if (can('patch') && sim.gold >= T.patch.cost + 20) this.cmd({ c: 'tool', id: 'patch', tid: emped[0].id });
|
|
}
|
|
const hidden = this.silent();
|
|
if (hidden.length >= 2 && awake && can('scan') && sim.gold >= T.scan.cost + 60) {
|
|
const core = sim.board.core, h = hidden.reduce((a, b) => (Math.hypot(a.x - core.x, a.y - core.y) < Math.hypot(b.x - core.x, b.y - core.y) ? a : b));
|
|
this.cmd({ c: 'tool', id: 'scan', x: h.x, y: h.y });
|
|
}
|
|
if (can('repair') && sim.lives <= sim.maxLives - T.repair.amount && sim.gold >= T.repair.cost + 40) this.cmd({ c: 'tool', id: 'repair' });
|
|
if (can('quarantine') && awake && sim.gold >= T.quarantine.cost) {
|
|
const core = sim.board.core; // units about to reach the server, by the integrity they would cost
|
|
let danger = 0;
|
|
for (const m of sim.monsters) if (!m.dead && Math.hypot(m.x - core.x - 0.5, m.y - core.y - 0.5) <= 5) danger += ENEMIES[m.kind].leak;
|
|
if (danger >= Math.max(4, sim.lives * 0.35)) this.cmd({ c: 'tool', id: 'quarantine' });
|
|
}
|
|
}
|
|
// Units standing inside the reach of an attack tower that is working and could hit them, while that tower has no target: something is hiding
|
|
// them (stealth). Only what a screen shows: the tower list, whether a tower is out (EMP) and what it is aiming at.
|
|
silent() {
|
|
const out = [];
|
|
for (const m of this.sim.monsters) {
|
|
if (m.dead) continue;
|
|
for (const t of this.sim.towers) {
|
|
const d = TOWERS[t.type];
|
|
if (d.role !== 'attack' || t.empT > 0 || t.tgt !== 0 || (m.air ? !d.air : !d.ground)) continue;
|
|
const r = d.levels[t.level - 1].range, dx = m.x - t.x - 0.5, dy = m.y - t.y - 0.5;
|
|
if (dx * dx + dy * dy <= r * r) { out.push(m); break; }
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
turretCount() { let n = 0; for (const t of this.sim.towers) if (TOWERS[t.type].role !== 'wall') n++; return n; }
|
|
|
|
step() {
|
|
if (this.turretCount() >= this.openN && this.mazeStep()) return true;
|
|
return this.buyBest();
|
|
}
|
|
|
|
// ---- the maze: wall lines that lengthen the route, under a budget that is a share of everything it has been paid
|
|
wallBudget() {
|
|
const sim = this.sim, total = this.spentWalls + this.spentOther + sim.gold;
|
|
const ramp = clamp((sim.time - 15) / 45, 0, 1); // the first minute belongs to the turrets
|
|
return this.share * ramp * total + (ramp > 0 ? 10 : 0) - this.spentWalls;
|
|
}
|
|
|
|
mazeStep() {
|
|
const sim = this.sim, wc = TOWERS.wall.levels[0].cost;
|
|
if (!this.plan.length) {
|
|
if (this.share <= 0 || sim.time < this.nextSeg || this.noSegRev === sim.rev) return false;
|
|
if (this.wallBudget() < 2 * wc || sim.gold < 2 * wc) return false;
|
|
this.nextSeg = sim.time + 4;
|
|
const seg = this.bestSegment();
|
|
if (!seg) { this.noSegRev = sim.rev; return false; }
|
|
this.plan = seg;
|
|
}
|
|
let placed = 0;
|
|
while (this.plan.length && sim.gold >= wc && this.wallBudget() >= wc) {
|
|
const c = this.plan[0], r = this.cmd({ c: 'place', type: 'wall', x: c[0], y: c[1] });
|
|
if (r.ok) { placed++; this.spentWalls += wc; this.plan.shift(); }
|
|
else if (r.reason === 'monster') break; // a packet is in the way: try again next time
|
|
else if (r.reason === 'occupied') this.plan.shift();
|
|
else { this.plan = []; break; }
|
|
}
|
|
return placed > 0;
|
|
}
|
|
|
|
// The wall line (from a border / a solid cell, straight, up to 14 cells) that adds the most route length per credit. A sample of
|
|
// the possible lines, a path field per candidate: the cost is bounded (about 700 fields).
|
|
bestSegment() {
|
|
const sim = this.sim, b = sim.board, cols = b.cols, rows = b.rows, rng = this.rng, wc = TOWERS.wall.levels[0].cost;
|
|
const mc = sim.monsterCells(), solid = Uint8Array.from(b.solid), base = b.routeLen, geo = this.geometry();
|
|
const starts = [];
|
|
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
|
|
const i = y * cols + x;
|
|
if (solid[i] || b.isSpecial(x, y) || mc.reserved.has(i)) continue;
|
|
for (const d of DIRS) {
|
|
const px = x - d[0], py = y - d[1];
|
|
if (px < 0 || py < 0 || px >= cols || py >= rows || solid[py * cols + px]) starts.push([x, y, d]);
|
|
}
|
|
}
|
|
for (let i = starts.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)), t = starts[i]; starts[i] = starts[j]; starts[j] = t; }
|
|
let best = null;
|
|
for (const [x0, y0, d] of starts.slice(0, 120)) {
|
|
let cx = x0, cy = y0, touched = false;
|
|
const added = [];
|
|
for (let l = 1; l <= 14; l++) {
|
|
if (cx < 0 || cy < 0 || cx >= cols || cy >= rows) break;
|
|
const ci = cy * cols + cx;
|
|
if (solid[ci] || b.isSpecial(cx, cy) || mc.reserved.has(ci)) break;
|
|
solid[ci] = 1; added.push(ci);
|
|
if (geo.onRoute[ci]) touched = true;
|
|
if (touched && l >= 3 && l % 2 === 1) {
|
|
const f = TD.buildField(cols, rows, solid, b.coreIdx);
|
|
let after = 0, blocked = false;
|
|
for (const sp of b.spawns) { const v = f[sp.y * cols + sp.x]; if (!isFinite(v)) { blocked = true; break; } after += v; }
|
|
if (!blocked) for (const m of mc.must) if (!isFinite(f[m])) { blocked = true; break; }
|
|
if (blocked) break;
|
|
const gain = after - base, near = 1 - clamp(Math.hypot(cx - b.core.x, cy - b.core.y) / 18, 0, 1);
|
|
const ratio = gain / (wc * l) * (1 + 0.8 * near);
|
|
if (gain >= 3 && (!best || ratio > best.ratio)) best = { ratio, x: x0, y: y0, d, l };
|
|
}
|
|
cx += d[0]; cy += d[1];
|
|
}
|
|
for (const ci of added) solid[ci] = 0;
|
|
}
|
|
if (!best) return null;
|
|
const cells = [];
|
|
for (let k = 0; k < best.l; k++) cells.push([best.x + best.d[0] * k, best.y + best.d[1] * k]);
|
|
return cells;
|
|
}
|
|
|
|
// ---- turrets and upgrades, scored by (damage x what the route lets the turret reach x what is coming) per credit
|
|
geometry() {
|
|
const sim = this.sim, b = sim.board;
|
|
if (this.geo && this.geo.rev === sim.rev) return this.geo;
|
|
const gx = [], gy = [], onRoute = new Uint8Array(b.cols * b.rows);
|
|
for (const route of b.routes) for (const c of route) { gx.push(c[0] + 0.5); gy.push(c[1] + 0.5); onRoute[c[1] * b.cols + c[0]] = 1; }
|
|
const ax = [], ay = []; // flyers go straight from each gateway to the server
|
|
for (const sp of b.spawns) {
|
|
const x0 = sp.x + 0.5, y0 = sp.y + 0.5, x1 = b.core.x + 0.5, y1 = b.core.y + 0.5, n = Math.max(2, Math.ceil(Math.hypot(x1 - x0, y1 - y0)));
|
|
for (let i = 0; i <= n; i++) { ax.push(x0 + (x1 - x0) * i / n); ay.push(y0 + (y1 - y0) * i / n); }
|
|
}
|
|
this.geo = { rev: sim.rev, gx, gy, ax, ay, onRoute };
|
|
this.tables = {};
|
|
return this.geo;
|
|
}
|
|
cover(x, y, r, air) { // how much route (and flight line) is within r of the point
|
|
const g = this.geometry(), r2 = r * r, wa = 0.3 + 1.5 * this.th.air;
|
|
let s = 0;
|
|
for (let i = 0; i < g.gx.length; i++) { const dx = g.gx[i] - x, dy = g.gy[i] - y; if (dx * dx + dy * dy <= r2) s++; }
|
|
if (air) for (let i = 0; i < g.ax.length; i++) { const dx = g.ax[i] - x, dy = g.ay[i] - y; if (dx * dx + dy * dy <= r2) s += wa * 0.5; }
|
|
return s;
|
|
}
|
|
// the best free cells for a tower of range r (cached until the board changes)
|
|
sites(r, air) {
|
|
const key = r + (air ? 'a' : 'g'), g = this.geometry(); // (the geometry drops the cached tables when the board has changed)
|
|
if (this.tables[key]) return this.tables[key];
|
|
const sim = this.sim, b = sim.board, res = sim.monsterCells().reserved, list = [];
|
|
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
|
|
const i = y * b.cols + x;
|
|
if (b.solid[i] || b.obst[i] || g.onRoute[i] || res.has(i) || b.isSpecial(x, y) || (this.badUntil.get(i) || 0) > sim.time) continue;
|
|
const c = this.cover(x + 0.5, y + 0.5, r, air);
|
|
if (c > 0) list.push({ x, y, c });
|
|
}
|
|
list.sort((p, q) => q.c - p.c);
|
|
return (this.tables[key] = list.slice(0, 8));
|
|
}
|
|
// a turret's worth in "damage per second against what is coming"
|
|
power(type, st) {
|
|
const def = TOWERS[type], th = this.th, arm = 1 + 3 * th.armor;
|
|
if (def.role === 'attack') {
|
|
let p = (type === 'uplink' ? st.dmg : perHit(st.dmg, arm)) * st.rate;
|
|
if (type === 'mortar') p *= 1.2 * (1 + th.swarm) * (1 - 0.9 * th.air);
|
|
else if (type === 'arc') { let c = 0, m = 1; for (let i = 0; i < st.chains; i++) { m *= st.falloff; c += m; } p *= 1 + c * (0.3 + th.swarm); }
|
|
else if (type === 'uplink') p *= 2.5;
|
|
else if (type === 'ids') p *= (1 + 0.5 * th.armor) * (1 - 0.6 * th.swarm); // one big shot at a time: poor against a crowd
|
|
return p;
|
|
}
|
|
if (def.role === 'aura') return st.slow * 60;
|
|
if (def.role === 'control') return (st.stun / st.pulse) * 70;
|
|
return 0;
|
|
}
|
|
options() {
|
|
const sim = this.sim, opts = [], count = {};
|
|
for (const t of sim.towers) count[t.type] = (count[t.type] || 0) + 1;
|
|
const jit = (v) => v * (1 + this.jitter * (this.rng() - 0.5) * 2);
|
|
const opening = this.turretCount() < this.openN;
|
|
const diversity = (type) => (opening && OPENING[type] !== undefined ? OPENING[type] : 1) / (1 + 0.2 * (count[type] || 0));
|
|
for (const type of this.types) {
|
|
const def = TOWERS[type], st = def.levels[0], price = TD.priceFor(type, sim.towers);
|
|
if (price > sim.gold * 3) continue;
|
|
if (def.role === 'support') { // a booster: next to several attackers
|
|
const att = sim.towers.filter((t) => TOWERS[t.type].role === 'attack');
|
|
if (att.length < 3) continue;
|
|
const b = sim.board, res = sim.monsterCells().reserved;
|
|
let bestN = 0, bestC = null;
|
|
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
|
|
const i = y * b.cols + x;
|
|
if (b.solid[i] || b.obst[i] || res.has(i) || b.isSpecial(x, y) || this.geometry().onRoute[i]) continue;
|
|
let n = 0;
|
|
for (const t of att) if ((t.x - x) * (t.x - x) + (t.y - y) * (t.y - y) <= st.range * st.range) n += this.power(t.type, TOWERS[t.type].levels[t.level - 1]);
|
|
if (n > bestN) { bestN = n; bestC = { x, y }; }
|
|
}
|
|
if (bestC) opts.push({ kind: 'new', type, x: bestC.x, y: bestC.y, cost: price, ratio: jit(st.boost * bestN * 0.6 / price * this.fav[type]) });
|
|
continue;
|
|
}
|
|
const air = !!def.air, sites = this.sites(st.range, air);
|
|
for (const site of sites.slice(0, 4)) {
|
|
const v = this.power(type, st) * site.c / price * this.fav[type] * diversity(type);
|
|
opts.push({ kind: 'new', type, x: site.x, y: site.y, cost: price, ratio: jit(v) });
|
|
}
|
|
}
|
|
for (const t of sim.towers) {
|
|
const def = TOWERS[t.type], nx = def.levels[t.level];
|
|
if (!nx || def.role === 'wall' || def.role === 'support' || !this.types.includes(t.type)) continue;
|
|
const cost = sim.upgradeCost(t);
|
|
if (cost === null || cost > sim.gold * 3) continue;
|
|
const cur = def.levels[t.level - 1], c = this.cover(t.x + 0.5, t.y + 0.5, nx.range, !!def.air);
|
|
const v = (this.power(t.type, nx) * c - this.power(t.type, cur) * this.cover(t.x + 0.5, t.y + 0.5, cur.range, !!def.air)) / cost * this.fav[t.type];
|
|
if (v > 0) opts.push({ kind: 'up', id: t.id, type: t.type, cost, ratio: jit(v) * (opening ? 0.5 : 1.1) });
|
|
}
|
|
return opts;
|
|
}
|
|
buyBest() {
|
|
const sim = this.sim;
|
|
if (sim.gold < 25) return false;
|
|
const opts = this.options().filter((o) => o.ratio > 0).sort((p, q) => q.ratio - p.ratio);
|
|
if (!opts.length) return false;
|
|
const best = opts[0], aff = opts.find((o) => o.cost <= sim.gold);
|
|
if (!aff) return false;
|
|
if (aff !== best && best.cost <= sim.gold * 3 && aff.ratio < 0.6 * best.ratio) return false; // rather save for the clearly better one
|
|
const r = aff.kind === 'up' ? this.cmd({ c: 'upgrade', id: aff.id }) : this.cmd({ c: 'place', type: aff.type, x: aff.x, y: aff.y });
|
|
if (r.ok) this.spentOther += aff.cost;
|
|
else if (aff.kind === 'new') { this.badUntil.set(aff.y * sim.board.cols + aff.x, sim.time + 6); this.tables = {}; }
|
|
return r.ok;
|
|
}
|
|
}
|
|
|
|
// ====================================================================================================================
|
|
// The attacker: reads the tower mix, buys what the defence is worst at per credit, saves a convoy, buys tech, plays the abilities.
|
|
// ====================================================================================================================
|
|
const TECH_WEIGHT = { armor: 1.0, health: 1.0, speed: 0.8, regen: 0.45, shield: 0.7, stealth: 0.7, crypt: 0.5 };
|
|
|
|
class Attacker extends Base {
|
|
constructor(sim, o) {
|
|
super(sim, 'attacker', o);
|
|
const r = this.rng, s = this.skill;
|
|
this.interval = 1 + (1 - s) * 2.5;
|
|
this.aggr = 0.75 + 0.6 * r(); // how big a convoy it wants before it launches
|
|
this.techShare = (0.15 + 0.2 * r()) * (s < 0.3 ? 0 : s); // the share of everything it has seen that may go into tech
|
|
this.spent = { tech: 0, units: 0, abilities: 0 };
|
|
this.lastLaunch = 0;
|
|
this.want = null; this.wantAt = 0; // the kind it is saving for
|
|
this.p = null;
|
|
}
|
|
|
|
act() {
|
|
const sim = this.sim, p = this.p = sim.privateState('attacker');
|
|
const def = this.assess();
|
|
this.def = def;
|
|
if (this.skill >= 0.3) { this.abilities(p, def); this.tech(this.p = sim.privateState('attacker'), def); }
|
|
this.units(this.p = sim.privateState('attacker'), def); // (what it has left after what it just bought)
|
|
}
|
|
|
|
// ---- the defence, in numbers
|
|
assess() {
|
|
const sim = this.sim, towers = [], hits = [];
|
|
let dps = 0, airDps = 0, splash = 0, slowers = 0, best = null;
|
|
for (const t of sim.towers) {
|
|
const def = TOWERS[t.type], st = def.levels[t.level - 1];
|
|
if (t.empT > 0) continue;
|
|
if (def.role === 'aura' || def.role === 'control') { slowers++; continue; }
|
|
if (def.role !== 'attack') continue;
|
|
const d = st.dmg * st.rate;
|
|
towers.push(t);
|
|
dps += d; if (def.air) airDps += d;
|
|
if (t.type === 'mortar' || t.type === 'arc' || t.type === 'uplink') splash += d;
|
|
hits.push({ dmg: st.dmg, w: d, ignore: t.type === 'uplink', air: !!def.air });
|
|
if (!best || d > best.d) best = { t, d };
|
|
}
|
|
return { n: towers.length, dps, airDps, splashShare: dps ? splash / dps : 0, slowers, hits, best: best && best.t };
|
|
}
|
|
// the part of the defence's damage that gets through to a unit with this much armour (and that can reach it at all)
|
|
bite(def, armor, air) {
|
|
let tot = 0, got = 0;
|
|
for (const h of def.hits) {
|
|
if (air && !h.air) continue;
|
|
tot += h.w; got += h.w * (h.ignore ? 1 : perHit(h.dmg, armor) / h.dmg);
|
|
}
|
|
return got;
|
|
}
|
|
|
|
// value per credit of a unit kind against this defence: leak damage x the chance to get through / price
|
|
kindValue(kind, def) {
|
|
const d = ENEMIES[kind], T = this.p.tech, X = VS.TECH;
|
|
const hp = d.hp * (1 + X.health.per * T.health) + (d.shield || 0) + X.shield.per * T.shield;
|
|
const dps = Math.max(1, this.bite(def, d.armor + X.armor.per * T.armor, d.air));
|
|
let dur = hp / dps; // seconds of the whole defence's fire to kill one
|
|
if (d.hp <= 20 && !d.air) dur *= 1 - 0.5 * def.splashShare; // little ones die in groups to splash
|
|
if (d.heal) dur *= 1.4; // a healer keeps the others alive
|
|
const speed = d.speed * (1 + X.speed.per * T.speed);
|
|
const escape = 1 - Math.exp(-dur * speed / 3);
|
|
return d.leak * escape / d.buyCost;
|
|
}
|
|
|
|
// ---- units: rush a weak defence, otherwise save a convoy and launch it
|
|
units(p, def) {
|
|
const sim = this.sim, rng = this.rng, left = sim.vs.limit - sim.time;
|
|
const price = (k) => ENEMIES[k].buyCost;
|
|
const weak = def.dps < 40; // (almost) nothing shoots yet: units that leak pay themselves back, so go now
|
|
const endgame = left < 50; // the clock is about to decide it: nothing is worth saving any more
|
|
const direct = weak || endgame;
|
|
const mix = this.mix(def);
|
|
// the money it can spend on units now: a share is kept for tech while that is still worth it
|
|
let budget = p.credits - this.techReserve(p);
|
|
if (direct && budget < price(mix[0].k)) budget = p.credits;
|
|
let room = direct ? VS.MAX_ALIVE - sim.vsAlive() : VS.MAX_STAGED - p.staged.reduce((s, e) => s + e[1], 0);
|
|
// a shopping list of one: draw a kind by its share, SAVE until it is affordable (not "spend on whatever is cheap meanwhile": a
|
|
// trojan would never get bought), then buy a chunk of it
|
|
for (let guard = 0; guard < 6 && room > 0; guard++) {
|
|
if (!this.want || sim.time - this.wantAt > 20 || !mix.some((m) => m.k === this.want)) { this.want = this.draw(mix); this.wantAt = sim.time; }
|
|
const cost = price(this.want);
|
|
if (budget < cost) break;
|
|
const n = Math.min(Math.max(1, Math.floor(Math.min(budget, 40 + 60 * rng()) / cost)), room);
|
|
const r = this.cmd({ c: direct ? 'spawn' : 'stage', kind: this.want, n });
|
|
if (!r.ok) break;
|
|
this.spent.units += n * cost; budget -= n * cost; room -= n; this.want = null;
|
|
}
|
|
// launch the convoy when it is big enough for this defence, when waiting has gone on long enough, or when the round is nearly over
|
|
const staged = sim.privateState('attacker').staged, value = staged.reduce((s, e) => s + e[1] * price(e[0]), 0);
|
|
if (!value) return;
|
|
const need = this.aggr * (60 + 22 * def.n + 0.5 * def.dps) * (0.8 + 0.4 * rng());
|
|
const waited = sim.time - this.lastLaunch;
|
|
if (value >= need || (waited > 90 && value >= 80) || (endgame && waited > 5)) {
|
|
if (this.cmd({ c: 'launch' }).ok) this.lastLaunch = sim.time;
|
|
}
|
|
}
|
|
draw(mix) { // a kind, with the probability of its share
|
|
let x = this.rng();
|
|
for (const m of mix) { x -= m.share; if (x <= 0) return m.k; }
|
|
return mix[0].k;
|
|
}
|
|
// the kinds worth buying, best first, with the share of the money each gets
|
|
mix(def) {
|
|
const rng = this.rng, noise = 0.1 + (1 - this.skill) * 0.6;
|
|
const kinds = ENEMY_ORDER.map((k) => ({ k, v: this.kindValue(k, def) * (1 + noise * (rng() - 0.5) * 2) })).sort((a, b) => b.v - a.v);
|
|
const top = kinds.slice(0, 3).filter((e, i) => i === 0 || e.v > 0.45 * kinds[0].v);
|
|
const sum = top.reduce((s, e) => s + e.v * e.v, 0) || 1;
|
|
const out = top.map((e) => ({ k: e.k, share: e.v * e.v / sum }));
|
|
if (out[0].k === 'trojan' && !out.some((e) => e.k === 'daemon')) { out[0].share *= 0.85; out.push({ k: 'daemon', share: 0.15 }); } // a healer behind the armour
|
|
return out;
|
|
}
|
|
|
|
// ---- tech: a share of everything seen, on whatever the defence is worst at stopping
|
|
techReserve(p) {
|
|
if (this.skill < 0.3) return 0;
|
|
const seen = p.credits + this.spent.tech + this.spent.units + this.spent.abilities;
|
|
const owed = this.techShare * seen - this.spent.tech;
|
|
return owed > 0 ? Math.min(owed, 400) : 0;
|
|
}
|
|
tech(p, def) {
|
|
const sim = this.sim, T = p.tech, reserve = this.techReserve(p);
|
|
if (reserve <= 0) return;
|
|
const wArmor = def.dps ? 1 - this.bite(def, 3, false) / def.dps : 0.3; // how much a few points of armour would cut the defence
|
|
const want = {
|
|
armor: TECH_WEIGHT.armor * (0.3 + wArmor), health: TECH_WEIGHT.health, speed: TECH_WEIGHT.speed, regen: TECH_WEIGHT.regen,
|
|
shield: TECH_WEIGHT.shield * (def.dps > 150 ? 1 : 0.6), stealth: TECH_WEIGHT.stealth * Math.min(1.5, 0.3 + def.n / 8),
|
|
crypt: TECH_WEIGHT.crypt * (def.slowers ? 1.6 : 0.2),
|
|
};
|
|
let bestId = null, bestV = 0, bestCost = 0;
|
|
for (const id of VS.TECH_ORDER) {
|
|
const cost = sim.techCost(id);
|
|
if (cost === null || cost > p.credits || cost > reserve * 1.6 + 1) continue; // (only when its share of the money has built up)
|
|
const v = want[id] / Math.pow(1.5, T[id]) * (1 + 0.2 * (this.rng() - 0.5)) / cost;
|
|
if (v > bestV) { bestV = v; bestId = id; bestCost = cost; }
|
|
}
|
|
if (bestId && this.cmd({ c: 'tech', id: bestId }).ok) this.spent.tech += bestCost;
|
|
}
|
|
|
|
// ---- abilities: only when there is a convoy on the map worth the money
|
|
abilities(p, def) {
|
|
const sim = this.sim, A = VS.ABILITIES, rng = this.rng;
|
|
const mine = sim.monsters.filter((m) => !m.dead && !m.decoy);
|
|
if (mine.length < 3 || !def.n) return;
|
|
const value = mine.reduce((s, m) => s + m.buyCost, 0);
|
|
const ready = (id) => p.cd[id] <= 0 && p.credits >= A[id].cost && value >= 2.2 * A[id].cost;
|
|
const inReach = (m) => def.best && (m.x - def.best.x - 0.5) * (m.x - def.best.x - 0.5) + (m.y - def.best.y - 0.5) * (m.y - def.best.y - 0.5) <= 100;
|
|
const pay = (id, extra) => { if (this.cmd(Object.assign({ c: 'ability', id }, extra)).ok) this.spent.abilities += A[id].cost; };
|
|
const underFire = mine.filter((m) => this.inRange(m)).length;
|
|
if (ready('emp') && def.best && mine.some(inReach) && rng() < 0.7) pay('emp', { tid: def.best.id });
|
|
else if (ready('ddos') && underFire >= Math.max(5, mine.length * 0.4) && value >= 400) pay('ddos');
|
|
else if (ready('surge') && mine.length >= 8 && underFire >= 2) pay('surge');
|
|
else if (ready('decoy') && def.best && underFire >= 3 && rng() < 0.5) pay('decoy', { tid: def.best.id });
|
|
}
|
|
inRange(m) { // is any attack tower reaching this unit now?
|
|
for (const t of this.sim.towers) {
|
|
const d = TOWERS[t.type];
|
|
if (d.role !== 'attack' || t.empT > 0) continue;
|
|
const r = d.levels[t.level - 1].range;
|
|
if ((m.x - t.x - 0.5) * (m.x - t.x - 0.5) + (m.y - t.y - 0.5) * (m.y - t.y - 0.5) <= r * r) return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function create(sim, role, opts) {
|
|
if (!sim || !sim.vs) throw new Error('NWBot needs a versus sim');
|
|
if (role === 'defender') return new Defender(sim, opts);
|
|
if (role === 'attacker') return new Attacker(sim, opts);
|
|
throw new Error('NWBot role must be "defender" or "attacker"');
|
|
}
|
|
|
|
return { create, Defender, Attacker, prng };
|
|
});
|