feat(engine): migrate monthly nation statistics

This commit is contained in:
2026-07-25 21:57:10 +00:00
parent 6adb5aa52b
commit 3aa0163755
7 changed files with 765 additions and 27 deletions
+4 -1
View File
@@ -516,7 +516,10 @@ const buildNationUpdate = (
rice: nation.rice,
level: nation.level,
typeCode: nation.typeCode,
meta: asJson(nation.meta),
meta: asJson({
...nation.meta,
power: nation.power,
}),
});
const buildTroopUpdate = (
+16 -9
View File
@@ -91,6 +91,7 @@ export interface InMemoryTurnWorldOptions {
schedule: TurnSchedule;
generalTurnHandler?: GeneralTurnHandler;
calendarHandler?: TurnCalendarHandler;
autoAdvanceDiplomacyMonth?: boolean;
}
export interface TurnWorldChanges {
@@ -257,6 +258,7 @@ export class InMemoryTurnWorld {
private schedule: TurnSchedule;
private readonly generalTurnHandler: GeneralTurnHandler;
private readonly calendarHandler?: TurnCalendarHandler;
private readonly autoAdvanceDiplomacyMonth: boolean;
private readonly generals = new Map<number, TurnGeneral>();
private readonly cities = new Map<number, City>();
private readonly nations = new Map<number, Nation>();
@@ -303,6 +305,7 @@ export class InMemoryTurnWorld {
execute: () => ({}),
} satisfies GeneralTurnHandler);
this.calendarHandler = options.calendarHandler;
this.autoAdvanceDiplomacyMonth = options.autoAdvanceDiplomacyMonth ?? true;
const worldKillturn = resolveWorldKillturn(this.state.meta);
for (const general of snapshot.generals) {
@@ -894,7 +897,9 @@ export class InMemoryTurnWorld {
meta,
};
this.advanceDiplomacyMonth();
if (this.autoAdvanceDiplomacyMonth) {
this.advanceDiplomacyMonth();
}
await this.calendarHandler?.onMonthChanged?.(context);
if (nextYear !== previousYear) {
await this.calendarHandler?.onYearChanged?.(context);
@@ -1122,20 +1127,22 @@ export class InMemoryTurnWorld {
}
}
private advanceDiplomacyMonth(): void {
advanceDiplomacyMonth(generalCounts?: Map<number, number>): void {
if (this.diplomacy.size === 0) {
return;
}
const generalCounts = new Map<number, number>();
for (const general of this.generals.values()) {
const nationId = general.nationId;
if (nationId <= 0) {
continue;
const resolvedGeneralCounts = generalCounts ?? new Map<number, number>();
if (!generalCounts) {
for (const general of this.generals.values()) {
const nationId = general.nationId;
if (nationId <= 0) {
continue;
}
resolvedGeneralCounts.set(nationId, (resolvedGeneralCounts.get(nationId) ?? 0) + 1);
}
generalCounts.set(nationId, (generalCounts.get(nationId) ?? 0) + 1);
}
const updated = processDiplomacyMonth(this.listDiplomacy(), generalCounts);
const updated = processDiplomacyMonth(this.listDiplomacy(), resolvedGeneralCounts);
for (const entry of updated) {
const key = buildDiplomacyKey(entry.fromNationId, entry.toNationId);
const prev = this.diplomacy.get(key);
@@ -0,0 +1,222 @@
import { asRecord, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
import { simpleSerialize } from '@sammo-ts/logic/war/utils.js';
import type { InMemoryTurnWorld, TurnCalendarHandler } from './inMemoryWorld.js';
const MAX_AVAILABLE_WAR_SETTING_COUNT = 10;
const MONTHLY_AVAILABLE_WAR_SETTING_INCREMENT = 2;
const readNumber = (value: unknown, fallback = 0): number => {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value === 'string') {
const parsed = Number(value);
if (Number.isFinite(parsed)) {
return parsed;
}
}
return fallback;
};
const resolveHiddenSeed = (world: InMemoryTurnWorld): string | number => {
const state = world.getState();
const value = state.meta.hiddenSeed ?? state.meta.seed ?? state.id;
return typeof value === 'string' || typeof value === 'number' ? value : String(value);
};
const calculateNationPower = (
world: InMemoryTurnWorld,
nationId: number
): {
power: number;
totalCrew: number;
} => {
const nation = world.getNationById(nationId);
if (!nation) {
return { power: 0, totalCrew: 0 };
}
const generals = world.listGenerals().filter((general) => general.nationId === nationId);
const suppliedCities = world.listCities().filter((city) => city.nationId === nationId && city.supplyState === 1);
const generalResources = generals.reduce((sum, general) => sum + general.gold + general.rice, 0);
const resourcePower = Math.round((nation.gold + nation.rice + generalResources) / 100);
const techPower = readNumber(asRecord(nation.meta).tech);
let cityPower = 0;
if (nation.level !== 0 && suppliedCities.length > 0) {
const population = suppliedCities.reduce((sum, city) => sum + city.population, 0);
const current = suppliedCities.reduce(
(sum, city) =>
sum + city.population + city.agriculture + city.commerce + city.security + city.wall + city.defence,
0
);
const maximum = suppliedCities.reduce(
(sum, city) =>
sum +
city.populationMax +
city.agricultureMax +
city.commerceMax +
city.securityMax +
city.wallMax +
city.defenceMax,
0
);
cityPower = maximum > 0 ? Math.round((population * current) / maximum / 100) : 0;
}
let generalPower = 0;
let dexterityPower = 0;
let experiencePower = 0;
let totalCrew = 0;
for (const general of generals) {
const meta = asRecord(general.meta);
const killCrew = readNumber(meta.rank_killcrew_person);
const deathCrew = readNumber(meta.rank_deathcrew_person);
const ratio = (killCrew + 1000) / (deathCrew + 1000);
const npcMultiplier = general.npcState < 2 ? 1.2 : 1;
const leadership = general.stats.leadership;
const leaderCore = leadership >= 40 ? leadership : 0;
generalPower +=
ratio * npcMultiplier * leaderCore * 2 +
(Math.sqrt(general.stats.intelligence * general.stats.strength) * 2 + leadership / 2) / 2;
dexterityPower +=
readNumber(meta.dex1) +
readNumber(meta.dex2) +
readNumber(meta.dex3) +
readNumber(meta.dex4) +
readNumber(meta.dex5);
experiencePower += general.experience + general.dedication;
totalCrew += general.crew;
}
const power = Math.round(
(resourcePower +
techPower +
cityPower +
generalPower +
Math.round(dexterityPower / 1000) +
Math.round(experiencePower / 100)) /
10
);
return { power, totalCrew };
};
const updateNationPower = (world: InMemoryTurnWorld, rng: RandUtil): void => {
const citiesByNation = new Map<number, string[]>();
for (const city of world.listCities().sort((left, right) => left.id - right.id)) {
const names = citiesByNation.get(city.nationId) ?? [];
names.push(city.name);
citiesByNation.set(city.nationId, names);
}
for (const nation of world.listNations().sort((left, right) => left.id - right.id)) {
const calculated = calculateNationPower(world, nation.id);
const power = Math.round(calculated.power * rng.nextRange(0.95, 1.05));
const meta = asRecord(nation.meta);
const previousMax = asRecord(meta.max_power);
const previousCities = Array.isArray(previousMax.maxCities)
? previousMax.maxCities.filter((name): name is string => typeof name === 'string')
: [];
const currentCities = citiesByNation.get(nation.id) ?? [];
const maxPower = {
...previousMax,
maxPower: Math.max(readNumber(previousMax.maxPower), power),
maxCrew: Math.max(readNumber(previousMax.maxCrew), Math.trunc(calculated.totalCrew)),
maxCities: currentCities.length > previousCities.length ? currentCities : previousCities,
};
world.updateNation(nation.id, {
power,
meta: {
...nation.meta,
power,
max_power: maxPower,
},
});
}
};
export const createMonthlyNationStatsHandler = (options: {
getWorld: () => InMemoryTurnWorld | null;
}): TurnCalendarHandler => ({
onMonthChanged: (context) => {
const world = options.getWorld();
if (!world) {
return;
}
const rng = new RandUtil(
new LiteHashDRBG(
simpleSerialize(resolveHiddenSeed(world), 'monthly', context.previousYear, context.previousMonth)
)
);
updateNationPower(world, rng);
},
});
export const createMonthlyDiplomacyHandler = (options: {
getWorld: () => InMemoryTurnWorld | null;
}): TurnCalendarHandler => ({
onMonthChanged: () => {
const world = options.getWorld();
if (!world) {
return;
}
const cachedGeneralCounts = new Map(
world.listNations().map((nation) => [nation.id, Math.max(1, Math.floor(readNumber(nation.meta.gennum, 1)))])
);
world.advanceDiplomacyMonth(cachedGeneralCounts);
},
});
export const createMonthlyWarSettingHandler = (options: {
getWorld: () => InMemoryTurnWorld | null;
}): TurnCalendarHandler => ({
onMonthChanged: () => {
const world = options.getWorld();
if (!world) {
return;
}
for (const nation of world.listNations()) {
const availableCount = Math.min(
MAX_AVAILABLE_WAR_SETTING_COUNT,
Math.max(0, Math.floor(readNumber(nation.meta.available_war_setting_cnt))) +
MONTHLY_AVAILABLE_WAR_SETTING_INCREMENT
);
world.updateNation(nation.id, {
meta: {
...nation.meta,
available_war_setting_cnt: availableCount,
},
});
}
},
});
export const createMonthlyNationCountHandler = (options: {
getWorld: () => InMemoryTurnWorld | null;
}): TurnCalendarHandler => ({
onMonthChanged: () => {
const world = options.getWorld();
if (!world) {
return;
}
const counts = new Map<number, number>();
for (const general of world.listGenerals()) {
if (general.nationId <= 0 || general.npcState === 5) {
continue;
}
counts.set(general.nationId, (counts.get(general.nationId) ?? 0) + 1);
}
for (const nation of world.listNations()) {
const count = counts.get(nation.id);
if (count === undefined) {
continue;
}
world.updateNation(nation.id, {
meta: {
...nation.meta,
gennum: count,
},
});
}
},
});
+24 -1
View File
@@ -27,6 +27,12 @@ import { composeCalendarHandlers } from './calendarHandlers.js';
import { createIncomeHandler } from './incomeHandler.js';
import { createNationTurnMonthlyHandler } from './nationTurnMonthlyHandler.js';
import { createMonthlyBoundaryPreHandler } from './monthlyBoundaryPreHandler.js';
import {
createMonthlyDiplomacyHandler,
createMonthlyNationCountHandler,
createMonthlyNationStatsHandler,
createMonthlyWarSettingHandler,
} from './monthlyNationStatsHandler.js';
import { createFrontStateHandler } from './frontStateHandler.js';
import { createReservedTurnHandler } from './reservedTurnHandler.js';
import { createReservedTurnStore } from './reservedTurnStore.js';
@@ -449,6 +455,18 @@ const createTurnDaemonRuntimeWithLease = async (
startYear: snapshot.scenarioMeta?.startYear ?? state.currentYear,
commandEnv: monthlyCommandEnv,
});
const monthlyNationStatsHandler = createMonthlyNationStatsHandler({
getWorld: () => worldRef,
});
const monthlyDiplomacyHandler = createMonthlyDiplomacyHandler({
getWorld: () => worldRef,
});
const monthlyNationCountHandler = createMonthlyNationCountHandler({
getWorld: () => worldRef,
});
const monthlyWarSettingHandler = createMonthlyWarSettingHandler({
getWorld: () => worldRef,
});
const frontStateHandler = createFrontStateHandler({
getWorld: () => worldRef,
map: snapshot.map ?? null,
@@ -474,9 +492,13 @@ const createTurnDaemonRuntimeWithLease = async (
const calendarHandler = composeCalendarHandlers(
monthlyEventHandler,
yearbookHandler.handler,
options.calendarHandler ?? unification?.handler,
monthlyBoundaryPreHandler,
nationTurnMonthlyHandler,
monthlyNationStatsHandler,
monthlyDiplomacyHandler,
monthlyWarSettingHandler,
monthlyNationCountHandler,
options.calendarHandler ?? unification?.handler,
hasEventAction('ProcessIncome') ? null : incomeHandler,
frontStateHandler,
neutralAuctionRegistrar.handler,
@@ -497,6 +519,7 @@ const createTurnDaemonRuntimeWithLease = async (
commandEnv: monthlyCommandEnv,
})),
calendarHandler: calendarHandler ?? undefined,
autoAdvanceDiplomacyMonth: false,
};
const world = new InMemoryTurnWorld(resolvedState, snapshot, worldOptions);
worldRef = world;
+19 -16
View File
@@ -282,22 +282,25 @@ const mapCityRow = (row: TurnEngineCityRow): City => {
};
};
const mapNationRow = (row: TurnEngineNationRow): Nation => ({
id: row.id,
name: row.name,
color: row.color,
capitalCityId: row.capitalCityId,
chiefGeneralId: row.chiefGeneralId,
gold: row.gold,
rice: row.rice,
power: 0,
level: row.level,
typeCode: row.typeCode,
meta: {
...asTriggerRecord(row.meta),
tech: row.tech,
},
});
const mapNationRow = (row: TurnEngineNationRow): Nation => {
const meta = asTriggerRecord(row.meta);
return {
id: row.id,
name: row.name,
color: row.color,
capitalCityId: row.capitalCityId,
chiefGeneralId: row.chiefGeneralId,
gold: row.gold,
rice: row.rice,
power: readMetaNumber(meta, 'power') ?? 0,
level: row.level,
typeCode: row.typeCode,
meta: {
...meta,
tech: row.tech,
},
};
};
const mapDiplomacyRow = (row: TurnEngineDiplomacyRow): TurnDiplomacy => {
const { meta, dead } = readDiplomacyMeta(asRecord(row.meta));