Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending
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
This commit is contained in:
parent
249818a7aa
commit
b18645dca1
87 changed files with 10201 additions and 71 deletions
|
|
@ -72,6 +72,8 @@ function arriveReinforce(ctx, mv, ev) {
|
|||
function arriveTransport(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
// A shipment to a backbone landing site (extra.siteId) feeds the site's stockpile; refused ones ride home like any undeliverable cargo.
|
||||
const siteDelivered = !!(mv.extra && mv.extra.siteId) && require('../endgame').deliverShipment(ctx, mv, now);
|
||||
const target = mv.toTownId ? loadTown(db, mv.toTownId) : null;
|
||||
let lost = {};
|
||||
if (target) {
|
||||
|
|
@ -82,7 +84,7 @@ function arriveTransport(ctx, mv, ev) {
|
|||
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
|
||||
const cargoBack = target || siteDelivered ? {} : 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) {
|
||||
|
|
@ -99,12 +101,12 @@ function arriveSettle(ctx, mv, ev) {
|
|||
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 tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
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) });
|
||||
const chk = R.settleCheck({ tileType: tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, x, y), 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);
|
||||
|
|
|
|||
|
|
@ -211,7 +211,8 @@ function resolveScanOnTown(ctx, mv, now, s) {
|
|||
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);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
if (tile.type === 'backbone') return require('./landing')(ctx, mv, now, world, tile); // end game: backbone landing site
|
||||
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);
|
||||
|
|
@ -274,6 +275,7 @@ function transferTown(ctx, town, newOp, oldOp, now) {
|
|||
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);
|
||||
require('../trade').onTownTransferred(ctx, town.id, now); // open Internet exchange offers of the old owner end, the escrow stays in the POP
|
||||
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 });
|
||||
|
|
|
|||
67
server/military/landing.js
Normal file
67
server/military/landing.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
'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.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const U = require('./units');
|
||||
const M = require('./movements');
|
||||
const E = require('../endgame');
|
||||
const { createReport } = require('./reports');
|
||||
const { bounce, townBrief, opBrief } = require('./arrivals');
|
||||
|
||||
const SCAN_STRENGTH = D.ENDGAME.scanStrength; // a landing site counts as this many defending scanners
|
||||
|
||||
function sendHome(ctx, mv, survivors) {
|
||||
if (U.isEmpty(survivors)) return null;
|
||||
const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId);
|
||||
if (!dest) return null;
|
||||
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) {
|
||||
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);
|
||||
const site = rows.find((r) => r.idx === tile.site);
|
||||
const attackerOp = U.getOperator(db, mv.ownerId);
|
||||
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);
|
||||
|
||||
if (mv.type === 'scan') {
|
||||
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
|
||||
const res = R.resolveScan(sa, SCAN_STRENGTH);
|
||||
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;
|
||||
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 },
|
||||
recipients: [{ userId: uid, role: 'attacker' }],
|
||||
});
|
||||
sendHome(ctx, mv, loss.survivors);
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 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);
|
||||
const oldHolder = site.holder_alliance_id;
|
||||
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,
|
||||
};
|
||||
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 });
|
||||
};
|
||||
|
|
@ -46,10 +46,12 @@ function launchReturn(ctx, o) {
|
|||
});
|
||||
}
|
||||
|
||||
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports.
|
||||
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports, plus the
|
||||
// open Internet exchange offers it posted (an open offer holds a link in reserve: accepting it sends the escrow on that link).
|
||||
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;
|
||||
((type = 'transport' AND from_town_id = ?) OR (type = 'return' AND to_town_id = ? AND json_extract(extra, '$.link') = 1))`, townId, townId).n
|
||||
+ db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE town_id = ? AND status = 'open'", townId).n;
|
||||
}
|
||||
|
||||
// Hooks for later stages (trade): called after a transport has been delivered. fn(ctx, movement, { added, lost }).
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ function ownerView(m, names) {
|
|||
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,
|
||||
target: extra.target || null, parentId: m.parent_id, siteId: extra.siteId || null, // siteId: a shipment to a backbone landing site
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -55,8 +55,27 @@ function movementLists(db, operatorId, townId) {
|
|||
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)) };
|
||||
// Confederation members (own alliance included) see what is heading for each other's POPs: origin and ETA only, the type
|
||||
// stays hidden. Movements of operators who are themselves partners of the target are friendly traffic and left out.
|
||||
// Only in the whole-operator list, not in the per-POP lists.
|
||||
let allied = [];
|
||||
if (!townId) {
|
||||
const partners = require('../alliances').confederatedOperators(db, operatorId);
|
||||
if (partners.length) {
|
||||
allied = db.all(`SELECT m.*, t.owner_id AS target_owner FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id IN (${partners.map(() => '?').join(',')})
|
||||
AND m.owner_id != t.owner_id AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return' ORDER BY m.arrive_at, m.id LIMIT ?`, ...partners, operatorId, D.MILITARY.maxLists)
|
||||
.filter((m) => !U.pactBlocks(db, m.owner_id, m.target_owner));
|
||||
}
|
||||
}
|
||||
const names = townNames(db, own.concat(inc, allied).flatMap((m) => [m.from_town_id, m.to_town_id]));
|
||||
const out = { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) };
|
||||
if (!townId) {
|
||||
out.alliedIncoming = allied.map((m) => {
|
||||
const o = db.get('SELECT id, name FROM operators WHERE id = ?', m.target_owner);
|
||||
return Object.assign(incomingView(m, names), { ally: true, toOperator: { id: o.id, name: o.name } });
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The military part of GET /towns/:id (the town object is already loaded and belongs to the caller).
|
||||
|
|
@ -127,7 +146,7 @@ function createMilitaryQueries({ db, clock, scheduler }) {
|
|||
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);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
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);
|
||||
|
|
@ -140,11 +159,18 @@ function createMilitaryQueries({ db, clock, scheduler }) {
|
|||
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 };
|
||||
}
|
||||
if (tile.type === 'backbone') { // end game: who holds the site, its node level and stockpile, whether you could attack it
|
||||
const E = require('../endgame');
|
||||
const st = E.siteStates(db, world, now).find((s) => s.site.index === tile.site);
|
||||
const v = E.siteView(db, world, st.site, st.row);
|
||||
const holds = !!(op.alliance_id && v.holder && v.holder.allianceId === op.alliance_id);
|
||||
out.backbone = { siteId: v.id, index: v.index, holder: v.holder, level: v.level, maxLevel: v.maxLevel, pool: v.pool, build: v.build, mine: holds, canAttack: !!op.alliance_id && !holds };
|
||||
}
|
||||
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 });
|
||||
const sc = R.settleCheck({ tileType: tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, x, y), 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;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue