'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; this.egDefTarget = 0; } // ------------------------------------------------------------------ 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 * R.storageCap(t)) && !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 || !!this.egDefTarget; 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 || !!this.egDefTarget; 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 = R.storageCap(t); 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 = R.storageCap(t); 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(R.transportCapacity(this.sim.world.speed), Math.floor((cur.amounts[surplus] - 0.4 * cap) * 0.6)); if (give < 100) continue; const want = Math.min(R.transportCapacity(this.sim.world.speed), 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 };