feat: refactor NPC simulation tests and add turn test harness utility
This commit is contained in:
@@ -0,0 +1,314 @@
|
|||||||
|
import { vi } from 'vitest';
|
||||||
|
import type { MapDefinition, TurnSchedule } from '@sammo-ts/logic';
|
||||||
|
import type { TurnWorldSnapshot, TurnWorldState } from '../../src/turn/types.js';
|
||||||
|
import type { InMemoryTurnWorld, GeneralTurnHandler } from '../../src/turn/inMemoryWorld.js';
|
||||||
|
import { InMemoryTurnWorld as InMemoryTurnWorldClass } from '../../src/turn/inMemoryWorld.js';
|
||||||
|
import { InMemoryReservedTurnStore } from '../../src/turn/reservedTurnStore.js';
|
||||||
|
import { createReservedTurnHandler } from '../../src/turn/reservedTurnHandler.js';
|
||||||
|
import type { InMemoryTurnProcessorOptions } from '../../src/turn/inMemoryTurnProcessor.js';
|
||||||
|
import { InMemoryTurnProcessor } from '../../src/turn/inMemoryTurnProcessor.js';
|
||||||
|
import { composeCalendarHandlers } from '../../src/turn/calendarHandlers.js';
|
||||||
|
import { createIncomeHandler } from '../../src/turn/incomeHandler.js';
|
||||||
|
import { createNpcTaxHandler } from '../../src/turn/npcTaxHandler.js';
|
||||||
|
import { createFrontStateHandler } from '../../src/turn/frontStateHandler.js';
|
||||||
|
|
||||||
|
export const createMockPrisma = (initialGeneralRows: any[] = []) => {
|
||||||
|
let generalRows = [...initialGeneralRows];
|
||||||
|
return {
|
||||||
|
generalTurn: {
|
||||||
|
findMany: vi.fn(async ({ where } = {}) => {
|
||||||
|
if (where?.generalId) {
|
||||||
|
return generalRows
|
||||||
|
.filter((row) => row.generalId === where.generalId)
|
||||||
|
.sort((a, b) => a.turnIdx - b.turnIdx);
|
||||||
|
}
|
||||||
|
return generalRows;
|
||||||
|
}),
|
||||||
|
deleteMany: vi.fn(async ({ where } = {}) => {
|
||||||
|
if (where?.generalId) {
|
||||||
|
generalRows = generalRows.filter((row) => row.generalId !== where.generalId);
|
||||||
|
}
|
||||||
|
return { count: 0 };
|
||||||
|
}),
|
||||||
|
createMany: vi.fn(async ({ data }) => {
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
generalRows.push(...data);
|
||||||
|
}
|
||||||
|
return { count: data.length };
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
nationTurn: {
|
||||||
|
findMany: vi.fn(async () => []),
|
||||||
|
deleteMany: vi.fn(async () => ({ count: 0 })),
|
||||||
|
createMany: vi.fn(async () => ({ count: 0 })),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const addMinutes = (time: Date, minutes: number): Date => new Date(time.getTime() + minutes * 60_000);
|
||||||
|
|
||||||
|
export type TurnHarnessRunOptions = {
|
||||||
|
minutes?: number;
|
||||||
|
budgetMs?: number;
|
||||||
|
maxGenerals?: number;
|
||||||
|
catchUpCap?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TurnTestHarnessOptions = {
|
||||||
|
snapshot: TurnWorldSnapshot;
|
||||||
|
state: TurnWorldState;
|
||||||
|
schedule: TurnSchedule;
|
||||||
|
map?: MapDefinition;
|
||||||
|
reservedTurnStoreOptions?: {
|
||||||
|
maxGeneralTurns: number;
|
||||||
|
maxNationTurns: number;
|
||||||
|
};
|
||||||
|
turnProcessorOptions?: {
|
||||||
|
tickMinutes: number;
|
||||||
|
afterExecuteGeneral?: InMemoryTurnProcessorOptions['afterExecuteGeneral'];
|
||||||
|
};
|
||||||
|
worldRef?: { current: InMemoryTurnWorld | null };
|
||||||
|
onActionResolved?: Parameters<typeof createReservedTurnHandler>[0]['onActionResolved'];
|
||||||
|
wrapGeneralTurnHandler?: (handler: GeneralTurnHandler) => GeneralTurnHandler;
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultRunOptions = {
|
||||||
|
budgetMs: 10000,
|
||||||
|
maxGenerals: 100000,
|
||||||
|
catchUpCap: 1,
|
||||||
|
} satisfies Required<Omit<TurnHarnessRunOptions, 'minutes'>>;
|
||||||
|
|
||||||
|
export const createTurnTestHarness = async (options: TurnTestHarnessOptions) => {
|
||||||
|
const mockPrisma = createMockPrisma();
|
||||||
|
const reservedTurnStore = new InMemoryReservedTurnStore(mockPrisma as any, {
|
||||||
|
maxGeneralTurns: 10,
|
||||||
|
maxNationTurns: 10,
|
||||||
|
...(options.reservedTurnStoreOptions ?? {}),
|
||||||
|
});
|
||||||
|
await reservedTurnStore.loadAll();
|
||||||
|
|
||||||
|
const worldRef = options.worldRef ?? { current: null as InMemoryTurnWorld | null };
|
||||||
|
|
||||||
|
const handler = await createReservedTurnHandler({
|
||||||
|
reservedTurns: reservedTurnStore,
|
||||||
|
scenarioConfig: options.snapshot.scenarioConfig,
|
||||||
|
scenarioMeta: options.snapshot.scenarioMeta,
|
||||||
|
map: options.map,
|
||||||
|
unitSet: options.snapshot.unitSet,
|
||||||
|
getWorld: () => worldRef.current,
|
||||||
|
onActionResolved: options.onActionResolved,
|
||||||
|
});
|
||||||
|
|
||||||
|
const generalTurnHandler = options.wrapGeneralTurnHandler ? options.wrapGeneralTurnHandler(handler) : handler;
|
||||||
|
|
||||||
|
const incomeHandler = createIncomeHandler({
|
||||||
|
getWorld: () => worldRef.current,
|
||||||
|
scenarioConfig: options.snapshot.scenarioConfig,
|
||||||
|
nationTraits: new Map(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const npcTaxHandler = createNpcTaxHandler({
|
||||||
|
getWorld: () => worldRef.current,
|
||||||
|
});
|
||||||
|
|
||||||
|
const frontStateHandler = createFrontStateHandler({
|
||||||
|
getWorld: () => worldRef.current,
|
||||||
|
map: options.map,
|
||||||
|
});
|
||||||
|
|
||||||
|
const calendarHandler = composeCalendarHandlers(incomeHandler, npcTaxHandler, frontStateHandler);
|
||||||
|
|
||||||
|
const world = new InMemoryTurnWorldClass(options.state, options.snapshot, {
|
||||||
|
schedule: options.schedule,
|
||||||
|
generalTurnHandler,
|
||||||
|
calendarHandler,
|
||||||
|
});
|
||||||
|
worldRef.current = world;
|
||||||
|
|
||||||
|
const processor = new InMemoryTurnProcessor(world, {
|
||||||
|
tickMinutes: options.turnProcessorOptions?.tickMinutes ?? 10,
|
||||||
|
afterExecuteGeneral: options.turnProcessorOptions?.afterExecuteGeneral,
|
||||||
|
});
|
||||||
|
|
||||||
|
const runOneTick = async (runOptions: TurnHarnessRunOptions = {}) => {
|
||||||
|
const minutes = runOptions.minutes ?? options.turnProcessorOptions?.tickMinutes ?? 10;
|
||||||
|
const target = addMinutes(world.getState().lastTurnTime, minutes);
|
||||||
|
await processor.run(target, {
|
||||||
|
budgetMs: runOptions.budgetMs ?? defaultRunOptions.budgetMs,
|
||||||
|
maxGenerals: runOptions.maxGenerals ?? defaultRunOptions.maxGenerals,
|
||||||
|
catchUpCap: runOptions.catchUpCap ?? defaultRunOptions.catchUpCap,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const runUntil = async (
|
||||||
|
shouldStop: (state: TurnWorldState) => boolean,
|
||||||
|
runOptions?: TurnHarnessRunOptions,
|
||||||
|
afterTick?: (state: TurnWorldState, world: InMemoryTurnWorld) => void
|
||||||
|
) => {
|
||||||
|
while (true) {
|
||||||
|
await runOneTick(runOptions);
|
||||||
|
const state = world.getState();
|
||||||
|
afterTick?.(state, world);
|
||||||
|
if (shouldStop(state)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
world,
|
||||||
|
worldRef,
|
||||||
|
reservedTurnStore,
|
||||||
|
handler,
|
||||||
|
processor,
|
||||||
|
runOneTick,
|
||||||
|
runUntil,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DebugWatchTargets = {
|
||||||
|
cityIds?: number[];
|
||||||
|
nationIds?: number[];
|
||||||
|
includeNationSummary?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const toList = (value?: number[] | number): number[] => {
|
||||||
|
if (Array.isArray(value)) return value;
|
||||||
|
if (typeof value === 'number') return [value];
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatCity = (city: ReturnType<InMemoryTurnWorld['getCityById']>) => {
|
||||||
|
if (!city) return null;
|
||||||
|
return {
|
||||||
|
id: city.id,
|
||||||
|
name: city.name,
|
||||||
|
nationId: city.nationId,
|
||||||
|
level: city.level,
|
||||||
|
state: city.state,
|
||||||
|
population: city.population,
|
||||||
|
populationMax: city.populationMax,
|
||||||
|
agriculture: city.agriculture,
|
||||||
|
agricultureMax: city.agricultureMax,
|
||||||
|
commerce: city.commerce,
|
||||||
|
commerceMax: city.commerceMax,
|
||||||
|
security: city.security,
|
||||||
|
securityMax: city.securityMax,
|
||||||
|
defence: city.defence,
|
||||||
|
defenceMax: city.defenceMax,
|
||||||
|
wall: city.wall,
|
||||||
|
wallMax: city.wallMax,
|
||||||
|
supplyState: city.supplyState,
|
||||||
|
frontState: city.frontState,
|
||||||
|
meta: city.meta,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createWorldDebugger = (
|
||||||
|
getWorld: () => InMemoryTurnWorld | null,
|
||||||
|
watchTargets: DebugWatchTargets = {}
|
||||||
|
) => {
|
||||||
|
const dumpWorldSummary = (label = 'WORLD') => {
|
||||||
|
const world = getWorld();
|
||||||
|
if (!world) {
|
||||||
|
console.log(`[DEBUG] ${label} (no world)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const nations = world.listNations();
|
||||||
|
const cities = world.listCities();
|
||||||
|
const generals = world.listGenerals();
|
||||||
|
const neutralCities = cities.filter((city) => city.nationId <= 0).length;
|
||||||
|
const state = world.getState();
|
||||||
|
console.log('[DEBUG] world summary', {
|
||||||
|
label,
|
||||||
|
year: state.currentYear,
|
||||||
|
month: state.currentMonth,
|
||||||
|
nations: nations.length,
|
||||||
|
cities: cities.length,
|
||||||
|
generals: generals.length,
|
||||||
|
neutralCities,
|
||||||
|
});
|
||||||
|
if (watchTargets.includeNationSummary) {
|
||||||
|
const nationSummaries = nations.map((nation) => {
|
||||||
|
const cityCount = cities.filter((city) => city.nationId === nation.id).length;
|
||||||
|
const generalCount = generals.filter((general) => general.nationId === nation.id).length;
|
||||||
|
return {
|
||||||
|
id: nation.id,
|
||||||
|
name: nation.name,
|
||||||
|
level: nation.level,
|
||||||
|
typeCode: nation.typeCode,
|
||||||
|
capitalCityId: nation.capitalCityId,
|
||||||
|
chiefGeneralId: nation.chiefGeneralId,
|
||||||
|
gold: nation.gold,
|
||||||
|
rice: nation.rice,
|
||||||
|
power: nation.power,
|
||||||
|
cityCount,
|
||||||
|
generalCount,
|
||||||
|
meta: nation.meta,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
console.log('[DEBUG] nation summary', nationSummaries);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const dumpCity = (cityId: number, label = 'CITY') => {
|
||||||
|
const world = getWorld();
|
||||||
|
if (!world) {
|
||||||
|
console.log(`[DEBUG] ${label} (no world)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const city = world.getCityById(cityId);
|
||||||
|
console.log('[DEBUG] city detail', { label, cityId, city: formatCity(city) });
|
||||||
|
};
|
||||||
|
|
||||||
|
const dumpNation = (nationId: number, label = 'NATION') => {
|
||||||
|
const world = getWorld();
|
||||||
|
if (!world) {
|
||||||
|
console.log(`[DEBUG] ${label} (no world)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const nation = world.getNationById(nationId);
|
||||||
|
if (!nation) {
|
||||||
|
console.log('[DEBUG] nation detail', { label, nationId, nation: null });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const cities = world.listCities().filter((city) => city.nationId === nationId);
|
||||||
|
const generals = world.listGenerals().filter((general) => general.nationId === nationId);
|
||||||
|
console.log('[DEBUG] nation detail', {
|
||||||
|
label,
|
||||||
|
nationId,
|
||||||
|
nation: {
|
||||||
|
id: nation.id,
|
||||||
|
name: nation.name,
|
||||||
|
level: nation.level,
|
||||||
|
typeCode: nation.typeCode,
|
||||||
|
capitalCityId: nation.capitalCityId,
|
||||||
|
chiefGeneralId: nation.chiefGeneralId,
|
||||||
|
gold: nation.gold,
|
||||||
|
rice: nation.rice,
|
||||||
|
power: nation.power,
|
||||||
|
meta: nation.meta,
|
||||||
|
},
|
||||||
|
cityCount: cities.length,
|
||||||
|
generalCount: generals.length,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const dumpWatched = (label = 'WATCH') => {
|
||||||
|
const { cityIds, nationIds } = watchTargets;
|
||||||
|
dumpWorldSummary(label);
|
||||||
|
for (const id of toList(nationIds)) {
|
||||||
|
dumpNation(id, label);
|
||||||
|
}
|
||||||
|
for (const id of toList(cityIds)) {
|
||||||
|
dumpCity(id, label);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
dumpWorldSummary,
|
||||||
|
dumpCity,
|
||||||
|
dumpNation,
|
||||||
|
dumpWatched,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import type {
|
import type {
|
||||||
ConstraintContext,
|
ConstraintContext,
|
||||||
LogEntryDraft,
|
LogEntryDraft,
|
||||||
@@ -10,57 +10,16 @@ import type {
|
|||||||
import { DEFAULT_TURN_COMMAND_PROFILE, LogCategory, evaluateConstraints } from '@sammo-ts/logic';
|
import { DEFAULT_TURN_COMMAND_PROFILE, LogCategory, evaluateConstraints } from '@sammo-ts/logic';
|
||||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||||
import type { GeneralAiDebugState } from '../src/turn/ai/generalAi.js';
|
import type { GeneralAiDebugState } from '../src/turn/ai/generalAi.js';
|
||||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
import type { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||||
import { InMemoryReservedTurnStore } from '../src/turn/reservedTurnStore.js';
|
|
||||||
import { createReservedTurnHandler } from '../src/turn/reservedTurnHandler.js';
|
|
||||||
import { InMemoryTurnProcessor } from '../src/turn/inMemoryTurnProcessor.js';
|
|
||||||
import { GeneralAI } from '../src/turn/ai/generalAi.js';
|
import { GeneralAI } from '../src/turn/ai/generalAi.js';
|
||||||
import { do징병 } from '../src/turn/ai/generalAiGeneralActions.js';
|
import { do징병 } from '../src/turn/ai/generalAiGeneralActions.js';
|
||||||
import { createIncomeHandler } from '../src/turn/incomeHandler.js';
|
|
||||||
import { createNpcTaxHandler } from '../src/turn/npcTaxHandler.js';
|
|
||||||
import { createFrontStateHandler } from '../src/turn/frontStateHandler.js';
|
|
||||||
import { composeCalendarHandlers } from '../src/turn/calendarHandlers.js';
|
|
||||||
import { buildCommandEnv, buildReservedTurnDefinitions } from '../src/turn/reservedTurnCommands.js';
|
import { buildCommandEnv, buildReservedTurnDefinitions } from '../src/turn/reservedTurnCommands.js';
|
||||||
import { LARGE_TEST_MAP, buildLargeTestCities } from './fixtures/largeTestMap.js';
|
import { LARGE_TEST_MAP, buildLargeTestCities } from './fixtures/largeTestMap.js';
|
||||||
import { round } from 'es-toolkit';
|
import { round } from 'es-toolkit';
|
||||||
|
import { createTurnTestHarness, createWorldDebugger } from './helpers/turnTestHarness.js';
|
||||||
|
|
||||||
const mockDate = new Date('0179-08-01T00:00:00Z');
|
const mockDate = new Date('0179-08-01T00:00:00Z');
|
||||||
|
|
||||||
const createMockPrisma = (initialGeneralRows: any[] = []) => {
|
|
||||||
let generalRows = [...initialGeneralRows];
|
|
||||||
return {
|
|
||||||
generalTurn: {
|
|
||||||
findMany: vi.fn(async ({ where } = {}) => {
|
|
||||||
if (where?.generalId) {
|
|
||||||
return generalRows
|
|
||||||
.filter((row) => row.generalId === where.generalId)
|
|
||||||
.sort((a, b) => a.turnIdx - b.turnIdx);
|
|
||||||
}
|
|
||||||
return generalRows;
|
|
||||||
}),
|
|
||||||
deleteMany: vi.fn(async ({ where } = {}) => {
|
|
||||||
if (where?.generalId) {
|
|
||||||
generalRows = generalRows.filter((row) => row.generalId !== where.generalId);
|
|
||||||
}
|
|
||||||
return { count: 0 };
|
|
||||||
}),
|
|
||||||
createMany: vi.fn(async ({ data }) => {
|
|
||||||
if (Array.isArray(data)) {
|
|
||||||
generalRows.push(...data);
|
|
||||||
}
|
|
||||||
return { count: data.length };
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
nationTurn: {
|
|
||||||
findMany: vi.fn(async () => []),
|
|
||||||
deleteMany: vi.fn(async () => ({ count: 0 })),
|
|
||||||
createMany: vi.fn(async () => ({ count: 0 })),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const addMinutes = (time: Date, minutes: number): Date => new Date(time.getTime() + minutes * 60_000);
|
|
||||||
|
|
||||||
const createNpcGeneral = (
|
const createNpcGeneral = (
|
||||||
id: number,
|
id: number,
|
||||||
cityId: number,
|
cityId: number,
|
||||||
@@ -213,14 +172,7 @@ describe('NPC 대형 시뮬레이션', () => {
|
|||||||
entries: [{ startMinute: 0, tickMinutes: 10 }],
|
entries: [{ startMinute: 0, tickMinutes: 10 }],
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockPrisma = createMockPrisma();
|
const worldRef = { current: null as InMemoryTurnWorld | null };
|
||||||
const reservedTurnStore = new InMemoryReservedTurnStore(mockPrisma as any, {
|
|
||||||
maxGeneralTurns: 10,
|
|
||||||
maxNationTurns: 10,
|
|
||||||
});
|
|
||||||
await reservedTurnStore.loadAll();
|
|
||||||
|
|
||||||
const wrapper = { world: null as InMemoryTurnWorld | null };
|
|
||||||
|
|
||||||
type TurnTrace = {
|
type TurnTrace = {
|
||||||
year: number;
|
year: number;
|
||||||
@@ -248,13 +200,12 @@ describe('NPC 대형 시뮬레이션', () => {
|
|||||||
|
|
||||||
const commandEnv = buildCommandEnv(snapshot.scenarioConfig, snapshot.unitSet);
|
const commandEnv = buildCommandEnv(snapshot.scenarioConfig, snapshot.unitSet);
|
||||||
|
|
||||||
const handler = await createReservedTurnHandler({
|
const { world, reservedTurnStore, runUntil } = await createTurnTestHarness({
|
||||||
reservedTurns: reservedTurnStore,
|
snapshot,
|
||||||
scenarioConfig: snapshot.scenarioConfig,
|
state,
|
||||||
scenarioMeta: snapshot.scenarioMeta,
|
schedule,
|
||||||
map: LARGE_TEST_MAP as any,
|
map: LARGE_TEST_MAP,
|
||||||
unitSet: snapshot.unitSet,
|
worldRef,
|
||||||
getWorld: () => wrapper.world,
|
|
||||||
onActionResolved: (payload) => {
|
onActionResolved: (payload) => {
|
||||||
if (payload.kind !== 'general') {
|
if (payload.kind !== 'general') {
|
||||||
return;
|
return;
|
||||||
@@ -269,73 +220,47 @@ describe('NPC 대형 시뮬레이션', () => {
|
|||||||
trace.blockedReason = payload.blockedReason;
|
trace.blockedReason = payload.blockedReason;
|
||||||
trace.aiState = payload.aiState;
|
trace.aiState = payload.aiState;
|
||||||
},
|
},
|
||||||
});
|
wrapGeneralTurnHandler: (handler) => ({
|
||||||
|
execute: (ctx) => {
|
||||||
const tracedHandler = {
|
const trace: TurnTrace = {
|
||||||
execute: (ctx: Parameters<typeof handler.execute>[0]) => {
|
year: ctx.world.currentYear,
|
||||||
const trace: TurnTrace = {
|
month: ctx.world.currentMonth,
|
||||||
year: ctx.world.currentYear,
|
nationId: ctx.general.nationId,
|
||||||
month: ctx.world.currentMonth,
|
generalId: ctx.general.id,
|
||||||
nationId: ctx.general.nationId,
|
gold: ctx.general.gold,
|
||||||
generalId: ctx.general.id,
|
rice: ctx.general.rice,
|
||||||
gold: ctx.general.gold,
|
crew: ctx.general.crew,
|
||||||
rice: ctx.general.rice,
|
train: ctx.general.train,
|
||||||
crew: ctx.general.crew,
|
atmos: ctx.general.atmos,
|
||||||
train: ctx.general.train,
|
actionKey: 'unknown',
|
||||||
atmos: ctx.general.atmos,
|
requestedAction: 'unknown',
|
||||||
actionKey: 'unknown',
|
usedFallback: false,
|
||||||
requestedAction: 'unknown',
|
ok: true,
|
||||||
usedFallback: false,
|
actionText: 'unknown',
|
||||||
ok: true,
|
logs: [],
|
||||||
actionText: 'unknown',
|
};
|
||||||
logs: [],
|
traceByGeneralId.set(ctx.general.id, trace);
|
||||||
};
|
const result = handler.execute(ctx);
|
||||||
traceByGeneralId.set(ctx.general.id, trace);
|
const actionLog = result.logs?.find((log) => log.category === LogCategory.ACTION);
|
||||||
const result = handler.execute(ctx);
|
trace.actionText = actionLog?.text ?? 'unknown';
|
||||||
const actionLog = result.logs?.find((log) => log.category === LogCategory.ACTION);
|
trace.logs = result.logs ?? [];
|
||||||
trace.actionText = actionLog?.text ?? 'unknown';
|
if (ctx.general.nationId === 0) {
|
||||||
trace.logs = result.logs ?? [];
|
return result;
|
||||||
if (ctx.general.nationId === 0) {
|
}
|
||||||
|
turnTraces.push(trace);
|
||||||
return result;
|
return result;
|
||||||
}
|
},
|
||||||
turnTraces.push(trace);
|
}),
|
||||||
return result;
|
turnProcessorOptions: {
|
||||||
},
|
tickMinutes: 10,
|
||||||
};
|
afterExecuteGeneral: async (general, result) => {
|
||||||
|
const trace = traceByGeneralId.get(general.id);
|
||||||
const incomeHandler = createIncomeHandler({
|
if (!trace) {
|
||||||
getWorld: () => wrapper.world,
|
return;
|
||||||
scenarioConfig: snapshot.scenarioConfig,
|
}
|
||||||
nationTraits: new Map(),
|
trace.ok = result.ok;
|
||||||
});
|
trace.error = result.error;
|
||||||
|
},
|
||||||
const npcTaxHandler = createNpcTaxHandler({
|
|
||||||
getWorld: () => wrapper.world,
|
|
||||||
});
|
|
||||||
|
|
||||||
const frontStateHandler = createFrontStateHandler({
|
|
||||||
getWorld: () => wrapper.world,
|
|
||||||
map: LARGE_TEST_MAP,
|
|
||||||
});
|
|
||||||
|
|
||||||
const calendarHandler = composeCalendarHandlers(incomeHandler, npcTaxHandler, frontStateHandler);
|
|
||||||
|
|
||||||
const world = new InMemoryTurnWorld(state, snapshot, {
|
|
||||||
schedule,
|
|
||||||
generalTurnHandler: tracedHandler,
|
|
||||||
calendarHandler,
|
|
||||||
});
|
|
||||||
wrapper.world = world;
|
|
||||||
|
|
||||||
const processor = new InMemoryTurnProcessor(world, {
|
|
||||||
tickMinutes: 10,
|
|
||||||
afterExecuteGeneral: async (general, result) => {
|
|
||||||
const trace = traceByGeneralId.get(general.id);
|
|
||||||
if (!trace) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
trace.ok = result.ok;
|
|
||||||
trace.error = result.error;
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const checkpointGoldByGeneral = new Map<number, number>();
|
const checkpointGoldByGeneral = new Map<number, number>();
|
||||||
@@ -355,15 +280,9 @@ describe('NPC 대형 시뮬레이션', () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const runOneMonth = async () => {
|
const debug = createWorldDebugger(() => worldRef.current, {
|
||||||
const target = addMinutes(world.getState().lastTurnTime, 10);
|
includeNationSummary: true,
|
||||||
await processor.run(target, {
|
});
|
||||||
budgetMs: 10000,
|
|
||||||
maxGenerals: 100000,
|
|
||||||
catchUpCap: 1,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const assertUprisingCount = (minCount: number) => {
|
const assertUprisingCount = (minCount: number) => {
|
||||||
const nations = world.listNations();
|
const nations = world.listNations();
|
||||||
expect(nations.length).toBeGreaterThanOrEqual(minCount);
|
expect(nations.length).toBeGreaterThanOrEqual(minCount);
|
||||||
@@ -653,18 +572,17 @@ describe('NPC 대형 시뮬레이션', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
while (true) {
|
await runUntil(
|
||||||
await runOneMonth();
|
(current) => current.currentYear > 183 || (current.currentYear === 183 && current.currentMonth >= 7),
|
||||||
const { currentYear, currentMonth } = world.getState();
|
undefined,
|
||||||
const key = toKey(currentYear, currentMonth);
|
(current) => {
|
||||||
const checker = targetChecks.get(key);
|
const key = toKey(current.currentYear, current.currentMonth);
|
||||||
if (checker) {
|
const checker = targetChecks.get(key);
|
||||||
checker();
|
if (checker) {
|
||||||
|
checker();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (currentYear > 183 || (currentYear === 183 && currentMonth >= 7)) {
|
);
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const lastAiTrace = [...turnTraces].reverse().find((trace) => trace.aiState);
|
const lastAiTrace = [...turnTraces].reverse().find((trace) => trace.aiState);
|
||||||
if (lastAiTrace?.aiState) {
|
if (lastAiTrace?.aiState) {
|
||||||
@@ -675,10 +593,12 @@ describe('NPC 대형 시뮬레이션', () => {
|
|||||||
await debugRecruitConstraints(debugGeneralId);
|
await debugRecruitConstraints(debugGeneralId);
|
||||||
}
|
}
|
||||||
dumpTraceSummary('NPC 대형 시뮬레이션 실패', 200);
|
dumpTraceSummary('NPC 대형 시뮬레이션 실패', 200);
|
||||||
|
debug.dumpWorldSummary('NPC 대형 시뮬레이션 실패');
|
||||||
const sampleNation = world.listNations().find((nation) => nation.level >= 1 && nation.capitalCityId);
|
const sampleNation = world.listNations().find((nation) => nation.level >= 1 && nation.capitalCityId);
|
||||||
if (sampleNation) {
|
if (sampleNation) {
|
||||||
const policy = (sampleNation.meta as Record<string, unknown>)?.npc_nation_policy;
|
const policy = (sampleNation.meta as Record<string, unknown>)?.npc_nation_policy;
|
||||||
console.log('[TRACE] sample npc_nation_policy:', policy);
|
console.log('[TRACE] sample npc_nation_policy:', policy);
|
||||||
|
debug.dumpNation(sampleNation.id, 'NPC 샘플 국가');
|
||||||
const sampleGeneral = world
|
const sampleGeneral = world
|
||||||
.listGenerals()
|
.listGenerals()
|
||||||
.find((general) => general.nationId === sampleNation.id && general.cityId > 0);
|
.find((general) => general.nationId === sampleNation.id && general.cityId > 0);
|
||||||
@@ -691,6 +611,7 @@ describe('NPC 대형 시뮬레이션', () => {
|
|||||||
population: city?.population,
|
population: city?.population,
|
||||||
populationMax: city?.populationMax,
|
populationMax: city?.populationMax,
|
||||||
});
|
});
|
||||||
|
debug.dumpCity(sampleGeneral.cityId, 'NPC 샘플 도시');
|
||||||
}
|
}
|
||||||
const nationGenerals = world.listGenerals().filter((general) => general.nationId === sampleNation.id);
|
const nationGenerals = world.listGenerals().filter((general) => general.nationId === sampleNation.id);
|
||||||
const crewOnly = nationGenerals.filter((general) => general.crew > 0);
|
const crewOnly = nationGenerals.filter((general) => general.crew > 0);
|
||||||
|
|||||||
@@ -1,53 +1,12 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import type { TurnSchedule, UnitSetDefinition } from '@sammo-ts/logic';
|
import type { TurnSchedule, UnitSetDefinition } from '@sammo-ts/logic';
|
||||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
import type { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||||
import { InMemoryReservedTurnStore } from '../src/turn/reservedTurnStore.js';
|
|
||||||
import { createReservedTurnHandler } from '../src/turn/reservedTurnHandler.js';
|
|
||||||
import { InMemoryTurnProcessor } from '../src/turn/inMemoryTurnProcessor.js';
|
|
||||||
import { composeCalendarHandlers } from '../src/turn/calendarHandlers.js';
|
|
||||||
import { createIncomeHandler } from '../src/turn/incomeHandler.js';
|
|
||||||
import { createNpcTaxHandler } from '../src/turn/npcTaxHandler.js';
|
|
||||||
import { createFrontStateHandler } from '../src/turn/frontStateHandler.js';
|
|
||||||
import { LARGE_TEST_MAP, buildLargeTestCities } from './fixtures/largeTestMap.js';
|
import { LARGE_TEST_MAP, buildLargeTestCities } from './fixtures/largeTestMap.js';
|
||||||
|
import { createTurnTestHarness } from './helpers/turnTestHarness.js';
|
||||||
|
|
||||||
const mockDate = new Date('0182-07-01T00:00:00Z');
|
const mockDate = new Date('0182-07-01T00:00:00Z');
|
||||||
|
|
||||||
const createMockPrisma = (initialGeneralRows: any[] = []) => {
|
|
||||||
let generalRows = [...initialGeneralRows];
|
|
||||||
return {
|
|
||||||
generalTurn: {
|
|
||||||
findMany: vi.fn(async ({ where } = {}) => {
|
|
||||||
if (where?.generalId) {
|
|
||||||
return generalRows
|
|
||||||
.filter((row) => row.generalId === where.generalId)
|
|
||||||
.sort((a, b) => a.turnIdx - b.turnIdx);
|
|
||||||
}
|
|
||||||
return generalRows;
|
|
||||||
}),
|
|
||||||
deleteMany: vi.fn(async ({ where } = {}) => {
|
|
||||||
if (where?.generalId) {
|
|
||||||
generalRows = generalRows.filter((row) => row.generalId !== where.generalId);
|
|
||||||
}
|
|
||||||
return { count: 0 };
|
|
||||||
}),
|
|
||||||
createMany: vi.fn(async ({ data }) => {
|
|
||||||
if (Array.isArray(data)) {
|
|
||||||
generalRows.push(...data);
|
|
||||||
}
|
|
||||||
return { count: data.length };
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
nationTurn: {
|
|
||||||
findMany: vi.fn(async () => []),
|
|
||||||
deleteMany: vi.fn(async () => ({ count: 0 })),
|
|
||||||
createMany: vi.fn(async () => ({ count: 0 })),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const addMinutes = (time: Date, minutes: number): Date => new Date(time.getTime() + minutes * 60_000);
|
|
||||||
|
|
||||||
const createNpcGeneral = (
|
const createNpcGeneral = (
|
||||||
id: number,
|
id: number,
|
||||||
cityId: number,
|
cityId: number,
|
||||||
@@ -213,12 +172,31 @@ describe('NPC 전투준비 턴 검증', () => {
|
|||||||
entries: [{ startMinute: 0, tickMinutes: 10 }],
|
entries: [{ startMinute: 0, tickMinutes: 10 }],
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockPrisma = createMockPrisma();
|
const worldRef = { current: null as InMemoryTurnWorld | null };
|
||||||
const reservedTurnStore = new InMemoryReservedTurnStore(mockPrisma as any, {
|
const trainingActions = new Set(['che_훈련', 'che_사기진작']);
|
||||||
maxGeneralTurns: 10,
|
const trainingCounts = new Map<string, number>();
|
||||||
maxNationTurns: 10,
|
const { world, reservedTurnStore, runUntil } = await createTurnTestHarness({
|
||||||
|
snapshot,
|
||||||
|
state,
|
||||||
|
schedule,
|
||||||
|
map: LARGE_TEST_MAP,
|
||||||
|
worldRef,
|
||||||
|
onActionResolved: (payload) => {
|
||||||
|
if (payload.kind !== 'general') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!trainingActions.has(payload.actionKey)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const currentWorld = worldRef.current;
|
||||||
|
if (!currentWorld) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { currentYear, currentMonth } = currentWorld.getState();
|
||||||
|
const key = `${currentYear}-${String(currentMonth).padStart(2, '0')}`;
|
||||||
|
trainingCounts.set(key, (trainingCounts.get(key) ?? 0) + 1);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
await reservedTurnStore.loadAll();
|
|
||||||
|
|
||||||
for (const general of generals.filter((g) => g.nationId === 1)) {
|
for (const general of generals.filter((g) => g.nationId === 1)) {
|
||||||
const turns = reservedTurnStore.getGeneralTurns(general.id);
|
const turns = reservedTurnStore.getGeneralTurns(general.id);
|
||||||
@@ -231,84 +209,9 @@ describe('NPC 전투준비 턴 검증', () => {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const wrapper = { world: null as InMemoryTurnWorld | null };
|
await runUntil(
|
||||||
const trainingActions = new Set(['che_훈련', 'che_사기진작']);
|
(current) => current.currentYear > 182 || (current.currentYear === 182 && current.currentMonth >= 11)
|
||||||
const trainingCounts = new Map<string, number>();
|
);
|
||||||
|
|
||||||
const handler = await createReservedTurnHandler({
|
|
||||||
reservedTurns: reservedTurnStore,
|
|
||||||
scenarioConfig: snapshot.scenarioConfig,
|
|
||||||
scenarioMeta: snapshot.scenarioMeta,
|
|
||||||
map: LARGE_TEST_MAP as any,
|
|
||||||
unitSet: snapshot.unitSet,
|
|
||||||
getWorld: () => wrapper.world,
|
|
||||||
onActionResolved: (payload) => {
|
|
||||||
if (payload.kind !== 'general') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!trainingActions.has(payload.actionKey)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const world = wrapper.world;
|
|
||||||
if (!world) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const { currentYear, currentMonth } = world.getState();
|
|
||||||
const key = `${currentYear}-${String(currentMonth).padStart(2, '0')}`;
|
|
||||||
trainingCounts.set(key, (trainingCounts.get(key) ?? 0) + 1);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const tracedHandler = {
|
|
||||||
execute: (ctx: Parameters<typeof handler.execute>[0]) => {
|
|
||||||
return handler.execute(ctx);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const incomeHandler = createIncomeHandler({
|
|
||||||
getWorld: () => wrapper.world,
|
|
||||||
scenarioConfig: snapshot.scenarioConfig,
|
|
||||||
nationTraits: new Map(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const npcTaxHandler = createNpcTaxHandler({
|
|
||||||
getWorld: () => wrapper.world,
|
|
||||||
});
|
|
||||||
|
|
||||||
const frontStateHandler = createFrontStateHandler({
|
|
||||||
getWorld: () => wrapper.world,
|
|
||||||
map: LARGE_TEST_MAP,
|
|
||||||
});
|
|
||||||
|
|
||||||
const calendarHandler = composeCalendarHandlers(incomeHandler, npcTaxHandler, frontStateHandler);
|
|
||||||
|
|
||||||
const world = new InMemoryTurnWorld(state, snapshot, {
|
|
||||||
schedule,
|
|
||||||
generalTurnHandler: tracedHandler,
|
|
||||||
calendarHandler,
|
|
||||||
});
|
|
||||||
wrapper.world = world;
|
|
||||||
|
|
||||||
const processor = new InMemoryTurnProcessor(world, {
|
|
||||||
tickMinutes: 10,
|
|
||||||
});
|
|
||||||
|
|
||||||
const runOneMonth = async () => {
|
|
||||||
const target = addMinutes(world.getState().lastTurnTime, 10);
|
|
||||||
await processor.run(target, {
|
|
||||||
budgetMs: 10000,
|
|
||||||
maxGenerals: 100000,
|
|
||||||
catchUpCap: 1,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
await runOneMonth();
|
|
||||||
const { currentYear, currentMonth } = world.getState();
|
|
||||||
if (currentYear > 182 || (currentYear === 182 && currentMonth >= 11)) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(trainingCounts.get('182-09') ?? 0).toBeGreaterThan(0);
|
expect(trainingCounts.get('182-09') ?? 0).toBeGreaterThan(0);
|
||||||
expect(trainingCounts.get('182-10') ?? 0).toBeGreaterThan(0);
|
expect(trainingCounts.get('182-10') ?? 0).toBeGreaterThan(0);
|
||||||
|
|||||||
Reference in New Issue
Block a user