Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy

Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic
combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances,
roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map,
alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js.
Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium
screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push,
bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 18:32:36 +02:00
parent b56b13880e
commit 249818a7aa
111 changed files with 17472 additions and 13 deletions

View file

@ -284,6 +284,37 @@
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) {
@ -291,10 +322,343 @@
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.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 };
}
return {
rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
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,
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap,
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs,
footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs,
};
}));