v0.28.0 (#46): per-region stats — area×population-weighted-median Nation.stats (PR 1 of 2)
CI / build + unit + e2e (pull_request) Successful in 2m34s

This commit is contained in:
2026-10-15 00:17:19 +00:00
parent 327fffb789
commit 22805a3be6
19 changed files with 8743 additions and 29 deletions
+137 -1
View File
@@ -8,10 +8,12 @@ import type {
GameState,
MarkerType,
Nation,
NationStats,
RelationStatus,
RegionStats,
StatKey,
} from './types';
import { MARKER_TYPES } from './types';
import { MARKER_TYPES, STAT_KEYS } from './types';
/** A numeric change to one of a nation's 0–100 stats. */
export type StateChange =
@@ -515,3 +517,137 @@ export function nationForPrompt(n: Nation) {
relations: n.relations,
};
}
// --- Per-region stats (v0.28, #46) ------------------------------------------
//
// A nation's 0–100 `NationStats` are no longer stored as independent per-nation
// values: they are DERIVED as the area×population-weighted median of the stats
// of the regions the nation owns (`GameState.regionStats`, keyed by region key).
// These pure helpers implement that derivation, the fresh-game / legacy seeding,
// and the one-time migration of a pre-v0.28 row. They have no runtime deps.
/**
* The weighted median of `values` with per-value `weights` (paired by index).
* The pairs are sorted by value ascending and the result is the value at the
* first point where the cumulative weight reaches at least half the total
* weight. An empty input, or a total weight of zero, yields 0. Non-finite or
* non-positive weights are treated as 0 (excluded from the median).
* Translation-invariant: adding a constant to every value shifts the result by
* that constant — so the median of a set of **identical** values is that value
* (the invariant the equal-value seeding and legacy migration rely on).
* Pure + shared.
*/
export function weightedMedian(values: number[], weights: number[]): number {
if (values.length === 0) return 0;
const pairs = values
.map((v, i) => {
const w =
typeof weights[i] === 'number' && Number.isFinite(weights[i]) && weights[i] > 0
? weights[i]
: 0;
return { v: Number.isFinite(v) ? v : 0, w };
})
.filter((p) => p.w > 0);
if (pairs.length === 0) return 0;
const total = pairs.reduce((s, p) => s + p.w, 0);
if (total <= 0) return 0;
pairs.sort((a, b) => a.v - b.v);
let cum = 0;
for (const p of pairs) {
cum += p.w;
if (cum >= total / 2) return p.v;
}
return pairs[pairs.length - 1]!.v;
}
/**
* Derive a nation's aggregate {@link NationStats} from the stats of the regions
* it owns: each of the four stats is the **area×population-weighted median**
* (see {@link weightedMedian}) over the nation's owned region keys. A region's
* weight is `(area > 0 ? area : 1) × (population > 0 ? population : 1)` — both
* factors fall back to 1 when the region has no geo entry (`geoOf` returns
* `undefined` for it), so every region carries weight ≥ 1 and a missing geo
* degrades gracefully to a uniform (unweighted) median. A region key with no
* `regionStats` entry is skipped. Returns the zero stats when the nation owns
* no region with a stats entry (the caller's 0-region guard keeps the nation's
* directly-maintained `n.stats` in that case). Pure + shared.
*/
export function deriveNationStats(
regionKeys: string[],
regionStats: Record<string, RegionStats>,
geoOf?: (key: string) => { area: number; population: number } | undefined,
): NationStats {
const zero: NationStats = { military: 0, economy: 0, stability: 0, population: 0 };
const byStat: Record<StatKey, number[]> = {
military: [],
economy: [],
stability: [],
population: [],
};
const weights: number[] = [];
for (const key of regionKeys) {
const rs = regionStats[key];
if (!rs) continue; // a key with no per-region stats is skipped
const g = geoOf?.(key);
const a = g && g.area > 0 ? g.area : 1;
const p = g && g.population > 0 ? g.population : 1;
weights.push(a * p);
for (const k of STAT_KEYS) byStat[k].push(rs[k]);
}
if (weights.length === 0) return zero;
const out: NationStats = { military: 0, economy: 0, stability: 0, population: 0 };
for (const k of STAT_KEYS) out[k] = clampStat(weightedMedian(byStat[k], weights));
return out;
}
/**
* Seed a per-region stats table from a set of nations (used both at game
* creation and by the legacy migration): every owned region key gets a **copy**
* of its owner's current `NationStats`, so a fresh nation's regions all start
* identical (the weighted median of identical values is that value, so the
* derived `n.stats` equals the seeded one). A region with two or more owners
* (corrupt) is seeded by the first owner encountered; a key owned by nobody gets
* no entry. Pure + shared.
*/
export function seedRegionStats(nations: Record<string, Nation>): Record<string, RegionStats> {
const out: Record<string, RegionStats> = {};
for (const n of Object.values(nations)) {
for (const key of n.territory) {
if (!(key in out)) out[key] = { ...n.stats }; // first owner wins (sole ownership holds normally)
}
}
return out;
}
/**
* (v0.28, #46) One-time migration of a **legacy** (pre-v0.28) `GameState` row
* into the per-region-stats model, returning a new state (the input is never
* mutated):
* - a row that already has `regionStats` (a v0.28+ save) is returned
* **UNCHANGED** — its `Nation.stats` are already the correct derived medians
* and must not be recomputed on load (that would drift them);
* - a legacy row (`regionStats` absent at runtime) seeds every owned region key
* with a copy of its owner's current stats (so each nation's regions start
* identical), then recomputes each nation's stats as the weighted median of
* its regions (a 0-region nation keeps its stats). Without `geoOf` the
* weighting is uniform, which is weight-invariant for the identical-value
* case, so the recomputed stats equal the originals — the migration is a
* no-op on the visible numbers and only materializes the (previously
* implicit) per-region values. Never throws.
*/
export function migrateRegionStats(
state: GameState,
geoOf?: (key: string) => { area: number; population: number } | undefined,
): GameState {
// A v0.28+ row already carries per-region stats: leave it exactly as saved.
if (state.regionStats !== undefined) return state;
// Legacy row: materialize per-region stats from each nation's (uniform) stats.
const next: GameState = { ...state, regionStats: seedRegionStats(state.nations) };
for (const n of Object.values(next.nations)) {
if (n.territory.length === 0) continue; // 0-region guard: keep its stats
if (n.territory.some((k) => next.regionStats[k])) {
n.stats = deriveNationStats(n.territory, next.regionStats, geoOf);
}
}
return next;
}