36 lines
1.2 KiB
JavaScript
36 lines
1.2 KiB
JavaScript
import { GOODS, NEWS_DAYS_PER_LANE, SNAPSHOT_KEEP } from './constants.js';
|
|
import { advancePlanet, priceOf } from './economy.js';
|
|
|
|
// Daily price snapshots per planet. Knowledge from `hops` lanes away
|
|
// is the snapshot from hops * NEWS_DAYS_PER_LANE days ago.
|
|
export class NewsLedger {
|
|
constructor() {
|
|
this.history = new Map(); // planetId -> [{time, prices}]
|
|
}
|
|
|
|
record(galaxy, t) {
|
|
for (const planet of galaxy.planets) {
|
|
advancePlanet(planet, t);
|
|
const prices = Object.fromEntries(GOODS.map((g) => [g, priceOf(g, planet.stock[g])]));
|
|
let arr = this.history.get(planet.id);
|
|
if (!arr) this.history.set(planet.id, (arr = []));
|
|
arr.push({ time: t, prices });
|
|
if (arr.length > SNAPSHOT_KEEP) arr.shift();
|
|
}
|
|
}
|
|
|
|
// Latest snapshot of planetId that has had time to travel `hops` lanes by time t.
|
|
// Clamped to t=0: the initial state is universally known.
|
|
knownPrices(planetId, hops, t) {
|
|
const arr = this.history.get(planetId);
|
|
if (!arr || arr.length === 0) return null;
|
|
const asOf = Math.max(0, t - hops * NEWS_DAYS_PER_LANE);
|
|
let best = null;
|
|
for (const snap of arr) {
|
|
if (snap.time <= asOf) best = snap;
|
|
else break;
|
|
}
|
|
return best ?? arr[0];
|
|
}
|
|
}
|