Built: - Economy: raid loot capped to the room the raiders have at home (rest stays with the victim, "lootLeft" in the report); trade escrow reserves its room so refunds always fit; trade accept refuses with no_room_for_goods when the goods would not fit. Loot destroyed per 30-day run 31-61k -> ~1k, refunds clipped ~27k -> 0 (docs/BALANCE.md, 3 seeds). - End game: members of the holding alliance garrison landing sites (migration 005_site_garrison.sql), garrison counts in site defence, 72 h capture shield, withdraw route, POP view lists garrisoned units. Shipping capacity scales with world speed (3x world: winner 76-98 -> ~30-36 days after sites open). Bot runs show real contests (84-194 attacks on held sites at 1x). - Ops: deploy/update.sh (backup, stop, ff-merge, npm ci --ignore-scripts, health check, rollback), deploy/upstream-offsite (rsync only), admin end-world snapshots results, EPIPE fix, docs/workflows/ filled in. - e2e 62 -> 163 checks: units, raids/reports, alliance+messages, trade, end game, nb, PWA, reconnect, slow polling fallback (opt-in). Two app bugs found: message push ignored, "New" button stayed English. Tested: npm test 274/274, openapi check, npm run e2e 163/163 (137 s), bot runs 50x30d seeds 1-3 and 140-day/60-day speed-3 end-game runs INVARIANTS OK, adversarial review pass (findings fixed or documented). NOT tested: update.sh on a real box (systemd, real npm, runuser; stubs only, shellcheck not installed), garrison card/loot text on a phone, Node 22.13, humans. Known leaks left open and documented (BALANCE S6): loot/shipments can still overflow when stock arrives in flight, bounced backbone shipments lose overflow (reported to the sender). Garrison numbers (heldDefenceMult 2, shield 72 h) are first guesses from 2 seeds. Not claimed: balanced. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
399 lines
23 KiB
JavaScript
399 lines
23 KiB
JavaScript
'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 a site with NO garrison has only a static defence that waves cannot wear down (nothing to kill), so ONE member
|
|
* with an Ops lab trains an army whose attack beats it on its own and attacks
|
|
* assault a site WITH a garrison (E6) is worn down by waves: every member with an Ops lab trains crews towards a share of
|
|
* what the alliance needs (about 1.15 x static + 2.2 x garrison), and once a war game over the members' real armies
|
|
* (rules.resolveBattle, wave by wave, the garrison shrinking by the real loss law) says the last wave takes the site,
|
|
* the plan says GO and every member with an army sends it at its next sitting (arrival order is the real one)
|
|
* 3. holders once the alliance holds a site every member ships its spare Fiber/Hardware/Capital to it (transport links,
|
|
* rules.transportCapacity each), anyone starts the next Backbone node level when the stockpile pays for it, and
|
|
* (contest, unless --no-contest) members station their defenders in the site and train more, towards what the
|
|
* strongest rival alliance could throw at it (the holders scout their rivals; bots read it from the db)
|
|
*
|
|
* 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 ATTACK_UNITS = ['script_crew', 'botnet'];
|
|
const DEFENDERS = ['blue_team', 'soc_analyst']; // movable defenders (honeypots are fixed)
|
|
|
|
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 G = require('../../server/military/garrison');
|
|
const contest = sim.opts.contest !== false;
|
|
const log = { assaults: 0, assaultGo: 0, assaultSkips: {}, garrisoned: 0, garrisonSends: 0, garrisonPeak: 0, garrisonTrained: 0, 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 });
|
|
}
|
|
|
|
// What a site is worth at `at`: its static defence (heavy while nobody holds it, light once an alliance does) and its garrison.
|
|
function siteDefence(s, at) {
|
|
const held = !!s.holder_alliance_id;
|
|
const staticDef = R.backboneDefence(sim.world.seed, s.x, s.y, E.ageDays(sim.world, at), s.level || 0, held);
|
|
const g = s.id ? G.defenders(sim.db, s.id, at) : { groups: [], power: 0 };
|
|
return { staticDef, garrison: g.power, groups: g.groups, total: staticDef + g.power };
|
|
}
|
|
const defenceAt = (s, at) => siteDefence(s, at).total;
|
|
|
|
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) { bot.armyOverride = 0; hold(bot, towns, row, now); return; }
|
|
// not ours yet. A site with a garrison is worn down by waves (assault), one without has a static defence that only a single
|
|
// army can beat (striker); the other members carry on with their economy
|
|
bot.egForce = null; bot.egDefTarget = 0;
|
|
const site = row || { id: null, idx: plan.site.idx, x: plan.site.x, y: plan.site.y, level: 0, holder_alliance_id: null };
|
|
const flight = R.movementMs(R.distance(main.x, main.y, site.x, site.y), { script_crew: 1 }, sim.world.speed);
|
|
const d = siteDefence(site, now + flight);
|
|
const shielded = E.shieldUntil(site, sim.world) > now + flight; // just taken: nothing can be attacked until the shield is down
|
|
if (contest && d.garrison > 0) { assault(bot, towns, plan, site, d, allianceId, now, shielded); return; }
|
|
bot.armyOverride = 0;
|
|
if (plan.striker === bot.idx) strike(bot, main, plan, row, now, shielded);
|
|
}
|
|
|
|
// ---- assault: every member trains towards a share, the plan says GO when the war game over the real armies says the site falls
|
|
const sumRes = (u) => ATTACK_UNITS.reduce((a, k) => a + (u[k] || 0), 0);
|
|
|
|
// Production share of one member inside its alliance (what it can carry of the army the alliance needs).
|
|
function shareOf(bot, allianceId) {
|
|
let mine = 0, all = 0;
|
|
for (const m of members(allianceId)) {
|
|
const t = sim.view.towns(m.operatorId)[0];
|
|
if (!t) continue;
|
|
const r = R.ratesPerHour(t);
|
|
const v = (m.archetype === 'turtle' ? 0.3 : 1) * (r.fiber + r.hardware + r.capital);
|
|
all += v; if (m === bot) mine = v;
|
|
}
|
|
return all > 0 ? mine / all : 0;
|
|
}
|
|
|
|
// Every POP of the alliance with attackers at home, as armies { townId, opId, bot, units, research, flightMs, attack }, nearest first.
|
|
function armies(allianceId, site, now) {
|
|
const out = [];
|
|
for (const m of members(allianceId)) {
|
|
for (const t of sim.view.towns(m.operatorId)) {
|
|
if (!R.unitsOnline(t, now)) continue;
|
|
const home = sim.view.home(t.id);
|
|
const units = {};
|
|
for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u];
|
|
if (!sumRes(units)) continue;
|
|
const research = sim.view.researchLevels(t.id);
|
|
const attack = R.attackPower(units, research);
|
|
if (attack < 400) continue;
|
|
out.push({ townId: t.id, opId: m.operatorId, units, research, attack, flightMs: R.movementMs(R.distance(t.x, t.y, site.x, site.y), units, sim.world.speed) });
|
|
}
|
|
}
|
|
return out.sort((a, b) => a.flightMs - b.flightMs || a.townId - b.townId);
|
|
}
|
|
|
|
// The war game: the armies arrive in this order, one battle each, against the static part (x margin) and the garrison, which shrinks
|
|
// by the real loss law. -> number of waves it takes, or 0 when the last wave still loses.
|
|
function wargame(list, d, margin) {
|
|
let groups = d.groups.filter((g) => g.online).map((g) => ({ id: g.id, units: Object.assign({}, g.units), research: g.research }));
|
|
for (let i = 0; i < list.length; i++) {
|
|
const b = R.resolveBattle({ kind: 'attack', attackers: { units: list[i].units, research: list[i].research }, defenders: groups, firewall: 0, staticDefence: d.staticDef * margin });
|
|
if (b.attackerWins) return i + 1;
|
|
groups = groups.map((g) => { const r = b.defenders.find((x) => x.id === g.id); return { id: g.id, units: r ? r.survivors : g.units, research: g.research }; });
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
function assault(bot, towns, plan, site, d, allianceId, now, shielded) {
|
|
const view = sim.view;
|
|
const main = towns[0];
|
|
// training: this member's share of ~1.15 x static + 2.2 x garrison (a lost wave only kills ratio^1.5 of the garrison)
|
|
const need = 1.15 * d.staticDef + 2.2 * d.garrison;
|
|
const research = view.researchLevels(main.id);
|
|
const mult = R.researchMult(R.researchLevel(research, 'script_crew', 'attack'));
|
|
bot.egForce = { ops_lab: 6, research_lab: 5, noc: 1 };
|
|
bot.armyOverride = Math.ceil(need * shareOf(bot, allianceId) / (R.unitDef('script_crew').attack * mult));
|
|
if (shielded) { bump(log.assaultSkips, 'shielded'); return; }
|
|
// GO? evaluated at most every 3 hours per alliance
|
|
if (!plan.go || now > plan.go.until) {
|
|
plan.go = null;
|
|
if (!plan.checkedAt || now - plan.checkedAt >= 3 * HOUR) {
|
|
plan.checkedAt = now;
|
|
const list = armies(allianceId, site, now);
|
|
const waves = list.length ? wargame(list, d, 1.15) : 0;
|
|
if (waves) { plan.go = { until: now + 30 * HOUR, towns: new Set(list.map((a) => a.townId)), waves, planned: list.length }; log.assaultGo += 1; }
|
|
else bump(log.assaultSkips, list.length ? 'army_short' : 'no_army');
|
|
}
|
|
}
|
|
if (!plan.go) return;
|
|
for (const t of towns) {
|
|
if (!plan.go.towns.has(t.id)) continue;
|
|
plan.go.towns.delete(t.id);
|
|
const home = view.home(t.id);
|
|
const units = {};
|
|
for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u];
|
|
if (!sumRes(units)) continue;
|
|
const r = bot.call('sendMovement', { fromTownId: t.id, type: 'attack', x: site.x, y: site.y, units });
|
|
if (r.ok) { log.assaults += 1; log.strikes += 1; } else bump(log.strikeSkips, r.code);
|
|
}
|
|
}
|
|
|
|
// ---- striker
|
|
function strike(bot, main, plan, row, now, shielded) {
|
|
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 = siteDefence({ x: site.x, y: site.y, level: site.level || 0, id: site.id, holder_alliance_id: site.holder_alliance_id }, now + flight).total;
|
|
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 (shielded) bump(log.strikeSkips, 'shielded');
|
|
else 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');
|
|
}
|
|
|
|
// ---- garrison (holders): what could the strongest rival throw, keep that much defence in the site
|
|
function rivalThreat(allianceId, now) {
|
|
const plan = plans.get(allianceId);
|
|
if (plan.threatAt && now - plan.threatAt < 4 * HOUR) return plan.threat;
|
|
let best = 0;
|
|
const byAlliance = new Map();
|
|
for (const b of sim.bots) {
|
|
const op = sim.view.operator(b.operatorId);
|
|
if (!op || !op.alliance_id || op.alliance_id === allianceId) continue;
|
|
let v = 0;
|
|
for (const t of sim.view.towns(b.operatorId)) {
|
|
const home = sim.view.home(t.id);
|
|
const units = {};
|
|
for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u];
|
|
v += R.attackPower(units, sim.view.researchLevels(t.id));
|
|
}
|
|
for (const m of sim.view.outgoing(b.operatorId)) { const u = JSON.parse(m.units || '{}'); v += R.attackPower({ script_crew: u.script_crew || 0, botnet: u.botnet || 0 }, {}); }
|
|
byAlliance.set(op.alliance_id, (byAlliance.get(op.alliance_id) || 0) + v);
|
|
}
|
|
for (const [aid, v] of byAlliance) {
|
|
if (A.memberCount(sim.db, aid) < sim.opts.endgameMinMembers) continue;
|
|
const rel = A.relationBetween(sim.db, allianceId, aid);
|
|
if (rel === 'nap' || rel === 'confed') continue;
|
|
best = Math.max(best, v);
|
|
}
|
|
plan.threatAt = now; plan.threat = best;
|
|
return best;
|
|
}
|
|
|
|
function garrison(bot, towns, row, now, allianceId) {
|
|
const view = sim.view;
|
|
const d = siteDefence(row, now);
|
|
const threat = rivalThreat(allianceId, now);
|
|
const goal = Math.max(1.1 * threat, 1.5 * d.staticDef); // total defence in the site the alliance wants (static + garrison)
|
|
const share = shareOf(bot, allianceId);
|
|
const mine = G.ofTown(sim.db, towns[0].id);
|
|
const main = towns[0];
|
|
// the garrison this member should keep: its share of (goal - static)
|
|
const want = Math.max(0, (goal - d.staticDef) * share);
|
|
bot.egDefTarget = want;
|
|
bot.egForce = { noc: 5, research_lab: 3 }; // blue teams need them
|
|
const have = R.defencePower(mine, {}) + R.defencePower(view.home(main.id), {}) + bot.queuedDefence(main);
|
|
if (have < want) {
|
|
const unit = R.unitMissing(main, 'blue_team').length === 0 ? 'blue_team' : 'soc_analyst';
|
|
const n = bot.trainSome(main, unit, Math.ceil((want - have) / R.unitDef(unit).defence), now, false);
|
|
log.garrisonTrained += n || 0;
|
|
}
|
|
// send every movable defender at home into the site (the member keeps none at home for the site)
|
|
for (const t of towns) {
|
|
const home = view.home(t.id);
|
|
const units = {};
|
|
for (const u of DEFENDERS) if (home[u] > 0) units[u] = home[u];
|
|
if (!Object.keys(units).length) continue;
|
|
if (!R.unitsOnline(t, now)) continue;
|
|
const r = bot.call('sendMovement', { fromTownId: t.id, type: 'reinforce', x: row.x, y: row.y, units });
|
|
if (r.ok) { log.garrisonSends += 1; log.garrisoned += Object.keys(units).reduce((a, k) => a + units[k], 0); } else bump(log.assaultSkips, 'garrison_' + r.code);
|
|
}
|
|
log.garrisonPeak = Math.max(log.garrisonPeak, siteDefence(row, now).garrison);
|
|
}
|
|
|
|
// ---- holders: ship and build
|
|
function hold(bot, towns, row, now) {
|
|
const view = sim.view;
|
|
if (contest) garrison(bot, towns, row, now, row.holder_alliance_id);
|
|
// 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 = R.storageCap(t);
|
|
const cargo = {};
|
|
let room = R.transportCapacity(sim.world.speed);
|
|
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 = sim.db.all('SELECT * FROM landing_sites WHERE world_id = ? AND level > 0', sim.world.id).reduce((m, r) => Math.max(m, siteDefence(r, now).total), 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,
|
|
contest: {
|
|
enabled: contest, assaultGo: log.assaultGo, assaultsSent: log.assaults, assaultSkips: log.assaultSkips, garrisonSends: log.garrisonSends, garrisonedUnits: log.garrisoned, garrisonTrained: log.garrisonTrained,
|
|
garrisonPeakPower: Math.round(log.garrisonPeak), garrisonNow: sites.map((x) => { const row = sim.db.get('SELECT id FROM landing_sites WHERE world_id = ? AND idx = ?', sim.world.id, x.idx); return row ? Math.round(G.defenders(sim.db, row.id, now).power) : 0; }),
|
|
attacksOnHeld: sim.col.landing.vsHeld, heldTaken: sim.col.landing.vsHeldTaken, metGarrison: sim.col.landing.vsGarrison, garrisonLostValue: Math.round(sim.col.landing.garrisonLostValue),
|
|
firstAttackOnHeldDay: sim.col.landing.firstVsHeldAt ? Math.round((sim.col.landing.firstVsHeldAt - sim.t0) / DAY * 10) / 10 : null, lastAttackOnHeldDay: sim.col.landing.lastVsHeldAt ? Math.round((sim.col.landing.lastVsHeldAt - sim.t0) / DAY * 10) / 10 : 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 };
|