'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 };