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:
parent
b56b13880e
commit
249818a7aa
111 changed files with 17472 additions and 13 deletions
122
server/military/arrivals.js
Normal file
122
server/military/arrivals.js
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Arrival handlers for the movements that are not fights: reinforce, transport, settle. Plus the shared pieces every
|
||||
* arrival uses (cargo delivery, bouncing a movement back, brief descriptions for reports). Each handler runs inside the
|
||||
* `arrive` event's transaction at the event's own due time.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { loadTown, settle, loadWorld } = require('../state');
|
||||
const { createTown } = require('../commands/joinWorld');
|
||||
const U = require('./units');
|
||||
const M = require('./movements');
|
||||
const P = require('./power');
|
||||
const { createReport } = require('./reports');
|
||||
|
||||
const townBrief = (t) => t ? { id: t.id, name: t.name, x: t.x, y: t.y } : null;
|
||||
const opBrief = (o) => o ? { id: o.id, name: o.name, asNumber: o.as_number } : null;
|
||||
|
||||
// Add resources to a SETTLED town, capped at its storage (an amount already above the cap is kept). -> what was lost
|
||||
function addCargo(db, town, cargo) {
|
||||
const cap = R.storageCap(town);
|
||||
const lost = {};
|
||||
for (const r of D.RESOURCES) {
|
||||
const add = (cargo && cargo[r]) || 0;
|
||||
if (!add) continue;
|
||||
const cur = town.res[r];
|
||||
const next = Math.min(Math.max(cap, cur), cur + add);
|
||||
lost[r] = Math.max(0, Math.round(cur + add - next));
|
||||
town.res[r] = next;
|
||||
}
|
||||
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id);
|
||||
return lost;
|
||||
}
|
||||
|
||||
// The movement cannot do what it came for: its units (and cargo) turn around and a report tells the sender why.
|
||||
function bounce(ctx, mv, now, reason, details) {
|
||||
const { db } = ctx;
|
||||
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||
if (dest && !U.isEmpty(mv.units)) {
|
||||
M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: mv.units, cargo: mv.cargo, parentId: mv.id, extra: { bounced: reason } });
|
||||
}
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'movement_failed', now,
|
||||
summary: { movementType: mv.type, reason, to: mv.to },
|
||||
data: { movementType: mv.type, reason, details: details || {}, to: mv.to, units: mv.units },
|
||||
recipients: [{ userId: U.userOfOperator(db, mv.ownerId), role: 'sender' }],
|
||||
});
|
||||
}
|
||||
|
||||
function arriveReinforce(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
const target = mv.toTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId) : null;
|
||||
if (!target || !U.mayReinforce(db, mv.ownerId, target.owner_id)) return bounce(ctx, mv, now, 'not_allied');
|
||||
const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||
if (!ownerTown) return; // the sender lost every POP meanwhile: nothing to belong to
|
||||
const host = loadTown(db, target.id);
|
||||
settle(db, host, now); // the host's draw rises at this moment
|
||||
// Moving units between your own POPs: they simply live in the new POP now. Only other operators' units are "stationed".
|
||||
if (ownerTown.id === host.id || target.owner_id === mv.ownerId) U.addHome(db, host.id, mv.units);
|
||||
else U.addStationed(db, host.id, ownerTown.id, mv.units);
|
||||
P.reschedule(ctx, host.id, now);
|
||||
const sender = U.getOperator(db, mv.ownerId), hostOp = U.getOperator(db, target.owner_id);
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'reinforce', now,
|
||||
summary: { host: townBrief(target), from: townBrief(ownerTown), units: mv.units },
|
||||
data: { host: townBrief(target), hostOperator: opBrief(hostOp), from: townBrief(ownerTown), operator: opBrief(sender), units: mv.units },
|
||||
recipients: [{ userId: U.userOfOperator(db, sender.id), role: 'sender' }, { userId: U.userOfOperator(db, hostOp.id), role: 'target' }],
|
||||
});
|
||||
}
|
||||
|
||||
function arriveTransport(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
const target = mv.toTownId ? loadTown(db, mv.toTownId) : null;
|
||||
let lost = {};
|
||||
if (target) {
|
||||
settle(db, target, now);
|
||||
lost = addCargo(db, target, mv.cargo);
|
||||
const sender = U.userOfOperator(db, mv.ownerId), receiver = U.userOfOperator(db, target.ownerId);
|
||||
if (receiver) ctx.notify(receiver, mv.worldId, 'transport_arrived', { movementId: mv.id, townId: target.id, fromTownId: mv.fromTownId, cargo: mv.cargo, cargoLost: lost, own: receiver === sender });
|
||||
if (sender && sender !== receiver) ctx.notify(sender, mv.worldId, 'transport_delivered', { movementId: mv.id, toTownId: target.id, cargo: mv.cargo, cargoLost: lost });
|
||||
for (const fn of M.hooks.transportArrived) fn(ctx, mv, { added: mv.cargo, lost });
|
||||
}
|
||||
const cargoBack = target ? {} : mv.cargo; // no such POP any more: the cargo rides home with the carriers
|
||||
// The empty carriers drive back; the link is busy until they are home.
|
||||
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||
if (dest) {
|
||||
const world = loadWorld(db, mv.worldId);
|
||||
const dist = R.distance(mv.to.x, mv.to.y, dest.x, dest.y);
|
||||
M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: {}, cargo: cargoBack, arriveAt: now + R.transportMs(dist, world.speed), parentId: mv.id, extra: Object.assign({}, mv.extra, { link: 1 }) });
|
||||
}
|
||||
}
|
||||
|
||||
// Three Rollout crews found a new POP on the empty tile, if it is still empty land, still in range, footprint still enough.
|
||||
function arriveSettle(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
const world = loadWorld(db, mv.worldId);
|
||||
const op = U.getOperator(db, mv.ownerId);
|
||||
const { x, y } = mv.to;
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||
const occupied = !!db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y);
|
||||
const own = U.operatorTowns(db, op.id);
|
||||
let nearest = Infinity;
|
||||
for (const t of own) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
|
||||
const chk = R.settleCheck({ tileType: tile.type, occupied, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
|
||||
if (!chk.ok) return bounce(ctx, mv, now, chk.code, chk);
|
||||
const wild = R.cleanWild(mv.extra.wild);
|
||||
const name = op.name + ' POP ' + (own.length + 1);
|
||||
const id = createTown(db, { worldId: world.id, ownerId: op.id, name, x, y, isCapital: false, now, buildings: R.newTownBuildings(wild), res: D.EXPANSION.startResources });
|
||||
db.run('UPDATE towns SET battery = 0, loyalty = ? WHERE id = ?', D.EXPANSION.foundedLoyalty, id);
|
||||
const founded = { id, name, x, y };
|
||||
createReport(ctx, {
|
||||
worldId: world.id, type: 'settle', now,
|
||||
summary: { success: true, town: founded },
|
||||
data: { success: true, town: founded, wild, crews: mv.units, from: mv.fromTownId },
|
||||
recipients: [{ userId: U.userOfOperator(db, op.id), role: 'sender' }],
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { addCargo, bounce, arriveReinforce, arriveTransport, arriveSettle, townBrief, opBrief };
|
||||
282
server/military/combat.js
Normal file
282
server/military/combat.js
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Arrival of scan / raid / attack / takeover. Everything here runs inside the `arrive` event's transaction at the
|
||||
* event's own due time, after every earlier event, so combat order is exactly event order. Deterministic: the only
|
||||
* dice (the loyalty roll) are seeded from (world seed, movement id).
|
||||
*
|
||||
* Steps: re-check the target (it may have changed since departure) -> settle the target to the due time -> gather
|
||||
* defenders (home crews + reinforcements, only while online) -> rules.resolveBattle -> apply losses, loot, siege,
|
||||
* takeover -> survivors drive home with the loot -> reports + battle points.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { loadTown, settle, loadWorld } = require('../state');
|
||||
const U = require('./units');
|
||||
const M = require('./movements');
|
||||
const P = require('./power');
|
||||
const { createReport } = require('./reports');
|
||||
const { bounce, townBrief, opBrief } = require('./arrivals');
|
||||
|
||||
const DAY = 24 * D.HOUR_MS;
|
||||
|
||||
// All groups standing in the target: home crews then each reinforcing POP's units, with the research that applies.
|
||||
function defenderGroups(db, target) {
|
||||
const groups = [];
|
||||
const home = U.homeUnits(db, target.id);
|
||||
if (!U.isEmpty(home)) groups.push({ id: 'home', ownerTownId: target.id, ownerOpId: target.ownerId, units: home, research: U.researchLevels(db, target.id) });
|
||||
for (const g of U.hostedGroups(db, target.id)) {
|
||||
const ot = db.get('SELECT owner_id FROM towns WHERE id = ?', g.ownerTownId);
|
||||
groups.push({ id: 'from:' + g.ownerTownId, ownerTownId: g.ownerTownId, ownerOpId: ot ? ot.owner_id : null, units: g.units, research: U.researchLevels(db, g.ownerTownId) });
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
// Write a defending group's units back after the battle.
|
||||
function writeGroup(db, hostTownId, group, units) {
|
||||
const keys = new Set(Object.keys(group.units).concat(Object.keys(units)));
|
||||
for (const k of keys) {
|
||||
if (group.id === 'home') U.setHomeUnit(db, hostTownId, k, units[k] || 0);
|
||||
else U.setStationed(db, hostTownId, group.ownerTownId, k, units[k] || 0);
|
||||
}
|
||||
}
|
||||
|
||||
function addPoints(db, operatorId, column, v) {
|
||||
if (!operatorId || !(v > 0)) return;
|
||||
db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 0, 0) ON CONFLICT (operator_id) DO NOTHING', operatorId);
|
||||
db.run('UPDATE operator_stats SET ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' = ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' + ? WHERE operator_id = ?', v, operatorId);
|
||||
}
|
||||
|
||||
const sumValues = (list) => list.reduce((acc, u) => U.sumInto(acc, u), {});
|
||||
|
||||
// Survivors drive home (with loot). No survivors, no movement.
|
||||
function sendHome(ctx, mv, survivors, cargo) {
|
||||
const { db } = ctx;
|
||||
if (U.isEmpty(survivors)) return null;
|
||||
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||
if (!dest) return null;
|
||||
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: survivors, cargo: cargo || {}, parentId: mv.id, extra: {} });
|
||||
}
|
||||
|
||||
function arrive(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
const world = loadWorld(db, mv.worldId);
|
||||
if (!mv.toTownId) return arriveSite(ctx, mv, now, world);
|
||||
const targetRow = db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId);
|
||||
if (!targetRow) return bounce(ctx, mv, now, 'target_gone');
|
||||
const attackerOp = U.getOperator(db, mv.ownerId);
|
||||
const defOp = U.getOperator(db, targetRow.owner_id);
|
||||
if (defOp.id === attackerOp.id) return bounce(ctx, mv, now, 'own_town');
|
||||
if (mv.type !== 'scan') {
|
||||
if (R.isProtected(defOp.protection_until, now)) return bounce(ctx, mv, now, 'protected', { until: defOp.protection_until });
|
||||
if (U.pactBlocks(db, attackerOp.id, defOp.id)) return bounce(ctx, mv, now, 'pact');
|
||||
}
|
||||
const target = loadTown(db, targetRow.id);
|
||||
settle(db, target, now);
|
||||
const online = P.online(target, now);
|
||||
const groups = defenderGroups(db, target);
|
||||
const active = online ? groups : [];
|
||||
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
|
||||
|
||||
if (mv.type === 'scan') return resolveScanOnTown(ctx, mv, now, { target, targetRow, defOp, attackerOp, origin, groups, active, online });
|
||||
|
||||
const kind = mv.type === 'raid' ? 'raid' : 'attack';
|
||||
const fwLevel = target.buildings.firewall ? target.buildings.firewall.level : 0;
|
||||
const b = R.resolveBattle({
|
||||
kind, attackers: { units: mv.units, research: mv.extra.research || {} },
|
||||
defenders: active.map((g) => ({ id: g.id, units: g.units, research: g.research })), firewall: fwLevel,
|
||||
});
|
||||
const win = b.attackerWins;
|
||||
|
||||
// ---- defenders: losses (a full attack lost by the defender wipes everything in the POP, offline units included)
|
||||
const wipe = b.defenderLossFraction >= 1;
|
||||
const groupReports = [];
|
||||
let defenderLost = {};
|
||||
for (const g of groups) {
|
||||
const res = b.defenders.find((d) => d.id === g.id);
|
||||
let survivors, lost;
|
||||
if (wipe) { survivors = {}; lost = g.units; }
|
||||
else if (res) { survivors = res.survivors; lost = res.lost; }
|
||||
else { survivors = g.units; lost = {}; } // offline and not wiped: untouched
|
||||
writeGroup(db, target.id, g, survivors);
|
||||
U.sumInto(defenderLost, lost);
|
||||
groupReports.push({ id: g.id, ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, sent: g.units, lost, survivors, share: res ? res.share : 0, offline: !res });
|
||||
}
|
||||
const survivorsAtt = Object.assign({}, b.attacker.survivors);
|
||||
|
||||
// ---- loot
|
||||
let loot = { fiber: 0, hardware: 0, capital: 0 };
|
||||
let hidden = 0;
|
||||
if (win) {
|
||||
hidden = kind === 'raid' ? R.cacheFraction(target.buildings.rack_hall ? target.buildings.rack_hall.level : 0) : 0;
|
||||
const avail = {};
|
||||
for (const r of D.RESOURCES) avail[r] = target.res[r] * (1 - hidden);
|
||||
loot = R.lootSplit(R.carryOf(survivorsAtt), avail);
|
||||
for (const r of D.RESOURCES) target.res[r] -= loot[r];
|
||||
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', target.res.fiber, target.res.hardware, target.res.capital, target.id);
|
||||
}
|
||||
|
||||
// ---- siege: exploit kits tear levels off the chosen building
|
||||
let siege = null;
|
||||
if (win && mv.type !== 'raid' && mv.extra.target) {
|
||||
const levels = R.siegeLevels(survivorsAtt.exploit_kit || 0);
|
||||
const cur = levels > 0 ? target.buildings[mv.extra.target] : null;
|
||||
if (cur && cur.level > 0) {
|
||||
const to = Math.max(0, cur.level - levels);
|
||||
db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', to, target.id, mv.extra.target);
|
||||
siege = { key: mv.extra.target, type: cur.type, from: cur.level, to };
|
||||
}
|
||||
}
|
||||
|
||||
// ---- takeover
|
||||
let takeover = null;
|
||||
let captured = false;
|
||||
if (mv.type === 'takeover' && win && (survivorsAtt[D.EXPANSION.conquestUnit] || 0) > 0) {
|
||||
const defTowns = db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', defOp.id).n;
|
||||
const block = R.takeoverBlock(!!targetRow.is_capital, defTowns);
|
||||
const gate = R.footprintGate(U.operatorTowns(db, attackerOp.id).length, U.operatorFootprint(db, attackerOp.id, now));
|
||||
takeover = { attempted: true, blocked: block === 'last_pop' ? 'last_pop' : (gate.ok ? null : 'footprint'), capital: block === 'capital', loyaltyBefore: target.loyalty, loyaltyAfter: target.loyalty, drop: 0, captured: false };
|
||||
if (takeover.blocked === null) {
|
||||
const rand = R.rng(R.hash(world.seed, mv.id, 0x7a11))();
|
||||
const drop = R.loyaltyDrop(rand);
|
||||
const after = Math.max(0, target.loyalty - drop);
|
||||
const left = survivorsAtt[D.EXPANSION.conquestUnit] - 1; // the M&A team that did the talking is used up
|
||||
if (left > 0) survivorsAtt[D.EXPANSION.conquestUnit] = left; else delete survivorsAtt[D.EXPANSION.conquestUnit];
|
||||
db.run('UPDATE towns SET loyalty = ?, loyalty_at = ? WHERE id = ?', after, now, target.id);
|
||||
Object.assign(takeover, { drop, loyaltyAfter: after });
|
||||
if (after <= 0 && block === null) { transferTown(ctx, target, attackerOp, defOp, now); captured = true; takeover.captured = true; }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- battle points
|
||||
const attLost = b.attacker.lost;
|
||||
addPoints(db, attackerOp.id, 'attack', R.battlePoints(defenderLost));
|
||||
const defPts = R.battlePoints(attLost);
|
||||
for (const g of groupReports) addPoints(db, g.ownerOpId, 'defense', defPts * g.share);
|
||||
|
||||
P.reschedule(ctx, target.id, now);
|
||||
const ret = sendHome(ctx, mv, survivorsAtt, loot);
|
||||
|
||||
// ---- reports
|
||||
const data = {
|
||||
type: mv.type, outcome: win ? 'attacker_won' : 'defender_won', arrivedAt: now,
|
||||
attacker: { operator: opBrief(attackerOp), town: townBrief(origin), units: { sent: mv.units, lost: attLost, survivors: survivorsAtt } },
|
||||
defender: { operator: opBrief(defOp), town: townBrief(target), online, groups: groupReports.map((g) => ({ ownerTownId: g.ownerTownId, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) },
|
||||
power: { attack: b.A, defence: b.D, defenceRaw: b.defenceRaw, firewallLevel: fwLevel, effectiveFirewall: b.effectiveFirewall },
|
||||
loot, cacheHidden: hidden, siege, takeover, capturedTown: captured, returnMovementId: ret ? ret.id : null,
|
||||
};
|
||||
const summary = { type: mv.type, outcome: data.outcome, attacker: opBrief(attackerOp), defender: opBrief(defOp), target: townBrief(target), loot, captured };
|
||||
const recipients = [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }, { userId: U.userOfOperator(db, defOp.id), role: 'defender' }];
|
||||
for (const g of groupReports) if (g.id !== 'home' && g.ownerOpId) recipients.push({ userId: U.userOfOperator(db, g.ownerOpId), role: 'reinforcer' });
|
||||
createReport(ctx, { worldId: mv.worldId, type: mv.type, now, summary, data, recipients });
|
||||
}
|
||||
|
||||
// ---- scans
|
||||
function resolveScanOnTown(ctx, mv, now, s) {
|
||||
const { db } = ctx;
|
||||
const { target, defOp, attackerOp, origin, groups, active, online } = s;
|
||||
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
|
||||
let sd = 0;
|
||||
for (const g of active) sd += R.scanStrength(g.units.port_scanner || 0, g.research);
|
||||
const res = R.resolveScan(sa, sd);
|
||||
const loss = R.applyLoss(mv.units, res.lossFraction);
|
||||
let intel = null;
|
||||
if (res.success) {
|
||||
intel = {
|
||||
detail: res.detail, online,
|
||||
units: { home: U.homeUnits(db, target.id), stationed: groups.filter((g) => g.id !== 'home').map((g) => ({ ownerTownId: g.ownerTownId, units: g.units })) },
|
||||
resources: { fiber: target.res.fiber, hardware: target.res.hardware, capital: target.res.capital },
|
||||
};
|
||||
if (res.detail === 'full') {
|
||||
intel.buildings = Object.keys(target.buildings).map((k) => ({ key: k, type: target.buildings[k].type, level: target.buildings[k].level }));
|
||||
intel.loyalty = target.loyalty;
|
||||
intel.outgoing = db.all("SELECT id, type, to_x, to_y, arrive_at FROM movements WHERE from_town_id = ? AND status = 'out' AND type != 'return' ORDER BY arrive_at, id", target.id)
|
||||
.map((m) => ({ type: m.type, to: { x: m.to_x, y: m.to_y }, arriveAt: m.arrive_at }));
|
||||
}
|
||||
}
|
||||
const aData = { success: res.success, detail: res.detail, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, strength: { attacker: sa, defender: sd }, target: townBrief(target), operator: opBrief(defOp), intel };
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, target: townBrief(target), operator: opBrief(defOp) },
|
||||
data: aData, recipients: [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }],
|
||||
});
|
||||
const dData = { identityRevealed: res.identityRevealed, target: townBrief(target), by: res.identityRevealed ? { operator: opBrief(attackerOp), town: townBrief(origin) } : null };
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'scan_detected', now, summary: { identityRevealed: res.identityRevealed, target: townBrief(target), by: dData.by && dData.by.operator },
|
||||
data: dData, recipients: [{ userId: U.userOfOperator(db, defOp.id), role: 'defender' }],
|
||||
});
|
||||
sendHome(ctx, mv, loss.survivors, {});
|
||||
}
|
||||
|
||||
// ---- incumbent sites (NPC): static defence, no losses for the site, never attack
|
||||
function arriveSite(ctx, mv, now, world) {
|
||||
const { db } = ctx;
|
||||
const { x, y } = mv.to;
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||
if (tile.type !== 'incumbent' || (mv.type !== 'scan' && mv.type !== 'attack')) return bounce(ctx, mv, now, 'invalid_target');
|
||||
const attackerOp = U.getOperator(db, mv.ownerId);
|
||||
const ageDays = Math.max(0, (now - world.start_at) / DAY * world.speed);
|
||||
const staticDef = R.incumbentDefence(world.seed, x, y, ageDays);
|
||||
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
|
||||
const site = { x, y, type: 'incumbent' };
|
||||
const uid = U.userOfOperator(db, attackerOp.id);
|
||||
|
||||
if (mv.type === 'scan') {
|
||||
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
|
||||
const res = R.resolveScan(sa, D.INCUMBENT.scanStrength);
|
||||
const loss = R.applyLoss(mv.units, res.lossFraction);
|
||||
const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, attackerOp.id);
|
||||
const intel = res.success ? { defence: staticDef, bonusAvailable: !taken, hardwareBonus: D.INCUMBENT.hardwareBonus } : null;
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site },
|
||||
data: { success: res.success, detail: res.detail, site, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel },
|
||||
recipients: [{ userId: uid, role: 'attacker' }],
|
||||
});
|
||||
sendHome(ctx, mv, loss.survivors, {});
|
||||
return;
|
||||
}
|
||||
|
||||
const b = R.resolveBattle({ kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, defenders: [], firewall: 0, staticDefence: staticDef });
|
||||
const survivors = Object.assign({}, b.attacker.survivors);
|
||||
let bonus = null;
|
||||
const cargo = {};
|
||||
if (b.attackerWins) {
|
||||
const first = db.run('INSERT OR IGNORE INTO incumbent_takes (world_id, x, y, operator_id, taken_at) VALUES (?, ?, ?, ?, ?)', world.id, x, y, attackerOp.id, now);
|
||||
if (first.changes) {
|
||||
cargo.hardware = D.INCUMBENT.hardwareBonus;
|
||||
bonus = { hardware: D.INCUMBENT.hardwareBonus, researchSpeedBonus: R.researchSpeedBonus(U.incumbentTakes(db, attackerOp.id)) };
|
||||
}
|
||||
}
|
||||
const ret = sendHome(ctx, mv, survivors, cargo);
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'incumbent', now,
|
||||
summary: { outcome: b.attackerWins ? 'attacker_won' : 'defender_won', site, bonus },
|
||||
data: {
|
||||
outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site, origin: townBrief(origin),
|
||||
attacker: { operator: opBrief(attackerOp), units: { sent: mv.units, lost: b.attacker.lost, survivors } },
|
||||
power: { attack: b.A, defence: b.D }, bonus, returnMovementId: ret ? ret.id : null,
|
||||
},
|
||||
recipients: [{ userId: uid, role: 'attacker' }],
|
||||
});
|
||||
}
|
||||
|
||||
// A takeover completed: the POP changes owner. Pending work of the old owner stops, reinforcements of the old owner
|
||||
// standing elsewhere are re-homed, the new owner starts at conqueredLoyalty.
|
||||
function transferTown(ctx, town, newOp, oldOp, now) {
|
||||
const { db } = ctx;
|
||||
db.run('UPDATE towns SET owner_id = ?, is_capital = 0, loyalty = ?, loyalty_at = ? WHERE id = ?', newOp.id, D.EXPANSION.conqueredLoyalty, now, town.id);
|
||||
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type IN ('trainDone', 'researchDone') AND status = 'pending'", now, town.id);
|
||||
db.run("UPDATE events SET payload = json_set(payload, '$.userId', ?) WHERE town_id = ? AND type = 'buildDone' AND status = 'pending'", U.userOfOperator(db, newOp.id), town.id);
|
||||
// units of the old owner that were hosted here (should be dead already) or that belonged to this POP and stand elsewhere
|
||||
const home = U.homeTownFor(db, oldOp.id);
|
||||
for (const g of U.awayGroups(db, town.id)) {
|
||||
db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', g.hostTownId, town.id);
|
||||
if (!home) continue;
|
||||
if (home.id === g.hostTownId) U.addHome(db, home.id, g.units); else U.addStationed(db, g.hostTownId, home.id, g.units);
|
||||
}
|
||||
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
|
||||
const oldUser = U.userOfOperator(db, oldOp.id), newUser = U.userOfOperator(db, newOp.id);
|
||||
if (oldUser) ctx.notify(oldUser, town.worldId, 'town_lost', { townId: town.id, name: town.name, by: opBrief(newOp) });
|
||||
if (newUser) ctx.notify(newUser, town.worldId, 'town_gained', { townId: town.id, name: town.name });
|
||||
}
|
||||
|
||||
module.exports = { arrive, defenderGroups, transferTown };
|
||||
8
server/military/ctx.js
Normal file
8
server/military/ctx.js
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
'use strict';
|
||||
/* Commands get { db, clock, now, scheduler }, events additionally { enqueue, notify }. Military code uses the event shape
|
||||
* everywhere, so command entry points call `ctxOf(ctx)` first (idempotent). */
|
||||
module.exports = function ctxOf(ctx) {
|
||||
if (ctx.enqueue && ctx.notify) return ctx;
|
||||
const s = ctx.scheduler;
|
||||
return Object.assign({}, ctx, { enqueue: (e) => s.enqueue(e), notify: (u, w, t, p) => s.notify(u, w, t, p) });
|
||||
};
|
||||
58
server/military/movements.js
Normal file
58
server/military/movements.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Movement rows: creating them (together with their arrive/return event), reading them, return legs.
|
||||
* A movement is `out` until its event runs; a recall turns it into `recalled` and creates a return movement.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
|
||||
const j = (s) => JSON.parse(s || '{}');
|
||||
|
||||
function fromRow(r) {
|
||||
if (!r) return null;
|
||||
return {
|
||||
id: r.id, worldId: r.world_id, ownerId: r.owner_id, type: r.type, fromTownId: r.from_town_id, toTownId: r.to_town_id,
|
||||
from: { x: r.from_x, y: r.from_y }, to: { x: r.to_x, y: r.to_y }, units: j(r.units), cargo: j(r.cargo),
|
||||
departAt: r.depart_at, arriveAt: r.arrive_at, status: r.status, eventId: r.event_id, parentId: r.parent_id, extra: j(r.extra),
|
||||
};
|
||||
}
|
||||
|
||||
function getMovement(db, id) { return fromRow(db.get('SELECT * FROM movements WHERE id = ?', id)); }
|
||||
|
||||
// Insert a movement and the event that will resolve it ('arrive' for everything but returns, 'return' for returns).
|
||||
// o: { worldId, ownerId, type, fromTownId, toTownId, from:{x,y}, to:{x,y}, units, cargo, departAt, arriveAt, parentId, extra }
|
||||
function insertMovement(ctx, o) {
|
||||
const { db } = ctx;
|
||||
const r = db.run(`INSERT INTO movements (world_id, owner_id, type, from_town_id, to_town_id, from_x, from_y, to_x, to_y, units, cargo,
|
||||
depart_at, arrive_at, status, parent_id, extra, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'out', ?, ?, ?)`,
|
||||
o.worldId, o.ownerId, o.type, o.fromTownId || null, o.toTownId || null, o.from.x, o.from.y, o.to.x, o.to.y,
|
||||
JSON.stringify(o.units || {}), JSON.stringify(o.cargo || {}), o.departAt, Math.round(o.arriveAt), o.parentId || null, JSON.stringify(o.extra || {}), ctx.now);
|
||||
const id = Number(r.lastInsertRowid);
|
||||
const eventId = ctx.enqueue({ worldId: o.worldId, dueAt: o.arriveAt, type: o.type === 'return' ? 'return' : 'arrive', townId: o.toTownId || null, payload: { movementId: id } });
|
||||
db.run('UPDATE movements SET event_id = ? WHERE id = ?', eventId, id);
|
||||
return getMovement(db, id);
|
||||
}
|
||||
|
||||
// Units (and cargo) heading home from where they are. `fromTown` may be null (an incumbent site or an empty tile);
|
||||
// `at` = where they are ({x,y}); `to` = the destination POP row. arriveAt defaults to now + travel time.
|
||||
function launchReturn(ctx, o) {
|
||||
const to = o.to;
|
||||
const dist = R.distance(o.at.x, o.at.y, to.x, to.y);
|
||||
const world = ctx.db.get('SELECT speed FROM worlds WHERE id = ?', o.worldId);
|
||||
const arriveAt = o.arriveAt !== undefined ? o.arriveAt : ctx.now + R.movementMs(dist, o.units, world.speed);
|
||||
return insertMovement(ctx, {
|
||||
worldId: o.worldId, ownerId: o.ownerId, type: 'return', fromTownId: o.fromTownId || null, toTownId: to.id,
|
||||
from: o.at, to: { x: to.x, y: to.y }, units: o.units, cargo: o.cargo, departAt: ctx.now, arriveAt, parentId: o.parentId, extra: o.extra,
|
||||
});
|
||||
}
|
||||
|
||||
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports.
|
||||
function activeLinks(db, townId) {
|
||||
return db.get(`SELECT COUNT(*) AS n FROM movements WHERE status = 'out' AND
|
||||
((type = 'transport' AND from_town_id = ?) OR (type = 'return' AND to_town_id = ? AND json_extract(extra, '$.link') = 1))`, townId, townId).n;
|
||||
}
|
||||
|
||||
// Hooks for later stages (trade): called after a transport has been delivered. fn(ctx, movement, { added, lost }).
|
||||
const hooks = { transportArrived: [] };
|
||||
|
||||
module.exports = { fromRow, getMovement, insertMovement, launchReturn, activeLinks, hooks };
|
||||
109
server/military/power.js
Normal file
109
server/military/power.js
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Unit power: while the battery is empty and net power is negative, the units in a POP are offline (no attack or
|
||||
* defence value, cannot move). After MILITARY.decommissionHours (divided by world speed) offline, the most expensive
|
||||
* units are decommissioned until the draw fits the output again.
|
||||
*
|
||||
* Whether units are online right now is always computed from the lazy battery value (`online`), so reads and combat
|
||||
* never depend on an event having run. The `powerCheck` event exists for the side effects: the "units offline"
|
||||
* notification and the decommission. `reschedule` is idempotent: it cancels the pending check of the POP and enqueues
|
||||
* the one that is correct for the current rates. Call it after ANYTHING that changes unit draw or building levels of a
|
||||
* POP (units arriving or leaving, losses, buildings finishing or being damaged).
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { loadTown, settle } = require('../state');
|
||||
const U = require('./units');
|
||||
|
||||
const EPS = D.MILITARY.batteryEpsilon;
|
||||
|
||||
// Are the units in this town online at `now`? (the town object may be unsettled: resourcesAt projects it)
|
||||
function online(town, now) {
|
||||
const c = R.resourcesAt(town, now);
|
||||
return !(c.amounts.battery <= EPS && c.rates.powerNet < 0);
|
||||
}
|
||||
|
||||
// Every unit drawing power in the POP: home + reinforcements hosted here, as { unit: count }.
|
||||
function drawingUnits(db, townId) {
|
||||
const out = U.homeUnits(db, townId);
|
||||
for (const g of U.hostedGroups(db, townId)) U.sumInto(out, g.units);
|
||||
return out;
|
||||
}
|
||||
|
||||
function reschedule(ctx, townId, now) {
|
||||
const { db } = ctx;
|
||||
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type = 'powerCheck' AND status = 'pending'", now, townId);
|
||||
const town = loadTown(db, townId);
|
||||
if (!town) return;
|
||||
if (!(town.unitDraw > 0)) { db.run('DELETE FROM town_power WHERE town_id = ?', townId); return; }
|
||||
if (online(town, now)) {
|
||||
db.run('DELETE FROM town_power WHERE town_id = ?', townId);
|
||||
const at = R.batteryEmptyAt(town, now);
|
||||
if (at !== null) ctx.enqueue({ worldId: town.worldId, dueAt: at + 1, type: 'powerCheck', townId, payload: { townId } });
|
||||
return;
|
||||
}
|
||||
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', townId);
|
||||
if (!row || row.offline_since === null) {
|
||||
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', townId, now);
|
||||
row = { offline_since: now };
|
||||
}
|
||||
ctx.enqueue({ worldId: town.worldId, dueAt: Math.max(now, row.offline_since + R.decommissionMs(town.speed)), type: 'powerCheck', townId, payload: { townId } });
|
||||
}
|
||||
|
||||
// Decommission the most expensive units (home first, then reinforcements) until the draw fits. The town is settled.
|
||||
function decommission(ctx, town, now) {
|
||||
const { db } = ctx;
|
||||
const units = drawingUnits(db, town.id);
|
||||
const rates = R.ratesPerHour(Object.assign({}, town, { unitDraw: 0 }));
|
||||
const plan = R.decommissionPlan(units, rates.powerOut - rates.powerDraw);
|
||||
const removed = {};
|
||||
const byOwner = new Map(); // userId -> { unit: n }, who lost units
|
||||
const note = (userId, unit, n) => { if (!byOwner.has(userId)) byOwner.set(userId, {}); const o = byOwner.get(userId); o[unit] = (o[unit] || 0) + n; };
|
||||
const ownerUser = U.userOfOperator(db, town.ownerId);
|
||||
for (const unit of Object.keys(plan)) {
|
||||
let left = plan[unit];
|
||||
const home = U.homeUnits(db, town.id)[unit] || 0;
|
||||
const fromHome = Math.min(home, left);
|
||||
if (fromHome > 0) { U.setHomeUnit(db, town.id, unit, home - fromHome); left -= fromHome; note(ownerUser, unit, fromHome); }
|
||||
for (const g of U.hostedGroups(db, town.id)) {
|
||||
if (left <= 0) break;
|
||||
const have = g.units[unit] || 0;
|
||||
const n = Math.min(have, left);
|
||||
if (n > 0) {
|
||||
U.setStationed(db, town.id, g.ownerTownId, unit, have - n); left -= n;
|
||||
const ot = db.get('SELECT t.owner_id AS oid FROM towns t WHERE t.id = ?', g.ownerTownId);
|
||||
note(ot ? U.userOfOperator(db, ot.oid) : null, unit, n);
|
||||
}
|
||||
}
|
||||
removed[unit] = plan[unit] - left;
|
||||
}
|
||||
for (const [userId, lost] of byOwner) if (userId) ctx.notify(userId, town.worldId, 'units_decommissioned', { townId: town.id, units: lost });
|
||||
return removed;
|
||||
}
|
||||
|
||||
// Event handler: payload { townId }. Settles the POP to the due time and acts on what it finds.
|
||||
function powerCheck(ctx, ev) {
|
||||
const { db } = ctx;
|
||||
const town = loadTown(db, ev.townId);
|
||||
if (!town) return;
|
||||
settle(db, town, ev.dueAt);
|
||||
if (town.unitDraw > 0 && !online(town, ev.dueAt)) {
|
||||
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', town.id);
|
||||
if (!row || row.offline_since === null) {
|
||||
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', town.id, ev.dueAt);
|
||||
row = { offline_since: ev.dueAt };
|
||||
const uid = U.userOfOperator(db, town.ownerId);
|
||||
if (uid) ctx.notify(uid, town.worldId, 'units_offline', { townId: town.id, since: ev.dueAt });
|
||||
}
|
||||
if (ev.dueAt >= row.offline_since + R.decommissionMs(town.speed)) {
|
||||
const removed = decommission(ctx, town, ev.dueAt);
|
||||
if (!Object.keys(removed).some((k) => removed[k] > 0)) { // rounding noise, nothing to remove: stand down, never loop
|
||||
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
reschedule(ctx, town.id, ev.dueAt);
|
||||
}
|
||||
|
||||
module.exports = { online, drawingUnits, reschedule, decommission, powerCheck };
|
||||
32
server/military/reports.js
Normal file
32
server/military/reports.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Reports: one `reports` row shared by every participant (`report_recipients`, with a per-user read flag). Kept
|
||||
* MILITARY.reportRetentionMs (real time); the `reportCleanup` event deletes expired ones and re-arms itself only while
|
||||
* reports remain.
|
||||
*/
|
||||
const D = require('../../public/js/data.js');
|
||||
|
||||
// o: { worldId, type, now, summary, data, recipients: [{ userId, role }] } -> report id
|
||||
function createReport(ctx, o) {
|
||||
const { db } = ctx;
|
||||
const r = db.run('INSERT INTO reports (world_id, type, created_at, expires_at, summary, data) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
o.worldId, o.type, o.now, o.now + D.MILITARY.reportRetentionMs, JSON.stringify(o.summary || {}), JSON.stringify(o.data || {}));
|
||||
const id = Number(r.lastInsertRowid);
|
||||
const seen = new Set();
|
||||
for (const rc of o.recipients) {
|
||||
if (!rc.userId || seen.has(rc.userId)) continue;
|
||||
seen.add(rc.userId);
|
||||
db.run('INSERT INTO report_recipients (report_id, user_id, role) VALUES (?, ?, ?)', id, rc.userId, rc.role);
|
||||
ctx.notify(rc.userId, o.worldId, 'report', { reportId: id, type: o.type, role: rc.role });
|
||||
}
|
||||
ensureCleanup(ctx, o.worldId, o.now);
|
||||
return id;
|
||||
}
|
||||
|
||||
function ensureCleanup(ctx, worldId, now) {
|
||||
const { db } = ctx;
|
||||
const pending = db.get("SELECT 1 AS x FROM events WHERE type = 'reportCleanup' AND world_id = ? AND status = 'pending' LIMIT 1", worldId);
|
||||
if (!pending) ctx.enqueue({ worldId, dueAt: now + D.MILITARY.reportRetentionMs, type: 'reportCleanup', payload: { worldId } });
|
||||
}
|
||||
|
||||
module.exports = { createReport, ensureCleanup };
|
||||
153
server/military/units.js
Normal file
153
server/military/units.js
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Data helpers for units, reinforcements, research and operators, shared by the military commands, events and views.
|
||||
* Units are always { unitId: count }. Always settle() a town before changing its units: unit power draw is part of its
|
||||
* rates (state.unitDraw reads town_units and stationed).
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadTown } = require('../state');
|
||||
|
||||
function homeUnits(db, townId) {
|
||||
const out = {};
|
||||
for (const r of db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId)) out[r.unit] = r.count;
|
||||
return out;
|
||||
}
|
||||
|
||||
function setHomeUnit(db, townId, unit, count) {
|
||||
if (count > 0) db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, ?) ON CONFLICT (town_id, unit) DO UPDATE SET count = excluded.count', townId, unit, count);
|
||||
else db.run('DELETE FROM town_units WHERE town_id = ? AND unit = ?', townId, unit);
|
||||
}
|
||||
|
||||
function addHome(db, townId, units) {
|
||||
const cur = homeUnits(db, townId);
|
||||
for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, (cur[k] || 0) + units[k]);
|
||||
}
|
||||
|
||||
// Removes `units` from home; throws not_enough_units when the town does not have them (callers check first).
|
||||
function removeHome(db, townId, units) {
|
||||
const cur = homeUnits(db, townId);
|
||||
for (const k of Object.keys(units || {})) {
|
||||
if (!(units[k] > 0)) continue;
|
||||
if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] });
|
||||
}
|
||||
for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, cur[k] - units[k]);
|
||||
}
|
||||
|
||||
// Reinforcements standing in a host town: [{ ownerTownId, units }] grouped by the POP they belong to.
|
||||
function hostedGroups(db, hostTownId) {
|
||||
const by = new Map();
|
||||
for (const r of db.all('SELECT owner_town_id, unit, count FROM stationed WHERE host_town_id = ? ORDER BY owner_town_id, unit', hostTownId)) {
|
||||
if (!by.has(r.owner_town_id)) by.set(r.owner_town_id, {});
|
||||
by.get(r.owner_town_id)[r.unit] = r.count;
|
||||
}
|
||||
return Array.from(by, ([ownerTownId, units]) => ({ ownerTownId, units }));
|
||||
}
|
||||
|
||||
// Units of owner_town_id's operator standing in other POPs: [{ hostTownId, units }].
|
||||
function awayGroups(db, ownerTownId) {
|
||||
const by = new Map();
|
||||
for (const r of db.all('SELECT host_town_id, unit, count FROM stationed WHERE owner_town_id = ? ORDER BY host_town_id, unit', ownerTownId)) {
|
||||
if (!by.has(r.host_town_id)) by.set(r.host_town_id, {});
|
||||
by.get(r.host_town_id)[r.unit] = r.count;
|
||||
}
|
||||
return Array.from(by, ([hostTownId, units]) => ({ hostTownId, units }));
|
||||
}
|
||||
|
||||
function stationedOf(db, hostTownId, ownerTownId) {
|
||||
const out = {};
|
||||
for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', hostTownId, ownerTownId)) out[r.unit] = r.count;
|
||||
return out;
|
||||
}
|
||||
|
||||
function setStationed(db, hostTownId, ownerTownId, unit, count) {
|
||||
if (count > 0) db.run('INSERT INTO stationed (host_town_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?) ON CONFLICT (host_town_id, owner_town_id, unit) DO UPDATE SET count = excluded.count', hostTownId, ownerTownId, unit, count);
|
||||
else db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ? AND unit = ?', hostTownId, ownerTownId, unit);
|
||||
}
|
||||
|
||||
function addStationed(db, hostTownId, ownerTownId, units) {
|
||||
const cur = stationedOf(db, hostTownId, ownerTownId);
|
||||
for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, (cur[k] || 0) + units[k]);
|
||||
}
|
||||
|
||||
function removeStationed(db, hostTownId, ownerTownId, units) {
|
||||
const cur = stationedOf(db, hostTownId, ownerTownId);
|
||||
for (const k of Object.keys(units || {})) {
|
||||
if (!(units[k] > 0)) continue;
|
||||
if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] });
|
||||
}
|
||||
for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, cur[k] - units[k]);
|
||||
}
|
||||
|
||||
// Research levels of a POP as { 'unit:stat': level }.
|
||||
function researchLevels(db, townId) {
|
||||
const out = {};
|
||||
for (const r of db.all('SELECT unit, stat, level FROM town_research WHERE town_id = ?', townId)) out[R.researchKey(r.unit, r.stat)] = r.level;
|
||||
return out;
|
||||
}
|
||||
|
||||
// Snapshot of the research of `townId` for the unit types in `units` (stored on a movement at departure).
|
||||
function researchSnapshot(db, townId, units) {
|
||||
const all = researchLevels(db, townId);
|
||||
const out = {};
|
||||
for (const u of Object.keys(units)) for (const stat of D.RESEARCH.stats) { const k = R.researchKey(u, stat); if (all[k]) out[k] = all[k]; }
|
||||
return out;
|
||||
}
|
||||
|
||||
// Validates and normalises the `units` object of a request: known ids, whole numbers >= 0, zeros dropped.
|
||||
function cleanUnits(raw) {
|
||||
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) throw new GameError('validation_failed', { errors: [{ path: 'units', message: 'must be an object' }] });
|
||||
const out = {};
|
||||
for (const k of Object.keys(raw)) {
|
||||
if (!R.unitDef(k)) throw new GameError('unknown_unit', { unit: k });
|
||||
const n = raw[k];
|
||||
if (!Number.isInteger(n) || n < 0 || n > 1e7) throw new GameError('validation_failed', { errors: [{ path: 'units.' + k, message: 'must be a whole number >= 0' }] });
|
||||
if (n > 0) out[k] = n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const sumInto = (a, b) => { for (const k of Object.keys(b || {})) a[k] = (a[k] || 0) + b[k]; return a; };
|
||||
const isEmpty = (units) => !Object.keys(units || {}).some((k) => units[k] > 0);
|
||||
|
||||
// ---- operators
|
||||
function getOperator(db, id) { return db.get('SELECT * FROM operators WHERE id = ?', id); }
|
||||
function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; }
|
||||
function operatorTowns(db, operatorId) { return db.all('SELECT * FROM towns WHERE owner_id = ? ORDER BY id', operatorId); }
|
||||
|
||||
// Footprint over all POPs of the operator at `now` (each POP's footprint keeps growing from its buildings).
|
||||
function operatorFootprint(db, operatorId, now) {
|
||||
let sum = 0;
|
||||
for (const t of operatorTowns(db, operatorId)) sum += R.footprintAt(loadTown(db, t.id), now);
|
||||
return sum;
|
||||
}
|
||||
|
||||
function incumbentTakes(db, operatorId) { return db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', operatorId).n; }
|
||||
function researchBonusOf(db, operatorId) { return R.researchSpeedBonus(incumbentTakes(db, operatorId)); }
|
||||
|
||||
// Where do units of `operatorId` go when their origin POP is gone: the capital, else the oldest POP; null if none.
|
||||
function homeTownFor(db, operatorId, preferTownId) {
|
||||
if (preferTownId) {
|
||||
const t = db.get('SELECT * FROM towns WHERE id = ? AND owner_id = ?', preferTownId, operatorId);
|
||||
if (t) return t;
|
||||
}
|
||||
return db.get('SELECT * FROM towns WHERE owner_id = ? ORDER BY is_capital DESC, id LIMIT 1', operatorId) || null;
|
||||
}
|
||||
|
||||
// May `fromOp` stand units in a POP of `toOp`? Own POPs, same alliance, confederation.
|
||||
function mayReinforce(db, fromOp, toOp) {
|
||||
if (fromOp === toOp) return true;
|
||||
return require('../alliances').confederated(db, fromOp, toOp);
|
||||
}
|
||||
// Pacts (same alliance, NAP, confederation) forbid hostile movements between the partners.
|
||||
function pactBlocks(db, fromOp, toOp) {
|
||||
if (fromOp === toOp) return false;
|
||||
return require('../alliances').pactPartners(db, fromOp, toOp);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
homeUnits, setHomeUnit, addHome, removeHome, hostedGroups, awayGroups, stationedOf, setStationed, addStationed, removeStationed,
|
||||
researchLevels, researchSnapshot, cleanUnits, sumInto, isEmpty,
|
||||
getOperator, userOfOperator, operatorTowns, operatorFootprint, incumbentTakes, researchBonusOf, homeTownFor, mayReinforce, pactBlocks,
|
||||
};
|
||||
155
server/military/views.js
Normal file
155
server/military/views.js
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Read models for the military stage: the military part of GET /towns/:id, the movements list with incoming warnings,
|
||||
* reports, and tile info for the send dialog. Reads catch the event queue up first (via `fresh`) and never write.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadWorld } = require('../state');
|
||||
const U = require('./units');
|
||||
const P = require('./power');
|
||||
|
||||
const j = (s) => JSON.parse(s || '{}');
|
||||
|
||||
function townNames(db, ids) {
|
||||
const out = new Map();
|
||||
for (const id of ids) {
|
||||
if (!id || out.has(id)) continue;
|
||||
const t = db.get('SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ?', id);
|
||||
out.set(id, t ? { id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital, owner: { id: t.oid, name: t.oname, asNumber: t.asn } } : null);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// What the owner of a movement sees.
|
||||
function ownerView(m, names) {
|
||||
const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null;
|
||||
const extra = j(m.extra);
|
||||
return {
|
||||
id: m.id, type: m.type, status: m.status, ownerId: m.owner_id,
|
||||
from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null },
|
||||
to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null },
|
||||
units: j(m.units), cargo: j(m.cargo), departAt: m.depart_at, arriveAt: m.arrive_at,
|
||||
recallableUntil: m.type === 'return' ? null : m.depart_at + D.MILITARY.recallWindowMs,
|
||||
target: extra.target || null, parentId: m.parent_id,
|
||||
};
|
||||
}
|
||||
|
||||
// What the target of somebody else's movement sees: origin and ETA, never the type, units or cargo.
|
||||
function incomingView(m, names) {
|
||||
const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null;
|
||||
return {
|
||||
id: m.id, type: 'unknown', status: m.status, incoming: true,
|
||||
from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null, owner: f ? f.owner : null },
|
||||
to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null },
|
||||
departAt: m.depart_at, arriveAt: m.arrive_at,
|
||||
};
|
||||
}
|
||||
|
||||
// Active movements: the operator's own (outgoing legs, returns, transports) and other operators' movements heading for
|
||||
// the operator's POPs. `townId` limits both to one POP.
|
||||
function movementLists(db, operatorId, townId) {
|
||||
const own = db.all(`SELECT * FROM movements WHERE owner_id = ? AND status = 'out' ${townId ? 'AND (from_town_id = ? OR to_town_id = ?)' : ''} ORDER BY arrive_at, id LIMIT ?`,
|
||||
...(townId ? [operatorId, townId, townId, D.MILITARY.maxLists] : [operatorId, D.MILITARY.maxLists]));
|
||||
const inc = db.all(`SELECT m.* FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id = ? AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return'
|
||||
${townId ? 'AND m.to_town_id = ?' : ''} ORDER BY m.arrive_at, m.id LIMIT ?`,
|
||||
...(townId ? [operatorId, operatorId, townId, D.MILITARY.maxLists] : [operatorId, operatorId, D.MILITARY.maxLists]));
|
||||
const names = townNames(db, own.concat(inc).flatMap((m) => [m.from_town_id, m.to_town_id]));
|
||||
return { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) };
|
||||
}
|
||||
|
||||
// The military part of GET /towns/:id (the town object is already loaded and belongs to the caller).
|
||||
function townMilitary(db, t, now, world) {
|
||||
const home = U.homeUnits(db, t.id);
|
||||
const online = P.online(t, now);
|
||||
const names = townNames(db, U.hostedGroups(db, t.id).map((g) => g.ownerTownId).concat(U.awayGroups(db, t.id).map((g) => g.hostTownId)));
|
||||
const hosted = U.hostedGroups(db, t.id).map((g) => ({ ownerTownId: g.ownerTownId, ownerTownName: names.get(g.ownerTownId) ? names.get(g.ownerTownId).name : null, owner: names.get(g.ownerTownId) ? names.get(g.ownerTownId).owner : null, units: g.units }));
|
||||
const away = U.awayGroups(db, t.id).map((g) => ({ hostTownId: g.hostTownId, hostTownName: names.get(g.hostTownId) ? names.get(g.hostTownId).name : null, units: g.units }));
|
||||
const training = db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", t.id)
|
||||
.map((e) => { const p = JSON.parse(e.payload); return { id: e.id, unit: p.unit, count: p.count, building: p.building, startAt: p.startAt, dueAt: e.due_at }; });
|
||||
const rq = db.get("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' ORDER BY due_at, id LIMIT 1", t.id);
|
||||
const rp = rq ? JSON.parse(rq.payload) : null;
|
||||
const bonus = U.researchBonusOf(db, t.ownerId);
|
||||
const trainable = D.UNIT_ORDER.map((unit) => {
|
||||
const def = D.UNITS[unit];
|
||||
const missing = R.unitMissing(t, unit);
|
||||
return { unit, building: def.building, role: def.role, cost: R.unitCost(unit, 1), timeMs: R.trainTimeMs(unit, 1, t.buildings[def.building] ? t.buildings[def.building].level : 0, world.speed), missing, locked: missing.length > 0 };
|
||||
});
|
||||
const offline = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', t.id);
|
||||
const op = U.getOperator(db, t.ownerId);
|
||||
const links = R.transportLinks(t);
|
||||
return {
|
||||
units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away },
|
||||
training, trainable,
|
||||
research: { levels: U.researchLevels(db, t.id), queue: rq ? { id: rq.id, unit: rp.unit, stat: rp.stat, toLevel: rp.toLevel, startedAt: rp.startedAt, dueAt: rq.due_at } : null, speedBonus: bonus, maxLevel: D.RESEARCH.maxLevel },
|
||||
transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: D.TRANSPORT.capacityPerLink },
|
||||
movements: movementLists(db, t.ownerId, t.id),
|
||||
protectionUntil: op.protection_until,
|
||||
};
|
||||
}
|
||||
|
||||
function createMilitaryQueries({ db, clock, scheduler }) {
|
||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||
|
||||
function operatorFor(userId, worldId) {
|
||||
const op = worldId ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId) : db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId);
|
||||
if (!op) throw new GameError('not_found', { what: 'operator' });
|
||||
return op;
|
||||
}
|
||||
|
||||
function movements(userId, { worldId }) {
|
||||
const now = fresh();
|
||||
const op = operatorFor(userId, worldId);
|
||||
return Object.assign({ serverTime: now }, movementLists(db, op.id, null));
|
||||
}
|
||||
|
||||
function reports(userId, { after, limit, unread }) {
|
||||
const now = fresh();
|
||||
const n = limit || 25;
|
||||
const rows = db.all(`SELECT r.id, r.type, r.created_at, r.summary, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id
|
||||
WHERE rr.user_id = ? ${after ? 'AND r.id < ?' : ''} ${unread ? 'AND rr.read_at IS NULL' : ''} ORDER BY r.id DESC LIMIT ?`, ...(after ? [userId, after, n + 1] : [userId, n + 1]));
|
||||
const items = rows.slice(0, n).map((r) => ({ id: r.id, type: r.type, createdAt: r.created_at, role: r.role, read: r.read_at !== null, summary: j(r.summary) }));
|
||||
const unreadCount = db.get('SELECT COUNT(*) AS n FROM report_recipients WHERE user_id = ? AND read_at IS NULL', userId).n;
|
||||
return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null, unread: unreadCount };
|
||||
}
|
||||
|
||||
function report(userId, id) {
|
||||
const now = fresh();
|
||||
const r = db.get(`SELECT r.*, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? AND r.id = ?`, userId, id);
|
||||
if (!r) throw new GameError('not_found', { what: 'report' });
|
||||
return { serverTime: now, report: { id: r.id, type: r.type, createdAt: r.created_at, expiresAt: r.expires_at, role: r.role, read: r.read_at !== null, summary: j(r.summary), data: j(r.data) } };
|
||||
}
|
||||
|
||||
// Public information about a tile, for the send dialog: what is there, who owns it, how far it is from each of my POPs,
|
||||
// whether I could found a POP there.
|
||||
function tileInfo(userId, { worldId, x, y }) {
|
||||
const now = fresh();
|
||||
const op = operatorFor(userId, worldId);
|
||||
const world = loadWorld(db, op.world_id);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||
if (tile.type === 'void') throw new GameError('not_found', { what: 'tile' });
|
||||
const row = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y);
|
||||
const mine = U.operatorTowns(db, op.id);
|
||||
const out = { serverTime: now, x, y, type: row ? 'pop' : tile.type, bonus: tile.bonus || null, distances: mine.map((t) => ({ townId: t.id, distance: R.distance(t.x, t.y, x, y) })) };
|
||||
if (row) {
|
||||
const o = U.getOperator(db, row.owner_id);
|
||||
out.town = { id: row.id, name: row.name, isCapital: !!row.is_capital, owner: { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protected: R.isProtected(o.protection_until, now), protectionUntil: o.protection_until }, mine: o.id === op.id };
|
||||
}
|
||||
if (tile.type === 'incumbent') {
|
||||
const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, op.id);
|
||||
out.incumbent = { takenByYou: taken, hardwareBonus: taken ? 0 : D.INCUMBENT.hardwareBonus };
|
||||
}
|
||||
const fp = U.operatorFootprint(db, op.id, now);
|
||||
const gate = R.footprintGate(mine.length, fp);
|
||||
let nearest = Infinity;
|
||||
for (const t of mine) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
|
||||
const sc = R.settleCheck({ tileType: tile.type, occupied: !!row, nearestOwnDist: nearest, ownedCount: mine.length, footprint: fp });
|
||||
out.settle = { possible: sc.ok, code: sc.ok ? null : sc.code, footprint: fp, footprintNeeded: gate.need, maxDistance: D.EXPANSION.maxDistance };
|
||||
return out;
|
||||
}
|
||||
|
||||
return { movements, reports, report, tileInfo };
|
||||
}
|
||||
|
||||
module.exports = { townMilitary, movementLists, createMilitaryQueries };
|
||||
Loading…
Add table
Add a link
Reference in a new issue