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
|
|
@ -52,7 +52,19 @@
|
|||
// ------------------------------------------------------------------ the map
|
||||
// Pure function of the world seed: 'land' | 'rural' | 'incumbent' | 'void' (outside the map). A rural tile also
|
||||
// says which resource it boosts. Towns are not part of this; they live in the database.
|
||||
function tileAt(seed, radius, x, y) {
|
||||
// `ageDays` (optional, world days) adds the end game: from D.ENDGAME.openDay on, the landing sites report 'backbone'
|
||||
// (with `site`: its index). Without it (old callers, previews without a clock) the map is the plain terrain.
|
||||
// Terrain never changes: a landing site is always a land tile underneath, see backboneSites.
|
||||
function tileAt(seed, radius, x, y, ageDays) {
|
||||
const t = terrainAt(seed, radius, x, y);
|
||||
if (t.type === 'land' && ageDays !== undefined && ageDays >= D.ENDGAME.openDay) {
|
||||
const s = backboneSiteAt(seed, radius, x, y);
|
||||
if (s) return { type: 'backbone', site: s.index };
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
function terrainAt(seed, radius, x, y) {
|
||||
if (Math.abs(x) > radius || Math.abs(y) > radius) return { type: 'void' };
|
||||
if (Math.abs(x) <= 2 && Math.abs(y) <= 2) return { type: 'land' }; // keep the centre free
|
||||
const h = hash(seed, x, y) / 4294967296;
|
||||
|
|
@ -64,6 +76,54 @@
|
|||
return { type: 'land' };
|
||||
}
|
||||
|
||||
// The backbone landing sites: D.ENDGAME.sites fixed positions, a pure function of (seed, radius). One per sector of the
|
||||
// circle (jittered), on plain land tiles between siteRingMin and siteRingMax of the radius, never in the free centre and
|
||||
// at least siteMinSpacing apart. They exist from the start (spawn and settling refuse them) but only SHOW from openDay.
|
||||
// -> [{ index, x, y }]
|
||||
const siteCache = new Map();
|
||||
function backboneSites(seed, radius) {
|
||||
const key = seed + '|' + radius;
|
||||
if (siteCache.has(key)) return siteCache.get(key);
|
||||
const E = D.ENDGAME;
|
||||
const out = [];
|
||||
for (let k = 0; k < E.sites; k++) {
|
||||
const rand = rng(hash(seed, k, 0xb4cb));
|
||||
const ang = (k + 0.15 + 0.7 * rand()) * 2 * Math.PI / E.sites;
|
||||
const rr = radius * (E.siteRingMin + (E.siteRingMax - E.siteRingMin) * rand());
|
||||
const cx = Math.round(Math.cos(ang) * rr), cy = Math.round(Math.sin(ang) * rr);
|
||||
let found = null;
|
||||
for (let d = 0; d <= radius && !found; d++) { // spiral outwards until a free land tile turns up
|
||||
for (let dy = -d; dy <= d && !found; dy++) {
|
||||
for (let dx = -d; dx <= d && !found; dx++) {
|
||||
if (Math.max(Math.abs(dx), Math.abs(dy)) !== d) continue;
|
||||
const x = cx + dx, y = cy + dy;
|
||||
if (terrainAt(seed, radius, x, y).type !== 'land') continue;
|
||||
if (Math.abs(x) <= 2 && Math.abs(y) <= 2) continue;
|
||||
if (out.some((s) => distance(s.x, s.y, x, y) < E.siteMinSpacing)) continue;
|
||||
found = { index: k, x, y };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (found) out.push(found);
|
||||
}
|
||||
if (siteCache.size > 64) siteCache.clear();
|
||||
siteCache.set(key, out);
|
||||
return out;
|
||||
}
|
||||
function backboneSiteAt(seed, radius, x, y) {
|
||||
for (const s of backboneSites(seed, radius)) if (s.x === x && s.y === y) return s;
|
||||
return null;
|
||||
}
|
||||
const isBackboneSite = (seed, radius, x, y) => !!backboneSiteAt(seed, radius, x, y);
|
||||
|
||||
// World age in world days (real days * speed). Negative ages are 0.
|
||||
function worldAgeDays(startAt, now, speed) { return Math.max(0, (now - startAt) / DAY * (speed || 1)); }
|
||||
// 'running' | 'backbone_open' | 'ended'.
|
||||
function worldPhase(status, ageDays) {
|
||||
if (status === 'ended') return 'ended';
|
||||
return ageDays >= D.ENDGAME.openDay ? 'backbone_open' : 'running';
|
||||
}
|
||||
|
||||
// Rural areas within reach of (x, y): the tiles whose bonus a POP there enjoys. Biggest bonus counts max 3.
|
||||
function ruralNear(seed, radius, x, y) {
|
||||
const out = [];
|
||||
|
|
@ -101,7 +161,7 @@
|
|||
const ang = rand() * Math.PI * 2;
|
||||
const rr = lo + rand() * (hi - lo);
|
||||
const x = Math.round(Math.cos(ang) * rr), y = Math.round(Math.sin(ang) * rr);
|
||||
if (tileAt(seed, radius, x, y).type !== 'land') continue;
|
||||
if (tileAt(seed, radius, x, y).type !== 'land' || isBackboneSite(seed, radius, x, y)) continue;
|
||||
if (near(x, y)) continue;
|
||||
return { x, y };
|
||||
}
|
||||
|
|
@ -577,6 +637,7 @@
|
|||
|
||||
// Founding a POP: info about the target tile and the operator. Codes: invalid_target, out_of_range, footprint_too_low.
|
||||
function settleCheck(o) {
|
||||
if (o.backbone) return { ok: false, code: 'invalid_target', reason: 'backbone_site' }; // landing sites are taken, never settled
|
||||
if (o.tileType !== 'land' || o.occupied) return { ok: false, code: 'invalid_target', reason: o.occupied ? 'occupied' : 'not_empty_land' };
|
||||
if (!(o.nearestOwnDist <= D.EXPANSION.maxDistance)) return { ok: false, code: 'out_of_range', max: D.EXPANSION.maxDistance, have: o.nearestOwnDist };
|
||||
const g = footprintGate(o.ownedCount, o.footprint);
|
||||
|
|
@ -654,8 +715,62 @@
|
|||
return { ok: true, total };
|
||||
}
|
||||
|
||||
// ---- trade (Internet exchange offers: give X of A for Y of B, max distance Z)
|
||||
// How far (tiles) a POP with this Internet exchange level sees and trades. Level 0 = no exchange = 0.
|
||||
const tradeReach = (level) => (level > 0 ? level * D.TRADE.reachPerLevel : 0);
|
||||
// Is the exchange rate within the 1:ratioMax band (give/want in [1/ratioMax, ratioMax])?
|
||||
const tradeRatioOk = (give, want) => give > 0 && want > 0 && give <= want * D.TRADE.ratioMax && want <= give * D.TRADE.ratioMax;
|
||||
// Validate the terms of a new offer. `o` = { giveRes, giveAmount, wantRes, wantAmount, maxDistance }. Codes: validation_failed,
|
||||
// trade_ratio, capacity_exceeded. Does not look at the town (resources, links) - the command does.
|
||||
function tradeTermsCheck(o) {
|
||||
const bad = (path, message) => ({ ok: false, code: 'validation_failed', errors: [{ path, message }] });
|
||||
if (D.RESOURCES.indexOf(o.giveRes) < 0) return bad('giveRes', 'must be one of ' + D.RESOURCES.join(', '));
|
||||
if (D.RESOURCES.indexOf(o.wantRes) < 0) return bad('wantRes', 'must be one of ' + D.RESOURCES.join(', '));
|
||||
if (o.giveRes === o.wantRes) return bad('wantRes', 'must differ from giveRes');
|
||||
if (!Number.isInteger(o.giveAmount) || o.giveAmount < 1) return bad('giveAmount', 'must be a whole number >= 1');
|
||||
if (!Number.isInteger(o.wantAmount) || o.wantAmount < 1) return bad('wantAmount', 'must be a whole number >= 1');
|
||||
if (!Number.isInteger(o.maxDistance) || o.maxDistance < 1 || o.maxDistance > D.TRADE.maxDistance) return bad('maxDistance', 'must be a whole number of tiles 1..' + D.TRADE.maxDistance);
|
||||
const cap = D.TRANSPORT.capacityPerLink;
|
||||
if (o.giveAmount > cap || o.wantAmount > cap) return { ok: false, code: 'capacity_exceeded', capacity: cap };
|
||||
if (!tradeRatioOk(o.giveAmount, o.wantAmount)) return { ok: false, code: 'trade_ratio', max: D.TRADE.ratioMax };
|
||||
return { ok: true };
|
||||
}
|
||||
// May a POP at `dist` tiles with Internet exchange `level` take an offer (max distance `maxDistance`)? Both the offer's own
|
||||
// limit and the taker's reach apply.
|
||||
const tradeInRange = (dist, maxDistance, level) => level >= 1 && dist <= maxDistance && dist <= tradeReach(level);
|
||||
|
||||
// ---- end game: backbone landing sites
|
||||
// Heavy static defence of a landing site: the incumbent's site defence x defenceMult, plus defencePerLevel per node level.
|
||||
function backboneDefence(seed, x, y, ageDays, level) {
|
||||
return Math.round(incumbentDefence(seed, x, y, ageDays) * D.ENDGAME.defenceMult * (1 + D.ENDGAME.defencePerLevel * Math.max(0, level || 0)));
|
||||
}
|
||||
// Cost to build the Backbone node UP TO `level` (1..maxLevel), per resource.
|
||||
function backboneCost(level) {
|
||||
const def = D.BUILDINGS.backbone_node;
|
||||
const out = {};
|
||||
for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * Math.pow(D.ENDGAME.costGrowth, level - 1));
|
||||
return out;
|
||||
}
|
||||
function backboneTimeMs(level, speed) {
|
||||
return Math.max(F.minBuildMs, Math.round(D.BUILDINGS.backbone_node.time * Math.pow(D.ENDGAME.timeGrowth, level - 1) / (speed || 1) * 1000));
|
||||
}
|
||||
// Can the holder alliance start the next level? site = { level, build (null | { to }), pool: { fiber, hardware, capital } }. Codes: max_level, already_queued, not_enough_resources.
|
||||
function backbonePlan(site, speed) {
|
||||
const toLevel = site.level + 1;
|
||||
const base = { ok: false, fromLevel: site.level, toLevel };
|
||||
if (toLevel > D.ENDGAME.maxLevel) return Object.assign(base, { code: 'max_level' });
|
||||
base.cost = backboneCost(toLevel);
|
||||
base.durationMs = backboneTimeMs(toLevel, speed);
|
||||
if (site.build) return Object.assign(base, { code: 'already_queued' });
|
||||
for (const r of D.RESOURCES) if ((site.pool[r] || 0) + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' });
|
||||
base.ok = true;
|
||||
return base;
|
||||
}
|
||||
|
||||
return {
|
||||
unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
|
||||
terrainAt, backboneSites, backboneSiteAt, isBackboneSite, worldAgeDays, worldPhase, tradeReach, tradeRatioOk, tradeTermsCheck, tradeInRange,
|
||||
backboneDefence, backboneCost, backboneTimeMs, backbonePlan,
|
||||
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap,
|
||||
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
|
||||
allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue