Phase 4: close loot/refund leaks, landing-site garrisons, speed-scaled shipping, update/offsite tooling, broad e2e
Built: - Economy: raid loot capped to the room the raiders have at home (rest stays with the victim, "lootLeft" in the report); trade escrow reserves its room so refunds always fit; trade accept refuses with no_room_for_goods when the goods would not fit. Loot destroyed per 30-day run 31-61k -> ~1k, refunds clipped ~27k -> 0 (docs/BALANCE.md, 3 seeds). - End game: members of the holding alliance garrison landing sites (migration 005_site_garrison.sql), garrison counts in site defence, 72 h capture shield, withdraw route, POP view lists garrisoned units. Shipping capacity scales with world speed (3x world: winner 76-98 -> ~30-36 days after sites open). Bot runs show real contests (84-194 attacks on held sites at 1x). - Ops: deploy/update.sh (backup, stop, ff-merge, npm ci --ignore-scripts, health check, rollback), deploy/upstream-offsite (rsync only), admin end-world snapshots results, EPIPE fix, docs/workflows/ filled in. - e2e 62 -> 163 checks: units, raids/reports, alliance+messages, trade, end game, nb, PWA, reconnect, slow polling fallback (opt-in). Two app bugs found: message push ignored, "New" button stayed English. Tested: npm test 274/274, openapi check, npm run e2e 163/163 (137 s), bot runs 50x30d seeds 1-3 and 140-day/60-day speed-3 end-game runs INVARIANTS OK, adversarial review pass (findings fixed or documented). NOT tested: update.sh on a real box (systemd, real npm, runuser; stubs only, shellcheck not installed), garrison card/loot text on a phone, Node 22.13, humans. Known leaks left open and documented (BALANCE S6): loot/shipments can still overflow when stock arrives in flight, bounced backbone shipments lose overflow (reported to the sender). Garrison numbers (heldDefenceMult 2, shield 72 h) are first guesses from 2 seeds. Not claimed: balanced. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
9104480463
commit
3c23c51902
92 changed files with 4887 additions and 300 deletions
|
|
@ -17,14 +17,15 @@ 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);
|
||||
// `bonus` (optional, per resource) is part of the cargo that is credited even above the Rack hall size (one-time rewards).
|
||||
function addCargo(db, town, cargo, bonus) {
|
||||
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);
|
||||
const free = Math.max(0, add - ((bonus && bonus[r]) || 0));
|
||||
const next = Math.min(Math.max(R.storageCapOf(town, r), cur), cur + free) + (add - free); // escrowed goods of open offers keep their room (storageCapOf)
|
||||
lost[r] = Math.max(0, Math.round(cur + add - next));
|
||||
town.res[r] = next;
|
||||
}
|
||||
|
|
@ -50,6 +51,7 @@ function bounce(ctx, mv, now, reason, details) {
|
|||
function arriveReinforce(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
if (!mv.toTownId) return require('./landing').reinforce(ctx, mv, ev); // a backbone landing site: the garrison (E6)
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -49,12 +49,34 @@ function addPoints(db, operatorId, column, v) {
|
|||
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) {
|
||||
function sendHome(ctx, mv, survivors, cargo, extra) {
|
||||
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: {} });
|
||||
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: extra || {} });
|
||||
}
|
||||
|
||||
// What the raiders' home can bank per resource when they are back: Rack hall room minus the stock projected to that moment (pure
|
||||
// projection, nothing is written). No home or no survivors to carry anything: no room at all (the loot would never be delivered).
|
||||
function homeRoom(ctx, mv, survivors, now, world) {
|
||||
const none = { fiber: 0, hardware: 0, capital: 0 };
|
||||
const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId);
|
||||
if (!dest || U.isEmpty(survivors)) return none;
|
||||
const home = loadTown(ctx.db, dest.id);
|
||||
const bankAt = now + R.movementMs(R.distance(mv.to.x, mv.to.y, dest.x, dest.y), survivors, world.speed);
|
||||
const cur = R.resourcesAt(home, bankAt);
|
||||
// Room already promised: cargo of other return legs still on the road to this POP (earlier raids, bounced shipments) will be banked
|
||||
// too, so two raids that each see the same free room cannot both fill it (the later one is limited, not destroyed on landing).
|
||||
// One-time bonus cargo (extra.bonus) is credited above the cap and holds no room.
|
||||
const booked = { fiber: 0, hardware: 0, capital: 0 };
|
||||
for (const row of ctx.db.all("SELECT cargo, extra FROM movements WHERE type = 'return' AND status = 'out' AND to_town_id = ? AND owner_id = ?", dest.id, mv.ownerId)) {
|
||||
const c = JSON.parse(row.cargo || '{}'), bonus = (JSON.parse(row.extra || '{}').bonus) || {};
|
||||
for (const r of D.RESOURCES) booked[r] += Math.max(0, (c[r] || 0) - (bonus[r] || 0));
|
||||
}
|
||||
const room = {};
|
||||
for (const r of D.RESOURCES) room[r] = Math.max(0, Math.floor(cur.caps[r] - cur.amounts[r] - booked[r]));
|
||||
return room;
|
||||
}
|
||||
|
||||
function arrive(ctx, mv, ev) {
|
||||
|
|
@ -106,12 +128,17 @@ function arrive(ctx, mv, ev) {
|
|||
|
||||
// ---- loot
|
||||
let loot = { fiber: 0, hardware: 0, capital: 0 };
|
||||
const lootLeft = {}; // available and carried, but with no room to bank at home
|
||||
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);
|
||||
// Only what the raiders' home Rack hall can bank when they arrive is taken; the rest stays with the victim and the report says so (S4).
|
||||
const room = homeRoom(ctx, mv, survivorsAtt, now, world);
|
||||
loot = R.lootSplit(R.carryOf(survivorsAtt), avail, room);
|
||||
const wanted = R.lootSplit(R.carryOf(survivorsAtt), avail);
|
||||
for (const r of D.RESOURCES) if (wanted[r] > loot[r]) lootLeft[r] = wanted[r] - loot[r];
|
||||
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);
|
||||
}
|
||||
|
|
@ -163,7 +190,7 @@ function arrive(ctx, mv, ev) {
|
|||
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,
|
||||
loot, lootLeft, 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' }];
|
||||
|
|
@ -247,7 +274,9 @@ function arriveSite(ctx, mv, now, world) {
|
|||
bonus = { hardware: D.INCUMBENT.hardwareBonus, researchSpeedBonus: R.researchSpeedBonus(U.incumbentTakes(db, attackerOp.id)) };
|
||||
}
|
||||
}
|
||||
const ret = sendHome(ctx, mv, survivors, cargo);
|
||||
// The once-only bonus is delivered in full even when the Rack hall is full (stock above the hall size is kept, it only stops growing): a reward
|
||||
// that can never be earned again must not vanish at the door (S4, events/return.js reads extra.bonus).
|
||||
const ret = sendHome(ctx, mv, survivors, cargo, bonus ? { bonus: { hardware: bonus.hardware } } : {});
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'incumbent', now,
|
||||
summary: { outcome: b.attackerWins ? 'attacker_won' : 'defender_won', site, bonus },
|
||||
|
|
@ -264,6 +293,7 @@ function arriveSite(ctx, mv, now, world) {
|
|||
// standing elsewhere are re-homed, the new owner starts at conqueredLoyalty.
|
||||
function transferTown(ctx, town, newOp, oldOp, now) {
|
||||
const { db } = ctx;
|
||||
require('./garrison').releaseTown(ctx, town.id, 'town_lost'); // what this POP had standing in a landing site goes home to its old owner (E6)
|
||||
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);
|
||||
|
|
|
|||
139
server/military/garrison.js
Normal file
139
server/military/garrison.js
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Garrisons at backbone landing sites (docs/DECISIONS.md E6): units of an operator whose alliance holds the site, standing in the
|
||||
* site and defending it on top of its static defence. Table `site_stationed(site_id, owner_town_id, unit, count)`.
|
||||
*
|
||||
* Rules in one place:
|
||||
* - Only members of the HOLDING alliance may station units (checked when sending and again when the units arrive).
|
||||
* - The units draw the power of their OWNER's POP (state.unitDraw), so garrisoning moves no power around; they are online
|
||||
* exactly when that POP's units are. Always loadTown + settle the owner BEFORE changing its garrison (the draw is part of its rates).
|
||||
* - A unit lives in exactly one place: home (town_units), stationed in a POP, in a garrison, or in a movement. Every function here
|
||||
* moves units, none creates or deletes them except through a battle report (losses) or `lost` below (no POP to go home to).
|
||||
* - Units leave a garrison only by (a) the owner withdrawing them, (b) the owner leaving/being kicked from the alliance or the alliance
|
||||
* dissolving, (c) the owner's POP changing hands, (d) dying in a battle, (e) decommission when the owner's POP has no power.
|
||||
* (a) to (c) are return movements to the owner's home, so nothing is ever lost on the way.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadTown, settle } = require('../state');
|
||||
const U = require('./units');
|
||||
const M = require('./movements');
|
||||
const P = require('./power');
|
||||
|
||||
// Units of one owner POP in a site as { unit: count }.
|
||||
function ownedAt(db, siteId, ownerTownId) {
|
||||
const out = {};
|
||||
for (const r of db.all('SELECT unit, count FROM site_stationed WHERE site_id = ? AND owner_town_id = ?', siteId, ownerTownId)) out[r.unit] = r.count;
|
||||
return out;
|
||||
}
|
||||
|
||||
// Everything standing in a site, grouped by owner POP: [{ ownerTownId, ownerOpId, units }] (ordered by owner POP id: a stable battle order).
|
||||
function groups(db, siteId) {
|
||||
const by = new Map();
|
||||
for (const r of db.all('SELECT s.owner_town_id AS tid, s.unit AS unit, s.count AS count, t.owner_id AS oid FROM site_stationed s LEFT JOIN towns t ON t.id = s.owner_town_id WHERE s.site_id = ? ORDER BY s.owner_town_id, s.unit', siteId)) {
|
||||
if (!by.has(r.tid)) by.set(r.tid, { ownerTownId: r.tid, ownerOpId: r.oid, units: {} });
|
||||
by.get(r.tid).units[r.unit] = r.count;
|
||||
}
|
||||
return Array.from(by.values());
|
||||
}
|
||||
|
||||
// All units an owner POP has standing in sites (its draw): { unit: count }.
|
||||
function ofTown(db, ownerTownId) {
|
||||
const out = {};
|
||||
for (const r of db.all('SELECT unit, SUM(count) AS n FROM site_stationed WHERE owner_town_id = ? GROUP BY unit', ownerTownId)) out[r.unit] = r.n;
|
||||
return out;
|
||||
}
|
||||
|
||||
function setUnit(db, siteId, ownerTownId, unit, count) {
|
||||
if (count > 0) db.run('INSERT INTO site_stationed (site_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?) ON CONFLICT (site_id, owner_town_id, unit) DO UPDATE SET count = excluded.count', siteId, ownerTownId, unit, count);
|
||||
else db.run('DELETE FROM site_stationed WHERE site_id = ? AND owner_town_id = ? AND unit = ?', siteId, ownerTownId, unit);
|
||||
}
|
||||
function add(db, siteId, ownerTownId, units) {
|
||||
const cur = ownedAt(db, siteId, ownerTownId);
|
||||
for (const k of Object.keys(units || {})) if (units[k] > 0) setUnit(db, siteId, ownerTownId, k, (cur[k] || 0) + units[k]);
|
||||
}
|
||||
function remove(db, siteId, ownerTownId, units) {
|
||||
const cur = ownedAt(db, siteId, ownerTownId);
|
||||
for (const k of Object.keys(units || {})) if (units[k] > 0 && (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) setUnit(db, siteId, ownerTownId, k, cur[k] - units[k]);
|
||||
}
|
||||
|
||||
// Defence figures of a site's garrison at `now`: only groups whose owner POP is online defend (like units at home). Reads only (online is projected).
|
||||
// -> { groups: [{ id, ownerTownId, ownerOpId, units, research, online }], power: raw defence of the online groups }
|
||||
function defenders(db, siteId, now) {
|
||||
const out = [];
|
||||
let power = 0;
|
||||
for (const g of groups(db, siteId)) {
|
||||
const town = loadTown(db, g.ownerTownId);
|
||||
const online = !town || P.online(town, now);
|
||||
const research = U.researchLevels(db, g.ownerTownId);
|
||||
out.push({ id: 'from:' + g.ownerTownId, ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, units: g.units, research, online });
|
||||
if (online) power += R.defencePower(g.units, research);
|
||||
}
|
||||
return { groups: out, power };
|
||||
}
|
||||
|
||||
// Take `units` out of the site and send them home to their owner (the owner POP, or the operator's capital/oldest POP when that POP has changed
|
||||
// hands). The owner POP is settled first and its power rescheduled. -> the return movement, or null when the owner has no POP left (units gone).
|
||||
function sendHome(ctx, site, ownerTownId, units, extra) {
|
||||
const { db, now } = ctx;
|
||||
units = Object.fromEntries(Object.entries(units).filter(([, n]) => n > 0));
|
||||
if (U.isEmpty(units)) return null;
|
||||
const ownerTown = db.get('SELECT * FROM towns WHERE id = ?', ownerTownId);
|
||||
const town = ownerTown ? loadTown(db, ownerTownId) : null;
|
||||
if (town) settle(db, town, now); // the draw of the owner changes now
|
||||
remove(db, site.id, ownerTownId, units);
|
||||
if (town) P.reschedule(ctx, town.id, now);
|
||||
const opId = ownerTown ? ownerTown.owner_id : null;
|
||||
const dest = opId ? U.homeTownFor(db, opId, ownerTownId) : null;
|
||||
if (!dest) return null;
|
||||
return M.launchReturn(ctx, { worldId: site.world_id, ownerId: dest.owner_id, fromTownId: null, at: { x: site.x, y: site.y }, to: dest, units, cargo: {}, extra: Object.assign({ garrison: true }, extra || {}) });
|
||||
}
|
||||
|
||||
// Everything of one owner POP in one site goes home. -> units sent
|
||||
function releaseGroup(ctx, site, ownerTownId, reason) {
|
||||
const units = ownedAt(ctx.db, site.id, ownerTownId);
|
||||
if (U.isEmpty(units)) return {};
|
||||
const mv = sendHome(ctx, site, ownerTownId, units, { released: reason });
|
||||
const t = ctx.db.get('SELECT owner_id AS oid, world_id AS wid FROM towns WHERE id = ?', ownerTownId);
|
||||
const uid = t ? U.userOfOperator(ctx.db, t.oid) : null;
|
||||
if (uid) ctx.notify(uid, site.world_id, 'garrison_released', { siteId: site.id, index: site.idx, ownerTownId, reason, units, movementId: mv ? mv.id : null });
|
||||
return units;
|
||||
}
|
||||
|
||||
// The whole garrison of a site goes home (the holding alliance is gone).
|
||||
function releaseSite(ctx, site, reason) {
|
||||
for (const g of groups(ctx.db, site.id)) releaseGroup(ctx, site, g.ownerTownId, reason);
|
||||
}
|
||||
|
||||
// Everything an operator has standing in sites goes home (it left or was kicked from the holding alliance). Only sites of its OLD alliance
|
||||
// can hold its units, so this takes no alliance argument.
|
||||
function releaseOperator(ctx, operatorId, reason) {
|
||||
const { db } = ctx;
|
||||
const rows = db.all(`SELECT DISTINCT s.site_id AS sid, s.owner_town_id AS tid FROM site_stationed s JOIN towns t ON t.id = s.owner_town_id WHERE t.owner_id = ? ORDER BY s.site_id, s.owner_town_id`, operatorId);
|
||||
for (const r of rows) releaseGroup(ctx, db.get('SELECT * FROM landing_sites WHERE id = ?', r.sid), r.tid, reason);
|
||||
}
|
||||
|
||||
// A POP changed hands (takeover): whatever it had standing in sites goes home to its OLD owner (like units it had in other POPs).
|
||||
function releaseTown(ctx, ownerTownId, reason) {
|
||||
const { db } = ctx;
|
||||
for (const r of db.all('SELECT DISTINCT site_id AS sid FROM site_stationed WHERE owner_town_id = ? ORDER BY site_id', ownerTownId)) {
|
||||
releaseGroup(ctx, db.get('SELECT * FROM landing_sites WHERE id = ?', r.sid), ownerTownId, reason);
|
||||
}
|
||||
}
|
||||
|
||||
// Read model for a site: groups with owner and units, total raw defence (online groups only) and the static part.
|
||||
function view(db, siteId, now) {
|
||||
const d = defenders(db, siteId, now);
|
||||
return {
|
||||
power: d.power,
|
||||
groups: d.groups.map((g) => {
|
||||
const op = g.ownerOpId ? db.get('SELECT id, name FROM operators WHERE id = ?', g.ownerOpId) : null;
|
||||
const t = db.get('SELECT id, name, x, y FROM towns WHERE id = ?', g.ownerTownId);
|
||||
return { ownerTownId: g.ownerTownId, townName: t ? t.name : null, operator: op ? { operatorId: op.id, name: op.name } : null, units: g.units, online: g.online, power: R.defencePower(g.units, g.research) };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { ownedAt, groups, ofTown, add, remove, setUnit, defenders, sendHome, releaseGroup, releaseSite, releaseOperator, releaseTown, view };
|
||||
|
|
@ -1,9 +1,14 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Arrival of a scan or an attack at a backbone landing site (hooked from combat.arriveSite, runs inside the `arrive` event).
|
||||
* A site is defended by a static value only: rules.backboneDefence(seed, x, y, world age, node level). Beating it as a member
|
||||
* of an alliance makes that alliance the holder (level, stockpile and a running build stay with the site). The site never
|
||||
* loses anything, so there is no loot and no raid; survivors drive home. Re-validates at arrival like every movement.
|
||||
* Arrival of a scan, an attack or a reinforcement at a backbone landing site (scan/attack hooked from combat.arriveSite, reinforce from
|
||||
* arrivals.arriveReinforce; all run inside the `arrive` event, at its due time, so waves resolve strictly in arrival order).
|
||||
*
|
||||
* Defence of a site = static value (rules.backboneDefence: heavy while nobody holds it, a modest `heldDefenceMult` once an alliance does,
|
||||
* both growing with the node level) + the garrison: units that members of the holding alliance stationed there (server/military/garrison.js,
|
||||
* DECISIONS E6), counted with their owner's defence research while their owner POP is online. A lost attack kills the same share of the
|
||||
* garrison as it would in a POP (ratio^1.5 of its units), so the next wave faces less; a won attack wipes it and the attacker's alliance
|
||||
* holds the site (level, stockpile and a running build stay with the site). The static part loses nothing; survivors drive home.
|
||||
* Re-validates at arrival like every movement.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
|
|
@ -11,10 +16,21 @@ const U = require('./units');
|
|||
const M = require('./movements');
|
||||
const E = require('../endgame');
|
||||
const { createReport } = require('./reports');
|
||||
const G = require('./garrison');
|
||||
const P = require('./power');
|
||||
const { loadTown, loadWorld, settle } = require('../state');
|
||||
const { bounce, townBrief, opBrief } = require('./arrivals');
|
||||
|
||||
const SCAN_STRENGTH = D.ENDGAME.scanStrength; // a landing site counts as this many defending scanners
|
||||
|
||||
// Battle points (the same bookkeeping as POP combat; combat.js keeps its own copy of this helper private).
|
||||
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);
|
||||
const col = column === 'attack' ? 'attack_points' : 'defense_points';
|
||||
db.run('UPDATE operator_stats SET ' + col + ' = ' + col + ' + ? WHERE operator_id = ?', v, operatorId);
|
||||
}
|
||||
|
||||
function sendHome(ctx, mv, survivors) {
|
||||
if (U.isEmpty(survivors)) return null;
|
||||
const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId);
|
||||
|
|
@ -22,7 +38,27 @@ function sendHome(ctx, mv, survivors) {
|
|||
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at: mv.to, to: dest, units: survivors, cargo: {}, parentId: mv.id, extra: {} });
|
||||
}
|
||||
|
||||
module.exports = function arriveLanding(ctx, mv, now, world, tile) {
|
||||
// A member of the holding alliance's units reach the site: they join its garrison. Anybody else, or a site that changed hands on the road, bounces them.
|
||||
function reinforce(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
const world = loadWorld(db, mv.worldId);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, mv.to.x, mv.to.y, E.ageDays(world, now));
|
||||
if (tile.type !== 'backbone') return bounce(ctx, mv, now, 'invalid_target');
|
||||
const site = E.ensureSites(db, world, now, ctx).find((r) => r.idx === tile.site);
|
||||
const op = U.getOperator(db, mv.ownerId);
|
||||
if (!op.alliance_id || !site.holder_alliance_id || site.holder_alliance_id !== op.alliance_id) return bounce(ctx, mv, now, 'not_holder');
|
||||
const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||
if (!ownerTown) return; // the sender lost every POP meanwhile: nothing to belong to
|
||||
const town = loadTown(db, ownerTown.id);
|
||||
settle(db, town, now); // the owner's draw is the same as before the trip, but only from this moment
|
||||
G.add(db, site.id, ownerTown.id, mv.units);
|
||||
P.reschedule(ctx, town.id, now);
|
||||
const uid = U.userOfOperator(db, op.id);
|
||||
if (uid) ctx.notify(uid, mv.worldId, 'garrison_arrived', { siteId: site.id, index: site.idx, ownerTownId: ownerTown.id, units: mv.units });
|
||||
}
|
||||
|
||||
function arriveLanding(ctx, mv, now, world, tile) {
|
||||
const { db } = ctx;
|
||||
if (mv.type !== 'scan' && mv.type !== 'attack') return bounce(ctx, mv, now, 'invalid_target');
|
||||
const rows = E.ensureSites(db, world, now, ctx);
|
||||
|
|
@ -31,13 +67,24 @@ module.exports = function arriveLanding(ctx, mv, now, world, tile) {
|
|||
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
|
||||
const uid = U.userOfOperator(db, attackerOp.id);
|
||||
const where = { x: site.x, y: site.y, index: site.idx, siteId: site.id, level: site.level, holder: E.allianceInfo(db, site.holder_alliance_id) };
|
||||
const staticDef = R.backboneDefence(world.seed, site.x, site.y, E.ageDays(world, now), site.level);
|
||||
const held = !!site.holder_alliance_id;
|
||||
const staticDef = R.backboneDefence(world.seed, site.x, site.y, E.ageDays(world, now), site.level, held);
|
||||
const def = G.defenders(db, site.id, now); // the garrison (read only: nothing changes until the battle is resolved)
|
||||
const active = def.groups.filter((g) => g.online);
|
||||
where.held = held;
|
||||
|
||||
if (mv.type === 'scan') {
|
||||
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
|
||||
const res = R.resolveScan(sa, SCAN_STRENGTH);
|
||||
let sd = SCAN_STRENGTH;
|
||||
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);
|
||||
const intel = res.success ? { defence: staticDef, level: site.level, holder: where.holder, build: site.build_to ? { toLevel: site.build_to, dueAt: site.build_due_at } : null } : null;
|
||||
const garrisonUnits = {};
|
||||
for (const g of def.groups) U.sumInto(garrisonUnits, g.units);
|
||||
const intel = res.success ? {
|
||||
defence: staticDef + def.power, static: staticDef, level: site.level, holder: where.holder, build: site.build_to ? { toLevel: site.build_to, dueAt: site.build_due_at } : null,
|
||||
garrison: { units: garrisonUnits, power: def.power, offline: def.groups.filter((g) => !g.online).map((g) => g.ownerTownId) },
|
||||
} : null;
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site: Object.assign({ type: 'backbone' }, where) },
|
||||
data: { success: res.success, detail: res.detail, site: Object.assign({ type: 'backbone' }, where), scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel },
|
||||
|
|
@ -50,18 +97,50 @@ module.exports = function arriveLanding(ctx, mv, now, world, tile) {
|
|||
// attack: alliance members only, and not against the own alliance or a pact partner (the world may have changed since it left)
|
||||
if (!attackerOp.alliance_id) return bounce(ctx, mv, now, 'no_alliance');
|
||||
try { E.denyIfFriendly(db, attackerOp, site); } catch (e) { return bounce(ctx, mv, now, e.details.reason || 'invalid_target'); }
|
||||
const shield = E.shieldUntil(site, world);
|
||||
if (shield > now) return bounce(ctx, mv, now, 'site_shielded', { until: shield }); // it changed hands while the attack was on the road
|
||||
|
||||
const b = R.resolveBattle({ kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, defenders: [], firewall: 0, staticDefence: staticDef });
|
||||
const b = R.resolveBattle({
|
||||
kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} },
|
||||
defenders: active.map((g) => ({ id: g.id, units: g.units, research: g.research })), firewall: 0, staticDefence: staticDef,
|
||||
});
|
||||
const survivors = Object.assign({}, b.attacker.survivors);
|
||||
const oldHolder = site.holder_alliance_id;
|
||||
|
||||
// ---- the garrison: losses (a won attack wipes every group, offline ones included), written after settling each owner POP (its draw changes)
|
||||
const wipe = b.attackerWins || b.defenderLossFraction >= 1; // (the offline groups are not in the battle, but a lost site takes them with it)
|
||||
const garrisonReport = [];
|
||||
let defenderLost = {};
|
||||
for (const g of def.groups) {
|
||||
const res = b.defenders.find((d) => d.id === g.id);
|
||||
let left, lost;
|
||||
if (wipe) { left = {}; lost = g.units; } else if (res) { left = res.survivors; lost = res.lost; } else { left = g.units; lost = {}; }
|
||||
if (!U.isEmpty(lost)) {
|
||||
const town = loadTown(db, g.ownerTownId);
|
||||
if (town) settle(db, town, now);
|
||||
for (const k of Object.keys(g.units)) G.setUnit(db, site.id, g.ownerTownId, k, left[k] || 0);
|
||||
if (town) P.reschedule(ctx, town.id, now);
|
||||
}
|
||||
U.sumInto(defenderLost, lost);
|
||||
garrisonReport.push({ ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, sent: g.units, lost, survivors: left, share: res ? res.share : 0, offline: !res });
|
||||
}
|
||||
const attLost = b.attacker.lost;
|
||||
addPoints(db, attackerOp.id, 'attack', R.battlePoints(defenderLost));
|
||||
const defPts = R.battlePoints(attLost);
|
||||
for (const g of garrisonReport) addPoints(db, g.ownerOpId, 'defense', defPts * g.share);
|
||||
|
||||
if (b.attackerWins) E.transferSite(ctx, site, attackerOp, now);
|
||||
const ret = sendHome(ctx, mv, survivors);
|
||||
const data = {
|
||||
outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site: Object.assign({ type: 'backbone' }, where), origin: townBrief(origin),
|
||||
attacker: { operator: opBrief({ id: attackerOp.id, name: attackerOp.name, as_number: attackerOp.as_number }), alliance: E.allianceInfo(db, attackerOp.alliance_id), units: { sent: mv.units, lost: b.attacker.lost, survivors } },
|
||||
power: { attack: b.A, defence: b.D }, taken: b.attackerWins, returnMovementId: ret ? ret.id : null,
|
||||
defender: { staticDefence: staticDef, garrison: garrisonReport.map((g) => ({ ownerTownId: g.ownerTownId, operator: g.ownerOpId ? opBrief(U.getOperator(db, g.ownerOpId)) : null, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) },
|
||||
power: { attack: b.A, defence: b.D, static: staticDef, garrison: b.defenceRaw }, taken: b.attackerWins, returnMovementId: ret ? ret.id : null,
|
||||
};
|
||||
const recipients = [{ userId: uid, role: 'attacker' }];
|
||||
if (oldHolder) for (const m of db.all('SELECT o.user_id AS uid FROM alliance_members am JOIN operators o ON o.id = am.operator_id WHERE am.alliance_id = ?', oldHolder)) recipients.push({ userId: m.uid, role: 'defender' });
|
||||
createReport(ctx, { worldId: mv.worldId, type: 'landing', now, summary: { outcome: data.outcome, site: data.site, attacker: data.attacker.operator, taken: b.attackerWins }, data, recipients });
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = arriveLanding;
|
||||
module.exports.reinforce = reinforce;
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ const R = require('../../public/js/rules.js');
|
|||
const D = require('../../public/js/data.js');
|
||||
const { loadTown, settle } = require('../state');
|
||||
const U = require('./units');
|
||||
const garrison = () => require('./garrison'); // lazy: garrison.js needs this module
|
||||
|
||||
const EPS = D.MILITARY.batteryEpsilon;
|
||||
|
||||
|
|
@ -23,10 +24,12 @@ function online(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 }.
|
||||
// Every unit drawing power in the POP: home + reinforcements hosted here + its own units standing in backbone landing sites (they draw
|
||||
// their owner's power, E6), 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);
|
||||
U.sumInto(out, garrison().ofTown(db, townId));
|
||||
return out;
|
||||
}
|
||||
|
||||
|
|
@ -52,7 +55,7 @@ function reschedule(ctx, townId, 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.
|
||||
// Decommission the most expensive units (home first, then reinforcements, then its own garrison units) until the draw fits. The town is settled.
|
||||
function decommission(ctx, town, now) {
|
||||
const { db } = ctx;
|
||||
const units = drawingUnits(db, town.id);
|
||||
|
|
@ -77,6 +80,14 @@ function decommission(ctx, town, now) {
|
|||
note(ot ? U.userOfOperator(db, ot.oid) : null, unit, n);
|
||||
}
|
||||
}
|
||||
if (left > 0) { // its own units standing in landing sites
|
||||
const G = garrison();
|
||||
for (const r of db.all('SELECT site_id, count FROM site_stationed WHERE owner_town_id = ? AND unit = ? ORDER BY site_id', town.id, unit)) {
|
||||
if (left <= 0) break;
|
||||
const n = Math.min(r.count, left);
|
||||
G.setUnit(db, r.site_id, town.id, unit, r.count - n); left -= n; note(ownerUser, 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 });
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadWorld } = require('../state');
|
||||
const { loadWorld, hasTable } = require('../state');
|
||||
const U = require('./units');
|
||||
const P = require('./power');
|
||||
|
||||
|
|
@ -78,6 +78,16 @@ function movementLists(db, operatorId, townId) {
|
|||
return out;
|
||||
}
|
||||
|
||||
// [{ siteId, x, y, units }] of one owner POP's units standing in landing sites (the `site_stationed` rows), ordered by site.
|
||||
function garrisonGroups(db, townId) {
|
||||
const by = new Map();
|
||||
for (const r of db.all('SELECT s.site_id AS sid, l.x AS x, l.y AS y, s.unit AS unit, s.count AS count FROM site_stationed s JOIN landing_sites l ON l.id = s.site_id WHERE s.owner_town_id = ? ORDER BY s.site_id, s.unit', townId)) {
|
||||
if (!by.has(r.sid)) by.set(r.sid, { siteId: r.sid, x: r.x, y: r.y, units: {} });
|
||||
by.get(r.sid).units[r.unit] = r.count;
|
||||
}
|
||||
return Array.from(by.values());
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
|
@ -85,6 +95,8 @@ function townMilitary(db, t, now, world) {
|
|||
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 }));
|
||||
// Units of this POP standing in backbone landing sites its alliance holds: they draw THIS POP's power (state.unitDraw), so they belong here.
|
||||
const garrisoned = hasTable(db, 'site_stationed') ? garrisonGroups(db, t.id) : [];
|
||||
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);
|
||||
|
|
@ -99,10 +111,10 @@ function townMilitary(db, t, now, world) {
|
|||
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 },
|
||||
units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away, garrisoned },
|
||||
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 },
|
||||
transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: R.transportCapacity(world.speed) },
|
||||
movements: movementLists(db, t.ownerId, t.id),
|
||||
protectionUntil: op.protection_until,
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue