Upstream/public/js/rules.js
jvanvik b56b13880e Stage 0-2 server spine: db, scheduler, REST, auth, economy, map
Built: SQLite (node:sqlite) via server/db.js with checksummed migrations, injectable clock, persistent event
scheduler with catch-up, tiny REST router (error envelope, idempotency keys, rate limits, bearer tokens with scrypt
passwords), lazy-resource economy in public/js/rules.js + data.js, build/cancel/rename commands, seeded map +
spawn ring, generated docs/openapi.json. NETWALL net.js/static.js reused.
Tested: manual smoke run only (signup, town view, build, map). No unit tests or e2e yet.
NOT done: military, expansion, social, client, push, deploy docs, bots/admin.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 18:07:42 +02:00

300 lines
14 KiB
JavaScript

'use strict';
/*
* ALL game rules for UPSTREAM: pure, deterministic, no DOM, no I/O, no Date.now(). `now` and randomness are arguments.
* Loads as a browser script (window.UpstreamRules, needs data.js first) and as a Node module.
* The client uses this for previews; the server recomputes everything and never trusts a client-sent amount.
*
* Time model: every growing quantity is stored as (amount, updatedAt) and its rate follows from the buildings. The
* server settles a town (stores the current value at the new time) before it changes anything that changes a rate.
* Between settles the rate is constant, so `resourcesAt` is exact.
*
* Town shape these functions work on (built by server/state.js, or by the client from an API response):
* { speed, updatedAt, res: { fiber, hardware, capital, battery }, footprint,
* buildings: { [key]: { type, level } }, unitDraw, bonus: { fiber, hardware, capital } }
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory(require('./data.js'));
else root.UpstreamRules = factory(root.UpstreamData);
}(typeof self !== 'undefined' ? self : this, function (D) {
const F = D.FORMULAS;
const HOUR = D.HOUR_MS;
const DAY = 24 * HOUR;
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
// ------------------------------------------------------------------ seeded randomness
// mulberry32: tiny, fast, good enough for map generation and combat variance.
function rng(seed) {
let a = seed >>> 0;
return function () {
a = (a + 0x6D2B79F5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// Stable 32-bit hash of a few integers (tile generation: the same (seed, x, y) always gives the same tile).
function hash(a, b, c) {
let h = (a | 0) ^ 0x9E3779B9;
h = Math.imul(h ^ (b | 0), 0x85EBCA6B);
h = Math.imul(h ^ (h >>> 13) ^ (c | 0), 0xC2B2AE35);
h ^= h >>> 16;
h = Math.imul(h, 0x27D4EB2F);
h ^= h >>> 15;
return h >>> 0;
}
// ------------------------------------------------------------------ geometry
function distance(ax, ay, bx, by) { return Math.hypot(ax - bx, ay - by); }
// ------------------------------------------------------------------ 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) {
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;
if (h < D.TILE.ruralShare) {
const kinds = D.TILE.ruralTypes;
return { type: 'rural', bonus: kinds[hash(seed ^ 0x5bd1e995, x, y) % kinds.length] };
}
if (h < D.TILE.ruralShare + D.TILE.incumbentShare) return { type: 'incumbent' };
return { type: 'land' };
}
// 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 = [];
const r = F.ruralReach;
for (let dy = -r; dy <= r; dy++) {
for (let dx = -r; dx <= r; dx++) {
if ((dx || dy) && Math.hypot(dx, dy) <= r) {
const t = tileAt(seed, radius, x + dx, y + dy);
if (t.type === 'rural') out.push({ x: x + dx, y: y + dy, bonus: t.bonus });
}
}
}
out.sort((a, b) => Math.hypot(a.x - x, a.y - y) - Math.hypot(b.x - x, b.y - y) || a.x - b.x || a.y - b.y);
return out.slice(0, F.ruralMax);
}
// Production bonus per resource for a POP at (x, y): { fiber, hardware, capital } as 0.25 steps.
function ruralBonus(seed, radius, x, y) {
const b = { fiber: 0, hardware: 0, capital: 0 };
for (const t of ruralNear(seed, radius, x, y)) b[t.bonus] += F.ruralBonus;
return b;
}
// Where does the n-th new operator's capital go? Expanding ring around the centre so early joiners are central.
// `occupied(x, y)` tells whether a tile is taken; `n` is the number of towns already in the world.
// Returns {x, y} or null when the map is full. Deterministic for (seed, n, occupancy).
function pickSpawn(seed, radius, n, towns) {
const rand = rng(hash(seed, n, 0x51a3));
const spacing = D.TILE.spawnMinSpacing;
const near = (x, y) => towns.some((t) => Math.max(Math.abs(t.x - x), Math.abs(t.y - y)) < spacing);
let ring = D.TILE.spawnRingStart + Math.floor(Math.sqrt(n)) * D.TILE.spawnRingStep;
for (; ring <= radius * 1.5 + D.TILE.spawnRingStep; ring += D.TILE.spawnRingStep) {
const lo = Math.max(2, ring - D.TILE.spawnRingStep), hi = Math.min(radius, ring);
for (let attempt = 0; attempt < 60; attempt++) {
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 (near(x, y)) continue;
return { x, y };
}
}
return null;
}
// ------------------------------------------------------------------ buildings
const growth = (base, g, level) => base * Math.pow(g, level - 1);
function buildingDef(type) { return hasOwn(D.BUILDINGS, type) ? D.BUILDINGS[type] : null; }
// Keys: infra buildings use their type; fields f1..f18.
const isFieldKey = (key) => /^f([1-9]|1[0-8])$/.test(key);
// The fields a fresh POP gets: 4 of each type plus the two wild ones. Returns { f1: 'cable_yard', ... }.
function fieldLayout(wild) {
const types = [];
for (const t of D.FIELD_TYPES) for (let i = 0; i < D.FIELDS_PER_TYPE; i++) types.push(t);
for (let i = 0; i < D.WILD_SLOTS; i++) types.push((wild || D.START.wild)[i] || D.START.wild[i]);
const out = {};
types.forEach((t, i) => { out['f' + (i + 1)] = t; });
return out;
}
// Cost to build `type` UP TO `level` (so level 1 is the base cost).
function buildingCost(type, level) {
const def = buildingDef(type);
const out = {};
for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * Math.pow(F.costGrowth, level - 1));
return out;
}
function coreLevel(town) { const c = town.buildings.core_router; return c ? c.level : 0; }
// Build time in ms to reach `level`. Core router shortens it; world speed divides it.
function buildTimeMs(type, level, core, speed) {
const def = buildingDef(type);
const secs = def.time * Math.pow(F.timeGrowth, level - 1) / (1 + F.coreSpeedPerLevel * core) / (speed || 1);
return Math.max(F.minBuildMs, Math.round(secs * 1000));
}
function queueSlots(town) { return coreLevel(town) >= F.secondQueueCoreLevel ? 2 : 1; }
function storageCap(town) {
const r = town.buildings.rack_hall;
if (!r || r.level < 1) return F.storageBase / 4; // no rack hall: a small floor so the POP is not stuck
return Math.round(F.storageBase * Math.pow(F.storageGrowth, r.level - 1));
}
function batteryCap(town) {
const b = town.buildings.battery_bank;
return b && b.level > 0 ? Math.round(F.batteryBase * Math.pow(F.batteryGrowth, b.level - 1)) : 0;
}
// Per-hour output of one field at `level` (before world speed and bonuses). Level 0 produces nothing.
function fieldOutputPerHour(level) {
return level > 0 ? growth(F.productionBase, F.productionGrowth, level) : 0;
}
// Rates per hour for a town: production per resource, power out/draw/net. World speed scales production; power is
// a rate of points, so it is not scaled (the battery drains faster in real time on fast worlds instead).
function ratesPerHour(town) {
const speed = town.speed || 1;
const bonus = town.bonus || {};
const prod = { fiber: 0, hardware: 0, capital: 0 };
let powerOut = 0, draw = 0;
for (const key of Object.keys(town.buildings)) {
const b = town.buildings[key];
const def = buildingDef(b.type);
if (!def) continue;
if (def.kind === 'field') {
const out = fieldOutputPerHour(b.level);
const res = D.FIELD_PRODUCES[b.type];
if (res === 'power') powerOut += out;
else prod[res] += out * speed * (1 + (bonus[res] || 0));
} else {
draw += def.draw * b.level;
}
}
draw += town.unitDraw || 0;
return { fiber: prod.fiber, hardware: prod.hardware, capital: prod.capital, powerOut, powerDraw: draw, powerNet: powerOut - draw };
}
// Current values at `now`, exact while the rates have not changed since town.updatedAt. Caps apply.
function resourcesAt(town, now) {
const dtH = Math.max(0, now - town.updatedAt) / HOUR;
const rates = ratesPerHour(town);
const cap = storageCap(town);
const bcap = batteryCap(town);
const speed = town.speed || 1;
const out = {};
for (const r of D.RESOURCES) {
// An amount already above the cap (the rack hall was lowered) is kept, it just stops growing.
out[r] = Math.max(0, Math.min(Math.max(cap, town.res[r]), town.res[r] + rates[r] * dtH));
}
out.battery = Math.max(0, Math.min(bcap, town.res.battery + rates.powerNet * speed * dtH));
return { amounts: out, caps: { fiber: cap, hardware: cap, capital: cap, battery: bcap }, rates };
}
// When will the battery hit zero (ms epoch)? null if it never does at the current rates. Units go offline then.
function batteryEmptyAt(town, now) {
const { amounts, rates } = resourcesAt(town, now);
if (rates.powerNet >= 0) return null;
if (amounts.battery <= 0) return now;
return now + Math.ceil(amounts.battery / (-rates.powerNet * (town.speed || 1)) * HOUR);
}
// Are units online right now? Offline when the battery is empty and net power is negative.
function unitsOnline(town, now) {
const { amounts, rates } = resourcesAt(town, now);
return !(amounts.battery <= 0 && rates.powerNet < 0);
}
// Footprint points per day: every building of level L contributes sum over steps l=1..L of (1 + l/5).
function footprintPerDay(town) {
let total = 0;
for (const key of Object.keys(town.buildings)) {
const L = town.buildings[key].level;
total += L * F.footprintBase + (L * (L + 1) / 2) / F.footprintDivisor;
}
return total * (town.speed || 1);
}
function footprintAt(town, now) {
return town.footprint + footprintPerDay(town) * Math.max(0, now - town.updatedAt) / DAY;
}
// Footprint an operator needs to found or take over their n-th extra POP (n = 1 for the second POP).
function footprintNeeded(extraTown) { return Math.round(F.footprintNeedBase * Math.pow(extraTown, F.footprintNeedExp)); }
function loyaltyAt(loyalty, updatedAt, now, speed) {
return Math.min(F.loyaltyMax, loyalty + F.loyaltyRegenPerHour * (speed || 1) * Math.max(0, now - updatedAt) / HOUR);
}
// ------------------------------------------------------------------ build planning
// The one function both client (preview) and server (command) use to decide whether `key` can be built or
// upgraded now. `pending` = the build events in flight: [{ key }]. `now` is for the resources at that moment.
// Returns { ok, code, key, type, fromLevel, toLevel, cost, durationMs, missing }.
// Codes are the stable API error codes: unknown_building, max_level, requirements_not_met, already_queued,
// queue_full, not_enough_resources, not_buildable.
function buildPlan(town, key, now, pending, typeHint) {
pending = pending || [];
const cur = hasOwn(town.buildings, key) ? town.buildings[key] : null;
let type = cur ? cur.type : null;
if (!type && !isFieldKey(key) && buildingDef(key)) type = key; // an infra building not built yet
if (!type && typeHint && buildingDef(typeHint) && !isFieldKey(key)) type = typeHint;
const base = { ok: false, key, type, fromLevel: cur ? cur.level : 0 };
const def = type && buildingDef(type);
if (!def) return Object.assign(base, { code: 'unknown_building' });
if (def.special) return Object.assign(base, { code: 'not_buildable' });
if (isFieldKey(key) && !cur) return Object.assign(base, { code: 'unknown_building' }); // fields exist from the start
if (!isFieldKey(key) && key !== type) return Object.assign(base, { code: 'unknown_building' });
const toLevel = base.fromLevel + 1;
base.toLevel = toLevel;
if (toLevel > def.maxLevel) return Object.assign(base, { code: 'max_level' });
const missing = [];
for (const rq of def.requires) {
const have = town.buildings[rq.type] ? town.buildings[rq.type].level : 0;
if (have < rq.level) missing.push({ type: rq.type, level: rq.level, have });
}
base.missing = missing;
base.cost = buildingCost(type, toLevel);
base.durationMs = buildTimeMs(type, toLevel, coreLevel(town), town.speed);
if (missing.length) return Object.assign(base, { code: 'requirements_not_met' });
if (pending.some((p) => p.key === key)) return Object.assign(base, { code: 'already_queued' });
if (pending.length >= queueSlots(town)) return Object.assign(base, { code: 'queue_full' });
const have = resourcesAt(town, now).amounts;
for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' });
base.ok = true;
return base;
}
// The state a brand-new capital POP starts in. `wild` = the two wild field types.
function initialBuildings(wild) {
const layout = fieldLayout(wild);
const out = {};
for (const key of Object.keys(layout)) out[key] = { type: layout[key], level: D.START.fieldLevel };
for (const type of Object.keys(D.START.infra)) out[type] = { type, level: D.START.infra[type] };
return out;
}
// ------------------------------------------------------------------ movement
// Latency in ms for a distance in tiles at `speed` tiles/hour (unit speed), world speed `worldSpeed`; min 10 min.
function latencyMs(dist, unitSpeed, worldSpeed) {
const hours = dist / (unitSpeed * (worldSpeed || 1));
return Math.max(10 * 60 * 1000, Math.round(hours * HOUR));
}
return {
rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap,
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs,
};
}));