refactor: update test setup, introduce system environment for commands, and streamline frontend build configuration.

This commit is contained in:
2026-01-07 17:17:04 +00:00
parent 57e9bbb4ea
commit 38a8d33242
22 changed files with 518 additions and 432 deletions
+8
View File
@@ -3,6 +3,14 @@
"private": true, "private": true,
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": { "scripts": {
"build": "tsdown -c ../../tsdown.config.ts -F @sammo-ts/game-api", "build": "tsdown -c ../../tsdown.config.ts -F @sammo-ts/game-api",
"dev": "tsdown -c ../../tsdown.config.ts -F @sammo-ts/game-api --watch", "dev": "tsdown -c ../../tsdown.config.ts -F @sammo-ts/game-api --watch",
+5 -5
View File
@@ -217,7 +217,7 @@ const resolveCityRiceConsumption = (options: {
year: number; year: number;
startYear: number; startYear: number;
}): number => { }): number => {
const cityReport = options.battle.reports.find((report) => report.type === 'city'); const cityReport = options.battle.reports.find((report: any) => report.type === 'city');
if (!cityReport) { if (!cityReport) {
return 0; return 0;
} }
@@ -225,7 +225,7 @@ const resolveCityRiceConsumption = (options: {
return 0; return 0;
} }
const crewType = options.unitSet.crewTypes?.find((item) => item.id === options.castleCrewTypeId); const crewType = options.unitSet.crewTypes?.find((item: any) => item.id === options.castleCrewTypeId);
const riceCoef = crewType?.rice ?? 1; const riceCoef = crewType?.rice ?? 1;
const tech = Number(options.defenderNation.meta.tech ?? 0); const tech = Number(options.defenderNation.meta.tech ?? 0);
const trainAtmos = resolveCityTrainAtmos(options.year, options.startYear); const trainAtmos = resolveCityTrainAtmos(options.year, options.startYear);
@@ -333,7 +333,7 @@ export const processBattleSimJob = (payload: BattleSimJobPayload): BattleSimResu
}); });
lastBattle = outcome; lastBattle = outcome;
const attackerReport = outcome.reports.find((report) => report.type === 'general' && report.isAttacker); const attackerReport = outcome.reports.find((report: any) => report.type === 'general' && report.isAttacker);
const killed = attackerReport?.killed ?? 0; const killed = attackerReport?.killed ?? 0;
const dead = attackerReport?.dead ?? 0; const dead = attackerReport?.dead ?? 0;
@@ -370,7 +370,7 @@ export const processBattleSimJob = (payload: BattleSimJobPayload): BattleSimResu
defenderAvgRice += (defenderRiceInit - defenderRiceAfter + cityRice) * weight; defenderAvgRice += (defenderRiceInit - defenderRiceAfter + cityRice) * weight;
const attackerActivated = outcome.metrics?.attackerActivatedSkills ?? {}; const attackerActivated = outcome.metrics?.attackerActivatedSkills ?? {};
for (const [skillName, value] of Object.entries(attackerActivated)) { for (const [skillName, value] of Object.entries(attackerActivated) as [string, number][]) {
attackerSkills[skillName] = (attackerSkills[skillName] ?? 0) + value * weight; attackerSkills[skillName] = (attackerSkills[skillName] ?? 0) + value * weight;
} }
@@ -380,7 +380,7 @@ export const processBattleSimJob = (payload: BattleSimJobPayload): BattleSimResu
defendersSkills.push({}); defendersSkills.push({});
} }
const bucket = defendersSkills[defIdx]!; const bucket = defendersSkills[defIdx]!;
for (const [skillName, value] of Object.entries(defenderActivated[defIdx]!)) { for (const [skillName, value] of Object.entries(defenderActivated[defIdx]!) as [string, number][]) {
bucket[skillName] = (bucket[skillName] ?? 0) + value * weight; bucket[skillName] = (bucket[skillName] ?? 0) + value * weight;
} }
} }
+2
View File
@@ -35,6 +35,8 @@ export type NationRow = GamePrisma.NationGetPayload<Record<string, never>>;
export type TroopRow = GamePrisma.TroopGetPayload<Record<string, never>>; export type TroopRow = GamePrisma.TroopGetPayload<Record<string, never>>;
export type JsonValue = GamePrisma.JsonValue; export type JsonValue = GamePrisma.JsonValue;
export type JsonObject = GamePrisma.JsonObject;
export type JsonArray = GamePrisma.JsonArray;
export type InputJsonValue = GamePrisma.InputJsonValue; export type InputJsonValue = GamePrisma.InputJsonValue;
export type DatabaseClient = InfraDatabaseClient; export type DatabaseClient = InfraDatabaseClient;
+6
View File
@@ -22,6 +22,12 @@ export * from './battleSim/inMemoryTransport.js';
export * from './battleSim/keys.js'; export * from './battleSim/keys.js';
export * from './battleSim/worker.js'; export * from './battleSim/worker.js';
// Types for TRPC consumer
export type { MessageView } from './messages/store.js';
export type { TurnCommandTable } from './turns/commandTable.js';
export type { ReservedTurnView } from './turns/reservedTurns.js';
export type { JsonObject, JsonArray } from './context.js';
const isMain = (): boolean => { const isMain = (): boolean => {
if (!process.argv[1]) { if (!process.argv[1]) {
return false; return false;
+1 -1
View File
@@ -328,7 +328,7 @@ const evaluateAvailability = (
reason: result.reason, reason: result.reason,
}; };
} }
const missingKinds = new Set(result.missing.map((req) => req.kind)); const missingKinds = new Set(result.missing.map((req: any) => req.kind));
const inputOnlyMissing = const inputOnlyMissing =
missingKinds.size === 0 ? reqArg : Array.from(missingKinds).every((kind) => INPUT_REQUIREMENT_KINDS.has(kind)); missingKinds.size === 0 ? reqArg : Array.from(missingKinds).every((kind) => INPUT_REQUIREMENT_KINDS.has(kind));
if (inputOnlyMissing) { if (inputOnlyMissing) {
+32 -11
View File
@@ -3,20 +3,41 @@
"compilerOptions": { "compilerOptions": {
"outDir": "dist", "outDir": "dist",
"composite": true, "composite": true,
"rootDir": "src",
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
"@sammo-ts/common": ["../../packages/common/src/index.ts"], "@sammo-ts/common": [
"@sammo-ts/common/*": ["../../packages/common/src/*"], "../../packages/common/src/index.ts"
"@sammo-ts/infra": ["../../packages/infra/src/index.ts"], ],
"@sammo-ts/infra/*": ["../../packages/infra/src/*"], "@sammo-ts/common/*": [
"@sammo-ts/logic": ["../../packages/logic/src/index.ts"], "../../packages/common/src/*"
"@sammo-ts/logic/*": ["../../packages/logic/src/*"] ],
"@sammo-ts/infra": [
"../../packages/infra/src/index.ts"
],
"@sammo-ts/infra/*": [
"../../packages/infra/src/*"
],
"@sammo-ts/logic": [
"../../packages/logic/src/index.ts"
],
"@sammo-ts/logic/*": [
"../../packages/logic/src/*"
]
} }
}, },
"include": ["src", "test", "*.ts"], "include": [
"src"
],
"references": [ "references": [
{ "path": "../../packages/common" }, {
{ "path": "../../packages/infra" }, "path": "../../packages/common"
{ "path": "../../packages/logic" } },
{
"path": "../../packages/infra"
},
{
"path": "../../packages/logic"
}
] ]
} }
+15 -6
View File
@@ -2,12 +2,21 @@
"extends": "../../tsconfig.paths.json", "extends": "../../tsconfig.paths.json",
"compilerOptions": { "compilerOptions": {
"outDir": "dist", "outDir": "dist",
"composite": true "composite": true,
"rootDir": "src"
}, },
"include": ["src", "test", "*.ts"], "include": [
"src"
],
"references": [ "references": [
{ "path": "../../packages/common" }, {
{ "path": "../../packages/infra" }, "path": "../../packages/common"
{ "path": "../../packages/logic" } },
{
"path": "../../packages/infra"
},
{
"path": "../../packages/logic"
}
] ]
} }
+8
View File
@@ -3,6 +3,14 @@
"private": true, "private": true,
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": { "scripts": {
"build": "tsdown -c ../../tsdown.config.ts -F @sammo-ts/gateway-api", "build": "tsdown -c ../../tsdown.config.ts -F @sammo-ts/gateway-api",
"dev": "tsdown -c ../../tsdown.config.ts -F @sammo-ts/gateway-api --watch", "dev": "tsdown -c ../../tsdown.config.ts -F @sammo-ts/gateway-api --watch",
+18 -7
View File
@@ -2,13 +2,24 @@
"extends": "../../tsconfig.paths.json", "extends": "../../tsconfig.paths.json",
"compilerOptions": { "compilerOptions": {
"outDir": "dist", "outDir": "dist",
"composite": true "composite": true,
"rootDir": "src"
}, },
"include": ["src", "test", "*.ts"], "include": [
"src"
],
"references": [ "references": [
{ "path": "../../packages/common" }, {
{ "path": "../../packages/infra" }, "path": "../../packages/common"
{ "path": "../../packages/logic" }, },
{ "path": "../../app/game-engine" } {
"path": "../../packages/infra"
},
{
"path": "../../packages/logic"
},
{
"path": "../../app/game-engine"
}
] ]
} }
+2
View File
@@ -14,6 +14,8 @@
"dependencies": { "dependencies": {
"@sammo-ts/common": "workspace:*", "@sammo-ts/common": "workspace:*",
"@sammo-ts/game-api": "workspace:*", "@sammo-ts/game-api": "workspace:*",
"@sammo-ts/gateway-api": "workspace:*",
"@sammo-ts/logic": "workspace:*",
"@trpc/client": "^11.8.1", "@trpc/client": "^11.8.1",
"@trpc/server": "^11.8.1", "@trpc/server": "^11.8.1",
"@vueuse/core": "^13.9.0", "@vueuse/core": "^13.9.0",
+1 -1
View File
@@ -1,5 +1,5 @@
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client'; import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { appRouter } from '../../../game-api/src/router'; import type { appRouter } from '@sammo-ts/game-api';
export type GameRouter = typeof appRouter; export type GameRouter = typeof appRouter;
+55 -28
View File
@@ -4,48 +4,75 @@
"target": "ESNext", "target": "ESNext",
"useDefineForClassFields": true, "useDefineForClassFields": true,
"module": "ESNext", "module": "ESNext",
"lib": ["ESNext", "DOM", "DOM.Iterable"], "lib": [
"ESNext",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true, "skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler", "moduleResolution": "bundler",
"allowImportingTsExtensions": true, "allowImportingTsExtensions": true,
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"noEmit": true, "noEmit": true,
"jsx": "preserve", "jsx": "preserve",
/* Linting */
"strict": true, "strict": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true, "noUnusedParameters": true,
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
"@/*": ["./src/*"], "@/*": [
"@sammo-ts/common": ["../../packages/common/src/index.ts"], "./src/*"
"@sammo-ts/common/*": ["../../packages/common/src/*"], ],
"@sammo-ts/infra": ["../../packages/infra/src/index.ts"], "@sammo-ts/common": [
"@sammo-ts/infra/*": ["../../packages/infra/src/*"], "../../packages/common/src/index.ts"
"@sammo-ts/logic": ["../../packages/logic/src/index.ts"], ],
"@sammo-ts/logic/*": ["../../packages/logic/src/*"], "@sammo-ts/common/*": [
"@sammo-ts/game-engine": ["../../app/game-engine/src/index.ts"], "../../packages/common/src/*"
"@sammo-ts/game-engine/*": ["../../app/game-engine/src/*"], ],
"@sammo-ts/game-api": ["../../app/game-api/src/index.ts"], "@sammo-ts/infra": [
"@sammo-ts/game-api/*": ["../../app/game-api/src/*"], "../../packages/infra/src/index.ts"
"@sammo-ts/gateway-api": ["../../app/gateway-api/src/index.ts"], ],
"@sammo-ts/gateway-api/*": ["../../app/gateway-api/src/*"] "@sammo-ts/infra/*": [
"../../packages/infra/src/*"
],
"@sammo-ts/logic": [
"../../packages/logic/src/index.ts"
],
"@sammo-ts/logic/*": [
"../../packages/logic/src/*"
],
"@sammo-ts/game-engine": [
"../../app/game-engine/src/index.ts"
],
"@sammo-ts/game-engine/*": [
"../../app/game-engine/src/*"
],
"@sammo-ts/game-api": [
"../../app/game-api/src/index.ts"
],
"@sammo-ts/game-api/*": [
"../../app/game-api/src/*"
],
"@sammo-ts/gateway-api": [
"../../app/gateway-api/src/index.ts"
],
"@sammo-ts/gateway-api/*": [
"../../app/gateway-api/src/*"
]
} }
}, },
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "test/**/*.ts", "*.ts"], "include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"test/**/*.ts"
],
"references": [ "references": [
{ "path": "./tsconfig.node.json" }, {
{ "path": "../../packages/common" }, "path": "./tsconfig.node.json"
{ "path": "../../packages/infra" }, }
{ "path": "../../packages/logic" },
{ "path": "../../app/game-engine" },
{ "path": "../../app/game-api" },
{ "path": "../../app/gateway-api" }
] ]
} }
-2
View File
@@ -1,2 +0,0 @@
declare const _default: import('vite').UserConfig;
export default _default;
-16
View File
@@ -1,16 +0,0 @@
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import tailwindcss from '@tailwindcss/vite';
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), tailwindcss()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
port: 3000,
},
});
@@ -5,19 +5,15 @@ import { MINIMAL_MAP } from '../fixtures/minimalMap.js';
import { InMemoryWorld, TestGameRunner } from '../testEnv.js'; import { InMemoryWorld, TestGameRunner } from '../testEnv.js';
import { buildScenarioBootstrap } from '../../src/world/bootstrap.js'; import { buildScenarioBootstrap } from '../../src/world/bootstrap.js';
import type { ScenarioDefinition, ScenarioGeneral } from '../../src/scenario/types.js'; import type { ScenarioDefinition, ScenarioGeneral } from '../../src/scenario/types.js';
import type { MapDefinition } from '../../src/world/types.js'; import type { Nation } from '../../src/domain/entities.js';
import type { General, Nation } from '../../src/domain/entities.js';
import { commandSpec as foundNationSpec } from '../../src/actions/turn/general/che_건국.js'; import { commandSpec as foundNationSpec } from '../../src/actions/turn/general/che_건국.js';
import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js'; import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js';
// Mock Scenario Definition // Mock Scenario Definition
const MOCK_SCENARIO: ScenarioDefinition = { const MOCK_SCENARIO: ScenarioDefinition = {
id: 'test_scenario',
title: 'Test Scenario', title: 'Test Scenario',
template: 'test',
startYear: 189, startYear: 189,
beginYear: 189, life: null,
endYear: 250,
fiction: 0, fiction: 0,
history: [], history: [],
ignoreDefaultEvents: false, ignoreDefaultEvents: false,
@@ -30,41 +26,44 @@ const MOCK_SCENARIO: ScenarioDefinition = {
events: [], events: [],
initialEvents: [], initialEvents: [],
config: { config: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
iconPath: '',
map: {},
const: {},
environment: { environment: {
mapName: 'minimal_map', mapName: 'minimal_map',
unitSet: 'test_set', unitSet: 'test_set',
startYear: 189,
}, },
options: {},
}, },
}; };
// Mock General Data // Mock General Data
const MOCK_GENERALS: ScenarioGeneral[] = Array.from({ length: 10 }, (_, i) => ({ const MOCK_GENERALS: ScenarioGeneral[] = Array.from({ length: 10 }, (_, i) => {
name: `General_${i}`, const cityDef = MINIMAL_MAP.cities[i % MINIMAL_MAP.cities.length];
nation: null, // neutral if (!cityDef) throw new Error('City definition missing');
city: MINIMAL_MAP.cities[i % MINIMAL_MAP.cities.length].name,
npc: 0, return {
p_name: `General_${i}`, // Using p_name as personality/picture placeholder if needed by types name: `General_${i}`,
uniqueName: `General_${i}`, nation: null, // neutral
officerLevel: 0, city: cityDef.name,
birthYear: 160, officerLevel: 0,
deathYear: 220, birthYear: 160,
strength: 70 + i, deathYear: 220,
intelligence: 70 + i, strength: 70 + i,
leadership: 70 + i, intelligence: 70 + i,
charm: 70 + i, // Note: entities.ts checks stats, ensuring keys match leadership: 70 + i,
personality: null, personality: null,
special: null, special: null,
specialWar: null, specialWar: null,
affinity: 0, affinity: 0,
picture: null, picture: null,
horse: null, horse: null,
weapon: null, weapon: null,
book: null, book: null,
item: null, item: null,
text: null, text: null,
})); };
});
// We need to inject generals into the scenario object for bootstrap // We need to inject generals into the scenario object for bootstrap
const scenarioWithGenerals = produce(MOCK_SCENARIO, draft => { const scenarioWithGenerals = produce(MOCK_SCENARIO, draft => {
@@ -95,18 +94,37 @@ describe('Blank Start Scenario', () => {
expect(targetGeneral).toBeDefined(); expect(targetGeneral).toBeDefined();
if (!targetGeneral) return; if (!targetGeneral) return;
expect(targetGeneral.nationId).toBe(0); // Should be neutral (nation 0 commonly used for neutral in sammo, or checking bootstrap logic) expect(targetGeneral.nationId).toBe(0);
// bootstrap puts neutral in nation 0 if includeNeutralNation is true.
// 3. Command: Found Nation // 3. Command: Found Nation
const env: TurnCommandEnv = { const systemEnv: TurnCommandEnv = {
general: targetGeneral, develCost: 50,
date: new Date(189, 0, 1), trainDelta: 5,
atmosDelta: 5,
maxTrainByCommand: 100,
maxAtmosByCommand: 100,
sabotageDefaultProb: 0.5,
sabotageProbCoefByStat: 0.1,
sabotageDefenceCoefByGeneralCount: 0.1,
sabotageDamageMin: 10,
sabotageDamageMax: 20,
openingPartYear: 200,
maxGeneral: 10,
defaultNpcGold: 1000,
defaultNpcRice: 1000,
defaultCrewTypeId: 1,
defaultSpecialDomestic: null,
defaultSpecialWar: null,
initialNationGenLimit: 10,
maxTechLevel: 10,
baseGold: 1000,
baseRice: 1000,
maxResourceActionAmount: 1000
}; };
const foundNationDef = foundNationSpec.createDefinition(env);
const foundNationDef = foundNationSpec.createDefinition(systemEnv);
// Execute Turn // Execute Turn
// We simulate the turn runner processing this command
await runner.runTurn([ await runner.runTurn([
{ {
generalId: targetGeneral.id, generalId: targetGeneral.id,
@@ -117,9 +135,6 @@ describe('Blank Start Scenario', () => {
]); ]);
// 4. Simulate Turn Processing (Daemon Logic Mock) // 4. Simulate Turn Processing (Daemon Logic Mock)
// Since logic/actions/engine doesn't auto-create nation, we simulate the "Post-Turn Phase"
// that scans for the 'founding' flag.
const generalAfter = world.getGeneral(targetGeneral.id); const generalAfter = world.getGeneral(targetGeneral.id);
expect(generalAfter?.meta?.founding).toBe(true); expect(generalAfter?.meta?.founding).toBe(true);
@@ -132,8 +147,8 @@ describe('Blank Start Scenario', () => {
color: '#FF0000', color: '#FF0000',
capitalCityId: generalAfter.cityId, capitalCityId: generalAfter.cityId,
chiefGeneralId: generalAfter.id, chiefGeneralId: generalAfter.id,
gold: 1000, gold: 10000,
rice: 1000, rice: 10000,
power: 0, power: 0,
level: 1, level: 1,
typeCode: 'che_def', typeCode: 'che_def',
@@ -141,15 +156,22 @@ describe('Blank Start Scenario', () => {
}; };
// Apply updates manually to world // Apply updates manually to world
// In a real test we'd add methods to InMemoryWorld to do this cleanly world.snapshot.nations.push(newNation);
(world as any).snapshot.nations.push(newNation);
const city = world.getCity(generalAfter.cityId); const city = world.getCity(generalAfter.cityId);
if (city) { if (city) {
(world as any).updateCity({ ...city, nationId: newNationId }); // Manually update nationId in city
const cityIdx = world.snapshot.cities.findIndex(c => c.id === city.id);
const cityToUpdate = world.snapshot.cities[cityIdx];
if (cityToUpdate) cityToUpdate.nationId = newNationId;
} }
(world as any).updateGeneral({ ...generalAfter, nationId: newNationId, meta: { ...generalAfter.meta, founding: false } }); const genIdx = world.snapshot.generals.findIndex(g => g.id === generalAfter.id);
const genToUpdate = world.snapshot.generals[genIdx];
if (genToUpdate) {
genToUpdate.nationId = newNationId;
genToUpdate.meta = { ...generalAfter.meta, founding: false };
}
} }
// 5. Verify // 5. Verify
+65 -37
View File
@@ -7,7 +7,7 @@ import type { WorldSnapshot } from '../../src/world/types.js';
import { commandSpec as declareWarSpec } from '../../src/actions/turn/nation/che_선전포고.js'; import { commandSpec as declareWarSpec } from '../../src/actions/turn/nation/che_선전포고.js';
import { commandSpec as deploySpec } from '../../src/actions/turn/general/che_출병.js'; import { commandSpec as deploySpec } from '../../src/actions/turn/general/che_출병.js';
import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js'; import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js';
import { processDiplomacyMonth, DIPLOMACY_STATE } from '../../src/diplomacy/index.js'; import { processDiplomacyMonth, DIPLOMACY_STATE, type DiplomacyEntry } from '../../src/diplomacy/index.js';
import { buildWarConfig, buildWarAftermathConfig } from '../../src/actions/turn/actionContextHelpers.js'; import { buildWarConfig, buildWarAftermathConfig } from '../../src/actions/turn/actionContextHelpers.js';
describe('Diplomacy Scenario', () => { describe('Diplomacy Scenario', () => {
@@ -18,30 +18,30 @@ describe('Diplomacy Scenario', () => {
const mockNationA: Nation = { const mockNationA: Nation = {
id: NATION_A_ID, name: 'Nation A', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1, id: NATION_A_ID, name: 'Nation A', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1,
gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: { tech: 1000 } gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: {}
}; };
const mockNationB: Nation = { const mockNationB: Nation = {
id: NATION_B_ID, name: 'Nation B', color: '#0000FF', capitalCityId: 2, chiefGeneralId: 2, id: NATION_B_ID, name: 'Nation B', color: '#0000FF', capitalCityId: 2, chiefGeneralId: 2,
gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: { tech: 1000 } gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: {}
}; };
// Two adjacent cities const cityADef = MINIMAL_MAP.cities[0];
const cityADef = MINIMAL_MAP.cities[0]; // A const cityBDef = MINIMAL_MAP.cities[1];
const cityBDef = MINIMAL_MAP.cities[1]; // B if (!cityADef || !cityBDef) throw new Error('City definition missing');
const mockCityA: City = { const mockCityA: City = {
id: 1, name: cityADef.name, nationId: NATION_A_ID, level: 1, region: 1, state: 0, id: 1, name: cityADef.name, nationId: NATION_A_ID, level: 1, state: 0,
population: 10000, populationMax: 10000, agriculture: 1000, agricultureMax: 1000, population: 10000, populationMax: 10000, agriculture: 1000, agricultureMax: 1000,
commerce: 1000, commerceMax: 1000, security: 1000, securityMax: 1000, commerce: 1000, commerceMax: 1000, security: 1000, securityMax: 1000,
defence: 1000, defenceMax: 1000, wall: 1000, wallMax: 1000, defence: 1000, defenceMax: 1000, wall: 1000, wallMax: 1000,
supplyState: 1, frontState: 0, trust: 1000, trade: 1000, meta: {} supplyState: 1, frontState: 0, meta: {}
}; };
const mockCityB: City = { const mockCityB: City = {
id: 2, name: cityBDef.name, nationId: NATION_B_ID, level: 1, region: 1, state: 0, id: 2, name: cityBDef.name, nationId: NATION_B_ID, level: 1, state: 0,
population: 10000, populationMax: 10000, agriculture: 1000, agricultureMax: 1000, population: 10000, populationMax: 10000, agriculture: 1000, agricultureMax: 1000,
commerce: 1000, commerceMax: 1000, security: 1000, securityMax: 1000, commerce: 1000, commerceMax: 1000, security: 1000, securityMax: 1000,
defence: 1000, defenceMax: 1000, wall: 1000, wallMax: 1000, defence: 1000, defenceMax: 1000, wall: 1000, wallMax: 1000,
supplyState: 1, frontState: 0, trust: 1000, trade: 1000, meta: {} supplyState: 1, frontState: 0, meta: {}
}; };
const mockGeneralA: General = { const mockGeneralA: General = {
@@ -75,15 +75,34 @@ describe('Diplomacy Scenario', () => {
const world = new InMemoryWorld(snapshot); const world = new InMemoryWorld(snapshot);
const runner = new TestGameRunner(world, 200, 1); const runner = new TestGameRunner(world, 200, 1);
const env: TurnCommandEnv = {
general: mockGeneralA, const systemEnv: TurnCommandEnv = {
date: new Date(200, 0, 1), develCost: 50,
unitSet: snapshot.unitSet, trainDelta: 5,
map: snapshot.map atmosDelta: 5,
maxTrainByCommand: 100,
maxAtmosByCommand: 100,
sabotageDefaultProb: 0.5,
sabotageProbCoefByStat: 0.1,
sabotageDefenceCoefByGeneralCount: 0.1,
sabotageDamageMin: 10,
sabotageDamageMax: 20,
openingPartYear: 200,
maxGeneral: 10,
defaultNpcGold: 1000,
defaultNpcRice: 1000,
defaultCrewTypeId: 1,
defaultSpecialDomestic: null,
defaultSpecialWar: null,
initialNationGenLimit: 10,
maxTechLevel: 10,
baseGold: 1000,
baseRice: 1000,
maxResourceActionAmount: 1000
}; };
// 2. Declare War // 2. Declare War
const declareWarDef = declareWarSpec.createDefinition(env); const declareWarDef = declareWarSpec.createDefinition(systemEnv);
await runner.runTurn([{ await runner.runTurn([{
generalId: 1, generalId: 1,
commandKey: 'che_선전포고', commandKey: 'che_선전포고',
@@ -99,12 +118,11 @@ describe('Diplomacy Scenario', () => {
const warConfig = buildWarConfig(snapshot.scenarioConfig, snapshot.unitSet!); const warConfig = buildWarConfig(snapshot.scenarioConfig, snapshot.unitSet!);
const aftermathConfig = buildWarAftermathConfig(snapshot.scenarioConfig, warConfig.castleCrewTypeId); const aftermathConfig = buildWarAftermathConfig(snapshot.scenarioConfig, warConfig.castleCrewTypeId);
// Manual WarTimeContext
const warTime = { const warTime = {
year: 200, year: 200,
month: 1, month: 1,
season: 0, // Spring season: 0,
turn: 1 // mock value turn: 1
}; };
const seedBase = 'test_seed'; const seedBase = 'test_seed';
@@ -112,8 +130,6 @@ describe('Diplomacy Scenario', () => {
const destCity = world.getCity(destCityId)!; const destCity = world.getCity(destCityId)!;
const destNation = world.getNation(destCity.nationId); const destNation = world.getNation(destCity.nationId);
// Update warTime based on runner's date if needed, but static is fine for test step
// Actually let's use runner's date for 'realism' in simulation step 5
warTime.year = runner.currentDate.getFullYear(); warTime.year = runner.currentDate.getFullYear();
warTime.month = runner.currentDate.getMonth() + 1; warTime.month = runner.currentDate.getMonth() + 1;
warTime.season = Math.floor(runner.currentDate.getMonth() / 3); warTime.season = Math.floor(runner.currentDate.getMonth() / 3);
@@ -124,13 +140,18 @@ describe('Diplomacy Scenario', () => {
warConfig, warConfig,
aftermathConfig, aftermathConfig,
time: { ...warTime }, time: { ...warTime },
seedBase seedBase,
map: world.snapshot.map,
unitSet: world.snapshot.unitSet,
cities: world.getAllCities(),
nations: world.getAllNations(),
generals: world.getAllGenerals(),
diplomacy: world.snapshot.diplomacy
}; };
}; };
// 3. Try to Deploy (Should Fail/Crash if blocked, or return empty effects) // 3. Try to Deploy
// With corrected context, this call should PROCEED to check logic. const deployDef = deploySpec.createDefinition(systemEnv);
const deployDef = deploySpec.createDefinition(env);
await runner.runTurn([{ await runner.runTurn([{
generalId: 1, generalId: 1,
commandKey: 'che_출병', commandKey: 'che_출병',
@@ -139,17 +160,30 @@ describe('Diplomacy Scenario', () => {
context: buildDispatchContext(2) context: buildDispatchContext(2)
}]); }]);
// Assert failure: No troops created (snapshot.troops still empty)
expect(world.snapshot.troops.length).toBe(0); expect(world.snapshot.troops.length).toBe(0);
// 4. Simulate State Transition // 4. Simulate State Transition
for (let i = 0; i < 24; i++) { for (let i = 0; i < 24; i++) {
world.snapshot.diplomacy = processDiplomacyMonth( const entries: DiplomacyEntry[] = world.snapshot.diplomacy.map(s => ({
world.snapshot.diplomacy, fromNationId: s.fromNationId,
new Map() toNationId: s.toNationId,
); state: s.state,
runner.currentDate.setMonth(runner.currentDate.getMonth() + 1); // Advance runner time too term: s.durationMonths,
dead: 0,
meta: {}
}));
const updatedEntries = processDiplomacyMonth(entries, new Map());
world.snapshot.diplomacy = updatedEntries.map(e => ({
fromNationId: e.fromNationId,
toNationId: e.toNationId,
state: e.state,
durationMonths: e.term
}));
runner.currentDate.setMonth(runner.currentDate.getMonth() + 1);
} }
const diplomacyAB_After = world.getDiplomacy(NATION_A_ID, NATION_B_ID); const diplomacyAB_After = world.getDiplomacy(NATION_A_ID, NATION_B_ID);
@@ -166,11 +200,5 @@ describe('Diplomacy Scenario', () => {
const generalAfter = world.getGeneral(1)!; const generalAfter = world.getGeneral(1)!;
console.log(`General Exp: ${mockGeneralA.experience} -> ${generalAfter.experience}`); console.log(`General Exp: ${mockGeneralA.experience} -> ${generalAfter.experience}`);
// Final assertion: expect experience to have changed (battle happened) or at least no crash
// Note: if battle outcome is stalemate/loss, exp might minimally change or change a lot.
// And if 'unable to find path' even in WAR (due to some other reason), exp won't change.
// But map is connected.
// We just verified critical path execution.
}); });
}); });
+101 -95
View File
@@ -5,94 +5,40 @@ import { InMemoryWorld, TestGameRunner } from '../testEnv.js';
import type { City, General, Nation } from '../../src/domain/entities.js'; import type { City, General, Nation } from '../../src/domain/entities.js';
import type { WorldSnapshot } from '../../src/world/types.js'; import type { WorldSnapshot } from '../../src/world/types.js';
import { commandSpec as developAgricultureSpec } from '../../src/actions/turn/general/che_농지개간.js'; import { commandSpec as developAgricultureSpec } from '../../src/actions/turn/general/che_농지개간.js';
import { commandSpec as commercialSpec } from '../../src/actions/turn/general/che_상업투자.js';
import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js'; import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js';
describe('Domestic Affairs Scenario', () => { describe('Domestic Affairs Scenario', () => {
it('should increase agriculture when executing "Farming" command', async () => { it('should increase agriculture when executing "Farming" command', async () => {
// 1. Setup World with existing nation/city/general // 1. Setup World
const NATION_ID = 1;
const CITY_ID = 1;
const GENERAL_ID = 1;
const mockNation: Nation = { const mockNation: Nation = {
id: NATION_ID, id: 1, name: 'Test Nation', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1,
name: 'TestNation', gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: {}
color: '#0000FF',
capitalCityId: CITY_ID,
chiefGeneralId: GENERAL_ID,
gold: 10000,
rice: 10000,
power: 0,
level: 1,
typeCode: 'test',
meta: { tech: 1000 }
}; };
const cityDef = MINIMAL_MAP.cities.find(c => c.id === CITY_ID)!; const cityDef = MINIMAL_MAP.cities[0];
if (!cityDef) throw new Error('City definition missing');
const mockCity: City = { const mockCity: City = {
id: CITY_ID, id: 1, name: cityDef.name, nationId: 1, level: 1, state: 0,
name: cityDef.name, population: 10000, populationMax: 10000, agriculture: 500, agricultureMax: 1000,
nationId: NATION_ID, commerce: 500, commerceMax: 1000, security: 500, securityMax: 1000,
level: cityDef.level, defence: 500, defenceMax: 1000, wall: 500, wallMax: 1000,
region: cityDef.region, supplyState: 1, frontState: 0, meta: {}
state: 0,
population: 10000,
populationMax: cityDef.max.population,
agriculture: 500,
agricultureMax: cityDef.max.agriculture,
commerce: 500,
commerceMax: cityDef.max.commerce,
security: 500,
securityMax: cityDef.max.security,
defence: 200,
defenceMax: cityDef.max.defence,
wall: 200,
wallMax: cityDef.max.wall,
supplyState: 1,
frontState: 0,
trust: 50,
trade: 100,
meta: {}
}; };
const mockGeneral: General = { const mockGeneral: General = {
id: GENERAL_ID, id: 1, name: 'Domestic Officer', nationId: 1, cityId: 1, troopId: 0, npcState: 0,
name: 'Governor A', experience: 100, dedication: 100, officerLevel: 5, gold: 1000, rice: 1000, crew: 0, crewTypeId: 0,
nationId: NATION_ID, train: 100, atmos: 100, injury: 0, age: 30,
cityId: CITY_ID, stats: { leadership: 50, strength: 50, intelligence: 100 },
troopId: 0, role: { personality: null, specialDomestic: null, specialWar: null, items: { horse: null, weapon: null, book: null, item: null } },
npcState: 0, triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, meta: {}
experience: 100,
dedication: 100,
officerLevel: 5,
gold: 1000,
rice: 1000,
crew: 5000,
crewTypeId: 1,
train: 80,
atmos: 80,
injury: 0,
age: 30,
stats: {
leadership: 80,
strength: 80,
intelligence: 80, // High int implies better political results usually
},
role: {
personality: null,
specialDomestic: null,
specialWar: null,
items: { horse: null, weapon: null, book: null, item: null }
},
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
meta: {}
}; };
const snapshot: WorldSnapshot = { const snapshot: WorldSnapshot = {
scenarioConfig: { environment: { mapName: 'minimal_map', unitSet: 'default' }, options: {} } as any, scenarioConfig: { environment: { mapName: 'minimal_map', unitSet: 'default' }, options: {} } as any,
scenarioMeta: { title: 'Test', startYear: 200, life: 0, fiction: 0, history: [], ignoreDefaultEvents: false }, scenarioMeta: { title: 'Test', startYear: 200, life: 0, fiction: 0, history: [], ignoreDefaultEvents: false },
map: MINIMAL_MAP, map: MINIMAL_MAP,
unitSet: { id: 'default', name: 'default' },
nations: [mockNation], nations: [mockNation],
cities: [mockCity], cities: [mockCity],
generals: [mockGeneral], generals: [mockGeneral],
@@ -105,35 +51,95 @@ describe('Domestic Affairs Scenario', () => {
const world = new InMemoryWorld(snapshot); const world = new InMemoryWorld(snapshot);
const runner = new TestGameRunner(world, 200, 1); const runner = new TestGameRunner(world, 200, 1);
// 2. Command: Develop Agriculture // 2. Prepare Command
const env: TurnCommandEnv = { const systemEnv: TurnCommandEnv = {
general: mockGeneral, develCost: 50,
date: new Date(200, 0, 1), trainDelta: 5,
atmosDelta: 5,
maxTrainByCommand: 100,
maxAtmosByCommand: 100,
sabotageDefaultProb: 0.5,
sabotageProbCoefByStat: 0.1,
sabotageDefenceCoefByGeneralCount: 0.1,
sabotageDamageMin: 10,
sabotageDamageMax: 20,
openingPartYear: 200,
maxGeneral: 10,
defaultNpcGold: 1000,
defaultNpcRice: 1000,
defaultCrewTypeId: 1,
defaultSpecialDomestic: null,
defaultSpecialWar: null,
initialNationGenLimit: 10,
maxTechLevel: 10,
baseGold: 1000,
baseRice: 1000,
maxResourceActionAmount: 1000
}; };
const farmingDef = developAgricultureSpec.createDefinition(env);
const initialAgri = world.getCity(CITY_ID)!.agriculture; const farmingDef = developAgricultureSpec.createDefinition(systemEnv);
// Execute Turn // 3. Execute
await runner.runTurn([ await runner.runTurn([{
{ generalId: 1,
generalId: GENERAL_ID, commandKey: 'che_농지개간',
commandKey: 'che_농지개간', resolver: farmingDef,
resolver: farmingDef, args: {}
args: {} }]);
}
]);
// 3. Verify // 4. Verify
const cityAfter = world.getCity(CITY_ID)!; const updatedCity = world.getCity(1)!;
expect(cityAfter.agriculture).toBeGreaterThan(initialAgri); console.log(`Agriculture: 500 -> ${updatedCity.agriculture}`);
expect(updatedCity.agriculture).toBeGreaterThan(500);
// Verify upper bound if applicable (handled by constraints usually, but good to check it changed)
console.log(`Agriculture: ${initialAgri} -> ${cityAfter.agriculture}`);
}); });
it('should NOT increase if city is fully developed or insufficient conditions', async () => { it('should not increase agriculture when city is already maxed', async () => {
// Setup similar to above but with max agriculture // Setup with max agriculture
// Implementation skipped for brevity in this step, focusing on success case first const mockNation: Nation = {
id: 1, name: 'Test Nation', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1,
gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: {}
};
const mockCity: City = {
id: 1, name: 'City A', nationId: 1, level: 1, state: 0,
population: 10000, populationMax: 10000, agriculture: 1000, agricultureMax: 1000,
commerce: 500, commerceMax: 1000, security: 500, securityMax: 1000,
defence: 500, defenceMax: 1000, wall: 500, wallMax: 1000,
supplyState: 1, frontState: 0, meta: {}
};
const mockGeneral: General = {
id: 1, name: 'Domestic Officer', nationId: 1, cityId: 1, troopId: 0, npcState: 0,
experience: 100, dedication: 100, officerLevel: 5, gold: 1000, rice: 1000, crew: 0, crewTypeId: 0,
train: 100, atmos: 100, injury: 0, age: 30,
stats: { leadership: 50, strength: 50, intelligence: 100 },
role: { personality: null, specialDomestic: null, specialWar: null, items: { horse: null, weapon: null, book: null, item: null } },
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, meta: {}
};
const snapshot: WorldSnapshot = {
scenarioConfig: { environment: { mapName: 'minimal_map', unitSet: 'default' }, options: {} } as any,
map: MINIMAL_MAP,
nations: [mockNation],
cities: [mockCity],
generals: [mockGeneral],
troops: [],
diplomacy: [],
events: [],
initialEvents: []
};
const world = new InMemoryWorld(snapshot);
const runner = new TestGameRunner(world, 200, 1);
const systemEnv: TurnCommandEnv = { develCost: 50 } as any;
const farmingDef = developAgricultureSpec.createDefinition(systemEnv);
await runner.runTurn([{
generalId: 1,
commandKey: 'che_농지개간',
resolver: farmingDef,
args: {}
}]);
const updatedCity = world.getCity(1)!;
expect(updatedCity.agriculture).toBe(1000);
}); });
}); });
+71 -142
View File
@@ -4,125 +4,49 @@ import { MINIMAL_MAP } from '../fixtures/minimalMap.js';
import { InMemoryWorld, TestGameRunner } from '../testEnv.js'; import { InMemoryWorld, TestGameRunner } from '../testEnv.js';
import type { City, General, Nation } from '../../src/domain/entities.js'; import type { City, General, Nation } from '../../src/domain/entities.js';
import type { WorldSnapshot } from '../../src/world/types.js'; import type { WorldSnapshot } from '../../src/world/types.js';
import { commandSpec as draftSpec } from '../../src/actions/turn/general/che_징병.js'; import { commandSpec as recruitSpec } from '../../src/actions/turn/general/che_징병.js';
import { commandSpec as trainSpec } from '../../src/actions/turn/general/che_훈련.js'; import { commandSpec as trainSpec } from '../../src/actions/turn/general/che_훈련.js';
import { commandSpec as moraleSpec } from '../../src/actions/turn/general/che_사기진작.js'; import { commandSpec as atmosSpec } from '../../src/actions/turn/general/che_사기진작.js';
import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js'; import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js';
describe('Troop Management Scenario', () => { describe('Troop Management Scenario', () => {
it('should successfully draft troops, then train and boost morale', async () => { it('should successfully draft troops, then train and boost morale', async () => {
// 1. Setup // 1. Setup World
const NATION_ID = 1;
const CITY_ID = 1;
const GENERAL_ID = 1;
const mockNation: Nation = { const mockNation: Nation = {
id: NATION_ID, id: 1, name: 'Militaristic Nation', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1,
name: 'TroopNation', gold: 50000, rice: 50000, power: 0, level: 5, typeCode: 'test', meta: {}
color: '#00FF00',
capitalCityId: CITY_ID,
chiefGeneralId: GENERAL_ID,
gold: 50000,
rice: 50000,
power: 0,
level: 3,
typeCode: 'test',
meta: { tech: 5000 } // High tech
}; };
const cityDef = MINIMAL_MAP.cities.find(c => c.id === CITY_ID)!; const cityDef = MINIMAL_MAP.cities[0];
if (!cityDef) throw new Error('City definition missing');
const mockCity: City = { const mockCity: City = {
id: CITY_ID, id: 1, name: cityDef.name, nationId: 1, level: 1, state: 0,
name: cityDef.name, population: 50000, populationMax: 50000, agriculture: 500, agricultureMax: 1000,
nationId: NATION_ID, commerce: 500, commerceMax: 1000, security: 500, securityMax: 1000,
level: cityDef.level, defence: 500, defenceMax: 1000, wall: 500, wallMax: 1000,
region: cityDef.region, supplyState: 1, frontState: 0, meta: {}
state: 0,
population: 50000, // Increased to meet minimum drafting population (30000+)
populationMax: cityDef.max.population,
agriculture: 1000,
agricultureMax: cityDef.max.agriculture,
commerce: 1000,
commerceMax: cityDef.max.commerce,
security: 1000,
securityMax: cityDef.max.security,
defence: 500,
defenceMax: cityDef.max.defence,
wall: 500,
wallMax: cityDef.max.wall,
supplyState: 1,
frontState: 0,
trust: 100,
trade: 100,
meta: {}
}; };
// General starts with 0 troops but high leadership
const mockGeneral: General = { const mockGeneral: General = {
id: GENERAL_ID, id: 1, name: 'General Lee', nationId: 1, cityId: 1, troopId: 0, npcState: 0,
name: 'Commander T', experience: 100, dedication: 100, officerLevel: 5, gold: 1000, rice: 1000, crew: 0, crewTypeId: 1,
nationId: NATION_ID, train: 10, atmos: 10, injury: 0, age: 30,
cityId: CITY_ID, stats: { leadership: 100, strength: 100, intelligence: 50 },
troopId: 0, role: { personality: null, specialDomestic: null, specialWar: null, items: { horse: null, weapon: null, book: null, item: null } },
npcState: 0, triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, meta: {}
experience: 100,
dedication: 100,
officerLevel: 5,
gold: 3000,
rice: 3000,
crew: 0,
crewTypeId: 1, // Basic infantry (assuming 1 is valid)
train: 10,
atmos: 10,
injury: 0,
age: 25,
stats: {
leadership: 95,
strength: 80,
intelligence: 80,
},
role: {
personality: null,
specialDomestic: null,
specialWar: null,
items: { horse: null, weapon: null, book: null, item: null }
},
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
meta: {}
};
// Simple UnitSet for test
const unitSet = {
id: 'default',
name: 'Default',
crewTypes: [
{
id: 1,
armType: 1,
name: '보병',
attack: 10,
defence: 10,
speed: 10,
avoid: 0,
magicCoef: 0,
cost: 10,
rice: 1,
requirements: [],
attackCoef: {},
defenceCoef: {},
info: [],
initSkillTrigger: [],
phaseSkillTrigger: [],
iActionList: []
}
]
}; };
const snapshot: WorldSnapshot = { const snapshot: WorldSnapshot = {
scenarioConfig: { environment: { mapName: 'minimal_map', unitSet: 'default' }, options: {} } as any, scenarioConfig: { environment: { mapName: 'minimal_map', unitSet: 'default' }, options: {} } as any,
scenarioMeta: { title: 'Test', startYear: 200, life: 0, fiction: 0, history: [], ignoreDefaultEvents: false }, scenarioMeta: { title: 'Test', startYear: 200, life: 0, fiction: 0, history: [], ignoreDefaultEvents: false },
map: MINIMAL_MAP, map: MINIMAL_MAP,
unitSet: unitSet as any, unitSet: {
id: 'default',
name: 'default',
crewTypes: [
{ id: 1, name: 'Infantry', armType: 1, cost: 10, requirements: [] }
]
} as any,
nations: [mockNation], nations: [mockNation],
cities: [mockCity], cities: [mockCity],
generals: [mockGeneral], generals: [mockGeneral],
@@ -133,65 +57,70 @@ describe('Troop Management Scenario', () => {
}; };
const world = new InMemoryWorld(snapshot); const world = new InMemoryWorld(snapshot);
const runner = new TestGameRunner(world, 201, 1); const runner = new TestGameRunner(world, 200, 1);
const env: TurnCommandEnv = {
general: mockGeneral, const systemEnv: TurnCommandEnv = {
date: new Date(201, 0, 1), develCost: 50,
unitSet: unitSet as any trainDelta: 35,
atmosDelta: 35,
maxTrainByCommand: 100,
maxAtmosByCommand: 100,
sabotageDefaultProb: 0.5,
sabotageProbCoefByStat: 0.1,
sabotageDefenceCoefByGeneralCount: 0.1,
sabotageDamageMin: 10,
sabotageDamageMax: 20,
openingPartYear: 200,
maxGeneral: 10,
defaultNpcGold: 1000,
defaultNpcRice: 1000,
defaultCrewTypeId: 1,
defaultSpecialDomestic: null,
defaultSpecialWar: null,
initialNationGenLimit: 10,
maxTechLevel: 10,
baseGold: 1000,
baseRice: 1000,
maxResourceActionAmount: 1000
}; };
const draftDef = draftSpec.createDefinition(env); // 2. Draft Troops
const trainDef = trainSpec.createDefinition(env); const recruitDef = recruitSpec.createDefinition(systemEnv);
const moraleDef = moraleSpec.createDefinition(env);
// Step 1: Draft command (args usually amount=0 means max or specific amount)
// Let's assume drafting 1000 troops.
// We need to check draft command args. `che_징병.ts` implementation details?
// Assuming { amount: 1000 } or similar.
// Let's check `che_징병.ts` args type if possible later, but standard is `amount: number`.
await runner.runTurn([{ await runner.runTurn([{
generalId: GENERAL_ID, generalId: 1,
commandKey: 'che_징병', commandKey: 'che_징병',
resolver: draftDef, resolver: recruitDef,
args: { args: { crewType: 1, amount: 1000 }
amount: 1000,
crewType: 1 // Must specify crewType
}
}]); }]);
let general = world.getGeneral(GENERAL_ID)!; const generalAfterDraft = world.getGeneral(1)!;
expect(general.crew).toBeGreaterThan(0); console.log(`Drafted: ${generalAfterDraft.crew}`);
console.log(`Drafted: ${general.crew}`); expect(generalAfterDraft.crew).toBe(1000);
const draftedCrew = general.crew;
// Step 2: Update env with new general state (important for constraints/logic that depends on current state) // 3. Train
env.general = general; const trainDef = trainSpec.createDefinition(systemEnv);
// Step 3: Train command
await runner.runTurn([{ await runner.runTurn([{
generalId: GENERAL_ID, generalId: 1,
commandKey: 'che_훈련', commandKey: 'che_훈련',
resolver: trainDef, resolver: trainDef,
args: {} args: {}
}]); }]);
general = world.getGeneral(GENERAL_ID)!; const generalAfterTrain = world.getGeneral(1)!;
expect(general.train).toBeGreaterThan(10); console.log(`Train: 10 -> ${generalAfterTrain.train}`);
console.log(`Train: 10 -> ${general.train}`); expect(generalAfterTrain.train).toBeGreaterThan(10);
env.general = general; // 4. Boost Morale
const atmosDef = atmosSpec.createDefinition(systemEnv);
// Step 4: Morale boost
await runner.runTurn([{ await runner.runTurn([{
generalId: GENERAL_ID, generalId: 1,
commandKey: 'che_사기진작', commandKey: 'che_사기진작',
resolver: moraleDef, resolver: atmosDef,
args: {} args: {}
}]); }]);
general = world.getGeneral(GENERAL_ID)!; const generalAfterAtmos = world.getGeneral(1)!;
expect(general.atmos).toBeGreaterThan(10); console.log(`Atmos: 10 -> ${generalAfterAtmos.atmos}`);
console.log(`Atmos: 10 -> ${general.atmos}`); expect(generalAfterAtmos.atmos).toBeGreaterThan(10);
}); });
}); });
+34 -26
View File
@@ -1,15 +1,16 @@
import { produceWithPatches, enablePatches } from 'immer'; import { enablePatches } from 'immer';
import type { City, General, Nation, GeneralId, NationId, CityId, GeneralTriggerState } from '../src/domain/entities.js'; import type { City, General, Nation, GeneralId, NationId, CityId } from '../src/domain/entities.js';
import type { WorldSnapshot } from '../src/world/types.js'; import type { WorldSnapshot } from '../src/world/types.js';
import { type GeneralActionResolution, resolveGeneralAction, type GeneralActionResolver } from '../src/actions/engine.js'; import { type GeneralActionResolution, resolveGeneralAction, type GeneralActionResolver } from '../src/actions/engine.js';
import type { TurnSchedule } from '../src/turn/calendar.js'; import type { TurnSchedule } from '../src/turn/calendar.js';
import { type DiplomacyEntry, applyDiplomacyPatch, buildDefaultDiplomacy } from '../src/diplomacy/index.js'; import { type DiplomacyEntry, applyDiplomacyPatch, buildDefaultDiplomacy } from '../src/diplomacy/index.js';
import type { ScenarioDiplomacy } from '../src/scenario/types.js';
enablePatches(); enablePatches();
export class InMemoryWorld { export class InMemoryWorld {
private snapshot: WorldSnapshot; public snapshot: WorldSnapshot;
constructor(initialSnapshot: WorldSnapshot) { constructor(initialSnapshot: WorldSnapshot) {
this.snapshot = initialSnapshot; this.snapshot = initialSnapshot;
@@ -89,8 +90,19 @@ export class InMemoryWorld {
if (effect.type === 'diplomacy:patch') { if (effect.type === 'diplomacy:patch') {
const srcId = effect.srcNationId; const srcId = effect.srcNationId;
const destId = effect.destNationId; const destId = effect.destNationId;
const existing = this.getDiplomacy(srcId, destId) ?? buildDefaultDiplomacy(srcId, destId); const existing = this.getDiplomacy(srcId, destId);
const patched = applyDiplomacyPatch(existing, effect.patch);
// Convert ScenarioDiplomacy to DiplomacyEntry for applying patch
const entry: DiplomacyEntry = existing ? {
fromNationId: existing.fromNationId,
toNationId: existing.toNationId,
state: existing.state,
term: existing.durationMonths,
dead: 0,
meta: {}
} : buildDefaultDiplomacy(srcId, destId);
const patched = applyDiplomacyPatch(entry, effect.patch);
this.updateDiplomacy(patched); this.updateDiplomacy(patched);
} }
} }
@@ -120,23 +132,30 @@ export class InMemoryWorld {
} }
} }
getDiplomacy(srcId: number, destId: number): DiplomacyEntry | undefined { getDiplomacy(srcId: number, destId: number): ScenarioDiplomacy | undefined {
return this.snapshot.diplomacy.find(d => d.fromNationId === srcId && d.toNationId === destId); return this.snapshot.diplomacy.find(d => d.fromNationId === srcId && d.toNationId === destId);
} }
updateDiplomacy(entry: DiplomacyEntry) { updateDiplomacy(entry: DiplomacyEntry) {
const scenarioEntry: ScenarioDiplomacy = {
fromNationId: entry.fromNationId,
toNationId: entry.toNationId,
state: entry.state,
durationMonths: entry.term
};
const idx = this.snapshot.diplomacy.findIndex(d => d.fromNationId === entry.fromNationId && d.toNationId === entry.toNationId); const idx = this.snapshot.diplomacy.findIndex(d => d.fromNationId === entry.fromNationId && d.toNationId === entry.toNationId);
if (idx >= 0) { if (idx >= 0) {
this.snapshot.diplomacy[idx] = entry; this.snapshot.diplomacy[idx] = scenarioEntry;
} else { } else {
this.snapshot.diplomacy.push(entry); this.snapshot.diplomacy.push(scenarioEntry);
} }
} }
} }
export interface TestCommand { export interface TestCommand {
generalId: GeneralId; generalId: GeneralId;
commandKey: string; // Not used directly here, but for clarity commandKey: string;
resolver: GeneralActionResolver; resolver: GeneralActionResolver;
args: unknown; args: unknown;
context?: Record<string, unknown>; context?: Record<string, unknown>;
@@ -151,11 +170,10 @@ export class TestGameRunner {
this.currentDate = new Date(startYear, startMonth - 1); this.currentDate = new Date(startYear, startMonth - 1);
} }
// A simplified run turn method
async runTurn(commands: TestCommand[]) { async runTurn(commands: TestCommand[]) {
const schedule: TurnSchedule = { const schedule: TurnSchedule = {
entries: [ entries: [
{ startMinute: 0, tickMinutes: 60 } // simplified: 1 hour ticks for whole day { startMinute: 0, tickMinutes: 60 }
] ]
}; };
@@ -164,9 +182,10 @@ export class TestGameRunner {
if (!general) continue; if (!general) continue;
const city = this.world.getCity(general.cityId); const city = this.world.getCity(general.cityId);
if (!city) throw new Error(`General ${general.id} is in non-existent city ${general.cityId}`);
const nation = general.nationId ? this.world.getNation(general.nationId) : null; const nation = general.nationId ? this.world.getNation(general.nationId) : null;
// In test env, we might not have full context, but engine needs basic entities
const inputContext = { const inputContext = {
general, general,
city, city,
@@ -174,23 +193,13 @@ export class TestGameRunner {
rng: { rng: {
real: () => Math.random(), real: () => Math.random(),
int: (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min, int: (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min,
nextInt: (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min, // Added nextInt nextInt: (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min,
next: () => Math.random() next: () => Math.random()
} as any, // Mock RNG } as any,
// Extended context for specific commands (Recruit etc.)
map: this.world.snapshot.map,
unitSet: this.world.snapshot.unitSet,
cities: this.world.getAllCities(),
nations: this.world.getAllNations(),
currentYear: this.currentDate.getFullYear(),
startYear: this.world.snapshot.scenarioMeta?.startYear,
// GeneralActionContext base requirements
year: this.currentDate.getFullYear(), year: this.currentDate.getFullYear(),
month: this.currentDate.getMonth() + 1, month: this.currentDate.getMonth() + 1,
season: Math.floor(this.currentDate.getMonth() / 3), season: Math.floor(this.currentDate.getMonth() / 3),
diplomacy: this.world.snapshot.diplomacy,
generals: this.world.getAllGenerals(),
...cmd.context ...cmd.context
}; };
@@ -201,7 +210,7 @@ export class TestGameRunner {
const resolution = resolveGeneralAction( const resolution = resolveGeneralAction(
cmd.resolver, cmd.resolver,
inputContext, inputContext as any,
scheduleContext, scheduleContext,
cmd.args cmd.args
); );
@@ -209,7 +218,6 @@ export class TestGameRunner {
await this.world.applyResolution(resolution); await this.world.applyResolution(resolution);
} }
// Advance time
this.currentDate.setMonth(this.currentDate.getMonth() + 1); this.currentDate.setMonth(this.currentDate.getMonth() + 1);
} }
} }
+14 -5
View File
@@ -7,7 +7,9 @@
"module": "NodeNext", "module": "NodeNext",
"moduleResolution": "NodeNext", "moduleResolution": "NodeNext",
"target": "ES2023", "target": "ES2023",
"lib": ["ES2024"], "lib": [
"ES2024"
],
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true,
"noUncheckedIndexedAccess": true, "noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true, "exactOptionalPropertyTypes": true,
@@ -16,8 +18,15 @@
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"useUnknownInCatchVariables": true, "useUnknownInCatchVariables": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true "noUnusedParameters": true,
"rootDir": "src"
}, },
"include": ["src", "test", "*.ts"], "include": [
"references": [{ "path": "../common" }] "src"
} ],
"references": [
{
"path": "../common"
}
]
}
+6
View File
@@ -203,6 +203,12 @@ importers:
'@sammo-ts/game-api': '@sammo-ts/game-api':
specifier: workspace:* specifier: workspace:*
version: link:../game-api version: link:../game-api
'@sammo-ts/gateway-api':
specifier: workspace:*
version: link:../gateway-api
'@sammo-ts/logic':
specifier: workspace:*
version: link:../../packages/logic
'@trpc/client': '@trpc/client':
specifier: ^11.8.1 specifier: ^11.8.1
version: 11.8.1(@trpc/server@11.8.1(typescript@5.9.3))(typescript@5.9.3) version: 11.8.1(@trpc/server@11.8.1(typescript@5.9.3))(typescript@5.9.3)
+3 -1
View File
@@ -8,7 +8,9 @@ export default defineConfig({
entry: 'src/index.ts', entry: 'src/index.ts',
format: 'es', format: 'es',
outDir: 'dist', outDir: 'dist',
dts: true, dts: {
build: true
},
sourcemap: true, sourcemap: true,
target: 'node22', target: 'node22',
platform: 'node', platform: 'node',