'use strict'; /* * ALL game rules for UPSTREAM: pure, deterministic, no DOM, no I/O, no Date.now(). `now` and randomness are arguments. * Loads as a browser script (window.UpstreamRules, needs data.js first) and as a Node module. * The client uses this for previews; the server recomputes everything and never trusts a client-sent amount. * * Time model: every growing quantity is stored as (amount, updatedAt) and its rate follows from the buildings. The * server settles a town (stores the current value at the new time) before it changes anything that changes a rate. * Between settles the rate is constant, so `resourcesAt` is exact. * * Town shape these functions work on (built by server/state.js, or by the client from an API response): * { speed, updatedAt, res: { fiber, hardware, capital, battery }, footprint, * buildings: { [key]: { type, level } }, unitDraw, bonus: { fiber, hardware, capital } } */ (function (root, factory) { if (typeof module === 'object' && module.exports) module.exports = factory(require('./data.js')); else root.UpstreamRules = factory(root.UpstreamData); }(typeof self !== 'undefined' ? self : this, function (D) { const F = D.FORMULAS; const HOUR = D.HOUR_MS; const DAY = 24 * HOUR; const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k); // ------------------------------------------------------------------ seeded randomness // mulberry32: tiny, fast, good enough for map generation and combat variance. function rng(seed) { let a = seed >>> 0; return function () { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } // Stable 32-bit hash of a few integers (tile generation: the same (seed, x, y) always gives the same tile). function hash(a, b, c) { let h = (a | 0) ^ 0x9E3779B9; h = Math.imul(h ^ (b | 0), 0x85EBCA6B); h = Math.imul(h ^ (h >>> 13) ^ (c | 0), 0xC2B2AE35); h ^= h >>> 16; h = Math.imul(h, 0x27D4EB2F); h ^= h >>> 15; return h >>> 0; } // ------------------------------------------------------------------ geometry function distance(ax, ay, bx, by) { return Math.hypot(ax - bx, ay - by); } // ------------------------------------------------------------------ the map // Pure function of the world seed: 'land' | 'rural' | 'incumbent' | 'void' (outside the map). A rural tile also // says which resource it boosts. Towns are not part of this; they live in the database. // `ageDays` (optional, world days) adds the end game: from D.ENDGAME.openDay on, the landing sites report 'backbone' // (with `site`: its index). Without it (old callers, previews without a clock) the map is the plain terrain. // Terrain never changes: a landing site is always a land tile underneath, see backboneSites. function tileAt(seed, radius, x, y, ageDays) { const t = terrainAt(seed, radius, x, y); if (t.type === 'land' && ageDays !== undefined && ageDays >= D.ENDGAME.openDay) { const s = backboneSiteAt(seed, radius, x, y); if (s) return { type: 'backbone', site: s.index }; } return t; } function terrainAt(seed, radius, x, y) { if (Math.abs(x) > radius || Math.abs(y) > radius) return { type: 'void' }; if (Math.abs(x) <= 2 && Math.abs(y) <= 2) return { type: 'land' }; // keep the centre free const h = hash(seed, x, y) / 4294967296; if (h < D.TILE.ruralShare) { const kinds = D.TILE.ruralTypes; return { type: 'rural', bonus: kinds[hash(seed ^ 0x5bd1e995, x, y) % kinds.length] }; } if (h < D.TILE.ruralShare + D.TILE.incumbentShare) return { type: 'incumbent' }; return { type: 'land' }; } // The backbone landing sites: D.ENDGAME.sites fixed positions, a pure function of (seed, radius). One per sector of the // circle (jittered), on plain land tiles between siteRingMin and siteRingMax of the radius, never in the free centre and // at least siteMinSpacing apart. They exist from the start (spawn and settling refuse them) but only SHOW from openDay. // -> [{ index, x, y }] const siteCache = new Map(); function backboneSites(seed, radius) { const key = seed + '|' + radius; if (siteCache.has(key)) return siteCache.get(key); const E = D.ENDGAME; const out = []; for (let k = 0; k < E.sites; k++) { const rand = rng(hash(seed, k, 0xb4cb)); const ang = (k + 0.15 + 0.7 * rand()) * 2 * Math.PI / E.sites; const rr = radius * (E.siteRingMin + (E.siteRingMax - E.siteRingMin) * rand()); const cx = Math.round(Math.cos(ang) * rr), cy = Math.round(Math.sin(ang) * rr); let found = null; for (let d = 0; d <= radius && !found; d++) { // spiral outwards until a free land tile turns up for (let dy = -d; dy <= d && !found; dy++) { for (let dx = -d; dx <= d && !found; dx++) { if (Math.max(Math.abs(dx), Math.abs(dy)) !== d) continue; const x = cx + dx, y = cy + dy; if (terrainAt(seed, radius, x, y).type !== 'land') continue; if (Math.abs(x) <= 2 && Math.abs(y) <= 2) continue; if (out.some((s) => distance(s.x, s.y, x, y) < E.siteMinSpacing)) continue; found = { index: k, x, y }; } } } if (found) out.push(found); } if (siteCache.size > 64) siteCache.clear(); siteCache.set(key, out); return out; } function backboneSiteAt(seed, radius, x, y) { for (const s of backboneSites(seed, radius)) if (s.x === x && s.y === y) return s; return null; } const isBackboneSite = (seed, radius, x, y) => !!backboneSiteAt(seed, radius, x, y); // World age in world days (real days * speed). Negative ages are 0. function worldAgeDays(startAt, now, speed) { return Math.max(0, (now - startAt) / DAY * (speed || 1)); } // 'running' | 'backbone_open' | 'ended'. function worldPhase(status, ageDays) { if (status === 'ended') return 'ended'; return ageDays >= D.ENDGAME.openDay ? 'backbone_open' : 'running'; } // Rural areas within reach of (x, y): the tiles whose bonus a POP there enjoys. Biggest bonus counts max 3. function ruralNear(seed, radius, x, y) { const out = []; const r = F.ruralReach; for (let dy = -r; dy <= r; dy++) { for (let dx = -r; dx <= r; dx++) { if ((dx || dy) && Math.hypot(dx, dy) <= r) { const t = tileAt(seed, radius, x + dx, y + dy); if (t.type === 'rural') out.push({ x: x + dx, y: y + dy, bonus: t.bonus }); } } } out.sort((a, b) => Math.hypot(a.x - x, a.y - y) - Math.hypot(b.x - x, b.y - y) || a.x - b.x || a.y - b.y); return out.slice(0, F.ruralMax); } // Production bonus per resource for a POP at (x, y): { fiber, hardware, capital } as 0.25 steps. function ruralBonus(seed, radius, x, y) { const b = { fiber: 0, hardware: 0, capital: 0 }; for (const t of ruralNear(seed, radius, x, y)) b[t.bonus] += F.ruralBonus; return b; } // Where does the n-th new operator's capital go? Expanding ring around the centre so early joiners are central. // `occupied(x, y)` tells whether a tile is taken; `n` is the number of towns already in the world. // Returns {x, y} or null when the map is full. Deterministic for (seed, n, occupancy). function pickSpawn(seed, radius, n, towns) { const rand = rng(hash(seed, n, 0x51a3)); const spacing = D.TILE.spawnMinSpacing; const near = (x, y) => towns.some((t) => Math.max(Math.abs(t.x - x), Math.abs(t.y - y)) < spacing); let ring = D.TILE.spawnRingStart + Math.floor(Math.sqrt(n)) * D.TILE.spawnRingStep; for (; ring <= radius * 1.5 + D.TILE.spawnRingStep; ring += D.TILE.spawnRingStep) { const lo = Math.max(2, ring - D.TILE.spawnRingStep), hi = Math.min(radius, ring); for (let attempt = 0; attempt < 60; attempt++) { const ang = rand() * Math.PI * 2; const rr = lo + rand() * (hi - lo); const x = Math.round(Math.cos(ang) * rr), y = Math.round(Math.sin(ang) * rr); if (tileAt(seed, radius, x, y).type !== 'land' || isBackboneSite(seed, radius, x, y)) continue; if (near(x, y)) continue; return { x, y }; } } return null; } // ------------------------------------------------------------------ buildings const growth = (base, g, level) => base * Math.pow(g, level - 1); function buildingDef(type) { return hasOwn(D.BUILDINGS, type) ? D.BUILDINGS[type] : null; } // Keys: infra buildings use their type; fields f1..f18. const isFieldKey = (key) => /^f([1-9]|1[0-8])$/.test(key); // The fields a fresh POP gets: 4 of each type plus the two wild ones. Returns { f1: 'cable_yard', ... }. function fieldLayout(wild) { const types = []; for (const t of D.FIELD_TYPES) for (let i = 0; i < D.FIELDS_PER_TYPE; i++) types.push(t); for (let i = 0; i < D.WILD_SLOTS; i++) types.push((wild || D.START.wild)[i] || D.START.wild[i]); const out = {}; types.forEach((t, i) => { out['f' + (i + 1)] = t; }); return out; } // Cost to build `type` UP TO `level` (so level 1 is the base cost). function buildingCost(type, level) { const def = buildingDef(type); const out = {}; for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * Math.pow(F.costGrowth, level - 1)); return out; } function coreLevel(town) { const c = town.buildings.core_router; return c ? c.level : 0; } // Early-level discount on build time (data: F.earlyLevels, F.earlyTimeFactor; docs/BALANCE.md B4). Building up to level L takes // earlyTimeFactor x the normal time for L = 1, rising evenly to the full time at level earlyLevels + 1; from there on nothing changes. // earlyLevels 0 (or a factor of 1) switches it off. function earlyTimeFactor(level) { const n = F.earlyLevels || 0, f = F.earlyTimeFactor == null ? 1 : F.earlyTimeFactor; if (!(n > 0) || level > n) return 1; return f + (1 - f) * (level - 1) / n; } // Build time in ms to reach `level`. Core router shortens it; world speed divides it; the first levels get the early discount. function buildTimeMs(type, level, core, speed) { const def = buildingDef(type); const secs = def.time * Math.pow(F.timeGrowth, level - 1) * earlyTimeFactor(level) / (1 + F.coreSpeedPerLevel * core) / (speed || 1); return Math.max(F.minBuildMs, Math.round(secs * 1000)); } // Build slots (builds running at once): 1, one more from Core router F.secondQueueCoreLevel, and one more at each level listed // in F.extraQueueCores (data, default none). function queueSlots(town) { const core = coreLevel(town); let n = core >= F.secondQueueCoreLevel ? 2 : 1; for (const lv of F.extraQueueCores || []) if (core >= lv) n += 1; return n; } function storageCap(town) { const r = town.buildings.rack_hall; if (!r || r.level < 1) return F.storageBase / 4; // no rack hall: a small floor so the POP is not stuck return Math.round(F.storageBase * Math.pow(F.storageGrowth, r.level - 1)); } function batteryCap(town) { const b = town.buildings.battery_bank; return b && b.level > 0 ? Math.round(F.batteryBase * Math.pow(F.batteryGrowth, b.level - 1)) : 0; } // Per-hour output of one field at `level` (before world speed and bonuses). Level 0 produces nothing. function fieldOutputPerHour(level) { return level > 0 ? growth(F.productionBase, F.productionGrowth, level) : 0; } // Rates per hour for a town: production per resource, power out/draw/net. World speed scales production; power is // a rate of points, so it is not scaled (the battery drains faster in real time on fast worlds instead). function ratesPerHour(town) { const speed = town.speed || 1; const bonus = town.bonus || {}; const prod = { fiber: 0, hardware: 0, capital: 0 }; let powerOut = 0, draw = 0; for (const key of Object.keys(town.buildings)) { const b = town.buildings[key]; const def = buildingDef(b.type); if (!def) continue; if (def.kind === 'field') { const out = fieldOutputPerHour(b.level); const res = D.FIELD_PRODUCES[b.type]; if (res === 'power') powerOut += out; else prod[res] += out * speed * (1 + (bonus[res] || 0)); } else { draw += def.draw * b.level; } } draw += town.unitDraw || 0; return { fiber: prod.fiber, hardware: prod.hardware, capital: prod.capital, powerOut, powerDraw: draw, powerNet: powerOut - draw }; } // Current values at `now`, exact while the rates have not changed since town.updatedAt. Caps apply. function resourcesAt(town, now) { const dtH = Math.max(0, now - town.updatedAt) / HOUR; const rates = ratesPerHour(town); const cap = storageCap(town); const bcap = batteryCap(town); const speed = town.speed || 1; const out = {}; for (const r of D.RESOURCES) { // An amount already above the cap (the rack hall was lowered) is kept, it just stops growing. out[r] = Math.max(0, Math.min(Math.max(cap, town.res[r]), town.res[r] + rates[r] * dtH)); } out.battery = Math.max(0, Math.min(bcap, town.res.battery + rates.powerNet * speed * dtH)); return { amounts: out, caps: { fiber: cap, hardware: cap, capital: cap, battery: bcap }, rates }; } // When will the battery hit zero (ms epoch)? null if it never does at the current rates. Units go offline then. function batteryEmptyAt(town, now) { const { amounts, rates } = resourcesAt(town, now); if (rates.powerNet >= 0) return null; if (amounts.battery <= 0) return now; return now + Math.ceil(amounts.battery / (-rates.powerNet * (town.speed || 1)) * HOUR); } // Are units online right now? Offline when the battery is empty and net power is negative. function unitsOnline(town, now) { const { amounts, rates } = resourcesAt(town, now); return !(amounts.battery <= 0 && rates.powerNet < 0); } // Footprint points per day: every building of level L contributes sum over steps l=1..L of (1 + l/5). function footprintPerDay(town) { let total = 0; for (const key of Object.keys(town.buildings)) { const L = town.buildings[key].level; total += L * F.footprintBase + (L * (L + 1) / 2) / F.footprintDivisor; } return total * (town.speed || 1); } function footprintAt(town, now) { return town.footprint + footprintPerDay(town) * Math.max(0, now - town.updatedAt) / DAY; } // Footprint an operator needs to found or take over their n-th extra POP (n = 1 for the second POP). function footprintNeeded(extraTown) { return Math.round(F.footprintNeedBase * Math.pow(extraTown, F.footprintNeedExp)); } function loyaltyAt(loyalty, updatedAt, now, speed) { return Math.min(F.loyaltyMax, loyalty + F.loyaltyRegenPerHour * (speed || 1) * Math.max(0, now - updatedAt) / HOUR); } // ------------------------------------------------------------------ build planning // The one function both client (preview) and server (command) use to decide whether `key` can be built or // upgraded now. `pending` = the build events in flight: [{ key }]. `now` is for the resources at that moment. // Returns { ok, code, key, type, fromLevel, toLevel, cost, durationMs, missing }. // Codes are the stable API error codes: unknown_building, max_level, requirements_not_met, already_queued, // queue_full, not_enough_resources, not_buildable. function buildPlan(town, key, now, pending, typeHint) { pending = pending || []; const cur = hasOwn(town.buildings, key) ? town.buildings[key] : null; let type = cur ? cur.type : null; if (!type && !isFieldKey(key) && buildingDef(key)) type = key; // an infra building not built yet if (!type && typeHint && buildingDef(typeHint) && !isFieldKey(key)) type = typeHint; const base = { ok: false, key, type, fromLevel: cur ? cur.level : 0 }; const def = type && buildingDef(type); if (!def) return Object.assign(base, { code: 'unknown_building' }); if (def.special) return Object.assign(base, { code: 'not_buildable' }); if (isFieldKey(key) && !cur) return Object.assign(base, { code: 'unknown_building' }); // fields exist from the start if (!isFieldKey(key) && key !== type) return Object.assign(base, { code: 'unknown_building' }); const toLevel = base.fromLevel + 1; base.toLevel = toLevel; if (toLevel > def.maxLevel) return Object.assign(base, { code: 'max_level' }); const missing = []; for (const rq of def.requires) { const have = town.buildings[rq.type] ? town.buildings[rq.type].level : 0; if (have < rq.level) missing.push({ type: rq.type, level: rq.level, have }); } base.missing = missing; base.cost = buildingCost(type, toLevel); base.durationMs = buildTimeMs(type, toLevel, coreLevel(town), town.speed); if (missing.length) return Object.assign(base, { code: 'requirements_not_met' }); if (pending.some((p) => p.key === key)) return Object.assign(base, { code: 'already_queued' }); if (pending.length >= queueSlots(town)) return Object.assign(base, { code: 'queue_full' }); const have = resourcesAt(town, now).amounts; for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' }); base.ok = true; return base; } // The state a brand-new capital POP starts in. `wild` = the two wild field types. function initialBuildings(wild) { const layout = fieldLayout(wild); const out = {}; for (const key of Object.keys(layout)) out[key] = { type: layout[key], level: D.START.fieldLevel }; for (const type of Object.keys(D.START.infra)) out[type] = { type, level: D.START.infra[type] }; return out; } // ------------------------------------------------------------------ alliances and diplomacy // Member cap of an alliance for a given Peering office level (best POP of the leader). The server stores the cap at // founding and only ever raises it (server/alliances.js effectiveCap), so a lost building never kicks anyone. function allianceCap(peeringLevel) { return D.SOCIAL.allianceBaseSize + D.SOCIAL.allianceSizePerLevel * Math.max(0, Math.floor(peeringLevel || 0)); } // May a member with `role` perform `action` (a key of SOCIAL.permissions)? function allianceCan(role, action) { const list = hasOwn(D.SOCIAL.permissions, action) ? D.SOCIAL.permissions[action] : null; return !!list && list.indexOf(role) >= 0; } // Seniority: leader 4 .. member 1, unknown roles -1. function roleRank(role) { const i = D.SOCIAL.roles.indexOf(role); return i < 0 ? -1 : D.SOCIAL.roles.length - i; } const outranks = (a, b) => roleRank(a) > roleRank(b); // How an alliance may move a relation from `from` to `to`: 'immediate' | 'proposal' | 'delayed' | null (not allowed). function diplomacyMove(from, to) { const row = hasOwn(D.SOCIAL.diplomacyMoves, from) ? D.SOCIAL.diplomacyMoves[from] : null; return row && hasOwn(row, to) ? row[to] : null; } // Time a unilateral cancel of a pact takes (24 h at 1x, shorter on faster worlds). function pactCancelMs(worldSpeed) { return Math.max(1000, Math.round(D.SOCIAL.pactCancelHours * HOUR / (worldSpeed || 1))); } // ------------------------------------------------------------------ movement // Latency in ms for a distance in tiles at `speed` tiles/hour (unit speed), world speed `worldSpeed`; min 10 min. function latencyMs(dist, unitSpeed, worldSpeed) { const hours = dist / (unitSpeed * (worldSpeed || 1)); return Math.max(10 * 60 * 1000, Math.round(hours * HOUR)); } // ------------------------------------------------------------------ military: units, training, research (stages 3-4) // Units are always plain objects { unitId: count }. `research` is { 'unitId:attack': level, 'unitId:defence': level }. const MIL = D.MILITARY; function unitDef(id) { return hasOwn(D.UNITS, id) ? D.UNITS[id] : null; } const buildingLevel = (town, type) => (town.buildings[type] ? town.buildings[type].level : 0); const unitCount = (units) => Object.keys(units || {}).reduce((s, k) => s + (units[k] || 0), 0); const costValue = (cost) => D.RESOURCES.reduce((s, r) => s + ((cost && cost[r]) || 0), 0); const unitValue = (id) => costValue(unitDef(id).cost); const researchKey = (unit, stat) => unit + ':' + stat; const researchLevel = (research, unit, stat) => (research && research[researchKey(unit, stat)]) || 0; const researchMult = (level) => 1 + MIL.researchPerLevel * level; // attack | defence of one unit of this type, with research function unitStat(unit, stat, research) { return unitDef(unit)[stat] * researchMult(researchLevel(research, unit, stat)); } function unitCost(unit, count) { const def = unitDef(unit), out = {}; for (const r of D.RESOURCES) out[r] = def.cost[r] * count; return out; } // Training time in ms for a batch. The training building's level shortens it; world speed divides it. function trainTimeMs(unit, count, buildingLvl, speed) { const secs = unitDef(unit).time * count / (1 + MIL.trainSpeedPerLevel * buildingLvl) / (speed || 1); return Math.max(1000, Math.round(secs * 1000)); } // Missing requirements of a unit in a town: [{ type, level, have }]. The training building counts at level 1. function unitMissing(town, unit) { const def = unitDef(unit); const need = [{ type: def.building, level: 1 }].concat(def.requires); const best = {}; for (const r of need) best[r.type] = Math.max(best[r.type] || 0, r.level); const missing = []; for (const type of Object.keys(best)) { const have = buildingLevel(town, type); if (have < best[type]) missing.push({ type, level: best[type], have }); } return missing; } // Can `count` of `unit` be queued now? `tailAt` = due time of the last batch queued in the same building (batches of // one building run one after another). Codes: unknown_unit, validation_failed, requirements_not_met, not_enough_resources. function trainPlan(town, unit, count, now, tailAt) { const def = unitDef(unit); const base = { ok: false, unit, count }; if (!def) return Object.assign(base, { code: 'unknown_unit' }); if (!Number.isInteger(count) || count < 1 || count > MIL.maxBatch) return Object.assign(base, { code: 'validation_failed' }); const missing = unitMissing(town, unit); base.building = def.building; base.cost = unitCost(unit, count); base.durationMs = trainTimeMs(unit, count, buildingLevel(town, def.building), town.speed); base.startAt = Math.max(now, tailAt || 0); base.dueAt = base.startAt + base.durationMs; base.missing = missing; if (missing.length) return Object.assign(base, { code: 'requirements_not_met' }); const have = resourcesAt(town, now).amounts; for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' }); base.ok = true; return base; } // ---- research const RS = D.RESEARCH; function researchCost(unit, toLevel) { const def = unitDef(unit), out = {}; for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * RS.costFactor * Math.pow(RS.costGrowth, toLevel - 1)); return out; } // speedBonus: the operator's permanent research speed bonus from incumbent sites (0.1 = +10%). function researchTimeMs(unit, toLevel, labLevel, speed, speedBonus) { const secs = RS.timeBase * Math.pow(RS.timeGrowth, toLevel - 1) / (1 + RS.labSpeedPerLevel * labLevel) / (speed || 1) / (1 + (speedBonus || 0)); return Math.max(1000, Math.round(secs * 1000)); } function researchSpeedBonus(sitesTaken) { return Math.min(D.INCUMBENT.researchSpeedMax, D.INCUMBENT.researchSpeedBonus * sitesTaken); } // Plan one research level. `current` = level now, `busy` = a research is already running in this POP. // Codes: unknown_unit, not_researchable, max_level, requirements_not_met, queue_full, not_enough_resources. function researchPlan(town, unit, stat, current, busy, now, speedBonus) { const def = unitDef(unit); const base = { ok: false, unit, stat, fromLevel: current, toLevel: current + 1 }; if (!def) return Object.assign(base, { code: 'unknown_unit' }); if (RS.stats.indexOf(stat) < 0 || !(def[stat] > 0)) return Object.assign(base, { code: 'not_researchable' }); if (current >= RS.maxLevel) return Object.assign(base, { code: 'max_level' }); const lab = buildingLevel(town, 'research_lab'); const missing = unitMissing(town, unit); const needLab = base.toLevel + RS.labOffset; if (lab < needLab) missing.push({ type: 'research_lab', level: needLab, have: lab }); base.missing = missing; base.cost = researchCost(unit, base.toLevel); base.durationMs = researchTimeMs(unit, base.toLevel, lab, town.speed, speedBonus); if (missing.length) return Object.assign(base, { code: 'requirements_not_met' }); if (busy) return Object.assign(base, { code: 'queue_full' }); const have = resourcesAt(town, now).amounts; for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' }); base.ok = true; return base; } // ------------------------------------------------------------------ military: movements // Slowest speed (tiles/hour at 1x) among the units actually in the group; Infinity when empty. function slowestSpeed(units) { let s = Infinity; for (const k of Object.keys(units || {})) if (units[k] > 0 && unitDef(k)) s = Math.min(s, unitDef(k).speed); return s; } // Travel time of a unit group over `dist` tiles (min 10 min, see latencyMs). An empty group travels at transport speed. function movementMs(dist, units, worldSpeed) { const s = slowestSpeed(units); return latencyMs(dist, isFinite(s) ? s : D.TRANSPORT.speed, worldSpeed); } function transportMs(dist, worldSpeed) { return latencyMs(dist, D.TRANSPORT.speed, worldSpeed); } // Shape and role check of the units on a movement of `type`. null when fine, otherwise { code, reason }. function checkUnitsForType(type, units) { const roles = hasOwn(D.MOVE_ROLES, type) ? D.MOVE_ROLES[type] : null; if (!roles) return { code: 'validation_failed', reason: 'type carries no units' }; let total = 0; for (const k of Object.keys(units || {})) { const n = units[k]; const def = unitDef(k); if (!def) return { code: 'unknown_unit', reason: k }; if (!Number.isInteger(n) || n < 0) return { code: 'validation_failed', reason: 'bad count for ' + k }; if (n === 0) continue; if (def.fixed) return { code: 'validation_failed', reason: k + ' cannot move' }; if (roles.indexOf(def.role) < 0) return { code: 'validation_failed', reason: k + ' cannot go on a ' + type }; total += n; } if (total < 1) return { code: 'validation_failed', reason: 'no units' }; if (type === 'settle') { const only = Object.keys(units).filter((k) => units[k] > 0); if (only.length !== 1 || only[0] !== D.EXPANSION.settleUnit || units[only[0]] !== D.EXPANSION.crews) { return { code: 'validation_failed', reason: 'a settle needs exactly ' + D.EXPANSION.crews + ' ' + D.EXPANSION.settleUnit }; } } if (type === 'takeover' && !(units[D.EXPANSION.conquestUnit] > 0)) return { code: 'validation_failed', reason: 'a takeover needs a ' + D.EXPANSION.conquestUnit }; return null; } // Beginner protection: a protected operator cannot be attacked (raid, attack, takeover). Scans are fine. const isProtected = (protectionUntil, at) => (protectionUntil || 0) > at; // ------------------------------------------------------------------ military: combat const firewallMult = (level) => 1 + F.firewallPerLevel * level; const effectiveFirewall = (level, rigs) => Math.max(0, level - (rigs || 0) / MIL.rigFirewallDivisor); function powerOf(units, research, stat) { let s = 0; for (const k of Object.keys(units || {})) if (units[k] > 0 && unitDef(k)) s += units[k] * unitStat(k, stat, research); return s; } const attackPower = (units, research) => powerOf(units, research, 'attack'); const defencePower = (units, research) => powerOf(units, research, 'defence'); // Remove a fraction of every unit type (rounded to whole units). -> { survivors, lost } function applyLoss(units, fraction) { const survivors = {}, lost = {}; for (const k of Object.keys(units || {})) { const n = units[k]; if (!(n > 0)) continue; const l = fraction >= 1 ? n : Math.min(n, Math.round(n * fraction)); if (l > 0) lost[k] = l; if (n - l > 0) survivors[k] = n - l; } return { survivors, lost }; } // The battle. Deterministic: inputs in, result out, no randomness. // o.kind: 'attack' (full) | 'raid' // o.attackers: { units, research } // o.defenders: [{ id, units, research }] everything defending the POP (home crews first, then each reinforcement) // o.firewall: Firewall level of the target; o.staticDefence: a number for an incumbent site (no groups, no losses) // Full attack: the loser loses everything, the winner loses (loser/winner)^1.5 of its units. // Raid: both sides lose 0.5 * (weaker/stronger)^1.5, whoever wins. Ties go to the defender. function resolveBattle(o) { const att = o.attackers.units || {}; const A = attackPower(att, o.attackers.research); const rigs = att.ddos_rig || 0; const effFw = effectiveFirewall(o.firewall || 0, rigs); const groups = o.defenders || []; const raw = groups.map((g) => defencePower(g.units, g.research)); const rawTotal = raw.reduce((s, v) => s + v, 0); const isStatic = o.staticDefence !== undefined && o.staticDefence !== null; const Dv = isStatic ? o.staticDefence : (rawTotal + MIL.defenceBase) * firewallMult(effFw); const attackerWins = A > Dv; const hi = Math.max(A, Dv), lo = Math.min(A, Dv); const ratio = hi > 0 ? lo / hi : 0; let attF, defF; if (o.kind === 'raid') { attF = defF = MIL.raidLossFactor * Math.pow(ratio, MIL.lossExponent); } else if (attackerWins) { attF = Math.min(1, Math.pow(ratio, MIL.lossExponent)); defF = 1; } else { attF = 1; defF = Math.min(1, Math.pow(ratio, MIL.lossExponent)); } if (isStatic) defF = 0; const a = applyLoss(att, attF); const defenders = groups.map((g, i) => { const r = applyLoss(g.units, defF); return { id: g.id, sent: g.units, lost: r.lost, survivors: r.survivors, share: rawTotal > 0 ? raw[i] / rawTotal : 0 }; }); return { kind: o.kind, A, D: Dv, defenceRaw: rawTotal, effectiveFirewall: effFw, attackerWins, ratio, attackerLossFraction: attF, defenderLossFraction: defF, attacker: { sent: att, lost: a.lost, survivors: a.survivors }, defenders }; } // Battle points for destroying units (operator_stats.attack_points / defense_points). function battlePoints(lostUnits) { let v = 0; for (const k of Object.keys(lostUnits || {})) if (unitDef(k)) v += unitValue(k) * lostUnits[k]; return v * MIL.pointsPerCost; } // Share of the stock the Rack hall hides from a raid ("cold spare"). const cacheFraction = (rackLevel) => Math.min(MIL.cacheMax, MIL.cachePerLevel * Math.max(0, rackLevel || 0)); // Loot: `carry` is split evenly over Fiber/Hardware/Capital; what one resource cannot give is shared by the others. // avail = what can be taken. -> whole-number { fiber, hardware, capital }. function lootSplit(carry, avail) { const take = { fiber: 0, hardware: 0, capital: 0 }; let left = Math.max(0, carry); for (let pass = 0; pass < 4 && left > 1e-9; pass++) { const open = D.RESOURCES.filter((r) => avail[r] - take[r] > 1e-9); if (!open.length) break; const share = left / open.length; for (const r of open) { const t = Math.min(share, avail[r] - take[r]); take[r] += t; left -= t; } } for (const r of D.RESOURCES) take[r] = Math.floor(take[r] + 1e-9); return take; } const carryOf = (units) => Object.keys(units || {}).reduce((s, k) => s + (unitDef(k) ? unitDef(k).carry * units[k] : 0), 0); // Exploit kits (survivors) tear levels off one chosen building after a win. const siegeLevels = (kits) => (kits >= MIL.kitsMin ? Math.max(1, Math.floor(kits / MIL.kitsPerLevel)) : 0); // Customer loyalty lost to one M&A team, from a seeded roll r in [0, 1). function loyaltyDrop(r) { const lo = MIL.loyaltyDrop[0], hi = MIL.loyaltyDrop[1]; return lo + Math.min(hi - lo, Math.floor(r * (hi - lo + 1))); } // Why a POP cannot change owner: 'capital' | 'last_pop' | null. (A capital can still be dragged to zero loyalty.) function takeoverBlock(isCapital, defenderTownCount) { if (defenderTownCount <= 1) return 'last_pop'; // wins over 'capital': a lone capital is not even drained if (isCapital) return 'capital'; return null; } // Footprint gate for founding or taking over: the operator owns `ownedCount` POPs now, `footprint` is their total. function footprintGate(ownedCount, footprint) { const need = footprintNeeded(ownedCount); return { ok: footprint + 1e-6 >= need, need, have: footprint }; } // Founding a POP: info about the target tile and the operator. Codes: invalid_target, out_of_range, footprint_too_low. function settleCheck(o) { if (o.backbone) return { ok: false, code: 'invalid_target', reason: 'backbone_site' }; // landing sites are taken, never settled if (o.tileType !== 'land' || o.occupied) return { ok: false, code: 'invalid_target', reason: o.occupied ? 'occupied' : 'not_empty_land' }; if (!(o.nearestOwnDist <= D.EXPANSION.maxDistance)) return { ok: false, code: 'out_of_range', max: D.EXPANSION.maxDistance, have: o.nearestOwnDist }; const g = footprintGate(o.ownedCount, o.footprint); if (!g.ok) return { ok: false, code: 'footprint_too_low', need: g.need, have: g.have }; return { ok: true }; } // Wild slot choice at founding: two field types (any of FIELD_TYPES). Anything else falls back to the defaults. function cleanWild(wild) { const out = []; for (let i = 0; i < D.WILD_SLOTS; i++) out.push(wild && D.FIELD_TYPES.indexOf(wild[i]) >= 0 ? wild[i] : D.START.wild[i]); return out; } // A new POP: every field at level 0, no infrastructure at all. function newTownBuildings(wild) { const layout = fieldLayout(wild); const out = {}; for (const key of Object.keys(layout)) out[key] = { type: layout[key], level: 0 }; return out; } // ---- scanning const scanStrength = (count, research) => count * researchMult(researchLevel(research, 'port_scanner', 'defence')); // sa = attacking scanner strength, sd = defending. Success needs sa > sd; buildings (and more) at 2:1. // A failed scan loses every scanner and reveals the scanner to the target; a successful one loses 0.5*(sd/sa)^1.5. function resolveScan(sa, sd) { const success = sa > sd; return { success, detail: !success ? 'none' : (sa >= MIL.scanBuildingsRatio * sd ? 'full' : 'basic'), identityRevealed: !success, lossFraction: success ? MIL.raidLossFactor * Math.pow(sd / sa, MIL.scanLossExponent) : 1, }; } // ---- incumbent (NPC) sites // Static defence of the site at (x, y); ageDays = world age in world days (real days * speed). function incumbentDefence(seed, x, y, ageDays) { const f = 1 + D.INCUMBENT.variance * (2 * (hash(seed ^ 0x1ac0, x, y) / 4294967296) - 1); return Math.round(D.INCUMBENT.baseDefence * f * (1 + D.INCUMBENT.perDayGrowth * Math.max(0, ageDays))); } // ---- power: when the battery is empty, units go offline and are decommissioned later const decommissionMs = (speed) => Math.round(MIL.decommissionHours * HOUR / (speed || 1)); // units = { unit: count } of everything drawing power in one POP; allowedDraw = output minus building draw. // Returns how many of each unit to decommission, most expensive first, until the draw fits. function decommissionPlan(units, allowedDraw) { let draw = 0; for (const k of Object.keys(units)) draw += (units[k] || 0) * unitDef(k).draw; const order = Object.keys(units).filter((k) => units[k] > 0).sort((a, b) => unitValue(b) - unitValue(a) || (a < b ? -1 : 1)); const remove = {}; for (const k of order) { if (draw <= Math.max(0, allowedDraw) + 1e-9) break; const d = unitDef(k).draw; const n = d > 0 ? Math.min(units[k], Math.ceil((draw - Math.max(0, allowedDraw)) / d)) : 0; if (n > 0) { remove[k] = n; draw -= n * d; } } return remove; } // ---- transport (trade is built on it): concurrent links = Internet exchange level, each carries up to capacityPerLink const transportLinks = (town) => buildingLevel(town, D.TRANSPORT.building); // Codes: validation_failed, capacity_exceeded, no_transport_link, not_enough_resources. function transportPlan(town, cargo, activeLinks, now) { let total = 0; for (const r of Object.keys(cargo || {})) { if (D.RESOURCES.indexOf(r) < 0 || !Number.isInteger(cargo[r]) || cargo[r] < 0) return { ok: false, code: 'validation_failed' }; total += cargo[r]; } if (total < 1) return { ok: false, code: 'validation_failed' }; if (activeLinks >= transportLinks(town)) return { ok: false, code: 'no_transport_link', links: transportLinks(town), active: activeLinks }; if (total > D.TRANSPORT.capacityPerLink) return { ok: false, code: 'capacity_exceeded', capacity: D.TRANSPORT.capacityPerLink, total }; const have = resourcesAt(town, now).amounts; for (const r of D.RESOURCES) if (have[r] + 1e-6 < (cargo[r] || 0)) return { ok: false, code: 'not_enough_resources' }; return { ok: true, total }; } // ---- trade (Internet exchange offers: give X of A for Y of B, max distance Z) // How far (tiles) a POP with this Internet exchange level sees and trades. Level 0 = no exchange = 0. const tradeReach = (level) => (level > 0 ? level * D.TRADE.reachPerLevel : 0); // Is the exchange rate within the 1:ratioMax band (give/want in [1/ratioMax, ratioMax])? const tradeRatioOk = (give, want) => give > 0 && want > 0 && give <= want * D.TRADE.ratioMax && want <= give * D.TRADE.ratioMax; // Validate the terms of a new offer. `o` = { giveRes, giveAmount, wantRes, wantAmount, maxDistance }. Codes: validation_failed, // trade_ratio, capacity_exceeded. Does not look at the town (resources, links) - the command does. function tradeTermsCheck(o) { const bad = (path, message) => ({ ok: false, code: 'validation_failed', errors: [{ path, message }] }); if (D.RESOURCES.indexOf(o.giveRes) < 0) return bad('giveRes', 'must be one of ' + D.RESOURCES.join(', ')); if (D.RESOURCES.indexOf(o.wantRes) < 0) return bad('wantRes', 'must be one of ' + D.RESOURCES.join(', ')); if (o.giveRes === o.wantRes) return bad('wantRes', 'must differ from giveRes'); if (!Number.isInteger(o.giveAmount) || o.giveAmount < 1) return bad('giveAmount', 'must be a whole number >= 1'); if (!Number.isInteger(o.wantAmount) || o.wantAmount < 1) return bad('wantAmount', 'must be a whole number >= 1'); if (!Number.isInteger(o.maxDistance) || o.maxDistance < 1 || o.maxDistance > D.TRADE.maxDistance) return bad('maxDistance', 'must be a whole number of tiles 1..' + D.TRADE.maxDistance); const cap = D.TRANSPORT.capacityPerLink; if (o.giveAmount > cap || o.wantAmount > cap) return { ok: false, code: 'capacity_exceeded', capacity: cap }; if (!tradeRatioOk(o.giveAmount, o.wantAmount)) return { ok: false, code: 'trade_ratio', max: D.TRADE.ratioMax }; return { ok: true }; } // May a POP at `dist` tiles with Internet exchange `level` take an offer (max distance `maxDistance`)? Both the offer's own // limit and the taker's reach apply. const tradeInRange = (dist, maxDistance, level) => level >= 1 && dist <= maxDistance && dist <= tradeReach(level); // ---- end game: backbone landing sites // Heavy static defence of a landing site: the incumbent's site defence x defenceMult, plus defencePerLevel per node level. function backboneDefence(seed, x, y, ageDays, level) { return Math.round(incumbentDefence(seed, x, y, ageDays) * D.ENDGAME.defenceMult * (1 + D.ENDGAME.defencePerLevel * Math.max(0, level || 0))); } // Cost to build the Backbone node UP TO `level` (1..maxLevel), per resource. function backboneCost(level) { const def = D.BUILDINGS.backbone_node; const out = {}; for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * Math.pow(D.ENDGAME.costGrowth, level - 1)); return out; } function backboneTimeMs(level, speed) { return Math.max(F.minBuildMs, Math.round(D.BUILDINGS.backbone_node.time * Math.pow(D.ENDGAME.timeGrowth, level - 1) / (speed || 1) * 1000)); } // Can the holder alliance start the next level? site = { level, build (null | { to }), pool: { fiber, hardware, capital } }. Codes: max_level, already_queued, not_enough_resources. function backbonePlan(site, speed) { const toLevel = site.level + 1; const base = { ok: false, fromLevel: site.level, toLevel }; if (toLevel > D.ENDGAME.maxLevel) return Object.assign(base, { code: 'max_level' }); base.cost = backboneCost(toLevel); base.durationMs = backboneTimeMs(toLevel, speed); if (site.build) return Object.assign(base, { code: 'already_queued' }); for (const r of D.RESOURCES) if ((site.pool[r] || 0) + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' }); base.ok = true; return base; } return { unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn, terrainAt, backboneSites, backboneSiteAt, isBackboneSite, worldAgeDays, worldPhase, tradeReach, tradeRatioOk, tradeTermsCheck, tradeInRange, backboneDefence, backboneCost, backboneTimeMs, backbonePlan, buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, earlyTimeFactor, queueSlots, storageCap, batteryCap, fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt, allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs, footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs, }; }));