Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push (docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels. Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js, rankings DoS, static headers, ...): fixes follow in the next commit. NOT done: bots/balance, e2e suite, real-device checks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
192 lines
12 KiB
JavaScript
192 lines
12 KiB
JavaScript
'use strict';
|
|
/*
|
|
* End game: backbone landing sites, the Backbone node race, the winner, the end of the world.
|
|
*
|
|
* Representation (DECISIONS.md E1): a landing site is NOT a POP. It is a row of `landing_sites` (position from the world seed,
|
|
* holder alliance, node level, stockpile, build in progress). The tile reads 'backbone' (rules.tileAt with the world age) from
|
|
* D.ENDGAME.openDay on; before that it is plain land that nobody may settle or spawn on. A site is defended by a static value
|
|
* only (rules.backboneDefence: incumbent defence x defenceMult, + a bonus per node level), so there are no reinforcements at a
|
|
* site. Holders keep the level when the site is taken; the stockpile and a running build stay with the site as well.
|
|
*
|
|
* Time: world age is in world days (real days x speed). Everything here takes `now` (ms) from the caller.
|
|
*/
|
|
const R = require('../public/js/rules.js');
|
|
const D = require('../public/js/data.js');
|
|
const { GameError } = require('./errors');
|
|
const { loadWorld } = require('./state');
|
|
|
|
const DAY = 24 * D.HOUR_MS;
|
|
const E = D.ENDGAME;
|
|
|
|
const ageDays = (world, now) => R.worldAgeDays(world.start_at, now, world.speed);
|
|
const phase = (world, now) => R.worldPhase(world.status, ageDays(world, now));
|
|
const isOpen = (world, now) => ageDays(world, now) >= E.openDay;
|
|
|
|
// ---------------------------------------------------------------- site rows
|
|
|
|
// Create the site rows (idempotent). Writers call this; reads use `siteStates`, which never writes. The first call that really
|
|
// creates them (whatever touches a site first once the world is old enough) tells every operator, when it was given a `ctx`
|
|
// with notify. There is no timer event for this on purpose: nothing is pending in a quiet world.
|
|
function ensureSites(db, world, now, ctx) {
|
|
if (!isOpen(world, now)) return [];
|
|
let created = 0;
|
|
for (const s of R.backboneSites(world.seed, world.map_radius)) created += Number(db.run('INSERT OR IGNORE INTO landing_sites (world_id, idx, x, y) VALUES (?, ?, ?, ?)', world.id, s.index, s.x, s.y).changes);
|
|
const rows = db.all('SELECT * FROM landing_sites WHERE world_id = ? ORDER BY idx', world.id);
|
|
if (created && ctx && ctx.notify) notifyWorld(ctx, world.id, 'backbone_open', { sites: rows.map((r) => ({ siteId: r.id, index: r.idx, x: r.x, y: r.y })) });
|
|
return rows;
|
|
}
|
|
const siteRow = (db, id) => db.get('SELECT * FROM landing_sites WHERE id = ?', id) || null;
|
|
const siteAt = (db, worldId, idx) => db.get('SELECT * FROM landing_sites WHERE world_id = ? AND idx = ?', worldId, idx) || null;
|
|
|
|
// Every site of the world as { site: {index,x,y}, row: landing_sites row | null } (no row = never touched: still the incumbent's).
|
|
function siteStates(db, world, now) {
|
|
if (!isOpen(world, now)) return [];
|
|
const rows = new Map(db.all('SELECT * FROM landing_sites WHERE world_id = ?', world.id).map((r) => [r.idx, r]));
|
|
return R.backboneSites(world.seed, world.map_radius).map((s) => ({ site: s, row: rows.get(s.index) || null }));
|
|
}
|
|
|
|
function allianceInfo(db, id) {
|
|
if (!id) return null;
|
|
const a = db.get('SELECT id, tag, name FROM alliances WHERE id = ?', id);
|
|
return a ? { allianceId: a.id, tag: a.tag, name: a.name } : null;
|
|
}
|
|
const opBrief = (db, id) => { const o = id ? db.get('SELECT id, name FROM operators WHERE id = ?', id) : null; return o ? { operatorId: o.id, name: o.name } : null; };
|
|
|
|
// Public view of one site. `row` may be null (untouched).
|
|
function siteView(db, world, s, row) {
|
|
const level = row ? row.level : 0;
|
|
const pool = { fiber: row ? row.fiber : 0, hardware: row ? row.hardware : 0, capital: row ? row.capital : 0 };
|
|
const build = row && row.build_to ? { toLevel: row.build_to, startedAt: row.build_started_at, dueAt: row.build_due_at } : null;
|
|
return {
|
|
id: row ? row.id : null, index: s.index, x: s.x, y: s.y,
|
|
holder: row ? allianceInfo(db, row.holder_alliance_id) : null,
|
|
takenBy: row ? opBrief(db, row.holder_operator_id) : null, takenAt: row ? row.taken_at : null,
|
|
level, maxLevel: E.maxLevel, progress: level / E.maxLevel, pool, build,
|
|
next: level < E.maxLevel ? { toLevel: level + 1, cost: R.backboneCost(level + 1), durationMs: R.backboneTimeMs(level + 1, world.speed) } : null,
|
|
};
|
|
}
|
|
|
|
function winnerView(w) {
|
|
return w.winner_alliance_id || w.winner_name ? { allianceId: w.winner_alliance_id, name: w.winner_name, tag: w.winner_tag, siteId: w.winner_site_id, wonAt: w.won_at } : null;
|
|
}
|
|
|
|
// GET /worlds/:id/status
|
|
function statusView(db, world, now) {
|
|
const age = ageDays(world, now);
|
|
return {
|
|
worldId: world.id, name: world.name, speed: world.speed, status: world.status, phase: phase(world, now),
|
|
ageDays: age, openDay: E.openDay, opensAt: world.start_at + Math.round(E.openDay * DAY / world.speed),
|
|
sites: siteStates(db, world, now).map(({ site, row }) => siteView(db, world, site, row)),
|
|
winner: winnerView(world), endsAt: world.status === 'ended' ? world.end_at : (world.won_at ? world.end_at : null), endedAt: world.status === 'ended' ? world.end_at : null,
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------- the ended-world gate
|
|
|
|
// Commands that stay possible after the world ended (reading state, chatting): everything else is refused with `world_ended`.
|
|
const WHEN_ENDED = new Set(['markReportRead', 'messageSend', 'messageRead', 'messageDelete', 'messageBlock', 'messageUnblock']);
|
|
const PROBES = [
|
|
['townId', 'SELECT world_id AS w FROM towns WHERE id = ?'], ['fromTownId', 'SELECT world_id AS w FROM towns WHERE id = ?'], ['hostTownId', 'SELECT world_id AS w FROM towns WHERE id = ?'],
|
|
['allianceId', 'SELECT world_id AS w FROM alliances WHERE id = ?'], ['movementId', 'SELECT world_id AS w FROM movements WHERE id = ?'],
|
|
['inviteId', 'SELECT a.world_id AS w FROM alliance_invites i JOIN alliances a ON a.id = i.alliance_id WHERE i.id = ?'],
|
|
['proposalId', 'SELECT world_id AS w FROM alliance_proposals WHERE id = ?'], ['offerId', 'SELECT world_id AS w FROM trade_offers WHERE id = ?'],
|
|
['siteId', 'SELECT world_id AS w FROM landing_sites WHERE id = ?'], ['reportId', 'SELECT world_id AS w FROM reports WHERE id = ?'],
|
|
];
|
|
// The world a command acts in: an explicit worldId, else the world of whatever it points at, else the caller's default operator's.
|
|
function worldOfCommand(db, args) {
|
|
if (args.worldId) return args.worldId;
|
|
for (const [key, sql] of PROBES) {
|
|
if (args[key]) { const r = db.get(sql, args[key]); if (r) return r.w; }
|
|
}
|
|
if (args.userId) { const r = db.get('SELECT world_id AS w FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', args.userId); if (r) return r.w; }
|
|
return null;
|
|
}
|
|
// Called by commands.run before every command. Throws world_ended when the world of the command has ended.
|
|
function guard(db, name, args) {
|
|
if (WHEN_ENDED.has(name) || !args) return;
|
|
const w = worldOfCommand(db, args);
|
|
if (!w) return;
|
|
const row = db.get('SELECT status FROM worlds WHERE id = ?', w);
|
|
if (row && row.status === 'ended') throw new GameError('world_ended', { worldId: w });
|
|
}
|
|
|
|
// ---------------------------------------------------------------- notifications
|
|
|
|
function notifyAlliance(ctx, allianceId, type, payload) {
|
|
for (const m of ctx.db.all('SELECT o.user_id AS uid, o.world_id AS wid FROM alliance_members am JOIN operators o ON o.id = am.operator_id WHERE am.alliance_id = ?', allianceId)) ctx.notify(m.uid, m.wid, type, payload);
|
|
}
|
|
function notifyWorld(ctx, worldId, type, payload) {
|
|
for (const o of ctx.db.all('SELECT user_id FROM operators WHERE world_id = ?', worldId)) ctx.notify(o.user_id, worldId, type, payload);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- taking a site, winning, the end
|
|
|
|
// Sending checks (sendMovement): landing sites can be scanned and attacked, nothing else. Attacking needs an alliance; you cannot
|
|
// attack a site your own alliance or a pact partner holds.
|
|
function checkLandingTarget(db, world, op, tgt, type, now, ctx) {
|
|
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'landing_scan_or_attack_only' });
|
|
if (type !== 'attack') return;
|
|
if (!op.alliance_id) throw new GameError('invalid_target', { reason: 'no_alliance' });
|
|
const row = ensureSites(db, world, now, ctx).find((r) => r.idx === tgt.tile.site);
|
|
denyIfFriendly(db, op, row);
|
|
}
|
|
function denyIfFriendly(db, op, row) {
|
|
if (!row || !row.holder_alliance_id) return;
|
|
if (row.holder_alliance_id === op.alliance_id) throw new GameError('invalid_target', { reason: 'own_site' });
|
|
const rel = require('./alliances').relationBetween(db, op.alliance_id, row.holder_alliance_id);
|
|
if (rel === 'nap' || rel === 'confed') throw new GameError('invalid_target', { reason: 'pact' });
|
|
}
|
|
|
|
// The site changes hands: the attacking operator's alliance holds it now. Level, stockpile and a running build stay.
|
|
function transferSite(ctx, site, attackerOp, now) {
|
|
const { db } = ctx;
|
|
const old = site.holder_alliance_id;
|
|
db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, taken_at = ? WHERE id = ?', attackerOp.alliance_id, attackerOp.id, now, site.id);
|
|
const body = { siteId: site.id, index: site.idx, x: site.x, y: site.y, level: site.level, by: allianceInfo(db, attackerOp.alliance_id), from: allianceInfo(db, old) };
|
|
if (old) notifyAlliance(ctx, old, 'backbone_lost', body);
|
|
notifyAlliance(ctx, attackerOp.alliance_id, 'backbone_taken', body);
|
|
maybeWin(ctx, siteRow(db, site.id), now); // a finished node taken while nobody held it completes for the new holder
|
|
}
|
|
|
|
// The holder of a node at maxLevel wins, once per world. Called when a level completes and when such a site changes hands.
|
|
function maybeWin(ctx, site, now) {
|
|
const { db } = ctx;
|
|
if (!site || site.level < E.maxLevel || !site.holder_alliance_id) return false;
|
|
const world = loadWorld(db, site.world_id);
|
|
if (!world || world.status === 'ended' || world.winner_alliance_id) return false;
|
|
const a = allianceInfo(db, site.holder_alliance_id);
|
|
const endsAt = now + Math.round(E.graceDays * DAY / world.speed);
|
|
db.run('UPDATE worlds SET winner_alliance_id = ?, winner_name = ?, winner_tag = ?, winner_site_id = ?, won_at = ?, end_at = ? WHERE id = ?', a.allianceId, a.name, a.tag, site.id, now, endsAt, world.id);
|
|
ctx.enqueue({ worldId: world.id, dueAt: endsAt, type: 'worldEnd', payload: { reason: 'backbone', siteId: site.id } });
|
|
notifyWorld(ctx, world.id, 'backbone_won', { allianceId: a.allianceId, name: a.name, tag: a.tag, siteId: site.id, endsAt });
|
|
return true;
|
|
}
|
|
|
|
// An alliance is gone: its sites are the incumbent's again (the level stays with the site).
|
|
function onAllianceDissolved(ctx, allianceId) {
|
|
ctx.db.run('UPDATE landing_sites SET holder_alliance_id = NULL WHERE holder_alliance_id = ?', allianceId);
|
|
}
|
|
|
|
// A shipment of resources reached a landing site (called from military/arrivals.arriveTransport). Only the holder alliance's
|
|
// members may feed the stockpile: if the site changed hands on the way the cargo rides home. -> true when it was stored
|
|
function deliverShipment(ctx, mv, now) {
|
|
const { db } = ctx;
|
|
const site = siteRow(db, mv.extra.siteId);
|
|
const sender = db.get('SELECT * FROM operators WHERE id = ?', mv.ownerId);
|
|
const uid = sender ? sender.user_id : null;
|
|
if (!site || !site.holder_alliance_id || !sender || sender.alliance_id !== site.holder_alliance_id) {
|
|
if (uid) ctx.notify(uid, mv.worldId, 'backbone_ship_bounced', { movementId: mv.id, siteId: mv.extra.siteId, cargo: mv.cargo });
|
|
return false;
|
|
}
|
|
const c = { fiber: mv.cargo.fiber || 0, hardware: mv.cargo.hardware || 0, capital: mv.cargo.capital || 0 };
|
|
db.run('UPDATE landing_sites SET fiber = fiber + ?, hardware = hardware + ?, capital = capital + ? WHERE id = ?', c.fiber, c.hardware, c.capital, site.id);
|
|
db.run(`INSERT INTO landing_contributions (site_id, operator_id, fiber, hardware, capital) VALUES (?, ?, ?, ?, ?)
|
|
ON CONFLICT (site_id, operator_id) DO UPDATE SET fiber = fiber + excluded.fiber, hardware = hardware + excluded.hardware, capital = capital + excluded.capital`, site.id, sender.id, c.fiber, c.hardware, c.capital);
|
|
if (uid) ctx.notify(uid, mv.worldId, 'backbone_delivered', { movementId: mv.id, siteId: site.id, cargo: c });
|
|
return true;
|
|
}
|
|
|
|
module.exports = {
|
|
DAY, ageDays, phase, isOpen, ensureSites, siteRow, siteAt, siteStates, siteView, allianceInfo, opBrief, winnerView, statusView,
|
|
guard, worldOfCommand, notifyAlliance, notifyWorld, checkLandingTarget, denyIfFriendly, transferSite, maybeWin, onAllianceDissolved, deliverShipment,
|
|
};
|