60 lines
2.2 KiB
JavaScript
60 lines
2.2 KiB
JavaScript
import { getConfig } from "./configLoader.js";
|
|
import {
|
|
ensureSeedEpoch,
|
|
getGridCells,
|
|
addEconScore,
|
|
setElementBonus,
|
|
} from "./db/gameDb.js";
|
|
import { computeTeamIncome, computeTeamElementBonus } from "./helpers/economy.js";
|
|
import { buildRealtimeSnapshot } from "./realtimeSnapshot.js";
|
|
import { broadcast } from "./ws/hub.js";
|
|
|
|
const TICK_SECONDS = 5;
|
|
let lastTickSeed = null;
|
|
|
|
/**
|
|
* Starts the server-side economy tick loop.
|
|
* Runs every TICK_SECONDS, reads the current grid from the DB, computes
|
|
* income and element bonus for each team, and persists the results.
|
|
* This runs independently of any connected browser.
|
|
*/
|
|
export function startEconTick() {
|
|
setInterval(async () => {
|
|
try {
|
|
const worldSeed = await ensureSeedEpoch();
|
|
if (lastTickSeed && lastTickSeed !== worldSeed) {
|
|
broadcast("seed-changed", { worldSeed });
|
|
}
|
|
lastTickSeed = worldSeed;
|
|
|
|
const rows = await getGridCells(worldSeed);
|
|
const cfg = getConfig();
|
|
|
|
const resourceWorth = cfg.resourceWorth ?? { common: {}, rare: {} };
|
|
const elementWorth = cfg.elementWorth ?? {};
|
|
|
|
// ── Economic score deltas ─────────────────────────────────────────────
|
|
const blueIncome = computeTeamIncome("blue", rows, resourceWorth);
|
|
const redIncome = computeTeamIncome("red", rows, resourceWorth);
|
|
|
|
const blueDelta = blueIncome * TICK_SECONDS;
|
|
const redDelta = redIncome * TICK_SECONDS;
|
|
|
|
if (blueDelta > 0) await addEconScore(worldSeed, "blue", blueDelta);
|
|
if (redDelta > 0) await addEconScore(worldSeed, "red", redDelta);
|
|
|
|
// ── Element bonus (overwrites; reflects current grid state) ──────────
|
|
const blueBonus = computeTeamElementBonus("blue", rows, elementWorth);
|
|
const redBonus = computeTeamElementBonus("red", rows, elementWorth);
|
|
|
|
await setElementBonus(worldSeed, "blue", blueBonus);
|
|
await setElementBonus(worldSeed, "red", redBonus);
|
|
|
|
const snapshot = await buildRealtimeSnapshot(worldSeed);
|
|
broadcast("snapshot", snapshot);
|
|
} catch (e) {
|
|
console.error("[econ tick]", e.message);
|
|
}
|
|
}, TICK_SECONDS * 1_000);
|
|
}
|