Phase 3: trade/end-game client, bot simulator, first balance pass
Built: - Client: trade screen, world/end-game screen (landing sites, shipping, node build, final ranking), report sharing + alliance reports tab, alert describers for all notification types, error-code strings (en+nb) for every server CODE. - tools/bot.js (+ tools/bot/): 50 headless bots against the real server in-process with a fake clock; resource/unit conservation ledger, exit 1 on broken invariants. docs/BALANCE.md has method and every run behind a number. - Balance changes (evidence in docs/BALANCE.md): secondQueueCoreLevel 10 -> 3, TRANSPORT.capacityPerLink 500 -> 1000 (end game was shipping-limited in bot runs). - Server fixes: POST /reports/:id/share 500 without a pending reportCleanup; bounced link shipments were silent about cargo overflow. Tested: npm test 207/207 (new: bot determinism + invariants, client alerts/world/i18n over CODES, two regression tests that failed before their fix); openapi check up to date. Real-browser scratch runs (not in repo): WebSocket push shows an incoming-attack banner ~214 ms after launch, polling fallback ~52 s, 15 scripted flows, 71 screenshots. NOT tested: Playwright suite (e2e/ still empty), real devices/Safari, nginx proxy websockets, throttled networks, HTTP-level bot load. NOT claimed: balance. Bots are not humans; open balance items (loot waste, escrow refund clipping, no garrisons at landing sites, end game not scaling with world speed) are listed in docs/BALANCE.md. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
d84b0c9d12
commit
931f59e11e
49 changed files with 4750 additions and 59 deletions
126
tools/bot.js
Normal file
126
tools/bot.js
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
/*
|
||||
* UPSTREAM bot harness: N headless players against the REAL server code, in-process, on a fake clock.
|
||||
*
|
||||
* node tools/bot.js --players 50 --days 14 --speed 1 [--seed 1] [--strategy-mix builder:12,raider:8,...] [--json out.json]
|
||||
*
|
||||
* Options
|
||||
* --players N bots (default 50) --days N simulated days (default 14)
|
||||
* --speed X world speed (default 1) --seed N world + bot seed (default 1)
|
||||
* --radius N map radius in tiles (default: data.js WORLD_DEFAULTS.mapRadius)
|
||||
* --strategy-mix M e.g. builder:12,raider:8,conqueror:3,turtle:6,expander:8,trader:6,alliancer:7 (default: a mix of all)
|
||||
* --sessions-per-day N every bot plays N short sessions a day (default: per archetype, 3-5)
|
||||
* --always-on every bot acts every --step-min minutes (upper bound of what attention could do)
|
||||
* --step-min N tick of --always-on (default 10) --join-days N joining spread over the first N days (default 2)
|
||||
* --session-min N length of a sitting in minutes (default 5; the first one 20, --first-session-min): a bot whose build
|
||||
* finishes inside its sitting starts the next one, so cheap early builds chain, long ones do not
|
||||
* --endgame-step-min N once the landing sites are open, members of alliances that chase the backbone also act every N minutes
|
||||
* (a final push with high attention; default 0 = off, normal sessions only) --endgame-min-members N (default 3)
|
||||
* --field-policy P marginal (default: keep the production mix at the ratio the player spends, upgrade whatever lags) or balanced
|
||||
* (all fields level up together; a lower bound of player skill)
|
||||
* --no-adapt bots do not answer raids with more defence (default: after being hit a bot trains defence up to 1.25 x the
|
||||
* strongest attack it saw, for 5 days; an upper bound of how defenders react)
|
||||
* --sample-min N economy sampling interval (default 120)
|
||||
* --set A.B.c=V override a data.js value for this run (repeatable, value is JSON), e.g. --set FORMULAS.costGrowth=1.25
|
||||
* Only values the code reads at call time are reached; a constant copied at require time (e.g.
|
||||
* ENDGAME.scanStrength in military/landing.js) is silently not overridden.
|
||||
* --json FILE write the full stats as JSON --quiet print only the verdict line --progress progress dots
|
||||
* --exit-0 never exit non-zero (default: exit 1 when an invariant breaks, 2 on usage errors)
|
||||
*
|
||||
* How it drives the server: srv.commands.run(name, args) - the function every REST route calls - so validation, transactions,
|
||||
* events and notifications are the real ones; HTTP, JSON and scrypt are skipped to keep 50 players x 30 days in well under a
|
||||
* minute. Bots read state through the server's own modules and use rules.js previews; they cannot change anything except by
|
||||
* command. Determinism: every choice comes from a generator seeded with (seed, bot, purpose); the same options give the same stats
|
||||
* (wall-clock numbers under `perf` excepted).
|
||||
*/
|
||||
const path = require('path');
|
||||
const D = require('../public/js/data.js');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const o = { players: 50, days: 14, speed: 1, seed: 1, radius: D.WORLD_DEFAULTS.mapRadius, mix: '', sessionsPerDay: 0, alwaysOn: false, stepMin: 10, joinDays: 2, sampleMin: 120, sessionMin: 5, firstSessionMin: 20, endgameMinMembers: 3, endgameStepMin: 0, adapt: true, fieldPolicy: 'marginal', set: [], json: null, quiet: false, progress: false, exit0: false };
|
||||
const need = (i, k) => { if (i + 1 >= argv.length) throw new Error('missing value for ' + k); return argv[i + 1]; };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
const num = (k) => { const v = Number(need(i, k)); if (!Number.isFinite(v)) throw new Error(k + ' needs a number'); i++; return v; };
|
||||
switch (a) {
|
||||
case '--players': o.players = num(a); break;
|
||||
case '--days': o.days = num(a); break;
|
||||
case '--speed': o.speed = num(a); break;
|
||||
case '--seed': o.seed = num(a); break;
|
||||
case '--radius': o.radius = num(a); break;
|
||||
case '--strategy-mix': o.mix = need(i, a); i++; break;
|
||||
case '--sessions-per-day': o.sessionsPerDay = num(a); break;
|
||||
case '--always-on': o.alwaysOn = true; break;
|
||||
case '--step-min': o.stepMin = num(a); break;
|
||||
case '--join-days': o.joinDays = num(a); break;
|
||||
case '--sample-min': o.sampleMin = num(a); break;
|
||||
case '--session-min': o.sessionMin = num(a); break;
|
||||
case '--first-session-min': o.firstSessionMin = num(a); break;
|
||||
case '--endgame-min-members': o.endgameMinMembers = num(a); break;
|
||||
case '--endgame-step-min': o.endgameStepMin = num(a); break;
|
||||
case '--no-adapt': o.adapt = false; break;
|
||||
case '--field-policy': o.fieldPolicy = need(i, a); i++; if (['marginal', 'balanced'].indexOf(o.fieldPolicy) < 0) throw new Error('--field-policy is marginal or balanced'); break;
|
||||
case '--set': o.set.push(need(i, a)); i++; break;
|
||||
case '--json': o.json = need(i, a); i++; break;
|
||||
case '--quiet': o.quiet = true; break;
|
||||
case '--progress': o.progress = true; break;
|
||||
case '--exit-0': o.exit0 = true; break;
|
||||
case '-h': case '--help': o.help = true; break;
|
||||
default: throw new Error('unknown option ' + a);
|
||||
}
|
||||
}
|
||||
if (!(o.players >= 1) || !(o.days > 0) || !(o.speed > 0)) throw new Error('players, days and speed must be positive');
|
||||
return o;
|
||||
}
|
||||
|
||||
// "FORMULAS.costGrowth=1.25" -> mutate the shared data module in place; returns a function that puts everything back.
|
||||
function applyOverrides(list) {
|
||||
const undo = [];
|
||||
for (const spec of list || []) {
|
||||
const eq = spec.indexOf('=');
|
||||
if (eq < 0) throw new Error('--set needs PATH=VALUE: ' + spec);
|
||||
const keys = spec.slice(0, eq).split('.');
|
||||
let value;
|
||||
try { value = JSON.parse(spec.slice(eq + 1)); } catch (e) { throw new Error('--set value must be JSON: ' + spec); }
|
||||
let node = D;
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
if (!node || typeof node[keys[i]] !== 'object') throw new Error('--set: no such path ' + spec.slice(0, eq));
|
||||
node = node[keys[i]];
|
||||
}
|
||||
const last = keys[keys.length - 1];
|
||||
if (!node || !(last in node)) throw new Error('--set: no such path ' + spec.slice(0, eq));
|
||||
const old = node[last];
|
||||
node[last] = value;
|
||||
undo.push(() => { node[last] = old; });
|
||||
}
|
||||
return () => { for (let i = undo.length - 1; i >= 0; i--) undo[i](); };
|
||||
}
|
||||
|
||||
// Library entry (used by the test): runBot({players, days, speed, seed, ...}) -> stats. Overrides are undone afterwards.
|
||||
async function runBot(opts) {
|
||||
const o = Object.assign({ players: 50, days: 14, speed: 1, seed: 1, radius: D.WORLD_DEFAULTS.mapRadius, mix: '', sessionsPerDay: 0, alwaysOn: false, stepMin: 10, joinDays: 2, sampleMin: 120, sessionMin: 5, firstSessionMin: 20, endgameMinMembers: 3, endgameStepMin: 0, adapt: true, fieldPolicy: 'marginal', set: [] }, opts || {});
|
||||
const restore = applyOverrides(o.set);
|
||||
try {
|
||||
const { runSim } = require('./bot/sim');
|
||||
return await runSim(o);
|
||||
} finally { restore(); }
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let o;
|
||||
try { o = parseArgs(process.argv.slice(2)); } catch (e) { console.error('tools/bot.js: ' + e.message + ' (see --help)'); process.exit(2); }
|
||||
if (o.help) { console.log(require('fs').readFileSync(__filename, 'utf8').split('*/')[0].replace(/^#!.*\n/, '').replace(/^'use strict';\n/, '').replace(/^\/\*\n?/, '')); return; }
|
||||
if (o.progress) o.progress = (d, n) => process.stderr.write(d % 10 === 0 ? ' ' + d + '/' + n + '\n' : '.');
|
||||
let stats;
|
||||
try { stats = await runBot(o); } catch (e) { console.error('bot run failed: ' + (e && e.stack || e)); process.exit(2); }
|
||||
if (o.json) { require('fs').writeFileSync(path.resolve(o.json), JSON.stringify(stats, null, 1)); }
|
||||
const verdict = stats.invariants.ok ? 'INVARIANTS OK' : 'INVARIANTS BROKEN';
|
||||
if (o.quiet) console.log(verdict + ' (' + stats.perf.wallSeconds + ' s, ' + stats.perf.commands + ' commands)');
|
||||
else { console.log(require('./bot/report').render(stats)); console.log('\n' + verdict); }
|
||||
if (!stats.invariants.ok && !o.exit0) process.exit(1);
|
||||
}
|
||||
|
||||
module.exports = { runBot, parseArgs, applyOverrides };
|
||||
|
||||
if (require.main === module) main();
|
||||
700
tools/bot/bots.js
Normal file
700
tools/bot/bots.js
Normal file
|
|
@ -0,0 +1,700 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Bot players. A bot is a seeded decision procedure that plays only through the server's commands (sim.call), looks at the world
|
||||
* only through what a client could see (view.js) and uses rules.js previews (buildPlan, trainPlan, footprintGate, resolveBattle ...)
|
||||
* to avoid sending commands the rules would refuse. It never touches the database to change anything.
|
||||
*
|
||||
* Archetypes differ in a profile (which buildings they push, how much of their income goes to defence / offence), a session
|
||||
* rate (human cadence: a few short sessions a day, see sim.js) and a few behaviours (raid, farm incumbents, settle, trade,
|
||||
* found/join alliances, play the end game). All choices come from the bot's own seeded generator.
|
||||
*/
|
||||
const D = require('../../public/js/data.js');
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { makeRng, HOUR, DAY } = require('./util');
|
||||
|
||||
const RES = D.RESOURCES;
|
||||
const MIL = D.MILITARY;
|
||||
|
||||
// target(type, F): level the bot wants of an infrastructure building when its weakest field is at level F.
|
||||
const T = (from, mult, add, max) => ({ from, mult, add: add || 0, max: max || 20 });
|
||||
const BASE = {
|
||||
core_router: T(0, 1.0), rack_hall: T(0, 0.8), battery_bank: T(0, 0.4),
|
||||
research_lab: T(4, 0.4), noc: T(4, 0.3), firewall: T(3, 0.3),
|
||||
internet_exchange: T(4, 0.4, 0, 12), peering_office: T(5, 0.25, 0, 4),
|
||||
};
|
||||
const prof = (over) => Object.assign({}, BASE, over);
|
||||
|
||||
const ARCHETYPES = {
|
||||
builder: {
|
||||
sessions: 4, defDays: 0.25, armyDays: 0, maxPops: 3, popF: 9, trade: 'accept', alliance: 'member',
|
||||
profile: prof({ rollout_depot: T(9, 0.3, 0, 5) }),
|
||||
order: ['core_router', 'rack_hall', 'battery_bank', 'peering_office', 'research_lab', 'noc', 'internet_exchange', 'firewall', 'rollout_depot'],
|
||||
weights: { cable_yard: 1, supply_depot: 1, sales_office: 0.9, substation: 0.6 },
|
||||
},
|
||||
raider: {
|
||||
sessions: 5, defDays: 0.1, armyDays: 1.5, maxPops: 2, popF: 12, trade: 'accept', alliance: 'member', raids: true, incumbents: true,
|
||||
profile: prof({ ops_lab: T(3, 0.5, 0, 12), research_lab: T(3, 0.5), noc: T(3, 0.15, 0, 5), firewall: T(6, 0.15), internet_exchange: T(6, 0.25, 0, 6) }),
|
||||
order: ['core_router', 'rack_hall', 'research_lab', 'ops_lab', 'battery_bank', 'peering_office', 'noc', 'firewall', 'internet_exchange', 'rollout_depot'],
|
||||
weights: { cable_yard: 1, supply_depot: 0.8, sales_office: 0.7, substation: 0.9 }, mix: { fiber: 1, hardware: 0.9, capital: 0.35 },
|
||||
},
|
||||
conqueror: {
|
||||
sessions: 5, defDays: 0.1, armyDays: 1.5, maxPops: 3, popF: 10, trade: 'none', alliance: 'member', raids: true, incumbents: true, conquer: true,
|
||||
profile: prof({ ops_lab: T(3, 0.5, 0, 12), research_lab: T(3, 0.5), noc: T(3, 0.15, 0, 5), rollout_depot: T(8, 0.4, 0, 8), internet_exchange: T(6, 0.25, 0, 6) }),
|
||||
order: ['core_router', 'rack_hall', 'research_lab', 'ops_lab', 'battery_bank', 'rollout_depot', 'peering_office', 'noc', 'firewall', 'internet_exchange'],
|
||||
weights: { cable_yard: 1, supply_depot: 0.9, sales_office: 1, substation: 0.9 },
|
||||
},
|
||||
turtle: {
|
||||
sessions: 3, defDays: 2.0, armyDays: 0, maxPops: 2, popF: 12, trade: 'accept', alliance: 'member',
|
||||
profile: prof({ noc: T(2, 0.6), firewall: T(2, 0.8), research_lab: T(3, 0.5), battery_bank: T(0, 0.5) }),
|
||||
order: ['core_router', 'rack_hall', 'noc', 'firewall', 'battery_bank', 'research_lab', 'peering_office', 'internet_exchange', 'rollout_depot'],
|
||||
weights: { cable_yard: 1, supply_depot: 1, sales_office: 0.6, substation: 0.7 }, mix: { fiber: 1, hardware: 1, capital: 0.3 },
|
||||
},
|
||||
expander: {
|
||||
sessions: 4, defDays: 0.2, armyDays: 0, maxPops: 8, popF: 6, trade: 'accept', alliance: 'member',
|
||||
profile: prof({ core_router: T(0, 1.2), rollout_depot: T(6, 0.5, 0, 6), internet_exchange: T(6, 0.3, 0, 6) }),
|
||||
order: ['core_router', 'rack_hall', 'rollout_depot', 'battery_bank', 'peering_office', 'noc', 'research_lab', 'internet_exchange', 'firewall'],
|
||||
weights: { cable_yard: 1, supply_depot: 1, sales_office: 1, substation: 0.6 }, mix: { fiber: 1, hardware: 0.6, capital: 0.6 },
|
||||
},
|
||||
trader: {
|
||||
sessions: 5, defDays: 0.2, armyDays: 0, maxPops: 3, popF: 10, trade: 'active', alliance: 'member',
|
||||
profile: prof({ internet_exchange: T(3, 0.6, 0, 14), rollout_depot: T(10, 0.3, 0, 5) }),
|
||||
order: ['core_router', 'internet_exchange', 'rack_hall', 'battery_bank', 'peering_office', 'noc', 'research_lab', 'firewall', 'rollout_depot'],
|
||||
weights: { cable_yard: 1, supply_depot: 0.6, sales_office: 0.6, substation: 0.6 }, mix: { fiber: 0.7, hardware: 1, capital: 1 },
|
||||
},
|
||||
alliancer: {
|
||||
sessions: 5, defDays: 0.4, armyDays: 0.3, maxPops: 3, popF: 10, trade: 'accept', alliance: 'founder',
|
||||
profile: prof({ peering_office: T(4, 0.5, 0, 8), ops_lab: T(5, 0.4, 0, 10), research_lab: T(4, 0.5), internet_exchange: T(5, 0.5, 0, 14), rollout_depot: T(10, 0.3, 0, 5) }),
|
||||
order: ['core_router', 'rack_hall', 'peering_office', 'battery_bank', 'research_lab', 'noc', 'ops_lab', 'internet_exchange', 'firewall', 'rollout_depot'],
|
||||
weights: { cable_yard: 1, supply_depot: 1, sales_office: 1, substation: 0.7 },
|
||||
},
|
||||
};
|
||||
|
||||
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
|
||||
const sumRes = (o) => RES.reduce((s, r) => s + ((o && o[r]) || 0), 0);
|
||||
const mulCost = (c, n) => { const o = {}; for (const r of RES) o[r] = (c[r] || 0) * n; return o; };
|
||||
|
||||
class Bot {
|
||||
constructor(sim, idx, archetype, ids, o) {
|
||||
this.sim = sim; this.idx = idx; this.archetype = archetype; this.arch = ARCHETYPES[archetype];
|
||||
this.userId = ids.userId; this.operatorId = ids.operatorId; this.name = ids.name;
|
||||
this.rng = makeRng(sim.opts.seed, idx, 0xb07);
|
||||
this.sessionsPerDay = o.sessionsPerDay || this.arch.sessions;
|
||||
this.tz = this.rng.int(-1, 1) * HOUR; // wake-up offset
|
||||
this.nextAt = 0;
|
||||
this.intel = new Map(); // townId -> { at, res, units, fw, rack }
|
||||
this.avoid = new Map(); // townId -> until
|
||||
this.hits = []; // raids/attacks that beat this bot's defence: { at }
|
||||
this.scanPending = new Map(); // townId -> arriveAt
|
||||
this.repCursor = { at: 0, seen: new Set() };
|
||||
this.reserve = {};
|
||||
this.spent = {};
|
||||
this.log = { sessions: 0, builds: 0, trains: 0, raids: 0, incumbents: 0, takeovers: 0, scans: 0, settles: 0, offers: 0, accepts: 0 };
|
||||
this.lastDiploDay = -1;
|
||||
this.firstAllianceTry = 0;
|
||||
this.incCache = null;
|
||||
this.takeoverTargets = new Map();
|
||||
this.armyOverride = 0; this.egForce = null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ session schedule (human cadence)
|
||||
// The k-th session of day d: spread over a 16 h waking day (07:00..23:00 + own offset) with jitter. Seeded, so the same bot
|
||||
// keeps the same rhythm in every run.
|
||||
sessionTimes(day, t0) {
|
||||
const n = this.sessionsPerDay;
|
||||
const out = [];
|
||||
const base = t0 + day * DAY + 7 * HOUR + this.tz;
|
||||
const slot = 16 * HOUR / n;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const jr = makeRng(this.sim.opts.seed, this.idx * 131 + day, 0x5e55 + k);
|
||||
out.push(Math.round(base + k * slot + jr() * slot));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ one session
|
||||
// A session is a short sitting (sim.opts.sessionMin, the first one longer): when the build in progress finishes before the
|
||||
// sitting is over the player is still there and starts the next one, so cheap early builds chain, expensive ones do not.
|
||||
session(now) {
|
||||
const sim = this.sim, view = sim.view;
|
||||
if (now > (this.sessionEnd || 0)) {
|
||||
this.sessionEnd = now + (this.log.sessions === 0 ? sim.opts.firstSessionMin : sim.opts.sessionMin) * 60000;
|
||||
this.log.sessions += 1;
|
||||
}
|
||||
this.now = now;
|
||||
this.op = view.operator(this.operatorId);
|
||||
this.readReports(now);
|
||||
this.social(now);
|
||||
let towns = view.towns(this.operatorId);
|
||||
if (!towns.length) return;
|
||||
for (const t of towns) this.econ(t, now);
|
||||
towns = view.towns(this.operatorId);
|
||||
const main = towns[0];
|
||||
this.military(main, towns, now);
|
||||
if (this.arch.raids && R.unitsOnline(main, now)) { this.raids(main, now); this.farmIncumbents(main, now); if (this.arch.conquer) this.conquer(main, towns, now); }
|
||||
this.expand(towns, now);
|
||||
this.trade(towns, now);
|
||||
sim.endgame.step(this, towns, now);
|
||||
}
|
||||
|
||||
// The time of the next step of the current sitting, or null when the sitting is over (or nothing is running).
|
||||
continuation(now) {
|
||||
const r = this.sim.db.get(`SELECT MIN(e.due_at) AS at FROM events e JOIN towns t ON t.id = e.town_id WHERE e.type = 'buildDone' AND e.status = 'pending' AND t.owner_id = ?`, this.operatorId);
|
||||
if (!r || r.at === null || r.at === undefined) return null;
|
||||
const at = Math.max(now + 1000, r.at + 2000);
|
||||
return at <= this.sessionEnd ? at : null;
|
||||
}
|
||||
|
||||
call(name, args) { return this.sim.call(this, name, args); }
|
||||
|
||||
// ------------------------------------------------------------------ economy
|
||||
target(type, F) {
|
||||
const p = this.arch.profile[type];
|
||||
if (!p || F < p.from) return 0;
|
||||
return Math.min(p.max, Math.max(1, Math.ceil(p.mult * F + p.add)));
|
||||
}
|
||||
|
||||
// The ordered list of building wishes for a POP: infrastructure that lags behind the fields first, then the next field.
|
||||
wishes(t, now, busy) {
|
||||
const view = this.sim.view;
|
||||
busy = busy || new Set();
|
||||
const fields = view.fieldLevels(t).filter((f) => !busy.has(f.key));
|
||||
const F = this.fieldF(view.fieldLevels(t));
|
||||
const sec = !t.isCapital;
|
||||
const out = [];
|
||||
if (!sec && this.egForce) for (const type of Object.keys(this.egForce)) if (view.level(t, type) < this.egForce[type]) out.push({ key: type, type });
|
||||
// a store that keeps hitting its cap is the first thing a player fixes
|
||||
const cur = R.resourcesAt(t, now);
|
||||
if (RES.every((r) => cur.amounts[r] >= 0.8 * cur.caps.fiber) && !busy.has('rack_hall') && view.level(t, 'rack_hall') < Math.min(20, Math.max(2, F + 1))) out.push({ key: 'rack_hall', type: 'rack_hall' });
|
||||
const order = sec ? ['core_router', 'rack_hall', 'battery_bank'] : this.arch.order;
|
||||
for (const type of order) {
|
||||
const tgt = sec ? Math.min(this.target(type, F), 6) : this.target(type, F);
|
||||
if (view.level(t, type) < tgt && !busy.has(type)) out.push({ key: type, type });
|
||||
}
|
||||
out.push(this.pickField(t, fields, F, now));
|
||||
return out.filter(Boolean);
|
||||
}
|
||||
|
||||
// The level the infrastructure targets follow: the weakest field under the 'balanced' policy, the mean under 'marginal'.
|
||||
fieldF(fields) {
|
||||
if (!fields.length) return 0;
|
||||
if (this.sim.opts.fieldPolicy === 'balanced') return Math.min(...fields.map((f) => f.level));
|
||||
return Math.floor(fields.reduce((s, f) => s + f.level, 0) / fields.length);
|
||||
}
|
||||
|
||||
// 'marginal': what a thoughtful player does - keep the production mix at the ratio the player actually spends (buildings and units
|
||||
// cost Fiber : Hardware : Capital of about 1 : 0.7 : 0.5), so the field type that lags its target share is upgraded next, whatever
|
||||
// level the other fields are at; substations only when power is short (or units are wanted).
|
||||
pickFieldMarginal(t, fields, now) {
|
||||
const rates = R.ratesPerHour(t);
|
||||
const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride;
|
||||
const lowest = (type) => fields.filter((f) => f.type === type && f.level < 20).sort((a, b) => a.level - b.level || (a.key < b.key ? -1 : 1))[0];
|
||||
if (rates.powerNet < 4 + 0.04 * rates.powerOut && (unitsWanted || rates.powerNet < 2)) {
|
||||
const s = lowest('substation');
|
||||
if (s) return { key: s.key, type: s.type };
|
||||
}
|
||||
const mix = this.arch.mix || { fiber: 1, hardware: 0.7, capital: 0.5 };
|
||||
let bestType = null, bestScore = Infinity;
|
||||
for (const type of ['cable_yard', 'supply_depot', 'sales_office']) {
|
||||
const res = D.FIELD_PRODUCES[type];
|
||||
if (!lowest(type)) continue;
|
||||
const score = rates[res] / mix[res];
|
||||
if (score < bestScore) { bestScore = score; bestType = type; }
|
||||
}
|
||||
const f = bestType ? lowest(bestType) : null;
|
||||
return f ? { key: f.key, type: f.type } : null;
|
||||
}
|
||||
|
||||
pickField(t, fields, F, now) {
|
||||
if (this.sim.opts.fieldPolicy !== 'balanced') return this.pickFieldMarginal(t, fields, now);
|
||||
const w = this.arch.weights;
|
||||
const rates = R.ratesPerHour(t);
|
||||
const power = rates.powerNet;
|
||||
const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride;
|
||||
const lag = fields.filter((f) => f.level === F);
|
||||
if (!lag.length) return null;
|
||||
// power first when it is short and units are on the way
|
||||
if (unitsWanted && power < 4 + 0.04 * (rates.powerOut)) {
|
||||
const s = lag.find((f) => f.type === 'substation') || fields.filter((f) => f.type === 'substation').sort((a, b) => a.level - b.level)[0];
|
||||
if (s && s.level <= F + 2) return { key: s.key, type: s.type };
|
||||
}
|
||||
const prod = {};
|
||||
for (const f of fields) prod[f.type] = (prod[f.type] || 0) + R.fieldOutputPerHour(f.level);
|
||||
let best = null, bestScore = Infinity;
|
||||
for (const f of lag) {
|
||||
const score = (prod[f.type] || 0) / (w[f.type] || 1);
|
||||
if (score < bestScore) { bestScore = score; best = f; }
|
||||
}
|
||||
return { key: best.key, type: best.type };
|
||||
}
|
||||
|
||||
resolve(t, wish, pending, now, depth) {
|
||||
const plan = R.buildPlan(t, wish.key, now, pending);
|
||||
if (plan.code === 'requirements_not_met' && depth < 4) {
|
||||
for (const m of plan.missing) {
|
||||
const sub = this.resolve(t, { key: m.type, type: m.type }, pending, now, depth + 1);
|
||||
if (sub) return sub;
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
econ(t0, now) {
|
||||
const sim = this.sim, view = sim.view;
|
||||
let t = t0;
|
||||
let guard = 0;
|
||||
this.reserve[t.id] = null;
|
||||
for (;;) {
|
||||
if (++guard > 4) break;
|
||||
const pending = view.pendingBuilds(t.id);
|
||||
if (pending.length >= R.queueSlots(t)) break;
|
||||
const cur = R.resourcesAt(t, now);
|
||||
const cap = cur.caps.fiber;
|
||||
const overflow = RES.some((r) => cur.amounts[r] >= 0.9 * cap);
|
||||
let acted = false;
|
||||
const list = this.wishes(t, now, new Set(pending.map((p) => p.key)));
|
||||
for (const w of list) {
|
||||
const plan = this.resolve(t, w, pending, now, 0);
|
||||
if (plan.ok) {
|
||||
const r = this.call('build', { townId: t.id, key: plan.key });
|
||||
if (r.ok) { this.log.builds += 1; t = view.town(t.id); acted = true; }
|
||||
break;
|
||||
}
|
||||
if (plan.code === 'not_enough_resources') {
|
||||
if (!this.reserve[t.id]) this.reserve[t.id] = plan.cost;
|
||||
// storage too small for this cost: grow the Rack hall first
|
||||
if (plan.cost && RES.some((r) => plan.cost[r] > cap) && !pending.some((p) => p.key === 'rack_hall')) {
|
||||
const rp = R.buildPlan(t, 'rack_hall', now, pending);
|
||||
if (rp.ok) { const r = this.call('build', { townId: t.id, key: 'rack_hall' }); if (r.ok) { this.log.builds += 1; t = view.town(t.id); acted = true; } }
|
||||
break;
|
||||
}
|
||||
if (overflow) continue; // do not waste production: spend on something cheaper
|
||||
// saving for the big item only makes sense when it is near: otherwise the other build slots would sit idle for hours
|
||||
let wait = 0;
|
||||
for (const r of RES) { const need = plan.cost[r] - cur.amounts[r]; if (need > 0) wait = Math.max(wait, cur.rates[r] > 0 ? need / cur.rates[r] : Infinity); }
|
||||
if (wait > 8) continue;
|
||||
break;
|
||||
}
|
||||
if (plan.code === 'queue_full') break;
|
||||
// max_level / already_queued / requirements: next wish
|
||||
}
|
||||
if (!acted) break;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ units
|
||||
prodTotal(t) { const r = R.ratesPerHour(t); return r.fiber + r.hardware + r.capital; }
|
||||
|
||||
// How many of `unit` can be trained now: affordable (above the reserve), power room, batch limit.
|
||||
affordable(t, unit, now, keepReserve) {
|
||||
const def = R.unitDef(unit);
|
||||
const have = R.resourcesAt(t, now).amounts;
|
||||
const rsv = (keepReserve && this.reserve[t.id]) || null;
|
||||
let n = MIL.maxBatch;
|
||||
for (const r of RES) {
|
||||
const avail = have[r] - (rsv ? Math.min(rsv[r] || 0, have[r] * 0.5) : 0);
|
||||
if (def.cost[r] > 0) n = Math.min(n, Math.floor(avail / def.cost[r]));
|
||||
}
|
||||
// power: new units must fit the steady-state output (units in training count too)
|
||||
const rates = R.ratesPerHour(t);
|
||||
let queuedDraw = 0;
|
||||
for (const b of this.sim.view.trainQueue(t.id)) queuedDraw += R.unitDef(b.unit).draw * b.count;
|
||||
const room = rates.powerNet - queuedDraw - 1;
|
||||
if (def.draw > 0) n = Math.min(n, Math.floor(Math.max(0, room) / def.draw));
|
||||
return Math.max(0, n);
|
||||
}
|
||||
|
||||
trainSome(t, unit, want, now, keepReserve) {
|
||||
const view = this.sim.view;
|
||||
const def = R.unitDef(unit);
|
||||
if (!def) return 0;
|
||||
if (R.unitMissing(t, unit).length) return 0;
|
||||
if (view.trainQueue(t.id, def.building).length >= MIL.maxTrainQueue) return 0;
|
||||
const n = Math.min(want, this.affordable(t, unit, now, keepReserve), 400);
|
||||
if (n < 1) return 0;
|
||||
const r = this.call('train', { townId: t.id, unit, count: n });
|
||||
if (r.ok) { this.log.trains += n; return n; }
|
||||
return 0;
|
||||
}
|
||||
|
||||
defenceHave(t) {
|
||||
const home = this.sim.view.home(t.id);
|
||||
return R.defencePower(home, {});
|
||||
}
|
||||
|
||||
military(main, towns, now) {
|
||||
const sim = this.sim, view = sim.view;
|
||||
let t = main;
|
||||
// defence
|
||||
if ((this.arch.defDays > 0 || this.hits.length) && view.level(t, 'noc') >= 1) {
|
||||
const fwm = R.firewallMult(view.level(t, 'firewall'));
|
||||
const target = Math.max(this.arch.defDays * 24 * this.prodTotal(t) * 0.42, // value invested ~ days of production, ~0.42 defence points per resource point
|
||||
this.defMatch(now) / fwm);
|
||||
const have = this.defenceHave(t) + this.queuedDefence(t);
|
||||
if (have < target) {
|
||||
const unit = R.unitMissing(t, 'honeypot').length === 0 ? 'honeypot' : 'soc_analyst';
|
||||
const def = R.unitDef(unit);
|
||||
const want = Math.ceil((target - have) / def.defence);
|
||||
if (this.trainSome(t, unit, want, now, this.arch.armyDays === 0)) t = view.town(t.id);
|
||||
}
|
||||
}
|
||||
// offence
|
||||
if ((this.arch.armyDays > 0 || this.armyOverride) && view.level(t, 'ops_lab') >= 1) {
|
||||
const have = this.armyHave(t);
|
||||
const unit = this.armyOverride ? 'script_crew' : (R.unitMissing(t, 'botnet').length === 0 && this.rng.chance(0.3) ? 'botnet' : 'script_crew');
|
||||
const per = sumRes(R.unitDef('script_crew').cost);
|
||||
const target = this.armyOverride ? this.armyOverride : Math.floor(this.arch.armyDays * 24 * this.prodTotal(t) / per);
|
||||
if (have < target) { if (this.trainSome(t, unit, target - have, now, false)) t = view.town(t.id); }
|
||||
// scouts: a handful
|
||||
if (view.level(t, 'noc') >= 1 && (view.home(t.id).port_scanner || 0) < 6) this.trainSome(t, 'port_scanner', 6 - (view.home(t.id).port_scanner || 0), now, false);
|
||||
this.research(t, now);
|
||||
} else if (this.arch.defDays >= 1 && view.level(t, 'research_lab') >= 3) this.research(t, now);
|
||||
}
|
||||
|
||||
queuedDefence(t) {
|
||||
let v = 0;
|
||||
for (const b of this.sim.view.trainQueue(t.id)) { const d = R.unitDef(b.unit); if (d.role === 'defender') v += d.defence * b.count; }
|
||||
return v;
|
||||
}
|
||||
armyHave(t) {
|
||||
const home = this.sim.view.home(t.id);
|
||||
let n = (home.script_crew || 0) + 2 * (home.botnet || 0);
|
||||
for (const b of this.sim.view.trainQueue(t.id)) if (b.unit === 'script_crew') n += b.count; else if (b.unit === 'botnet') n += 2 * b.count;
|
||||
for (const m of this.sim.view.outgoing(this.operatorId)) { const u = JSON.parse(m.units || '{}'); n += (u.script_crew || 0) + 2 * (u.botnet || 0); }
|
||||
return n;
|
||||
}
|
||||
|
||||
research(t, now) {
|
||||
const view = this.sim.view;
|
||||
if (view.researchBusy(t.id)) return;
|
||||
const levels = view.researchLevels(t.id);
|
||||
const wants = this.arch.armyDays > 0 ? [['script_crew', 'attack'], ['port_scanner', 'defence'], ['script_crew', 'defence']] : [['honeypot', 'defence'], ['soc_analyst', 'defence']];
|
||||
for (const [unit, stat] of wants) {
|
||||
const cur = levels[R.researchKey(unit, stat)] || 0;
|
||||
const plan = R.researchPlan(t, unit, stat, cur, false, now, 0);
|
||||
if (plan.ok) {
|
||||
// research competes with buildings: only when the stock is comfortably above the cost
|
||||
const have = R.resourcesAt(t, now).amounts;
|
||||
if (RES.every((r) => have[r] >= 1.6 * plan.cost[r])) { this.call('research', { townId: t.id, unit, stat }); return; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ scouting and raids
|
||||
// After being hit a player matches the strongest attacker they saw (the report shows its attack power): the defence target
|
||||
// becomes 1.25 x that for the next 5 world-adjusted days. Without --no-adapt only; the base target of the archetype still applies.
|
||||
defMatch(now) {
|
||||
if (!this.sim.opts.adapt) return 0;
|
||||
const win = 5 * DAY / this.sim.world.speed;
|
||||
this.hits = this.hits.filter((h) => now - h.at < win);
|
||||
let a = 0;
|
||||
for (const h of this.hits) a = Math.max(a, h.atk);
|
||||
return 1.25 * a;
|
||||
}
|
||||
|
||||
readReports(now) {
|
||||
const view = this.sim.view;
|
||||
for (const rep of view.reportsFor(this.userId, this.repCursor)) {
|
||||
const d = rep.data;
|
||||
if (rep.type === 'scan' && rep.role === 'attacker' && d.target) {
|
||||
this.scanPending.delete(d.target.id);
|
||||
if (d.success && d.intel) {
|
||||
const units = Object.assign({}, d.intel.units.home || {});
|
||||
for (const g of d.intel.units.stationed || []) for (const k of Object.keys(g.units)) units[k] = (units[k] || 0) + g.units[k];
|
||||
const bld = d.intel.buildings;
|
||||
const lvl = (type) => { if (!bld) return null; const b = bld.find((x) => x.type === type); return b ? b.level : 0; };
|
||||
this.intel.set(d.target.id, { at: rep.at, res: d.intel.resources, units, fw: lvl('firewall'), rack: lvl('rack_hall'), online: d.intel.online, loyalty: d.intel.loyalty });
|
||||
} else this.avoid.set(d.target.id, rep.at + 12 * HOUR / this.sim.world.speed);
|
||||
} else if ((rep.type === 'raid' || rep.type === 'attack' || rep.type === 'takeover') && rep.role === 'attacker' && d.defender && d.defender.town) {
|
||||
if (d.outcome !== 'attacker_won') this.avoid.set(d.defender.town.id, rep.at + 24 * HOUR / this.sim.world.speed);
|
||||
} else if ((rep.type === 'raid' || rep.type === 'attack' || rep.type === 'takeover') && rep.role === 'defender' && d.outcome === 'attacker_won') {
|
||||
this.hits.push({ at: rep.at, atk: d.power ? d.power.attack : 0, fw: d.power ? d.power.firewallLevel : 0 }); // somebody got through: a player answers with more defence
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
raids(main, now) {
|
||||
const sim = this.sim, view = sim.view, world = sim.world;
|
||||
const home = Object.assign({}, view.home(main.id));
|
||||
if (!(home.script_crew || home.botnet)) return;
|
||||
const speed = world.speed;
|
||||
const maxDist = 32;
|
||||
const op = this.op;
|
||||
const others = view.otherTowns(this.operatorId).map((o) => Object.assign(o, { dist: R.distance(main.x, main.y, o.x, o.y) })).filter((o) => o.dist <= maxDist).sort((a, b) => a.dist - b.dist);
|
||||
const myAlliance = op.alliance_id;
|
||||
const A = require('../../server/alliances');
|
||||
const rack = view.level(main, 'rack_hall');
|
||||
let scans = Math.min(home.port_scanner || 0, 6);
|
||||
let sent = 0;
|
||||
const evaluated = [];
|
||||
for (const o of others) {
|
||||
if (this.avoid.get(o.id) > now) continue;
|
||||
if (myAlliance && o.ally === myAlliance) continue;
|
||||
const arriveGuess = now + R.movementMs(o.dist, { script_crew: 1 }, speed);
|
||||
if (R.isProtected(o.prot, arriveGuess)) continue;
|
||||
if (A.pactPartners(sim.db, this.operatorId, o.ownerId)) continue;
|
||||
const info = this.intel.get(o.id);
|
||||
const fresh = info && now - info.at < 10 * HOUR / speed;
|
||||
if (!fresh) {
|
||||
if (scans > 0 && (home.port_scanner || 0) > 0 && !(this.scanPending.get(o.id) > now)) {
|
||||
const r = this.call('sendMovement', { fromTownId: main.id, type: 'scan', toTownId: o.id, units: { port_scanner: 2 > (home.port_scanner || 0) ? 1 : 2 } });
|
||||
if (r.ok) { scans -= 1; home.port_scanner -= r.args.units.port_scanner; this.scanPending.set(o.id, r.out.arriveAt); this.log.scans += 1; }
|
||||
}
|
||||
continue;
|
||||
}
|
||||
evaluated.push({ o, info });
|
||||
}
|
||||
// value each candidate, best loot per travel hour first
|
||||
const cands = [];
|
||||
for (const { o, info } of evaluated) {
|
||||
const fw = info.fw === null || info.fw === undefined ? 3 : info.fw;
|
||||
const rk = info.rack === null || info.rack === undefined ? 3 : info.rack;
|
||||
const defRaw = R.defencePower(info.units, {});
|
||||
const Dv = (defRaw + MIL.defenceBase) * R.firewallMult(fw);
|
||||
const hidden = R.cacheFraction(rk);
|
||||
const lootable = RES.reduce((s, r) => s + info.res[r] * (1 - hidden), 0);
|
||||
if (lootable < 200) continue;
|
||||
cands.push({ o, info, Dv, lootable, score: lootable / Math.max(1, o.dist) });
|
||||
}
|
||||
cands.sort((a, b) => b.score - a.score);
|
||||
for (const c of cands) {
|
||||
if (sent >= 8) break;
|
||||
if (!(home.script_crew || home.botnet)) break;
|
||||
// force: botnets first, then crews, until attack >= 1.3 x defence and the carry covers the loot
|
||||
const units = {};
|
||||
let atk = 0, carry = 0;
|
||||
const order = ['botnet', 'script_crew'];
|
||||
for (const u of order) {
|
||||
const have = home[u] || 0;
|
||||
if (!have) continue;
|
||||
const def = R.unitDef(u);
|
||||
const needAtk = Math.max(0, 1.3 * c.Dv - atk), needCarry = Math.max(0, c.lootable - carry);
|
||||
const n = Math.min(have, Math.max(Math.ceil(needAtk / def.attack), Math.ceil(needCarry / def.carry)));
|
||||
if (n > 0) { units[u] = n; atk += n * def.attack; carry += n * def.carry; }
|
||||
}
|
||||
if (atk < 1.3 * c.Dv) continue;
|
||||
const loot = Math.min(carry, c.lootable);
|
||||
const lossFrac = MIL.raidLossFactor * Math.pow(Math.min(1, c.Dv / atk), MIL.lossExponent);
|
||||
let value = 0; for (const u of Object.keys(units)) value += R.unitValue(u) * units[u];
|
||||
if (loot < 150 || loot < 2.5 * lossFrac * value) continue;
|
||||
const r = this.call('sendMovement', { fromTownId: main.id, type: 'raid', toTownId: c.o.id, units, confirmEndProtection: true });
|
||||
if (r.ok) {
|
||||
for (const u of Object.keys(units)) home[u] -= units[u];
|
||||
this.log.raids += 1; sent += 1;
|
||||
this.avoid.set(c.o.id, now + 3 * HOUR / speed); // the stock is gone, do not hit it again at once
|
||||
this.intel.delete(c.o.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attack incumbent sites for the one-time Hardware bonus (defence is public: the world seed is in /me).
|
||||
farmIncumbents(main, now) {
|
||||
const sim = this.sim, view = sim.view, world = sim.world;
|
||||
if (!this.incCache) {
|
||||
const list = [];
|
||||
const rad = 40;
|
||||
for (let dy = -rad; dy <= rad; dy++) for (let dx = -rad; dx <= rad; dx++) {
|
||||
const x = main.x + dx, y = main.y + dy;
|
||||
if (Math.hypot(dx, dy) > rad) continue;
|
||||
if (R.tileAt(world.seed, world.map_radius, x, y).type === 'incumbent') list.push({ x, y, dist: Math.hypot(dx, dy) });
|
||||
}
|
||||
this.incCache = list.sort((a, b) => a.dist - b.dist);
|
||||
}
|
||||
const taken = new Set(sim.db.all('SELECT x, y FROM incumbent_takes WHERE operator_id = ?', this.operatorId).map((r) => r.x + ',' + r.y));
|
||||
const busy = new Set(view.outgoing(this.operatorId).filter((m) => m.type === 'attack' && !m.toTownId).map((m) => m.tx + ',' + m.ty));
|
||||
const home = Object.assign({}, view.home(main.id));
|
||||
const age = R.worldAgeDays(world.start_at, now, world.speed);
|
||||
let sent = 0;
|
||||
for (const s of this.incCache) {
|
||||
if (sent >= 2) break;
|
||||
const k = s.x + ',' + s.y;
|
||||
if (taken.has(k) || busy.has(k)) continue;
|
||||
if (this.avoid.get('inc' + k) > now) continue;
|
||||
const defence = R.incumbentDefence(world.seed, s.x, s.y, age + s.dist / 8 / 24 * world.speed);
|
||||
const units = {};
|
||||
let atk = 0;
|
||||
for (const u of ['botnet', 'script_crew']) {
|
||||
const have = home[u] || 0;
|
||||
if (!have || atk >= 2.4 * defence) continue;
|
||||
const def = R.unitDef(u);
|
||||
const n = Math.min(have, Math.ceil((2.4 * defence - atk) / def.attack));
|
||||
if (n > 0) { units[u] = n; atk += n * def.attack; }
|
||||
}
|
||||
if (atk < 2.4 * defence) continue;
|
||||
const lossFrac = Math.pow(defence / atk, MIL.lossExponent);
|
||||
let value = 0; for (const u of Object.keys(units)) value += R.unitValue(u) * units[u];
|
||||
if (D.INCUMBENT.hardwareBonus < 1.5 * lossFrac * value) continue;
|
||||
const r = this.call('sendMovement', { fromTownId: main.id, type: 'attack', x: s.x, y: s.y, units });
|
||||
if (r.ok) { for (const u of Object.keys(units)) home[u] -= units[u]; sent += 1; this.log.incumbents += 1; this.avoid.set('inc' + k, now + 2 * HOUR); }
|
||||
}
|
||||
}
|
||||
|
||||
// Hostile takeover of other operators' non-capital POPs: scan, attack with an M&A team, repeat while loyalty is low.
|
||||
conquer(main, towns, now) {
|
||||
const sim = this.sim, view = sim.view, world = sim.world;
|
||||
if (view.level(main, 'rollout_depot') < D.UNITS.ma_team.requires[0].level) return;
|
||||
const home = Object.assign({}, view.home(main.id));
|
||||
const ma = home.ma_team || 0;
|
||||
const A = require('../../server/alliances');
|
||||
const gate = R.footprintGate(towns.length, view.footprint(this.operatorId, now));
|
||||
if (!gate.ok) return;
|
||||
// keep one M&A team per wave in stock
|
||||
const queued = view.trainQueue(main.id, 'rollout_depot').reduce((s, b) => s + (b.unit === 'ma_team' ? b.count : 0), 0);
|
||||
if (ma + queued < 2) this.trainSome(main, 'ma_team', 2 - ma - queued, now, false);
|
||||
if (!ma) return;
|
||||
const others = view.otherTowns(this.operatorId).filter((o) => !o.isCapital && R.distance(main.x, main.y, o.x, o.y) <= 30 && !R.isProtected(o.prot, now + 12 * HOUR));
|
||||
others.sort((a, b) => R.distance(main.x, main.y, a.x, a.y) - R.distance(main.x, main.y, b.x, b.y));
|
||||
for (const o of others.slice(0, 5)) {
|
||||
if (A.pactPartners(sim.db, this.operatorId, o.ownerId)) continue;
|
||||
const info = this.intel.get(o.id);
|
||||
if (!info) continue;
|
||||
const fw = info.fw === null || info.fw === undefined ? 3 : info.fw;
|
||||
const Dv = (R.defencePower(info.units, {}) + MIL.defenceBase) * R.firewallMult(fw);
|
||||
const units = { ma_team: 1 };
|
||||
let atk = 0;
|
||||
for (const u of ['botnet', 'script_crew']) {
|
||||
const have = home[u] || 0; if (!have) continue;
|
||||
const n = Math.min(have, Math.ceil(Math.max(0, 1.4 * Dv - atk) / R.unitDef(u).attack));
|
||||
if (n > 0) { units[u] = n; atk += n * R.unitDef(u).attack; }
|
||||
}
|
||||
if (atk < 1.4 * Dv) continue;
|
||||
const r = this.call('sendMovement', { fromTownId: main.id, type: 'takeover', toTownId: o.id, units, confirmEndProtection: true });
|
||||
if (r.ok) { this.log.takeovers += 1; home.ma_team -= 1; for (const u of Object.keys(units)) if (u !== 'ma_team') home[u] -= units[u]; this.intel.delete(o.id); return; }
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ expansion
|
||||
expand(towns, now) {
|
||||
const sim = this.sim, view = sim.view, world = sim.world;
|
||||
const own = towns.length;
|
||||
if (own >= this.arch.maxPops) return;
|
||||
const main = towns[0];
|
||||
const fields = view.fieldLevels(main);
|
||||
const F = this.fieldF(fields);
|
||||
if (F < this.arch.popF) return;
|
||||
const fp = view.footprint(this.operatorId, now);
|
||||
const gate = R.footprintGate(own, fp);
|
||||
// crews wherever they are at home
|
||||
let holder = null, have = 0;
|
||||
for (const t of towns) { const n = view.home(t.id).rollout_crew || 0; if (n > have) { have = n; holder = t; } }
|
||||
const depotTown = towns.find((t) => view.level(t, 'rollout_depot') >= 1);
|
||||
if (!depotTown) return;
|
||||
const queued = view.trainQueue(depotTown.id, 'rollout_depot').reduce((s, b) => s + (b.unit === 'rollout_crew' ? b.count : 0), 0);
|
||||
if (have + queued < D.EXPANSION.crews && gate.have >= 0.8 * gate.need) {
|
||||
const fresh = view.town(depotTown.id);
|
||||
this.trainSome(fresh, 'rollout_crew', D.EXPANSION.crews - have - queued, now, false);
|
||||
}
|
||||
if (!gate.ok || have < D.EXPANSION.crews || !holder) return;
|
||||
// choose a tile
|
||||
let best = null, bestScore = -1;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const base = towns[this.rng.int(0, towns.length - 1)];
|
||||
const ang = this.rng() * Math.PI * 2, rr = 3 + this.rng() * 11;
|
||||
const x = Math.round(base.x + Math.cos(ang) * rr), y = Math.round(base.y + Math.sin(ang) * rr);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||
if (tile.type !== 'land' || R.isBackboneSite(world.seed, world.map_radius, x, y)) continue;
|
||||
if (sim.db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y)) continue;
|
||||
let nearest = Infinity; for (const t of towns) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
|
||||
if (nearest > D.EXPANSION.maxDistance) continue;
|
||||
const b = R.ruralBonus(world.seed, world.map_radius, x, y);
|
||||
const score = b.fiber + b.hardware + b.capital + this.rng() * 0.1;
|
||||
if (score > bestScore) { bestScore = score; best = { x, y }; }
|
||||
}
|
||||
if (!best) return;
|
||||
const r = this.call('sendMovement', { fromTownId: holder.id, type: 'settle', x: best.x, y: best.y, units: { rollout_crew: D.EXPANSION.crews }, wild: ['sales_office', 'cable_yard'] });
|
||||
if (r.ok) this.log.settles += 1;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ trade
|
||||
trade(towns, now) {
|
||||
const mode = this.arch.trade;
|
||||
if (mode === 'none') return;
|
||||
const sim = this.sim, view = sim.view, world = sim.world;
|
||||
const db = sim.db;
|
||||
for (const t0 of towns) {
|
||||
const lvl = view.level(t0, D.TRANSPORT.building);
|
||||
if (lvl < 1) continue;
|
||||
let t = t0;
|
||||
const cur = R.resourcesAt(t, now);
|
||||
const cap = cur.caps.fiber;
|
||||
const fill = {}; for (const r of RES) fill[r] = cur.amounts[r] / cap;
|
||||
const sorted = RES.slice().sort((a, b) => fill[b] - fill[a]);
|
||||
const surplus = sorted[0], deficit = sorted[2];
|
||||
if (fill[surplus] - fill[deficit] < 0.35 || cur.amounts[surplus] < 300) continue;
|
||||
const reach = R.tradeReach(lvl);
|
||||
// take a matching open offer: they give what we lack for what we have too much of
|
||||
const offers = db.all("SELECT * FROM trade_offers WHERE world_id = ? AND status = 'open' AND operator_id != ? AND give_res = ? AND want_res = ? ORDER BY id DESC LIMIT 40", world.id, this.operatorId, deficit, surplus);
|
||||
let done = false;
|
||||
for (const o of offers) {
|
||||
const poster = db.get('SELECT x, y FROM towns WHERE id = ?', o.town_id);
|
||||
if (!poster) continue;
|
||||
const dist = R.distance(t.x, t.y, poster.x, poster.y);
|
||||
if (!R.tradeInRange(dist, o.max_distance, lvl)) continue;
|
||||
if (o.want_amount > cur.amounts[surplus] * 0.5) continue;
|
||||
if (o.give_amount < o.want_amount * 0.9) continue; // not worse than ~1:1
|
||||
const r = this.call('tradeAccept', { offerId: o.id, townId: t.id });
|
||||
if (r.ok) { this.log.accepts += 1; done = true; break; }
|
||||
}
|
||||
if (done || mode !== 'active') continue;
|
||||
// post one of our own (one open offer per POP at a time)
|
||||
const open = db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE town_id = ? AND status = 'open'", t.id).n;
|
||||
if (open >= 1) continue;
|
||||
const give = Math.min(D.TRANSPORT.capacityPerLink, Math.floor((cur.amounts[surplus] - 0.4 * cap) * 0.6));
|
||||
if (give < 100) continue;
|
||||
const want = Math.min(D.TRANSPORT.capacityPerLink, Math.max(50, Math.floor(give * (0.9 + this.rng() * 0.2))));
|
||||
const r = this.call('tradeOffer', { townId: t.id, giveRes: surplus, giveAmount: give, wantRes: deficit, wantAmount: want, maxDistance: Math.max(10, Math.min(reach, 40)) });
|
||||
if (r.ok) this.log.offers += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ alliances and diplomacy
|
||||
social(now) {
|
||||
const sim = this.sim, db = sim.db, view = sim.view, world = sim.world;
|
||||
const A = require('../../server/alliances');
|
||||
const op = this.op;
|
||||
const peering = view.peering(this.operatorId);
|
||||
if (!op.alliance_id) {
|
||||
// accept the first invite
|
||||
const inv = db.get("SELECT id, expires_at FROM alliance_invites WHERE operator_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id LIMIT 1", this.operatorId, now);
|
||||
if (inv && peering >= 1) { const r = this.call('allianceInviteAnswer', { inviteId: inv.id, accept: true }); if (r.ok) return; }
|
||||
if (this.arch.alliance === 'founder' && peering >= 1 && now - this.firstAllianceTry > 6 * HOUR) {
|
||||
this.firstAllianceTry = now;
|
||||
const r = this.call('allianceCreate', { worldId: world.id, name: 'Alliance ' + this.name, tag: 'A' + this.idx });
|
||||
if (r.ok) sim.alliancePlans.set(r.out.allianceId, { leaderBot: this.idx, created: now });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const m = A.membership(db, this.operatorId);
|
||||
if (!m || m.role !== 'leader') return;
|
||||
const alliance = A.getAlliance(db, m.alliance_id);
|
||||
// recruit: nearby operators without an alliance that have a Peering office
|
||||
const count = A.memberCount(db, alliance.id);
|
||||
if (count < A.effectiveCap(db, alliance)) {
|
||||
const pending = db.get("SELECT COUNT(*) AS n FROM alliance_invites WHERE alliance_id = ? AND status = 'pending' AND expires_at > ?", alliance.id, now).n;
|
||||
if (pending < 4) {
|
||||
const main = view.towns(this.operatorId)[0];
|
||||
const cands = db.all(`SELECT o.id, t.x, t.y FROM operators o JOIN towns t ON t.owner_id = o.id AND t.is_capital = 1 WHERE o.world_id = ? AND o.alliance_id IS NULL AND o.id != ?
|
||||
AND EXISTS (SELECT 1 FROM buildings b JOIN towns tt ON tt.id = b.town_id WHERE tt.owner_id = o.id AND b.type = 'peering_office' AND b.level >= 1)
|
||||
AND NOT EXISTS (SELECT 1 FROM alliance_invites i WHERE i.alliance_id = ? AND i.operator_id = o.id AND i.status = 'pending' AND i.expires_at > ?)`, world.id, this.operatorId, alliance.id, now)
|
||||
.map((c) => ({ id: c.id, d: R.distance(main.x, main.y, c.x, c.y) })).sort((a, b) => a.d - b.d).slice(0, 4 - pending);
|
||||
for (const c of cands) this.call('allianceInvite', { allianceId: alliance.id, operatorId: c.id });
|
||||
}
|
||||
}
|
||||
// diplomacy, at most once per simulated day: answer proposals, propose a pact to the nearest neighbour, raiders declare war now and then
|
||||
const day = Math.floor((now - sim.t0) / DAY);
|
||||
if (day === this.lastDiploDay) return;
|
||||
this.lastDiploDay = day;
|
||||
for (const p of db.all("SELECT id, state FROM alliance_proposals WHERE to_id = ? AND status = 'pending' AND expires_at > ?", alliance.id, now)) {
|
||||
this.call('diploAnswer', { proposalId: p.id, accept: p.state === 'nap' ? this.rng.chance(0.7) : this.rng.chance(0.4) });
|
||||
}
|
||||
if (count >= 3 && this.rng.chance(0.4)) {
|
||||
const others = db.all('SELECT a.id FROM alliances a WHERE a.world_id = ? AND a.id != ? ORDER BY a.id', world.id, alliance.id);
|
||||
if (others.length) {
|
||||
const o = this.rng.pick(others);
|
||||
const rel = A.relationBetween(db, alliance.id, o.id);
|
||||
if (rel === 'neutral') this.call('diploPropose', { allianceId: alliance.id, targetId: o.id, state: this.rng.chance(0.15) ? 'war' : (this.rng.chance(0.3) ? 'confed' : 'nap') });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Bot, ARCHETYPES, clamp, mulCost, sumRes };
|
||||
150
tools/bot/collector.js
Normal file
150
tools/bot/collector.js
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Incremental ingestion of what the server wrote down: reports (battles, scans, settles), and the notifications that carry
|
||||
* numbers the ledger needs (cargo lost at delivery, decommissioned units). Reports are cleaned after 14 days, so the harness
|
||||
* ingests at least once per simulated day and keeps its own totals. Everything here only READS the database.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { bump, addInto, DAY } = require('./util');
|
||||
|
||||
const RES = D.RESOURCES;
|
||||
const lootValue = (l) => RES.reduce((s, r) => s + ((l && l[r]) || 0), 0);
|
||||
const unitsValue = (u) => Object.keys(u || {}).reduce((s, k) => s + (R.unitDef(k) ? R.unitValue(k) * u[k] : 0), 0);
|
||||
|
||||
function newOpStats() { return { raids: 0, raidWins: 0, raidLoot: 0, raidLostValue: 0, attacks: 0, attackWins: 0, hit: 0, hitLoot: 0, defLostValue: 0, scans: 0, scanOk: 0, incumbent: 0, incumbentWins: 0, incumbentHw: 0 }; }
|
||||
|
||||
class Collector {
|
||||
constructor(db) {
|
||||
this.db = db;
|
||||
// Cursors are (created_at, ids seen at that instant), not plain ids: the report cleanup deletes every expired report and SQLite then
|
||||
// reuses low ids (rowid without AUTOINCREMENT), so "id > last id" would silently skip new reports in a long run.
|
||||
this.rep = { at: 0, seen: new Set() }; this.noteCursor = 0;
|
||||
this.foundedTowns = 0;
|
||||
this.unitsLost = {}; // unit -> count, every way of losing units that the ledger knows about
|
||||
this.unitsConsumed = {}; // crews/teams used up (not battle losses)
|
||||
this.byType = {}; // report type -> count
|
||||
this.battles = { raid: { n: 0, att: 0, loot: 0, lootRes: { fiber: 0, hardware: 0, capital: 0 }, attLost: 0, defLost: 0 }, attack: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 }, takeover: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 } };
|
||||
this.raidSamples = []; // { loot, attLostValue, defLostValue, A, D, win, targetAgeDays, undefended }
|
||||
this.takeovers = { attempted: 0, dropped: 0, blocked: {}, captured: 0, loyaltyDropped: 0 };
|
||||
this.scans = { n: 0, ok: 0, failed: 0, detected: 0, revealed: 0 };
|
||||
this.incumbent = { n: 0, wins: 0, hardware: 0, attLostValue: 0 };
|
||||
this.landing = { n: 0, taken: 0, attLostValue: 0 };
|
||||
this.movementFailed = {};
|
||||
this.settles = { ok: 0 };
|
||||
this.siege = { n: 0, levels: 0 };
|
||||
this.ops = new Map(); // operatorId -> opStats
|
||||
this.notes = {}; // notification type -> count
|
||||
this.cargoLostTotal = { fiber: 0, hardware: 0, capital: 0 };
|
||||
this.cargoLostEvents = 0;
|
||||
this.decommissioned = {};
|
||||
this.unitsOfflineNotes = 0;
|
||||
this.opCreated = new Map();
|
||||
this.bounces = 0;
|
||||
}
|
||||
|
||||
op(id) { if (!this.ops.has(id)) this.ops.set(id, newOpStats()); return this.ops.get(id); }
|
||||
created(opId) {
|
||||
if (!this.opCreated.has(opId)) { const o = this.db.get('SELECT created_at FROM operators WHERE id = ?', opId); this.opCreated.set(opId, o ? o.created_at : 0); }
|
||||
return this.opCreated.get(opId);
|
||||
}
|
||||
|
||||
ingest(ledger) {
|
||||
const db = this.db;
|
||||
for (const rep of db.all('SELECT id, type, created_at, data FROM reports WHERE created_at >= ? ORDER BY created_at, id', this.rep.at)) {
|
||||
if (rep.created_at === this.rep.at && this.rep.seen.has(rep.id)) continue;
|
||||
if (rep.created_at > this.rep.at) { this.rep.at = rep.created_at; this.rep.seen = new Set(); }
|
||||
this.rep.seen.add(rep.id);
|
||||
bump(this.byType, rep.type);
|
||||
const d = JSON.parse(rep.data);
|
||||
switch (rep.type) {
|
||||
case 'raid': case 'attack': case 'takeover': this.battle(rep, d); break;
|
||||
case 'scan': this.scan(d); break;
|
||||
case 'scan_detected': this.scans.detected += 1; if (d.identityRevealed) this.scans.revealed += 1; break;
|
||||
case 'incumbent': this.incumbentReport(d); break;
|
||||
case 'landing': this.landingReport(d); break;
|
||||
case 'settle': if (d.success) { this.foundedTowns += 1; bump(this.unitsConsumed, D.EXPANSION.settleUnit, D.EXPANSION.crews); this.settles.ok += 1; } break;
|
||||
case 'movement_failed': bump(this.movementFailed, d.movementType + ':' + d.reason); this.bounces += 1; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
const rows = db.all("SELECT id, type, payload FROM notifications WHERE id > ? AND type IN ('transport_arrived','movement_returned','units_decommissioned','units_offline') ORDER BY id", this.noteCursor);
|
||||
for (const n of rows) {
|
||||
this.noteCursor = n.id;
|
||||
const p = JSON.parse(n.payload);
|
||||
bump(this.notes, n.type);
|
||||
if (n.type === 'units_decommissioned') { addInto(this.decommissioned, p.units); addInto(this.unitsLost, p.units); }
|
||||
else if (n.type === 'units_offline') this.unitsOfflineNotes += 1;
|
||||
else if (p.cargoLost) {
|
||||
let any = false;
|
||||
for (const r of RES) if (p.cargoLost[r]) { this.cargoLostTotal[r] += p.cargoLost[r]; ledger.sinkLost[r] += p.cargoLost[r]; any = true; }
|
||||
if (any) { ledger.lostEvents += 1; this.cargoLostEvents += 1; }
|
||||
}
|
||||
}
|
||||
// notifications are numbered independently of the filter above: move the cursor past rows we skipped
|
||||
const top = db.get('SELECT MAX(id) AS m FROM notifications').m || 0;
|
||||
if (top > this.noteCursor) this.noteCursor = top;
|
||||
}
|
||||
|
||||
battle(rep, d) {
|
||||
const kind = rep.type;
|
||||
const b = this.battles[kind];
|
||||
b.n += 1;
|
||||
const win = d.outcome === 'attacker_won';
|
||||
const attLost = d.attacker.units.lost || {};
|
||||
const attLostVal = unitsValue(attLost);
|
||||
let defLost = {};
|
||||
for (const g of d.defender.groups || []) addInto(defLost, g.lost);
|
||||
const defLostVal = unitsValue(defLost);
|
||||
addInto(this.unitsLost, attLost); addInto(this.unitsLost, defLost);
|
||||
const loot = lootValue(d.loot);
|
||||
if (win) b.att += 1;
|
||||
b.loot += loot; b.attLost += attLostVal; b.defLost += defLostVal;
|
||||
if (kind === 'raid') addInto(b.lootRes, d.loot);
|
||||
const aId = d.attacker.operator.id, dId = d.defender.operator.id;
|
||||
const a = this.op(aId), df = this.op(dId);
|
||||
if (kind === 'raid') { a.raids += 1; if (win) a.raidWins += 1; a.raidLoot += loot; a.raidLostValue += attLostVal; }
|
||||
else { a.attacks += 1; if (win) a.attackWins += 1; a.raidLoot += loot; a.raidLostValue += attLostVal; }
|
||||
df.hit += 1; df.hitLoot += loot; df.defLostValue += defLostVal;
|
||||
if (d.siege) { this.siege.n += 1; this.siege.levels += d.siege.from - d.siege.to; }
|
||||
if (d.takeover) {
|
||||
const t = d.takeover;
|
||||
this.takeovers.attempted += 1;
|
||||
if (t.blocked) bump(this.takeovers.blocked, t.blocked);
|
||||
if (t.drop > 0) { this.takeovers.dropped += 1; this.takeovers.loyaltyDropped += t.drop; bump(this.unitsConsumed, D.EXPANSION.conquestUnit, 1); }
|
||||
if (t.captured) this.takeovers.captured += 1;
|
||||
}
|
||||
if (kind === 'raid') {
|
||||
const defenderHome = (d.defender.groups || []).reduce((s, g) => s + R.defencePower(g.sent, {}), 0);
|
||||
this.raidSamples.push({
|
||||
loot, attLost: attLostVal, defLost: defLostVal, A: d.power.attack, D: d.power.defence, win,
|
||||
targetAgeDays: (rep.created_at - this.created(dId)) / DAY, undefended: defenderHome <= 0, at: rep.created_at, attacker: aId, defender: dId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
scan(d) {
|
||||
this.scans.n += 1;
|
||||
if (d.success) this.scans.ok += 1; else this.scans.failed += 1;
|
||||
addInto(this.unitsLost, (d.scanners && d.scanners.lost) || {});
|
||||
}
|
||||
incumbentReport(d) {
|
||||
this.incumbent.n += 1;
|
||||
if (d.outcome === 'attacker_won') this.incumbent.wins += 1;
|
||||
if (d.bonus) this.incumbent.hardware += d.bonus.hardware || 0;
|
||||
const lost = (d.attacker.units && d.attacker.units.lost) || {};
|
||||
this.incumbent.attLostValue += unitsValue(lost);
|
||||
addInto(this.unitsLost, lost);
|
||||
const a = this.op(d.attacker.operator.id);
|
||||
a.incumbent += 1; if (d.outcome === 'attacker_won') a.incumbentWins += 1; if (d.bonus) a.incumbentHw += d.bonus.hardware || 0;
|
||||
}
|
||||
landingReport(d) {
|
||||
this.landing.n += 1;
|
||||
if (d.taken) this.landing.taken += 1;
|
||||
const lost = (d.attacker.units && d.attacker.units.lost) || {};
|
||||
this.landing.attLostValue += unitsValue(lost);
|
||||
addInto(this.unitsLost, lost);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Collector, lootValue, unitsValue };
|
||||
226
tools/bot/endgame.js
Normal file
226
tools/bot/endgame.js
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
'use strict';
|
||||
/*
|
||||
* End game bots: once the landing sites open (world age >= ENDGAME.openDay) every alliance with enough members tries for the
|
||||
* backbone, coordinated through a plan kept in memory (what an alliance would agree in its chat):
|
||||
*
|
||||
* 1. site the site that is cheapest to take for the alliance (static defence, a little distance weight)
|
||||
* 2. striker ONE member with an Ops lab trains an army whose attack beats the site's defence on its own (every attack is
|
||||
* resolved separately against the full static defence, so attacks cannot be added up) and attacks
|
||||
* 3. holders once the alliance holds a site every member ships its spare Fiber/Hardware/Capital to it (transport links, 500
|
||||
* each), anyone starts the next Backbone node level when the stockpile pays for it
|
||||
*
|
||||
* Everything goes through the normal commands; the plan only decides who does what.
|
||||
*/
|
||||
const D = require('../../public/js/data.js');
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { DAY, HOUR } = require('./util');
|
||||
|
||||
const RES = D.RESOURCES;
|
||||
const EG = D.ENDGAME;
|
||||
|
||||
function createEndgame(sim) {
|
||||
const E = require('../../server/endgame');
|
||||
const A = require('../../server/alliances');
|
||||
const M = require('../../server/military/movements');
|
||||
const log = { opened: null, plans: 0, strikes: 0, strikeWins: 0, shipments: 0, shipped: { fiber: 0, hardware: 0, capital: 0 }, builds: 0, buildErrors: {}, strikeSkips: {}, firstCapture: null, shipLinks: 0, wins: null };
|
||||
const plans = sim.alliancePlans;
|
||||
const bump = (o, k) => { o[k] = (o[k] || 0) + 1; };
|
||||
|
||||
const isOpen = (now) => E.isOpen(sim.world, now);
|
||||
|
||||
function members(allianceId) {
|
||||
return sim.bots.filter((b) => { const op = sim.view.operator(b.operatorId); return op && op.alliance_id === allianceId; });
|
||||
}
|
||||
|
||||
function centroid(allianceId) {
|
||||
const ms = members(allianceId);
|
||||
let x = 0, y = 0, n = 0;
|
||||
for (const b of ms) { const t = sim.view.towns(b.operatorId)[0]; if (t) { x += t.x; y += t.y; n += 1; } }
|
||||
return n ? { x: x / n, y: y / n } : { x: 0, y: 0 };
|
||||
}
|
||||
|
||||
// What the status endpoint shows: every site, with the stored row if somebody touched it, else the incumbent's untouched site.
|
||||
function siteRows(now) {
|
||||
return E.siteStates(sim.db, sim.world, now).map(({ site, row }) => row || { id: null, idx: site.index, x: site.x, y: site.y, holder_alliance_id: null, level: 0, build_to: null, fiber: 0, hardware: 0, capital: 0 });
|
||||
}
|
||||
|
||||
const defenceAt = (s, at) => R.backboneDefence(sim.world.seed, s.x, s.y, E.ageDays(sim.world, at), s.level);
|
||||
|
||||
function choose(plan, allianceId, now) {
|
||||
const c = centroid(allianceId);
|
||||
let best = null, bestScore = Infinity;
|
||||
for (const s of siteRows(now)) {
|
||||
if (s.holder_alliance_id === allianceId) { best = s; bestScore = -1; break; }
|
||||
if (s.holder_alliance_id) {
|
||||
const rel = A.relationBetween(sim.db, allianceId, s.holder_alliance_id);
|
||||
if (rel === 'nap' || rel === 'confed') continue;
|
||||
}
|
||||
const score = defenceAt(s, now + 6 * HOUR) * (1 + R.distance(c.x, c.y, s.x, s.y) / 60);
|
||||
if (score < bestScore) { bestScore = score; best = s; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// The member who strikes: highest production with an Ops lab (or the best candidate to get one).
|
||||
function pickStriker(allianceId) {
|
||||
let best = null, bestScore = -1;
|
||||
for (const b of members(allianceId)) {
|
||||
if (b.archetype === 'turtle') continue;
|
||||
const t = sim.view.towns(b.operatorId)[0];
|
||||
if (!t) continue;
|
||||
const prod = R.ratesPerHour(t);
|
||||
const score = (prod.fiber + prod.hardware + prod.capital) * (1 + sim.view.level(t, 'ops_lab'));
|
||||
if (score > bestScore) { bestScore = score; best = b; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function armyAttack(t, home, research) {
|
||||
return R.attackPower({ script_crew: home.script_crew || 0, botnet: home.botnet || 0 }, research);
|
||||
}
|
||||
|
||||
function step(bot, towns, now) {
|
||||
if (!isOpen(now) || sim.world.status === 'ended') return;
|
||||
if (log.opened === null) log.opened = (now - sim.t0) / DAY;
|
||||
const op = bot.op;
|
||||
if (!op || !op.alliance_id) return;
|
||||
const allianceId = op.alliance_id;
|
||||
let plan = plans.get(allianceId);
|
||||
if (!plan) { plan = { created: now }; plans.set(allianceId, plan); }
|
||||
const mem = A.memberCount(sim.db, allianceId);
|
||||
if (mem < sim.opts.endgameMinMembers) return;
|
||||
const main = towns[0];
|
||||
|
||||
// (re)plan once a day
|
||||
const day = Math.floor((now - sim.t0) / DAY);
|
||||
if (plan.planDay !== day) {
|
||||
plan.planDay = day;
|
||||
if (!plan.siteHeld) {
|
||||
const site = choose(plan, allianceId, now);
|
||||
if (site) { if (!plan.site || plan.site.idx !== site.idx) log.plans += 1; plan.site = { idx: site.idx, x: site.x, y: site.y }; }
|
||||
}
|
||||
const striker = pickStriker(allianceId);
|
||||
if (striker) plan.striker = striker.idx;
|
||||
}
|
||||
if (!plan.site) return;
|
||||
const row = siteRows(now).find((r) => r.idx === plan.site.idx);
|
||||
plan.siteHeld = !!(row && row.holder_alliance_id === allianceId);
|
||||
|
||||
if (plan.siteHeld) { hold(bot, towns, row, now); return; }
|
||||
// not ours yet: the striker prepares and attacks, the others carry on with their economy
|
||||
bot.egForce = null;
|
||||
if (plan.striker === bot.idx) strike(bot, main, plan, row, now);
|
||||
}
|
||||
|
||||
// ---- striker
|
||||
function strike(bot, main, plan, row, now) {
|
||||
const view = sim.view;
|
||||
const site = row || { x: plan.site.x, y: plan.site.y, level: 0 };
|
||||
const flight = R.movementMs(R.distance(main.x, main.y, site.x, site.y), { script_crew: 1 }, sim.world.speed);
|
||||
const dv = defenceAt({ x: site.x, y: site.y, level: site.level || 0 }, now + flight);
|
||||
const research = view.researchLevels(main.id);
|
||||
const mult = R.researchMult(R.researchLevel(research, 'script_crew', 'attack'));
|
||||
const need = Math.ceil(1.12 * dv / (R.unitDef('script_crew').attack * mult));
|
||||
bot.egForce = { ops_lab: 6, research_lab: 5, noc: 1 }; // build what the army needs
|
||||
bot.armyOverride = need;
|
||||
const home = view.home(main.id);
|
||||
const attack = armyAttack(main, home, research);
|
||||
if (attack >= 1.08 * dv) {
|
||||
const units = {};
|
||||
for (const u of ['script_crew', 'botnet']) if (home[u]) units[u] = home[u];
|
||||
const r = bot.call('sendMovement', { fromTownId: main.id, type: 'attack', x: site.x, y: site.y, units });
|
||||
if (r.ok) log.strikes += 1; else bump(log.strikeSkips, r.code);
|
||||
} else bump(log.strikeSkips, 'army_short');
|
||||
}
|
||||
|
||||
// ---- holders: ship and build
|
||||
function hold(bot, towns, row, now) {
|
||||
const view = sim.view;
|
||||
// start the next level when the stockpile pays for it
|
||||
if (!row.build_to && row.level < EG.maxLevel) {
|
||||
const cost = R.backboneCost(row.level + 1);
|
||||
if (RES.every((r) => row[r] >= cost[r])) {
|
||||
const r = bot.call('backboneBuild', { siteId: row.id });
|
||||
if (r.ok) log.builds += 1; else bump(log.buildErrors, r.code);
|
||||
}
|
||||
}
|
||||
if (row.level >= EG.maxLevel) return;
|
||||
// ship: need = next level (and the one after) minus what is already there / on the road
|
||||
const want = {};
|
||||
const c1 = R.backboneCost(row.level + 1), c2 = R.backboneCost(Math.min(EG.maxLevel, row.level + 2));
|
||||
for (const r of RES) want[r] = Math.max(0, c1[r] + c2[r] - row[r]);
|
||||
const roads = sim.db.all("SELECT cargo FROM movements WHERE status = 'out' AND type = 'transport' AND json_extract(extra, '$.siteId') = ?", row.id);
|
||||
for (const m of roads) { const cg = JSON.parse(m.cargo); for (const r of RES) want[r] = Math.max(0, want[r] - (cg[r] || 0)); }
|
||||
for (const t0 of towns) {
|
||||
let t = t0;
|
||||
const lvl = view.level(t, D.TRANSPORT.building);
|
||||
for (let i = 0; i < lvl; i++) {
|
||||
if (M.activeLinks(sim.db, t.id) >= lvl) break;
|
||||
const cur = R.resourcesAt(t, now);
|
||||
const cap = cur.caps.fiber;
|
||||
const cargo = {};
|
||||
let room = D.TRANSPORT.capacityPerLink;
|
||||
const order = RES.slice().sort((a, b) => want[b] - want[a]);
|
||||
for (const r of order) {
|
||||
const spare = Math.max(0, cur.amounts[r] - 0.12 * cap);
|
||||
const give = Math.floor(Math.min(room, spare, want[r]));
|
||||
if (give > 0) { cargo[r] = give; room -= give; }
|
||||
}
|
||||
let total = 0; for (const r of RES) total += cargo[r] || 0;
|
||||
if (total < 100) break;
|
||||
const res = bot.call('backboneShip', { siteId: row.id, fromTownId: t.id, cargo });
|
||||
if (!res.ok) break;
|
||||
log.shipments += 1; log.shipLinks += 1;
|
||||
for (const r of RES) { log.shipped[r] += cargo[r] || 0; want[r] = Math.max(0, want[r] - (cargo[r] || 0)); }
|
||||
t = view.town(t.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const x0 = (site) => { const p = R.backboneSites(sim.world.seed, sim.world.map_radius).find((q) => q.index === site.idx); return p || { x: 0, y: 0 }; };
|
||||
|
||||
function summary(now) {
|
||||
const world = sim.db.get('SELECT * FROM worlds WHERE id = ?', sim.world.id);
|
||||
const age = E.ageDays(world, now);
|
||||
if (age < EG.openDay && !log.opened) return { open: false, ageDays: age, openDay: EG.openDay };
|
||||
const sites = sim.db.all('SELECT * FROM landing_sites WHERE world_id = ? ORDER BY idx', sim.world.id).map((s) => {
|
||||
const contrib = sim.db.get('SELECT COALESCE(SUM(fiber),0) AS f, COALESCE(SUM(hardware),0) AS h, COALESCE(SUM(capital),0) AS c, COUNT(*) AS n FROM landing_contributions WHERE site_id = ?', s.id);
|
||||
const a = s.holder_alliance_id ? sim.db.get('SELECT tag FROM alliances WHERE id = ?', s.holder_alliance_id) : null;
|
||||
const sunk = { fiber: 0, hardware: 0, capital: 0 };
|
||||
for (let l = 1; l <= s.level; l++) { const c = R.backboneCost(l); for (const r of RES) sunk[r] += c[r]; }
|
||||
const total = contrib.f + contrib.h + contrib.c;
|
||||
const sinceTaken = s.taken_at ? Math.max(1e-9, (now - s.taken_at) / DAY) : null;
|
||||
const rest = { fiber: 0, hardware: 0, capital: 0 };
|
||||
for (let l = s.level + 1; l <= EG.maxLevel; l++) { const c = R.backboneCost(l); for (const r of RES) rest[r] += c[r]; }
|
||||
const restTotal = rest.fiber + rest.hardware + rest.capital;
|
||||
const rate = sinceTaken ? total / sinceTaken : 0;
|
||||
return { idx: s.idx, level: s.level, holder: a ? a.tag : null, takenAt: s.taken_at ? (s.taken_at - sim.t0) / DAY : null, stock: { fiber: s.fiber, hardware: s.hardware, capital: s.capital }, contributors: contrib.n, shippedIn: { fiber: contrib.f, hardware: contrib.h, capital: contrib.c }, builtCost: sunk,
|
||||
shippedPerDay: Math.round(rate), daysToLevel100: rate > 0 ? Math.round(restTotal / rate) : null, sinceTaken };
|
||||
});
|
||||
const remaining = { fiber: 0, hardware: 0, capital: 0 };
|
||||
let bestLevel = 0;
|
||||
for (const s of sites) bestLevel = Math.max(bestLevel, s.level);
|
||||
for (let l = bestLevel + 1; l <= EG.maxLevel; l++) { const c = R.backboneCost(l); for (const r of RES) remaining[r] += c[r]; }
|
||||
// the biggest army any single POP holds (an attack is one movement from one POP): can anybody still take a built-up site?
|
||||
const perTown = {};
|
||||
for (const r of sim.db.all('SELECT town_id, unit, count FROM town_units')) { (perTown[r.town_id] = perTown[r.town_id] || {})[r.unit] = r.count; }
|
||||
let maxPopAttack = 0;
|
||||
for (const id of Object.keys(perTown)) maxPopAttack = Math.max(maxPopAttack, R.attackPower(perTown[id], {}));
|
||||
const bestDefence = sites.filter((x) => x.level > 0).reduce((m, x) => Math.max(m, R.backboneDefence(sim.world.seed, x0(x).x, x0(x).y, E.ageDays(world, now), x.level)), 0);
|
||||
const daysSinceOpen = Math.max(1e-9, (now - sim.t0) / DAY - (log.opened || 0));
|
||||
const shippedTotal = RES.reduce((s, r) => s + log.shipped[r], 0);
|
||||
const perDay = shippedTotal / daysSinceOpen;
|
||||
const remainTotal = RES.reduce((s, r) => s + remaining[r], 0);
|
||||
const links = sim.db.get("SELECT COUNT(*) AS n FROM towns").n;
|
||||
return {
|
||||
open: true, ageDays: age, openedAtSimDay: log.opened, plans: log.plans, strikes: log.strikes, strikeSkips: log.strikeSkips, landingReports: sim.col.landing, shipments: log.shipments, shippedTotal, shipped: log.shipped,
|
||||
maxPopAttackNoResearch: Math.round(maxPopAttack), bestHeldSiteDefenceNow: bestDefence, shippedPerSimDay: Math.round(perDay), buildsStarted: log.builds, buildErrors: log.buildErrors, sites, bestLevel,
|
||||
remainingToLevel100: remaining, remainingTotal: remainTotal, simDaysToFinishAtThisRate: perDay > 0 ? Math.round(remainTotal / perDay) : null,
|
||||
winner: world.winner_alliance_id ? { allianceId: world.winner_alliance_id, tag: world.winner_tag, wonAtSimDay: (world.won_at - sim.t0) / DAY } : null, worldStatus: world.status, towns: links,
|
||||
};
|
||||
}
|
||||
|
||||
return { step, summary, isOpen, log, plans };
|
||||
}
|
||||
|
||||
module.exports = { createEndgame };
|
||||
164
tools/bot/ledger.js
Normal file
164
tools/bot/ledger.js
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Conservation ledger for the bot harness.
|
||||
*
|
||||
* RESOURCES. Pools that hold Fiber/Hardware/Capital: POP stock (stored columns, settled values), open trade escrow, cargo of
|
||||
* movements that are `out`, and landing-site stockpiles. The identity checked at every checkpoint:
|
||||
*
|
||||
* pools_now = pools_at_start + sources + production - sinks (to within rounding of reported losses)
|
||||
*
|
||||
* sources the start stock of every operator and of every founded POP, the incumbent Hardware bonus
|
||||
* production EXACT: every `UPDATE towns SET fiber..., res_at ...` (state.settle) writes the lazily grown stock back; the tap
|
||||
* on db.run reads the previous stored value and books the difference. A transaction that rolls back discards its
|
||||
* bookings (db.tx is tapped too), so only committed settles count. Caps are already inside the stored numbers.
|
||||
* sinks build/train/research costs (from the command results), Backbone node levels (from landing_sites), cargo that
|
||||
* did not fit the Rack hall (`cargoLost` in notifications), trade escrow refunds clipped by the Rack hall cap
|
||||
* (tap on the refund statement)
|
||||
*
|
||||
* Anything else is DRIFT: a leak or a duplication in the server (or a missing sink here). Drift is printed and fails the run.
|
||||
*
|
||||
* UNITS. units_alive = trained - lost, where alive = home + stationed + in `out` movements; trained = `trainDone` events that
|
||||
* ran; lost = battle/scan/incumbent/landing reports, decommission notifications, 3 crews per founded POP, 1 M&A team per loyalty drop.
|
||||
*/
|
||||
const D = require('../../public/js/data.js');
|
||||
const R = require('../../public/js/rules.js');
|
||||
|
||||
const RES = D.RESOURCES;
|
||||
const zero = () => ({ fiber: 0, hardware: 0, capital: 0 });
|
||||
const addRes = (a, b) => { for (const r of RES) a[r] += (b && b[r]) || 0; return a; };
|
||||
|
||||
const SETTLE_SQL = 'UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ?, res_at = ?, loyalty = ?, loyalty_at = ? WHERE id = ?';
|
||||
const REFUND_RE = /^UPDATE towns SET (fiber|hardware|capital) = \? WHERE id = \?$/;
|
||||
const CLOSE_PREFIX = 'UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?';
|
||||
|
||||
class Ledger {
|
||||
constructor(db) {
|
||||
this.db = db;
|
||||
this.production = zero(); // exact, committed settles only
|
||||
this.sinkCosts = zero(); // build / train / research (command results)
|
||||
this.sinkLost = zero(); // cargoLost notifications
|
||||
this.lostEvents = 0;
|
||||
this.sinkClip = zero(); // trade refund clipped by the Rack hall cap
|
||||
this.clipEvents = 0;
|
||||
this.sourceStart = zero(); // operators' start stock
|
||||
this.stack = [];
|
||||
this.closing = null;
|
||||
this.t = { settles: 0 };
|
||||
this.installed = false;
|
||||
}
|
||||
|
||||
frame() { return this.stack.length ? this.stack[this.stack.length - 1] : null; }
|
||||
book(prodDelta, clip, clipN) {
|
||||
const f = this.frame();
|
||||
if (f) { addRes(f.prod, prodDelta); addRes(f.clip, clip); f.clipN += clipN; f.settles += 1; }
|
||||
else { addRes(this.production, prodDelta); addRes(this.sinkClip, clip); this.clipEvents += clipN; this.t.settles += 1; }
|
||||
}
|
||||
|
||||
install() {
|
||||
if (this.installed) return;
|
||||
this.installed = true;
|
||||
const db = this.db, self = this;
|
||||
const run = db.run.bind(db), tx = db.tx.bind(db);
|
||||
db.run = function tappedRun(sql, ...p) {
|
||||
if (sql === SETTLE_SQL) {
|
||||
const prev = db.get('SELECT fiber, hardware, capital FROM towns WHERE id = ?', p[8]);
|
||||
if (prev) self.book({ fiber: p[0] - prev.fiber, hardware: p[1] - prev.hardware, capital: p[2] - prev.capital }, zero(), 0);
|
||||
} else if (sql === CLOSE_PREFIX) {
|
||||
self.closing = p[2];
|
||||
} else {
|
||||
const m = REFUND_RE.exec(sql);
|
||||
if (m && self.closing !== null) {
|
||||
const prev = db.get('SELECT ' + m[1] + ' AS v FROM towns WHERE id = ?', p[1]);
|
||||
const off = db.get('SELECT give_amount, give_res FROM trade_offers WHERE id = ?', self.closing);
|
||||
if (prev && off && off.give_res === m[1]) {
|
||||
const credit = p[0] - prev.v;
|
||||
const clip = Math.max(0, off.give_amount - credit);
|
||||
if (clip > 1e-9) { const c = zero(); c[m[1]] = clip; self.book(zero(), c, 1); }
|
||||
}
|
||||
self.closing = null;
|
||||
}
|
||||
}
|
||||
return run(sql, ...p);
|
||||
};
|
||||
db.tx = function tappedTx(fn) {
|
||||
const f = { prod: zero(), clip: zero(), clipN: 0, settles: 0 };
|
||||
self.stack.push(f);
|
||||
let out;
|
||||
try { out = tx(fn); } catch (e) { self.stack.pop(); throw e; }
|
||||
self.stack.pop();
|
||||
const parent = self.frame();
|
||||
if (parent) { addRes(parent.prod, f.prod); addRes(parent.clip, f.clip); parent.clipN += f.clipN; parent.settles += f.settles; }
|
||||
else { addRes(self.production, f.prod); addRes(self.sinkClip, f.clip); self.clipEvents += f.clipN; self.t.settles += f.settles; }
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
sinkCost(cost) { addRes(this.sinkCosts, cost); }
|
||||
|
||||
// ---- pools (committed DB state) ----
|
||||
pools() {
|
||||
const db = this.db;
|
||||
const stock = zero(), escrow = zero(), cargo = zero(), sites = zero();
|
||||
const s = db.get('SELECT COALESCE(SUM(fiber),0) AS fiber, COALESCE(SUM(hardware),0) AS hardware, COALESCE(SUM(capital),0) AS capital FROM towns');
|
||||
addRes(stock, s);
|
||||
for (const r of RES) escrow[r] = db.get("SELECT COALESCE(SUM(give_amount),0) AS n FROM trade_offers WHERE status = 'open' AND give_res = ?", r).n;
|
||||
for (const m of db.all("SELECT cargo FROM movements WHERE status = 'out' AND cargo != '{}'")) addRes(cargo, JSON.parse(m.cargo));
|
||||
const ls = db.get('SELECT COALESCE(SUM(fiber),0) AS fiber, COALESCE(SUM(hardware),0) AS hardware, COALESCE(SUM(capital),0) AS capital FROM landing_sites');
|
||||
addRes(sites, ls);
|
||||
const total = zero();
|
||||
for (const p of [stock, escrow, cargo, sites]) addRes(total, p);
|
||||
return { stock, escrow, cargo, sites, total };
|
||||
}
|
||||
|
||||
// Cost of everything ever built on landing sites (levels done + the one running).
|
||||
backboneSunk() {
|
||||
const out = zero();
|
||||
for (const s of this.db.all('SELECT level, build_cost FROM landing_sites')) {
|
||||
for (let l = 1; l <= s.level; l++) addRes(out, R.backboneCost(l));
|
||||
if (s.build_cost) addRes(out, JSON.parse(s.build_cost));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The resource identity. `col` = collector (sources that come from reports), `start` = pools at the first call.
|
||||
checkResources(col) {
|
||||
const db = this.db;
|
||||
const p = this.pools();
|
||||
const nOps = db.get('SELECT COUNT(*) AS n FROM operators').n;
|
||||
const sources = zero();
|
||||
for (const r of RES) sources[r] += nOps * D.START.resources[r] + col.foundedTowns * D.EXPANSION.startResources[r];
|
||||
sources.hardware += db.get('SELECT COUNT(*) AS n FROM incumbent_takes').n * D.INCUMBENT.hardwareBonus;
|
||||
const bb = this.backboneSunk();
|
||||
const res = {};
|
||||
let worst = 0;
|
||||
for (const r of RES) {
|
||||
const expected = sources[r] + this.production[r] - this.sinkCosts[r] - this.sinkLost[r] - this.sinkClip[r] - bb[r];
|
||||
const drift = p.total[r] - expected;
|
||||
res[r] = { pools: p.total[r], sources: sources[r], production: this.production[r], costs: this.sinkCosts[r], lost: this.sinkLost[r], clipped: this.sinkClip[r], backbone: bb[r], drift };
|
||||
worst = Math.max(worst, Math.abs(drift));
|
||||
}
|
||||
const tol = 0.5 * (this.lostEvents + this.clipEvents) + 1;
|
||||
return { ok: worst <= tol, worstDrift: worst, tolerance: tol, perResource: res, pools: p };
|
||||
}
|
||||
|
||||
// Negative stock anywhere.
|
||||
negatives() {
|
||||
const db = this.db;
|
||||
const bad = [];
|
||||
for (const t of db.all('SELECT id, fiber, hardware, capital, battery FROM towns WHERE fiber < -1e-6 OR hardware < -1e-6 OR capital < -1e-6 OR battery < -1e-6')) bad.push({ town: t.id, fiber: t.fiber, hardware: t.hardware, capital: t.capital, battery: t.battery });
|
||||
for (const s of db.all('SELECT id, fiber, hardware, capital FROM landing_sites WHERE fiber < 0 OR hardware < 0 OR capital < 0')) bad.push({ site: s.id });
|
||||
return bad;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- units ----
|
||||
function aliveUnits(db) {
|
||||
const out = {};
|
||||
const add = (k, n) => { out[k] = (out[k] || 0) + n; };
|
||||
for (const r of db.all('SELECT unit, SUM(count) AS n FROM town_units GROUP BY unit')) add(r.unit, r.n);
|
||||
for (const r of db.all('SELECT unit, SUM(count) AS n FROM stationed GROUP BY unit')) add(r.unit, r.n);
|
||||
for (const m of db.all("SELECT units FROM movements WHERE status = 'out' AND units != '{}'")) { const u = JSON.parse(m.units); for (const k of Object.keys(u)) add(k, u[k]); }
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = { Ledger, aliveUnits, zero, addRes };
|
||||
109
tools/bot/report.js
Normal file
109
tools/bot/report.js
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
'use strict';
|
||||
/* Plain-text report of a bot run (the JSON file has everything; this is what a person reads in the terminal). */
|
||||
const { fmt, table, round } = require('./util');
|
||||
|
||||
const pc = (p, k) => (p && p[k] !== null && p[k] !== undefined ? fmt(p[k]) : '-');
|
||||
|
||||
function render(s, opts) {
|
||||
opts = opts || {};
|
||||
const out = [];
|
||||
const h = (t) => out.push('', '== ' + t + ' ==');
|
||||
const m = s.meta;
|
||||
out.push('UPSTREAM bot run: ' + m.players + ' players, ' + m.days + ' days, world speed ' + m.speed + 'x, seed ' + m.seed + ', radius ' + m.radius +
|
||||
', sessions/day ' + m.sessionsPerDay + (m.alwaysOn ? ', ALWAYS-ON' : '') + (m.set.length ? ', overrides: ' + m.set.join(' ') : ''));
|
||||
out.push('mix: ' + Object.entries(m.mix).map(([k, v]) => k + ':' + v).join(' '));
|
||||
|
||||
h('invariants');
|
||||
const inv = s.invariants;
|
||||
out.push((inv.ok ? 'OK' : 'BROKEN') + ': resources ' + (inv.resources.ok ? 'conserved' : 'DRIFT') + ' (worst drift ' + fmt(inv.resources.worstDrift, 2) + ', tolerance ' + fmt(inv.resources.tolerance, 1) + '), units ' + (inv.units.ok ? 'conserved' : 'DRIFT ' + JSON.stringify(inv.units.drift)) +
|
||||
', negative stock ' + (inv.negativeStock.ok ? 'none' : 'FOUND'), ' failed events ' + inv.failedEvents.n + ', unexpected errors ' + inv.unexpectedErrors.n);
|
||||
for (const r of Object.keys(inv.resources.final)) {
|
||||
const f = inv.resources.final[r];
|
||||
out.push(' ' + r.padEnd(9) + 'pools ' + fmt(f.pools, 0).padStart(9) + ' = sources ' + fmt(f.sources, 0) + ' + production ' + fmt(f.production, 0) + ' - spent ' + fmt(f.costs, 0) + ' - overflow lost ' + fmt(f.lost, 0) + ' - refund clipped ' + fmt(f.clipped, 0) + ' - backbone ' + fmt(f.backbone, 0) + ' drift ' + fmt(f.drift, 3));
|
||||
}
|
||||
for (const e of inv.failedEvents.sample) out.push(' failed event ' + e.id + ' ' + e.type + ': ' + e.error);
|
||||
for (const e of inv.unexpectedErrors.sample.slice(0, 5)) out.push(' unexpected: ' + e.command + ' ' + e.code + ' ' + (e.message || '') + (e.stack ? ' ' + e.stack : ''));
|
||||
for (const l of inv.serverLog.slice(0, 5)) out.push(' server log: ' + l);
|
||||
|
||||
h('economy per day (mean per POP; stock/production per resource F/H/C)');
|
||||
const rows = [];
|
||||
const step = s.days.length > 16 ? Math.ceil(s.days.length / 16) : 1;
|
||||
for (const d of s.days) {
|
||||
if (d.day % step !== 0 && d.day !== 1 && d.day !== s.days.length) continue;
|
||||
rows.push([d.day, d.operators, d.towns, fmt(d.stock.fiber) + '/' + fmt(d.stock.hardware) + '/' + fmt(d.stock.capital), fmt(d.prodPerHour.fiber) + '/' + fmt(d.prodPerHour.hardware) + '/' + fmt(d.prodPerHour.capital),
|
||||
fmt(d.fillPct, 0) + '%', fmt(d.fullPct, 0) + '%', fmt(d.queueUtilPct, 0) + '%', fmt(d.powerNet), fmt(d.powerNegPct, 0) + '%', fmt(d.unitPowerBoundPct, 0) + '%', fmt(d.unitOfflinePct, 0) + '%']);
|
||||
}
|
||||
out.push(table(rows, ['day', 'ops', 'POPs', 'stock F/H/C', 'prod/h F/H/C', 'fill', 'full', 'queue', 'pwrNet', 'unit POPs net<0', 'unit POPs pwr-bound', 'unit POPs offline']));
|
||||
|
||||
out.push('production lost to full storage over the run (share of what the rates would give): fiber ' + s.storageWastePct.fiber + '%, hardware ' + s.storageWastePct.hardware + '%, capital ' + s.storageWastePct.capital + '%');
|
||||
out.push('time at a full store (share of POP-samples >= 95% of the Rack hall) last day: ' + JSON.stringify(s.days[s.days.length - 1].fullBy));
|
||||
|
||||
h('progression per day');
|
||||
const prow = [];
|
||||
for (const d of s.days) {
|
||||
if (d.day % step !== 0 && d.day !== 1 && d.day !== s.days.length) continue;
|
||||
const u = d.units;
|
||||
prow.push([d.day, fmt(d.fieldAvg, 1), pc(d.core, 'p10') + '/' + pc(d.core, 'p50') + '/' + pc(d.core, 'p90'), pc(d.footprint, 'p10') + '/' + pc(d.footprint, 'p50') + '/' + pc(d.footprint, 'p90'), d.multiPop + ' (max ' + d.popsMax + ')', fmt(d.gateReadyPct, 0) + '%',
|
||||
Object.keys(u).sort().map((k) => k.replace(/_.*/, '') + ':' + fmt(u[k], 0)).join(' ')]);
|
||||
}
|
||||
out.push(table(prow, ['day', 'field avg', 'core p10/50/90', 'footprint p10/50/90', 'operators >=2 POPs', 'over gate', 'units alive']));
|
||||
const f = s.final;
|
||||
out.push('time to Core router 10 (days after joining): ' + pc(f.core10Days, 'p10') + '/' + pc(f.core10Days, 'p50') + '/' + pc(f.core10Days, 'p90') + ' (reached by ' + f.core10Reached + ' of ' + m.players + ')');
|
||||
out.push('time to first expansion (days after joining): ' + pc(f.firstExpansionDays, 'p10') + '/' + pc(f.firstExpansionDays, 'p50') + '/' + pc(f.firstExpansionDays, 'p90') + ' (reached by ' + f.firstExpansionReached + ' of ' + m.players + ')');
|
||||
out.push('by archetype, days after joining to Core router 10 / first expansion (p10/50/90): ' + Object.keys(f.milestones || {}).sort().map((a) => a + ' ' + pc(f.milestones[a].core10Days, 'p10') + '/' + pc(f.milestones[a].core10Days, 'p50') + '/' + pc(f.milestones[a].core10Days, 'p90') + ' | ' + pc(f.milestones[a].firstExpansionDays, 'p10') + '/' + pc(f.milestones[a].firstExpansionDays, 'p50') + '/' + pc(f.milestones[a].firstExpansionDays, 'p90')).join('; '));
|
||||
out.push('POPs per operator: ' + Object.keys(f.pops).sort((a, b) => a - b).map((k) => k + ':' + f.pops[k]).join(' '));
|
||||
out.push('infrastructure levels at the capital (mean; the histogram 0..20 is in --json): ' + Object.keys(f.levels).map((k) => k + ' ' + f.levels[k].mean).join(', '));
|
||||
|
||||
h('by archetype (means)');
|
||||
const arows = Object.keys(f.byArchetype).sort().map((a) => {
|
||||
const r = f.byArchetype[a];
|
||||
return [a, r.n, r.footprintMean, r.fieldAvg, r.core, r.pops, fmt(r.spentBuild), fmt(r.spentTrain), fmt(r.stock), fmt(r.netWorth), r.raids + '/' + r.raidWins, fmt(r.lootTaken), fmt(r.raidLostValue), r.timesHit, fmt(r.lootLostToRaids), r.incumbentWins];
|
||||
});
|
||||
out.push(table(arows, ['archetype', 'n', 'footprint', 'field avg', 'core', 'POPs', 'spent build', 'spent units', 'stock', 'net worth', 'raids/won', 'loot taken', 'raid loss value', 'times hit', 'loot lost', 'incumbent wins']));
|
||||
|
||||
h('combat');
|
||||
const c = s.combat;
|
||||
out.push('reports: ' + Object.entries(c.reports).map(([k, v]) => k + ':' + v).join(' '));
|
||||
const r = c.raids;
|
||||
out.push('raids ' + r.n + ', won ' + r.wins + (r.winRate !== null ? ' (' + fmt(r.winRate * 100, 0) + '%)' : '') + ', loot ' + fmt(r.lootTotal) + ' (' + Object.entries(r.lootRes).map(([k, v]) => k[0] + ':' + fmt(v)).join(' ') + '), loot/raid p10/50/90 ' + pc(r.lootPerRaid, 'p10') + '/' + pc(r.lootPerRaid, 'p50') + '/' + pc(r.lootPerRaid, 'p90'));
|
||||
out.push(' attacker lost value ' + fmt(r.attackerLostValue) + ', defender lost value ' + fmt(r.defenderLostValue) + ', loot per lost value ' + fmt(r.lootPerLostValue) + ', share against undefended POPs ' + (r.undefendedShare === null ? '-' : fmt(r.undefendedShare * 100, 0) + '%') + ', attack/defence p10/50/90 ' + pc(r.attackOverDefence, 'p10') + '/' + pc(r.attackOverDefence, 'p50') + '/' + pc(r.attackOverDefence, 'p90'));
|
||||
out.push(' target age at raid (days since the target joined): ' + Object.entries(r.targetAge).map(([k, v]) => k + ':' + v).join(' '));
|
||||
out.push('full attacks ' + c.attacks.n + ' (won ' + c.attacks.att + '), takeover attacks ' + c.takeoverBattles.n + ' (won ' + c.takeoverBattles.att + '), takeovers: attempted ' + c.takeovers.attempted + ', loyalty hits ' + c.takeovers.dropped + ', captured ' + c.takeovers.captured + ', blocked ' + JSON.stringify(c.takeovers.blocked) + ', siege ' + c.siege.n);
|
||||
out.push('scans ' + c.scans.n + ' (ok ' + c.scans.ok + ', failed ' + c.scans.failed + '), detected-by-target reports ' + c.scans.detected + ' (identity revealed ' + c.scans.revealed + ')');
|
||||
out.push('incumbent sites: attacks ' + c.incumbent.n + ', won ' + c.incumbent.wins + ', hardware bonus ' + fmt(c.incumbent.hardware) + ', attacker lost value ' + fmt(c.incumbent.attLostValue));
|
||||
out.push('bounced movements: ' + JSON.stringify(c.movementFailed));
|
||||
out.push('units lost: ' + JSON.stringify(c.unitsLost) + ' consumed: ' + JSON.stringify(c.unitsConsumed) + ' decommissioned: ' + JSON.stringify(c.decommissioned));
|
||||
|
||||
h('trade and alliances');
|
||||
const t = s.trade;
|
||||
out.push('offers by status: ' + Object.entries(t.byStatus).map(([k, v]) => k + ':' + v.n).join(' ') + ', completed volume ' + fmt(t.volumeCompleted) + ', completed give/want ratio p10/50/90 ' + pc(t.ratio, 'p10') + '/' + pc(t.ratio, 'p50') + '/' + pc(t.ratio, 'p90'));
|
||||
out.push('transport overflow lost (' + t.cargoLostEvents + ' deliveries): ' + JSON.stringify(t.cargoLost) + ', trade refunds clipped by the Rack hall cap (' + t.clipEvents + '): ' + JSON.stringify(t.refundClipped));
|
||||
const a = s.alliances;
|
||||
out.push('alliances ' + a.count + ', members p10/50/90 ' + pc(a.members, 'p10') + '/' + pc(a.members, 'p50') + '/' + pc(a.members, 'p90') + ' (max ' + a.membersMax + '), operators in an alliance ' + a.inAlliance + '/' + a.operators + ', relations ' + JSON.stringify(a.relations) + ', proposals ' + JSON.stringify(a.proposals));
|
||||
|
||||
if (s.endgame) {
|
||||
h('end game');
|
||||
const e = s.endgame;
|
||||
if (!e.open) out.push('sites not open yet (world age ' + fmt(e.ageDays, 1) + ' days, opens at ' + e.openDay + ')');
|
||||
else {
|
||||
out.push('opened at simulated day ' + fmt(e.openedAtSimDay, 1) + ' (world age now ' + fmt(e.ageDays, 0) + '), alliance plans ' + e.plans + ', strikes sent ' + e.strikes + ' (landing reports ' + e.landingReports.n + ', taken ' + e.landingReports.taken + ', units lost value ' + fmt(e.landingReports.attLostValue) + '), strike blockers ' + JSON.stringify(e.strikeSkips));
|
||||
out.push('shipments ' + e.shipments + ' carrying ' + fmt(e.shippedTotal) + ' (F ' + fmt(e.shipped.fiber) + ' H ' + fmt(e.shipped.hardware) + ' C ' + fmt(e.shipped.capital) + '), ' + fmt(e.shippedPerSimDay) + ' per simulated day; node levels started ' + e.buildsStarted + ' ' + JSON.stringify(e.buildErrors));
|
||||
out.push(table(e.sites.map((x) => [x.idx, x.holder || '-', x.level, x.takenAt === null ? '-' : fmt(x.takenAt, 1), x.contributors, fmt(x.shippedIn.fiber + x.shippedIn.hardware + x.shippedIn.capital), fmt(x.shippedPerDay), x.daysToLevel100 === null ? '-' : x.daysToLevel100, fmt(x.stock.fiber + x.stock.hardware + x.stock.capital)]), ['site', 'holder', 'node level', 'taken (day)', 'contributors', 'shipped in', 'shipped/day', 'days to lvl 100 at that rate', 'stockpile now']));
|
||||
out.push('largest army (attack, before research) any single POP holds: ' + fmt(e.maxPopAttackNoResearch) + ' against the defence of the best built-up site now: ' + fmt(e.bestHeldSiteDefenceNow) + ' (one attack is one movement from one POP, so attacks cannot be added up)');
|
||||
out.push('best node level ' + e.bestLevel + '; still to ship for level 100 from there (per resource) ' + fmt(e.remainingToLevel100.fiber) + '; world ' + e.worldStatus + (e.winner ? ', WINNER ' + e.winner.tag + ' on day ' + fmt(e.winner.wonAtSimDay, 1) : ', no winner'));
|
||||
}
|
||||
}
|
||||
|
||||
h('performance and errors');
|
||||
const p = s.perf;
|
||||
out.push('wall ' + p.wallSeconds + ' s for ' + m.days + ' simulated days (' + p.simulatedPerWallSecond + ' simulated hours per wall second), commands ' + p.commands + ' (' + p.commandsOk + ' ok, ' + p.commandsPerSecond + '/s), p50/p95/p99 latency ' + fmt(p.latencyMs.p50, 2) + '/' + fmt(p.latencyMs.p95, 2) + '/' + fmt(p.latencyMs.p99, 2) + ' ms');
|
||||
out.push('events processed in the loop ' + p.eventsProcessed + ' (' + fmt(p.runDueSeconds, 2) + ' s in runDue), done by type: ' + Object.entries(p.eventsDone).map(([k, v]) => k + ':' + v).join(' '));
|
||||
const slow = Object.entries(p.latencyByCommand).sort((x, y) => (y[1].p95 || 0) - (x[1].p95 || 0)).slice(0, 5);
|
||||
out.push('slowest commands (p95 ms): ' + slow.map(([k, v]) => k + ' ' + fmt(v.p95, 2) + ' (n ' + v.n + ')').join(', '));
|
||||
out.push('bot actions: ' + JSON.stringify(s.botLogs));
|
||||
const er = s.errors.rows.slice(0, 14);
|
||||
out.push('command errors (' + s.errors.expectedTotal + ' expected, ' + s.errors.unexpectedTotal + ' unexpected): ' + er.map((x) => x.key + ' x' + x.n + (x.expected ? '' : ' (!)')).join(', '));
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
module.exports = { render };
|
||||
289
tools/bot/sim.js
Normal file
289
tools/bot/sim.js
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The simulation: the real server in-process (createServer: in-memory SQLite, FakeClock, autoArm false), N bots playing through
|
||||
* srv.commands.run (the function every REST route calls, so the same validation and transactions, without HTTP/JSON/scrypt
|
||||
* overhead), the clock advanced stop by stop (next bot session / next sample), scheduler.runDue() settling every event that falls due.
|
||||
* Called from tools/bot.js; returns a plain stats object (see report.js for how it is printed).
|
||||
*/
|
||||
const { performance } = require('perf_hooks');
|
||||
const crypto = require('crypto');
|
||||
const D = require('../../public/js/data.js');
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { FakeClock } = require('../../server/clock');
|
||||
const { HOUR, DAY, makeRng, percentiles, mean, round, bump, addInto } = require('./util');
|
||||
const { Ledger, aliveUnits, zero } = require('./ledger');
|
||||
const { Collector } = require('./collector');
|
||||
|
||||
const RES = D.RESOURCES;
|
||||
const DEFAULT_MIX = { builder: 0.22, raider: 0.14, conqueror: 0.06, turtle: 0.12, expander: 0.16, trader: 0.12, alliancer: 0.18 };
|
||||
|
||||
// Error codes a sensible bot may run into now and then (rules it pre-checks can still change between check and send).
|
||||
const EXPECTED = new Set(['not_enough_resources', 'queue_full', 'requirements_not_met', 'already_queued', 'target_protected', 'protection_active',
|
||||
'footprint_too_low', 'no_transport_link', 'units_offline', 'invalid_target', 'trade_out_of_range', 'alliance_full', 'peering_office_required',
|
||||
'max_level', 'offer_closed', 'own_offer', 'queue_full', 'out_of_range', 'cannot_takeover', 'diplomacy_invalid', 'diplomacy_pending', 'proposal_exists',
|
||||
'proposal_expired', 'invite_expired', 'world_ended', 'already_in_alliance', 'capacity_exceeded', 'conflict', 'backbone_closed', 'not_enough_units', 'alliance_name_taken', 'alliance_tag_taken', 'forbidden']);
|
||||
|
||||
function parseMix(str, n) {
|
||||
const weights = {};
|
||||
if (str) {
|
||||
for (const part of String(str).split(',')) { const [k, v] = part.split(':'); if (k) weights[k.trim()] = Number(v === undefined ? 1 : v); }
|
||||
} else Object.assign(weights, DEFAULT_MIX);
|
||||
const { ARCHETYPES } = require('./bots');
|
||||
for (const k of Object.keys(weights)) if (!Object.prototype.hasOwnProperty.call(ARCHETYPES, k) || !(weights[k] >= 0)) throw new Error('--strategy-mix: unknown archetype or bad weight "' + k + '" (known: ' + Object.keys(ARCHETYPES).join(', ') + ')');
|
||||
const names = Object.keys(weights).filter((k) => weights[k] > 0);
|
||||
if (!names.length) throw new Error('--strategy-mix needs at least one positive weight');
|
||||
const total = names.reduce((s, k) => s + weights[k], 0);
|
||||
// largest remainder, so the counts add up to n
|
||||
const exact = names.map((k) => ({ k, v: weights[k] / total * n }));
|
||||
const counts = {};
|
||||
let used = 0;
|
||||
for (const e of exact) { counts[e.k] = Math.floor(e.v); used += counts[e.k]; }
|
||||
exact.sort((a, b) => (b.v - Math.floor(b.v)) - (a.v - Math.floor(a.v)) || (a.k < b.k ? -1 : 1));
|
||||
for (let i = 0; used < n; i++, used++) counts[exact[i % exact.length].k] += 1;
|
||||
const list = [];
|
||||
for (const k of names) for (let i = 0; i < counts[k]; i++) list.push(k);
|
||||
return list;
|
||||
}
|
||||
|
||||
async function runSim(o) {
|
||||
const { createServer } = require('../../server');
|
||||
const { Bot, ARCHETYPES } = require('./bots');
|
||||
const makeView = require('./view');
|
||||
const { createEndgame } = require('./endgame');
|
||||
|
||||
const logs = [];
|
||||
const clock = new FakeClock(Date.UTC(2026, 0, 1));
|
||||
const t0 = clock.now();
|
||||
const srv = await createServer({
|
||||
port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false,
|
||||
log: (m) => { if (/fail|error|exception/i.test(m)) { if (logs.length < 50) logs.push(m); } },
|
||||
world: { seed: o.seed, speed: o.speed, mapRadius: o.radius, name: 'bot world' },
|
||||
});
|
||||
const db = srv.db;
|
||||
const world = require('../../server/state').loadWorld(db, db.get('SELECT id FROM worlds LIMIT 1').id);
|
||||
const ledger = new Ledger(db);
|
||||
ledger.install();
|
||||
const col = new Collector(db);
|
||||
const view = makeView(db, world);
|
||||
const wall0 = performance.now();
|
||||
|
||||
const sim = { potential: zero(), opts: o, srv, db, world, clock, t0, view, ledger, col, bots: [], alliancePlans: new Map(), call: null, endgame: null };
|
||||
|
||||
// ---------------------------------------------------------------- command wrapper (accounting, latency, errors)
|
||||
const lat = {};
|
||||
const counts = {};
|
||||
const errors = {};
|
||||
const unexpected = [];
|
||||
let commandsRun = 0, commandsOk = 0;
|
||||
let runDueMs = 0, eventsProcessed = 0;
|
||||
sim.call = (bot, name, args) => {
|
||||
const a = Object.assign({ userId: bot.userId }, args);
|
||||
const s = performance.now();
|
||||
commandsRun += 1;
|
||||
try {
|
||||
const out = srv.commands.run(name, a);
|
||||
const ms = performance.now() - s;
|
||||
(lat[name] || (lat[name] = [])).push(ms);
|
||||
bump(counts, name); commandsOk += 1;
|
||||
if (out && out.cost && (name === 'build' || name === 'train' || name === 'research')) {
|
||||
ledger.sinkCost(out.cost);
|
||||
const v = RES.reduce((sum, r) => sum + (out.cost[r] || 0), 0);
|
||||
bot.spent[name] = (bot.spent[name] || 0) + v;
|
||||
}
|
||||
return { ok: true, out, args: a };
|
||||
} catch (e) {
|
||||
const ms = performance.now() - s;
|
||||
(lat[name] || (lat[name] = [])).push(ms);
|
||||
const code = e && e.code ? e.code : 'EXC:' + (e && e.message || e);
|
||||
bump(errors, name + ':' + code);
|
||||
if (process.env.BOT_DEBUG && (errors[name + ':' + code] <= 3)) console.error('DEBUG error', name, code, JSON.stringify(a).slice(0, 300), JSON.stringify(e.details || {}));
|
||||
if (!(e && e.code && EXPECTED.has(e.code)) && unexpected.length < 30) unexpected.push({ command: name, code, message: String(e && e.message || e).slice(0, 200), details: e && e.details, stack: e && !e.code ? String(e.stack).split('\n').slice(0, 4).join(' | ') : undefined });
|
||||
return { ok: false, code, error: e, args: a };
|
||||
}
|
||||
};
|
||||
|
||||
sim.endgame = createEndgame(sim);
|
||||
|
||||
// ---------------------------------------------------------------- the bots
|
||||
const mix = parseMix(o.mix, o.players);
|
||||
const order = mix.map((k, i) => ({ k, r: makeRng(o.seed, i, 0xa11)() })).sort((a, b) => a.r - b.r).map((x) => x.k); // seeded shuffle
|
||||
const joinSpan = Math.max(0, o.joinDays) * DAY;
|
||||
const pending = []; // bots waiting to join
|
||||
for (let i = 0; i < o.players; i++) {
|
||||
const jr = makeRng(o.seed, i, 0x70a);
|
||||
pending.push({ idx: i, archetype: order[i], at: t0 + Math.floor(i * joinSpan / Math.max(1, o.players) + jr() * (joinSpan / Math.max(1, o.players)) * 0.9) });
|
||||
}
|
||||
const join = (p) => {
|
||||
const name = 'bot' + p.idx;
|
||||
const r = srv.commands.run('signup', { username: name, passHash: 'x', tokenHash: crypto.createHash('sha256').update('bot-token-' + o.seed + '-' + p.idx).digest('hex'), device: 'bot' });
|
||||
const bot = new Bot(sim, p.idx, p.archetype, { userId: r.userId, operatorId: r.operatorId, name }, { sessionsPerDay: o.sessionsPerDay });
|
||||
bot.joinedAt = clock.now();
|
||||
bot.dayIdx = Math.floor((clock.now() - t0) / DAY);
|
||||
bot.times = bot.sessionTimes(bot.dayIdx, t0).filter((t) => t >= clock.now());
|
||||
bot.times.unshift(clock.now() + 1000); // a first look right after signing up
|
||||
sim.bots.push(bot);
|
||||
bot.nextAt = bot.times.shift();
|
||||
if (o.alwaysOn) bot.nextAt = Infinity;
|
||||
};
|
||||
const advanceBot = (bot) => {
|
||||
if (o.alwaysOn) { bot.nextAt = Infinity; return; }
|
||||
while (!bot.times.length) {
|
||||
bot.dayIdx += 1;
|
||||
bot.times = bot.sessionTimes(bot.dayIdx, t0);
|
||||
}
|
||||
bot.nextAt = bot.times.shift();
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- sampling
|
||||
const sampleEvery = Math.max(10, o.sampleMin) * 60 * 1000;
|
||||
const days = [];
|
||||
const dayAcc = new Map(); // day index -> accumulators of the periodic samples
|
||||
const S = require('../../server/state');
|
||||
const sample = (now) => {
|
||||
const di = Math.floor((now - t0) / DAY);
|
||||
let acc = dayAcc.get(di);
|
||||
if (!acc) { acc = { fullBy: {}, n: 0, towns: 0, stock: zero(), prod: zero(), fill: 0, full: 0, qUtil: 0, qTowns: 0, pNet: 0, pNeg: 0, pEmpty: 0, unitTowns: 0, unitPowerBound: 0, unitOffline: 0, pDraw: 0, pOut: 0, capSum: 0, batFill: 0 }; dayAcc.set(di, acc); }
|
||||
acc.n += 1;
|
||||
const qs = new Map(db.all("SELECT town_id AS id, COUNT(*) AS n FROM events WHERE type = 'buildDone' AND status = 'pending' GROUP BY town_id").map((r) => [r.id, r.n]));
|
||||
for (const row of db.all('SELECT * FROM towns ORDER BY id')) {
|
||||
const t = S.townFromRow(db, row, world);
|
||||
const cur = R.resourcesAt(t, now);
|
||||
const cap = cur.caps.fiber;
|
||||
acc.towns += 1;
|
||||
for (const r of RES) { acc.stock[r] += cur.amounts[r]; acc.prod[r] += cur.rates[r]; }
|
||||
const fills = RES.map((r) => cur.amounts[r] / cap);
|
||||
acc.fill += mean(fills);
|
||||
if (fills.some((f) => f >= 0.95)) acc.full += 1;
|
||||
RES.forEach((r, i) => { if (fills[i] >= 0.95) acc.fullBy[r] = (acc.fullBy[r] || 0) + 1; sim.potential[r] += cur.rates[r] * sampleEvery / HOUR; });
|
||||
const slots = R.queueSlots(t);
|
||||
acc.qUtil += Math.min(1, (qs.get(row.id) || 0) / slots); acc.qTowns += 1;
|
||||
acc.pNet += cur.rates.powerNet; acc.pDraw += cur.rates.powerDraw; acc.pOut += cur.rates.powerOut;
|
||||
const hasUnits = t.unitDraw > 0;
|
||||
if (cur.rates.powerNet < 0 && hasUnits) acc.pNeg += 1;
|
||||
if (hasUnits) { acc.unitTowns += 1; if (cur.rates.powerNet < 3) acc.unitPowerBound += 1; if (cur.amounts.battery <= 1e-6 && cur.rates.powerNet < 0) acc.unitOffline += 1; }
|
||||
}
|
||||
};
|
||||
|
||||
const snapshot = (now, di) => {
|
||||
const acc = dayAcc.get(di) || { n: 1, towns: 1, stock: zero(), prod: zero(), fill: 0, full: 0, qUtil: 0, qTowns: 1, pNet: 0, pNeg: 0, pEmpty: 0, unitTowns: 0, unitPowerBound: 0, unitOffline: 0, pDraw: 0, pOut: 0 };
|
||||
const tn = Math.max(1, acc.towns);
|
||||
const ops = db.all('SELECT id, alliance_id FROM operators ORDER BY id');
|
||||
const fps = [], cores = [], fields = [], pops = [];
|
||||
const gate = { ready: 0, n: 0 };
|
||||
for (const op of ops) {
|
||||
const towns = view.towns(op.id);
|
||||
pops.push(towns.length);
|
||||
if (!towns.length) continue;
|
||||
let fp = 0;
|
||||
for (const t of towns) fp += R.footprintAt(t, now);
|
||||
fps.push(fp);
|
||||
const cap = towns[0];
|
||||
cores.push(view.level(cap, 'core_router'));
|
||||
const fl = view.fieldLevels(cap).map((f) => f.level);
|
||||
fields.push(mean(fl));
|
||||
gate.n += 1;
|
||||
if (R.footprintGate(towns.length, fp).ok) gate.ready += 1;
|
||||
}
|
||||
const units = aliveUnits(db);
|
||||
const stockAvg = {}, prodAvg = {};
|
||||
for (const r of RES) { stockAvg[r] = acc.stock[r] / tn; prodAvg[r] = acc.prod[r] / tn; }
|
||||
days.push({
|
||||
day: di + 1, operators: ops.length, towns: db.get('SELECT COUNT(*) AS n FROM towns').n,
|
||||
stock: stockAvg, prodPerHour: prodAvg, fullBy: Object.fromEntries(RES.map((r) => [r, round((acc.fullBy[r] || 0) / tn * 100, 1)])), fillPct: acc.fill / tn * 100, fullPct: acc.full / tn * 100,
|
||||
queueUtilPct: acc.qUtil / Math.max(1, acc.qTowns) * 100,
|
||||
powerNet: acc.pNet / tn, powerDraw: acc.pDraw / tn, powerOut: acc.pOut / tn, powerNegPct: acc.unitTowns ? acc.pNeg / acc.unitTowns * 100 : 0,
|
||||
unitTownsPct: acc.unitTowns / tn * 100, unitPowerBoundPct: acc.unitTowns ? acc.unitPowerBound / acc.unitTowns * 100 : 0, unitOfflinePct: acc.unitTowns ? acc.unitOffline / acc.unitTowns * 100 : 0,
|
||||
fieldAvg: mean(fields), core: percentiles(cores, [10, 50, 90]), footprint: percentiles(fps, [10, 50, 90]),
|
||||
popsMax: Math.max(0, ...pops), popsMean: mean(pops), multiPop: pops.filter((p) => p >= 2).length, gateReadyPct: gate.n ? gate.ready / gate.n * 100 : 0,
|
||||
units, alliances: db.get('SELECT COUNT(*) AS n FROM alliances').n, allied: db.get('SELECT COUNT(*) AS n FROM operators WHERE alliance_id IS NOT NULL').n,
|
||||
openOffers: db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE status = 'open'").n, eventsPending: db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending'").n,
|
||||
});
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- invariants, checked at every day boundary
|
||||
const invariantLog = [];
|
||||
const checkpoint = (now, final) => {
|
||||
col.ingest(ledger);
|
||||
const res = ledger.checkResources(col);
|
||||
const neg = ledger.negatives();
|
||||
const failed = db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n;
|
||||
const trained = {};
|
||||
for (const r of db.all("SELECT json_extract(payload, '$.unit') AS u, SUM(json_extract(payload, '$.count')) AS n FROM events WHERE type = 'trainDone' AND status = 'done' GROUP BY u")) trained[r.u] = r.n;
|
||||
const alive = aliveUnits(db);
|
||||
const lost = addInto(addInto({}, col.unitsLost), col.unitsConsumed);
|
||||
const unitDrift = {};
|
||||
for (const k of new Set([...Object.keys(trained), ...Object.keys(alive), ...Object.keys(lost)])) {
|
||||
const d = (alive[k] || 0) - ((trained[k] || 0) - (lost[k] || 0));
|
||||
if (d !== 0) unitDrift[k] = d;
|
||||
}
|
||||
const rec = { day: (now - t0) / DAY, resourcesOk: res.ok, worstDrift: res.worstDrift, tolerance: res.tolerance, negatives: neg.length, failedEvents: failed, unitDrift };
|
||||
invariantLog.push(rec);
|
||||
if (final) rec.detail = res.perResource;
|
||||
return { res, neg, failed, unitDrift, trained, alive, lost };
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- main loop
|
||||
const end = t0 + o.days * DAY;
|
||||
let nextSample = t0 + sampleEvery;
|
||||
let nextDay = t0 + DAY;
|
||||
let guard = 0;
|
||||
while (clock.now() < end) {
|
||||
// next stop
|
||||
let next = end;
|
||||
let kind = 'end', who = null;
|
||||
if (pending.length && pending[0].at < next) { next = pending[0].at; kind = 'join'; }
|
||||
for (const b of sim.bots) if (b.nextAt < next) { next = b.nextAt; kind = 'bot'; who = b; }
|
||||
if (o.alwaysOn) {
|
||||
const tick = Math.ceil((clock.now() + 1) / (o.stepMin * 60000)) * (o.stepMin * 60000);
|
||||
if (tick < next) { next = tick; kind = 'tick'; }
|
||||
}
|
||||
if (o.endgameStepMin > 0 && sim.endgame.isOpen(clock.now())) {
|
||||
const tick = Math.ceil((clock.now() + 1) / (o.endgameStepMin * 60000)) * (o.endgameStepMin * 60000);
|
||||
if (tick < next) { next = tick; kind = 'egtick'; }
|
||||
}
|
||||
if (nextSample < next) { next = nextSample; kind = 'sample'; }
|
||||
if (nextDay <= next) { next = nextDay; kind = 'day'; }
|
||||
if (next < clock.now()) next = clock.now();
|
||||
clock.set(next);
|
||||
const r0 = performance.now();
|
||||
eventsProcessed += srv.scheduler.runDue();
|
||||
runDueMs += performance.now() - r0;
|
||||
if (++guard > 5e6) throw new Error('simulation loop did not terminate');
|
||||
if (kind === 'join') { join(pending.shift()); }
|
||||
else if (kind === 'bot') {
|
||||
if (db.get('SELECT status FROM worlds WHERE id = ?', world.id).status === 'ended') { advanceBot(who); continue; } // the world is over: nothing to play
|
||||
who.session(next);
|
||||
const cont = who.continuation(next);
|
||||
if (cont !== null) who.nextAt = cont; else advanceBot(who);
|
||||
}
|
||||
else if (kind === 'egtick') { for (const b of sim.bots) { if (sim.alliancePlans.has(b.op && b.op.alliance_id) || (b.op && b.op.alliance_id)) { b.session(next); } } }
|
||||
else if (kind === 'tick') { for (const b of sim.bots) { b.session(next); } }
|
||||
else if (kind === 'sample') {
|
||||
sample(next); nextSample += sampleEvery;
|
||||
if (process.env.BOT_DEBUG_DRIFT) {
|
||||
col.ingest(ledger);
|
||||
const c = ledger.checkResources(col);
|
||||
const d = RES.map((r) => c.perResource[r].drift.toFixed(2)).join('/');
|
||||
if (d !== sim.lastDrift) { console.error('drift at day ' + ((next - t0) / DAY).toFixed(3) + ' = ' + d); sim.lastDrift = d; }
|
||||
}
|
||||
}
|
||||
else if (kind === 'day') {
|
||||
const di = Math.floor((next - t0) / DAY) - 1;
|
||||
if (!dayAcc.has(di)) sample(next - 1);
|
||||
checkpoint(next, false);
|
||||
snapshot(next, di);
|
||||
nextDay += DAY;
|
||||
if (o.progress) o.progress(di + 1, o.days);
|
||||
if (o.onDay) o.onDay(sim, di + 1); // test hook: lets a test tamper with the world to prove the invariants notice
|
||||
}
|
||||
}
|
||||
srv.scheduler.runDue();
|
||||
const fin = checkpoint(clock.now(), true);
|
||||
const wallMs = performance.now() - wall0;
|
||||
|
||||
const stats = require('./stats').build({ sim, o, days, ledger, col, fin, invariantLog, lat, counts, errors, unexpected, commandsRun, commandsOk, runDueMs, eventsProcessed, wallMs, logs, EXPECTED, mix: order });
|
||||
await srv.close();
|
||||
return stats;
|
||||
}
|
||||
|
||||
module.exports = { runSim, parseMix, DEFAULT_MIX, EXPECTED };
|
||||
172
tools/bot/stats.js
Normal file
172
tools/bot/stats.js
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
'use strict';
|
||||
/* Builds the final stats object (JSON-able) from what the simulation collected. Wall-clock numbers live under `perf` only,
|
||||
* so everything else is identical for the same seed (the determinism test compares it without `perf`). */
|
||||
const D = require('../../public/js/data.js');
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { DAY, percentiles, mean, round, sum } = require('./util');
|
||||
const { lootValue } = require('./collector');
|
||||
|
||||
const RES = D.RESOURCES;
|
||||
|
||||
function histogram(values, max) {
|
||||
const h = {};
|
||||
for (const v of values) h[v] = (h[v] || 0) + 1;
|
||||
const out = [];
|
||||
for (let i = 0; i <= max; i++) out.push(h[i] || 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
function build(x) {
|
||||
const { sim, o, days, ledger, col, fin, invariantLog, lat, counts, errors, unexpected, commandsRun, commandsOk, runDueMs, eventsProcessed, wallMs, logs, EXPECTED } = x;
|
||||
const { db, world, view, t0 } = sim;
|
||||
const now = sim.clock.now();
|
||||
const S = require('../../server/state');
|
||||
|
||||
// ---- progression at the end
|
||||
const ops = db.all('SELECT * FROM operators ORDER BY id');
|
||||
const byArch = {};
|
||||
const opArch = new Map(sim.bots.map((b) => [b.operatorId, b]));
|
||||
const levels = {};
|
||||
const fieldMins = [];
|
||||
const popsDist = {};
|
||||
const footprints = [];
|
||||
const core10 = [], expand1 = [];
|
||||
const milestones = {};
|
||||
const core10Rows = new Map(db.all(`SELECT t.owner_id AS oid, MIN(e.due_at) AS at FROM events e JOIN towns t ON t.id = e.town_id
|
||||
WHERE e.type = 'buildDone' AND e.status = 'done' AND json_extract(e.payload, '$.type') = 'core_router' AND json_extract(e.payload, '$.toLevel') >= 10 GROUP BY t.owner_id`).map((r) => [r.oid, r.at]));
|
||||
const exp1Rows = new Map(db.all(`SELECT m.owner_id AS oid, MIN(m.arrive_at) AS at FROM movements m JOIN towns t ON t.world_id = m.world_id AND t.x = m.to_x AND t.y = m.to_y AND t.created_at = m.arrive_at
|
||||
WHERE m.type = 'settle' AND m.status = 'done' GROUP BY m.owner_id`).map((r) => [r.oid, r.at]));
|
||||
const infraTypes = Object.keys(D.BUILDINGS).filter((k) => D.BUILDINGS[k].kind === 'infra' && !D.BUILDINGS[k].special);
|
||||
for (const t of infraTypes) levels[t] = [];
|
||||
for (const op of ops) {
|
||||
const towns = view.towns(op.id);
|
||||
const bot = opArch.get(op.id);
|
||||
const a = bot ? bot.archetype : '?';
|
||||
const row = byArch[a] || (byArch[a] = { n: 0, footprint: [], fieldAvg: [], pops: [], spentBuild: [], spentTrain: [], spentResearch: [], stock: [], core: [] });
|
||||
row.n += 1;
|
||||
popsDist[towns.length] = (popsDist[towns.length] || 0) + 1;
|
||||
if (!towns.length) continue;
|
||||
const fp = towns.reduce((s2, t) => s2 + R.footprintAt(t, now), 0);
|
||||
footprints.push(fp);
|
||||
const cap = towns[0];
|
||||
for (const t of infraTypes) levels[t].push(view.level(cap, t));
|
||||
const fl = view.fieldLevels(cap).map((f) => f.level);
|
||||
fieldMins.push(Math.min(...fl));
|
||||
row.footprint.push(fp); row.fieldAvg.push(mean(fl)); row.pops.push(towns.length); row.core.push(view.level(cap, 'core_router'));
|
||||
row.spentBuild.push(bot ? (bot.spent.build || 0) : 0); row.spentTrain.push(bot ? (bot.spent.train || 0) : 0); row.spentResearch.push(bot ? (bot.spent.research || 0) : 0);
|
||||
row.stock.push(towns.reduce((s2, t) => s2 + RES.reduce((q, r) => q + R.resourcesAt(t, now).amounts[r], 0), 0));
|
||||
if (core10Rows.has(op.id)) { const d0 = (core10Rows.get(op.id) - op.created_at) / DAY; core10.push(d0); (milestones[a] || (milestones[a] = { core10: [], exp1: [] })).core10.push(d0); }
|
||||
if (exp1Rows.has(op.id)) { const d1 = (exp1Rows.get(op.id) - op.created_at) / DAY; expand1.push(d1); (milestones[a] || (milestones[a] = { core10: [], exp1: [] })).exp1.push(d1); }
|
||||
}
|
||||
const archTable = {};
|
||||
for (const a of Object.keys(byArch)) {
|
||||
const r = byArch[a];
|
||||
const cs = col.ops;
|
||||
let raids = 0, wins = 0, loot = 0, lost = 0, hit = 0, hitLoot = 0, incWins = 0, incHw = 0;
|
||||
for (const b of sim.bots) if (b.archetype === a) {
|
||||
const s = cs.get(b.operatorId);
|
||||
if (!s) continue;
|
||||
raids += s.raids; wins += s.raidWins; loot += s.raidLoot; lost += s.raidLostValue; hit += s.hit; hitLoot += s.hitLoot; incWins += s.incumbentWins; incHw += s.incumbentHw;
|
||||
}
|
||||
archTable[a] = {
|
||||
n: r.n, footprintMean: round(mean(r.footprint), 0), footprintP50: round(percentiles(r.footprint, [50]).p50 || 0, 0), fieldAvg: round(mean(r.fieldAvg), 1), core: round(mean(r.core), 1), pops: round(mean(r.pops), 2),
|
||||
spentBuild: round(mean(r.spentBuild), 0), spentTrain: round(mean(r.spentTrain), 0), spentResearch: round(mean(r.spentResearch), 0), stock: round(mean(r.stock), 0),
|
||||
netWorth: round(mean(r.spentBuild) + mean(r.spentTrain) + mean(r.spentResearch) + mean(r.stock), 0),
|
||||
raids: raids, raidWins: wins, lootTaken: round(loot, 0), raidLostValue: round(lost, 0), timesHit: hit, lootLostToRaids: round(hitLoot, 0), incumbentWins: incWins, incumbentHardware: incHw,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- combat summary
|
||||
const raid = col.battles.raid;
|
||||
const samples = col.raidSamples;
|
||||
const ratio = samples.filter((s) => s.attLost > 0).map((s) => s.loot / s.attLost);
|
||||
const lootPerRaid = samples.map((s) => s.loot);
|
||||
const ageBuckets = { '<3d': 0, '3-4d': 0, '4-7d': 0, '7-14d': 0, '14d+': 0 };
|
||||
for (const s of samples) { const a = s.targetAgeDays; ageBuckets[a < 3 ? '<3d' : a < 4 ? '3-4d' : a < 7 ? '4-7d' : a < 14 ? '7-14d' : '14d+'] += 1; }
|
||||
const undefended = samples.filter((s) => s.undefended);
|
||||
const combat = {
|
||||
reports: col.byType,
|
||||
raids: { n: raid.n, wins: raid.att, winRate: raid.n ? raid.att / raid.n : null, lootTotal: round(raid.loot, 0), lootRes: raid.lootRes, lootPerRaid: percentiles(lootPerRaid, [10, 50, 90]), attackerLostValue: round(raid.attLost, 0), defenderLostValue: round(raid.defLost, 0),
|
||||
lootPerLostValue: raid.attLost > 0 ? round(raid.loot / raid.attLost, 2) : null, undefendedShare: samples.length ? round(undefended.length / samples.length, 3) : null, undefendedLoot: round(sum(undefended.map((s) => s.loot)), 0),
|
||||
lootOverLossValue: percentiles(ratio, [10, 50, 90]), targetAge: ageBuckets, attackOverDefence: percentiles(samples.filter((s) => s.D > 0).map((s) => s.A / s.D), [10, 50, 90]) },
|
||||
attacks: col.battles.attack, takeoverBattles: col.battles.takeover, takeovers: col.takeovers, siege: col.siege,
|
||||
scans: col.scans, incumbent: col.incumbent, landing: col.landing, movementFailed: col.movementFailed,
|
||||
unitsLost: col.unitsLost, unitsConsumed: col.unitsConsumed, decommissioned: col.decommissioned, unitsOfflineNotes: col.unitsOfflineNotes,
|
||||
};
|
||||
|
||||
// ---- trade, alliances
|
||||
const tradeRows = db.all('SELECT status, COUNT(*) AS n, SUM(give_amount) AS give, SUM(want_amount) AS want FROM trade_offers GROUP BY status');
|
||||
const trade = { byStatus: Object.fromEntries(tradeRows.map((r) => [r.status, { n: r.n, give: r.give, want: r.want }])), refundClipped: ledger.sinkClip, clipEvents: ledger.clipEvents,
|
||||
cargoLost: col.cargoLostTotal, cargoLostEvents: col.cargoLostEvents };
|
||||
const completed = db.all("SELECT give_res, give_amount, want_res, want_amount FROM trade_offers WHERE status = 'completed'");
|
||||
trade.volumeCompleted = sum(completed.map((r) => r.give_amount + r.want_amount));
|
||||
trade.ratio = percentiles(completed.map((r) => r.give_amount / r.want_amount), [10, 50, 90]);
|
||||
const allianceRows = db.all('SELECT a.id, a.tag, (SELECT COUNT(*) FROM alliance_members m WHERE m.alliance_id = a.id) AS members FROM alliances a ORDER BY a.id');
|
||||
const relRows = db.all('SELECT state, COUNT(*) AS n FROM alliance_relations GROUP BY state');
|
||||
const alliances = {
|
||||
count: allianceRows.length, members: percentiles(allianceRows.map((a) => a.members), [10, 50, 90]), membersMax: Math.max(0, ...allianceRows.map((a) => a.members)),
|
||||
inAlliance: db.get('SELECT COUNT(*) AS n FROM operators WHERE alliance_id IS NOT NULL').n, operators: ops.length,
|
||||
relations: Object.fromEntries(relRows.map((r) => [r.state, r.n])),
|
||||
proposals: Object.fromEntries(db.all('SELECT status, COUNT(*) AS n FROM alliance_proposals GROUP BY status').map((r) => [r.status, r.n])),
|
||||
};
|
||||
|
||||
// ---- endgame
|
||||
const endgame = sim.endgame.summary(now);
|
||||
|
||||
// ---- perf and errors
|
||||
const latency = {};
|
||||
const all = [];
|
||||
for (const k of Object.keys(lat)) { latency[k] = Object.assign({ n: lat[k].length }, percentiles(lat[k], [50, 95, 99])); for (const v of lat[k]) all.push(v); }
|
||||
const failedRows = db.all("SELECT id, type, error FROM events WHERE status = 'failed' ORDER BY id LIMIT 10");
|
||||
const evByStatus = Object.fromEntries(db.all('SELECT status, COUNT(*) AS n FROM events GROUP BY status').map((r) => [r.status, r.n]));
|
||||
const evByType = Object.fromEntries(db.all("SELECT type, COUNT(*) AS n FROM events WHERE status = 'done' GROUP BY type").map((r) => [r.type, r.n]));
|
||||
const errorRows = Object.keys(errors).sort((a, b) => errors[b] - errors[a]).map((k) => ({ key: k, n: errors[k], expected: EXPECTED.has(k.split(':').slice(1).join(':')) }));
|
||||
// production lost to the storage cap: what the rates would have produced (sampled) against what was really stored
|
||||
const unsettled = { fiber: 0, hardware: 0, capital: 0 };
|
||||
for (const row of db.all('SELECT * FROM towns')) { const t = S.townFromRow(db, row, world); const cur = R.resourcesAt(t, now).amounts; for (const r of RES) unsettled[r] += cur[r] - row[r]; }
|
||||
const waste = {};
|
||||
for (const r of RES) { const actual = ledger.production[r] + unsettled[r]; waste[r] = sim.potential[r] > 0 ? round(Math.max(0, 1 - actual / sim.potential[r]) * 100, 1) : 0; }
|
||||
const perf = {
|
||||
wallSeconds: round(wallMs / 1000, 2), commands: commandsRun, commandsOk, commandsPerSecond: round(commandsRun / (wallMs / 1000), 0),
|
||||
latencyMs: Object.assign({ n: all.length }, percentiles(all, [50, 95, 99])), latencyByCommand: latency,
|
||||
eventsProcessed, eventsDone: evByType, runDueSeconds: round(runDueMs / 1000, 2),
|
||||
simulatedPerWallSecond: round(o.days * DAY / 1000 / (wallMs / 1000) / 3600, 1), // simulated hours per wall second
|
||||
};
|
||||
|
||||
// ---- invariants
|
||||
const resBad = invariantLog.filter((r) => !r.resourcesOk);
|
||||
const negBad = invariantLog.filter((r) => r.negatives > 0);
|
||||
const unitBad = invariantLog.filter((r) => Object.keys(r.unitDrift).length);
|
||||
const failedEvents = fin.failed;
|
||||
const invariants = {
|
||||
ok: !resBad.length && !negBad.length && !failedEvents && !unitBad.length,
|
||||
resources: { ok: !resBad.length, worstDrift: Math.max(0, ...invariantLog.map((r) => r.worstDrift)), tolerance: fin.res.tolerance, final: fin.res.perResource, firstBad: resBad[0] || null },
|
||||
units: { ok: !unitBad.length, trained: fin.trained, alive: fin.alive, lost: fin.lost, drift: fin.unitDrift, firstBad: unitBad[0] || null },
|
||||
negativeStock: { ok: !negBad.length, firstBad: negBad[0] || null },
|
||||
failedEvents: { n: failedEvents, sample: failedRows },
|
||||
unexpectedErrors: { n: unexpected.length, sample: unexpected.slice(0, 10) },
|
||||
serverLog: logs.slice(0, 10),
|
||||
};
|
||||
if (unexpected.length) invariants.ok = false;
|
||||
if (logs.length) invariants.ok = false;
|
||||
|
||||
const meta = {
|
||||
players: o.players, days: o.days, speed: o.speed, seed: o.seed, radius: o.radius, sessionsPerDay: o.sessionsPerDay || 'per archetype', alwaysOn: !!o.alwaysOn, joinDays: o.joinDays,
|
||||
mix: Object.fromEntries(Object.entries(sim.bots.reduce((m, b) => { m[b.archetype] = (m[b.archetype] || 0) + 1; return m; }, {})).sort()),
|
||||
set: o.set || [], worldId: world.id, endAt: now,
|
||||
};
|
||||
|
||||
return {
|
||||
meta, invariants, days,
|
||||
final: { levels: Object.fromEntries(Object.keys(levels).map((k) => [k, { mean: round(mean(levels[k]), 2), hist: histogram(levels[k], 20) }])), fieldMin: percentiles(fieldMins, [10, 50, 90]),
|
||||
pops: popsDist, footprint: percentiles(footprints, [10, 50, 90]), core10Days: percentiles(core10, [10, 50, 90]), core10Reached: core10.length, firstExpansionDays: percentiles(expand1, [10, 50, 90]), firstExpansionReached: expand1.length,
|
||||
milestones: Object.fromEntries(Object.entries(milestones).map(([k, v]) => [k, { core10Days: percentiles(v.core10, [10, 50, 90]), firstExpansionDays: percentiles(v.exp1, [10, 50, 90]) }])),
|
||||
unitsAlive: fin.alive, byArchetype: archTable, eventsFailed: evByStatus.failed || 0 },
|
||||
storageWastePct: waste, combat, trade, alliances, endgame,
|
||||
errors: { rows: errorRows, expectedTotal: errorRows.filter((r) => r.expected).reduce((s2, r) => s2 + r.n, 0), unexpectedTotal: errorRows.filter((r) => !r.expected).reduce((s2, r) => s2 + r.n, 0), commandCounts: counts },
|
||||
botLogs: sim.bots.reduce((m, b) => { for (const k of Object.keys(b.log)) m[k] = (m[k] || 0) + b.log[k]; return m; }, {}),
|
||||
perf,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { build };
|
||||
61
tools/bot/util.js
Normal file
61
tools/bot/util.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
'use strict';
|
||||
/* Small helpers for the bot harness: seeded randomness, statistics, formatting. No game logic here. */
|
||||
const R = require('../../public/js/rules.js');
|
||||
|
||||
const HOUR = 3600 * 1000;
|
||||
const DAY = 24 * HOUR;
|
||||
|
||||
// A seeded generator with helpers. Everything a bot decides comes from one of these (never Math.random).
|
||||
function makeRng(seed, a, b) {
|
||||
const next = R.rng(R.hash(seed | 0, a | 0, b | 0));
|
||||
const r = () => next();
|
||||
r.int = (lo, hi) => lo + Math.floor(next() * (hi - lo + 1)); // inclusive
|
||||
r.pick = (list) => list[Math.floor(next() * list.length)];
|
||||
r.chance = (p) => next() < p;
|
||||
r.range = (lo, hi) => lo + next() * (hi - lo);
|
||||
return r;
|
||||
}
|
||||
|
||||
function pct(sorted, p) {
|
||||
if (!sorted.length) return 0;
|
||||
const i = Math.min(sorted.length - 1, Math.max(0, Math.round((p / 100) * (sorted.length - 1))));
|
||||
return sorted[i];
|
||||
}
|
||||
function percentiles(values, ps) {
|
||||
const s = values.filter((v) => Number.isFinite(v)).sort((a, b) => a - b);
|
||||
const out = {};
|
||||
for (const p of ps || [10, 50, 90]) out['p' + p] = s.length ? pct(s, p) : null;
|
||||
out.n = s.length;
|
||||
return out;
|
||||
}
|
||||
const mean = (a) => (a.length ? a.reduce((s, v) => s + v, 0) / a.length : 0);
|
||||
const sum = (a) => a.reduce((s, v) => s + v, 0);
|
||||
const round = (v, d) => { const k = Math.pow(10, d === undefined ? 1 : d); return Math.round(v * k) / k; };
|
||||
|
||||
// Seeded string key for a stable iteration order.
|
||||
const byId = (a, b) => a.id - b.id;
|
||||
|
||||
function fmt(v, d) {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return '-';
|
||||
if (typeof v !== 'number') return String(v);
|
||||
const a = Math.abs(v);
|
||||
if (d !== undefined) return v.toFixed(d);
|
||||
if (a >= 1e6) return (v / 1e6).toFixed(2) + 'M';
|
||||
if (a >= 1e4) return (v / 1e3).toFixed(1) + 'k';
|
||||
if (a >= 100) return String(Math.round(v));
|
||||
if (a >= 10) return v.toFixed(1);
|
||||
return v.toFixed(2);
|
||||
}
|
||||
|
||||
function table(rows, header) {
|
||||
const all = header ? [header].concat(rows) : rows;
|
||||
const w = [];
|
||||
for (const r of all) r.forEach((c, i) => { w[i] = Math.max(w[i] || 0, String(c).length); });
|
||||
return all.map((r) => r.map((c, i) => (i === 0 ? String(c).padEnd(w[i]) : String(c).padStart(w[i]))).join(' ')).join('\n');
|
||||
}
|
||||
|
||||
// Add `n` to obj[key] (counter maps).
|
||||
const bump = (obj, key, n) => { obj[key] = (obj[key] || 0) + (n === undefined ? 1 : n); };
|
||||
const addInto = (a, b) => { for (const k of Object.keys(b || {})) a[k] = (a[k] || 0) + b[k]; return a; };
|
||||
|
||||
module.exports = { HOUR, DAY, makeRng, pct, percentiles, mean, sum, round, byId, fmt, table, bump, addInto };
|
||||
54
tools/bot/view.js
Normal file
54
tools/bot/view.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Read helpers for the bots: what a client would see (own POPs with the same shape rules.js previews use, the map's towns,
|
||||
* pending queues). Plain reads through the server's own modules; nothing here writes. Created per run, after the data overrides
|
||||
* were applied (the server modules cache some constants when first required).
|
||||
*/
|
||||
module.exports = function makeView(db, world) {
|
||||
const R = require('../../public/js/rules.js');
|
||||
const S = require('../../server/state');
|
||||
const U = require('../../server/military/units');
|
||||
const trainCmd = require('../../server/commands/train');
|
||||
|
||||
const v = {
|
||||
world,
|
||||
townRows(opId) { return db.all('SELECT * FROM towns WHERE owner_id = ? ORDER BY is_capital DESC, id', opId); },
|
||||
towns(opId) { return v.townRows(opId).map((r) => S.townFromRow(db, r, world)); },
|
||||
town(id) { return S.loadTown(db, id); },
|
||||
pendingBuilds(townId) { return S.pendingBuilds(db, townId); },
|
||||
trainQueue(townId, building) { return trainCmd.pendingBatches(db, townId, building); },
|
||||
researchBusy(townId) { return !!db.get("SELECT 1 AS x FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' LIMIT 1", townId); },
|
||||
researchLevels(townId) { return U.researchLevels(db, townId); },
|
||||
home(townId) { return U.homeUnits(db, townId); },
|
||||
operator(id) { return db.get('SELECT * FROM operators WHERE id = ?', id); },
|
||||
// Every POP of every other operator with what the map shows (position, owner, alliance, protection).
|
||||
otherTowns(opId) {
|
||||
return db.all(`SELECT t.id, t.x, t.y, t.owner_id AS ownerId, t.is_capital AS isCapital, o.protection_until AS prot, o.alliance_id AS ally, o.name AS opName
|
||||
FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.world_id = ? AND t.owner_id != ? ORDER BY t.id`, world.id, opId);
|
||||
},
|
||||
outgoing(opId) { return db.all("SELECT id, type, to_town_id AS toTownId, to_x AS tx, to_y AS ty, arrive_at AS arriveAt, units, extra FROM movements WHERE owner_id = ? AND status = 'out' AND type != 'return' ORDER BY id", opId); },
|
||||
incomingTo(townIds) {
|
||||
if (!townIds.length) return [];
|
||||
return db.all("SELECT id, type, owner_id AS ownerId, to_town_id AS toTownId, arrive_at AS arriveAt FROM movements WHERE status = 'out' AND type IN ('raid','attack','takeover','scan') AND to_town_id IN (" + townIds.map(() => '?').join(',') + ')', ...townIds);
|
||||
},
|
||||
// New reports of this user since `cursor` ({ at, seen }; mutated). Not "id > last id": see collector.js (ids are reused after a cleanup).
|
||||
reportsFor(userId, cursor) {
|
||||
const rows = db.all(`SELECT r.id, r.type, r.created_at AS at, r.data, rr.role FROM reports r JOIN report_recipients rr ON rr.report_id = r.id
|
||||
WHERE rr.user_id = ? AND r.created_at >= ? AND r.type IN ('scan','raid','attack','takeover','settle','incumbent','landing') ORDER BY r.created_at, r.id`, userId, cursor.at);
|
||||
const out = [];
|
||||
for (const x of rows) {
|
||||
if (x.at === cursor.at && cursor.seen.has(x.id)) continue;
|
||||
if (x.at > cursor.at) { cursor.at = x.at; cursor.seen = new Set(); }
|
||||
cursor.seen.add(x.id);
|
||||
out.push(Object.assign(x, { data: JSON.parse(x.data) }));
|
||||
}
|
||||
return out;
|
||||
},
|
||||
footprint(opId, now) { return U.operatorFootprint(db, opId, now); },
|
||||
level(T, type) { return T.buildings[type] ? T.buildings[type].level : 0; },
|
||||
fieldLevels(T) { const out = []; for (let i = 1; i <= 18; i++) { const b = T.buildings['f' + i]; if (b) out.push({ key: 'f' + i, type: b.type, level: b.level }); } return out; },
|
||||
peering(opId) { return require('../../server/alliances').peeringLevel(db, opId); },
|
||||
R, U,
|
||||
};
|
||||
return v;
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue