refactor: apply consistent formatting and minor import adjustments across test and tsconfig files.

This commit is contained in:
2026-01-07 18:05:22 +00:00
parent 542a65c2a9
commit f62bbb7927
12 changed files with 419 additions and 195 deletions
+2 -1
View File
@@ -27,7 +27,8 @@
}, },
"include": [ "include": [
"src", "src",
"test" "test",
"*.ts"
], ],
"references": [ "references": [
{ {
+2 -1
View File
@@ -6,7 +6,8 @@
}, },
"include": [ "include": [
"src", "src",
"test" "test",
"*.ts"
], ],
"references": [ "references": [
{ {
+2 -1
View File
@@ -6,7 +6,8 @@
}, },
"include": [ "include": [
"src", "src",
"test" "test",
"*.ts"
], ],
"references": [ "references": [
{ {
@@ -17,8 +17,6 @@ export const itemModule: ItemModule = {
unique: false, unique: false,
getBattleInitTriggerList: (context) => { getBattleInitTriggerList: (context) => {
if (!context.unit) return null; if (!context.unit) return null;
return new WarTriggerCaller( return new WarTriggerCaller(new che_사기(context.unit, BaseWarUnitTrigger.TYPE_CONSUMABLE_ITEM, 30));
new che_사기(context.unit, BaseWarUnitTrigger.TYPE_CONSUMABLE_ITEM, 30)
);
}, },
}; };
@@ -32,9 +32,6 @@ export const itemModule: ItemModule = {
return null; return null;
} }
return new WarTriggerCaller( return new WarTriggerCaller(new che_저지_시도(unit), new che_저지(unit));
new che_저지_시도(unit),
new che_저지(unit)
);
}, },
}; };
@@ -17,8 +17,6 @@ export const itemModule: ItemModule = {
unique: false, unique: false,
getBattleInitTriggerList: (context) => { getBattleInitTriggerList: (context) => {
if (!context.unit) return null; if (!context.unit) return null;
return new WarTriggerCaller( return new WarTriggerCaller(new che_훈련(context.unit, BaseWarUnitTrigger.TYPE_CONSUMABLE_ITEM, 40));
new che_훈련(context.unit, BaseWarUnitTrigger.TYPE_CONSUMABLE_ITEM, 40)
);
}, },
}; };
@@ -1,11 +1,10 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { produce } from 'immer'; import { produce } from 'immer';
import { MINIMAL_MAP } from '../fixtures/minimalMap.js'; 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 { Nation } from '../../src/domain/entities.js'; import type { Nation, City } 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';
@@ -66,13 +65,12 @@ const MOCK_GENERALS: ScenarioGeneral[] = Array.from({ length: 10 }, (_, i) => {
}); });
// 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) => {
// bootstrap expects generals in specific arrays. // bootstrap expects generals in specific arrays.
// We'll put them in generalsNeutral since they are neutral // We'll put them in generalsNeutral since they are neutral
draft.generalsNeutral = MOCK_GENERALS; draft.generalsNeutral = MOCK_GENERALS;
}); });
describe('Blank Start Scenario', () => { describe('Blank Start Scenario', () => {
it('should allow neutral generals to found nations', async () => { it('should allow neutral generals to found nations', async () => {
// 1. Setup World // 1. Setup World
@@ -83,14 +81,14 @@ describe('Blank Start Scenario', () => {
includeNeutralNation: true, includeNeutralNation: true,
defaultGeneralGold: 1000, defaultGeneralGold: 1000,
defaultGeneralRice: 1000, defaultGeneralRice: 1000,
} },
}); });
const world = new InMemoryWorld(bootstrapResult.snapshot); const world = new InMemoryWorld(bootstrapResult.snapshot);
const runner = new TestGameRunner(world, 189, 1); const runner = new TestGameRunner(world, 189, 1);
// 2. Identify a target general (e.g., General_0 in City 1) // 2. Identify a target general (e.g., General_0 in City 1)
const targetGeneral = world.getAllGenerals().find(g => g.name === 'General_0'); const targetGeneral = world.getAllGenerals().find((g) => g.name === 'General_0');
expect(targetGeneral).toBeDefined(); expect(targetGeneral).toBeDefined();
if (!targetGeneral) return; if (!targetGeneral) return;
@@ -119,7 +117,7 @@ describe('Blank Start Scenario', () => {
maxTechLevel: 10, maxTechLevel: 10,
baseGold: 1000, baseGold: 1000,
baseRice: 1000, baseRice: 1000,
maxResourceActionAmount: 1000 maxResourceActionAmount: 1000,
}; };
const foundNationDef = foundNationSpec.createDefinition(systemEnv); const foundNationDef = foundNationSpec.createDefinition(systemEnv);
@@ -130,8 +128,8 @@ describe('Blank Start Scenario', () => {
generalId: targetGeneral.id, generalId: targetGeneral.id,
commandKey: 'che_건국', commandKey: 'che_건국',
resolver: foundNationDef, resolver: foundNationDef,
args: {} args: {},
} },
]); ]);
// 4. Simulate Turn Processing (Daemon Logic Mock) // 4. Simulate Turn Processing (Daemon Logic Mock)
@@ -140,7 +138,7 @@ describe('Blank Start Scenario', () => {
if (generalAfter?.meta?.founding) { if (generalAfter?.meta?.founding) {
// Mock Daemon: Create Nation // Mock Daemon: Create Nation
const newNationId = Math.max(...world.getAllNations().map(n => n.id), 0) + 1; const newNationId = Math.max(...world.getAllNations().map((n) => n.id), 0) + 1;
const newNation: Nation = { const newNation: Nation = {
id: newNationId, id: newNationId,
name: `${generalAfter.name}`, name: `${generalAfter.name}`,
@@ -152,7 +150,7 @@ describe('Blank Start Scenario', () => {
power: 0, power: 0,
level: 1, level: 1,
typeCode: 'che_def', typeCode: 'che_def',
meta: {} meta: {},
}; };
// Apply updates manually to world // Apply updates manually to world
@@ -161,16 +159,16 @@ describe('Blank Start Scenario', () => {
const city = world.getCity(generalAfter.cityId); const city = world.getCity(generalAfter.cityId);
if (city) { if (city) {
// Manually update nationId in city // Manually update nationId in city
const cityIdx = world.snapshot.cities.findIndex(c => c.id === city.id); const cityIdx = world.snapshot.cities.findIndex((c) => c.id === city.id);
world.snapshot.cities[cityIdx] = { ...world.snapshot.cities[cityIdx], nationId: newNationId }; world.snapshot.cities[cityIdx] = { ...world.snapshot.cities[cityIdx], nationId: newNationId } as City;
} }
const genIdx = world.snapshot.generals.findIndex(g => g.id === generalAfter.id); const genIdx = world.snapshot.generals.findIndex((g) => g.id === generalAfter.id);
world.snapshot.generals[genIdx] = { world.snapshot.generals[genIdx] = {
...world.snapshot.generals[genIdx], ...world.snapshot.generals[genIdx],
nationId: newNationId, nationId: newNationId,
meta: { ...generalAfter.meta, founding: false } meta: { ...generalAfter.meta, founding: false },
}; } as any;
} }
// 5. Verify // 5. Verify
+130 -53
View File
@@ -1,4 +1,3 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { MINIMAL_MAP } from '../fixtures/minimalMap.js'; import { MINIMAL_MAP } from '../fixtures/minimalMap.js';
import { InMemoryWorld, TestGameRunner } from '../testEnv.js'; import { InMemoryWorld, TestGameRunner } from '../testEnv.js';
@@ -17,12 +16,30 @@ describe('Diplomacy Scenario', () => {
const NATION_B_ID = 2; // Target nation const NATION_B_ID = 2; // Target nation
const mockNationA: Nation = { const mockNationA: Nation = {
id: NATION_A_ID, name: 'Nation A', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1, id: NATION_A_ID,
gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: {} name: 'Nation A',
color: '#FF0000',
capitalCityId: 1,
chiefGeneralId: 1,
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,
gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: {} name: 'Nation B',
color: '#0000FF',
capitalCityId: 2,
chiefGeneralId: 2,
gold: 10000,
rice: 10000,
power: 0,
level: 5,
typeCode: 'test',
meta: {},
}; };
const cityADef = MINIMAL_MAP.cities[0]; const cityADef = MINIMAL_MAP.cities[0];
@@ -30,39 +47,94 @@ describe('Diplomacy Scenario', () => {
if (!cityADef || !cityBDef) throw new Error('City definition missing'); 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, state: 0, id: 1,
population: 10000, populationMax: 10000, agriculture: 1000, agricultureMax: 1000, name: cityADef.name,
commerce: 1000, commerceMax: 1000, security: 1000, securityMax: 1000, nationId: NATION_A_ID,
defence: 1000, defenceMax: 1000, wall: 1000, wallMax: 1000, level: 1,
supplyState: 1, frontState: 0, meta: {} state: 0,
population: 10000,
populationMax: 10000,
agriculture: 1000,
agricultureMax: 1000,
commerce: 1000,
commerceMax: 1000,
security: 1000,
securityMax: 1000,
defence: 1000,
defenceMax: 1000,
wall: 1000,
wallMax: 1000,
supplyState: 1,
frontState: 0,
meta: {},
}; };
const mockCityB: City = { const mockCityB: City = {
id: 2, name: cityBDef.name, nationId: NATION_B_ID, level: 1, state: 0, id: 2,
population: 10000, populationMax: 10000, agriculture: 1000, agricultureMax: 1000, name: cityBDef.name,
commerce: 1000, commerceMax: 1000, security: 1000, securityMax: 1000, nationId: NATION_B_ID,
defence: 1000, defenceMax: 1000, wall: 1000, wallMax: 1000, level: 1,
supplyState: 1, frontState: 0, meta: {} state: 0,
population: 10000,
populationMax: 10000,
agriculture: 1000,
agricultureMax: 1000,
commerce: 1000,
commerceMax: 1000,
security: 1000,
securityMax: 1000,
defence: 1000,
defenceMax: 1000,
wall: 1000,
wallMax: 1000,
supplyState: 1,
frontState: 0,
meta: {},
}; };
const mockGeneralA: General = { const mockGeneralA: General = {
id: 1, name: 'Leader A', nationId: NATION_A_ID, cityId: 1, troopId: 0, npcState: 0, id: 1,
experience: 100, dedication: 100, officerLevel: 5, gold: 1000, rice: 1000, crew: 5000, crewTypeId: 1, name: 'Leader A',
train: 100, atmos: 100, injury: 0, age: 30, nationId: NATION_A_ID,
cityId: 1,
troopId: 0,
npcState: 0,
experience: 100,
dedication: 100,
officerLevel: 5,
gold: 1000,
rice: 1000,
crew: 5000,
crewTypeId: 1,
train: 100,
atmos: 100,
injury: 0,
age: 30,
stats: { leadership: 100, strength: 100, intelligence: 100 }, stats: { leadership: 100, strength: 100, intelligence: 100 },
role: { personality: null, specialDomestic: null, specialWar: null, items: { horse: null, weapon: null, book: null, item: null } }, role: {
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, meta: {} 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: { unitSet: {
id: 'default', id: 'default',
name: 'default', name: 'default',
crewTypes: [ crewTypes: [{ id: 1, name: 'Infantry', armType: 1, cost: 10, requirements: [] }],
{ id: 1, name: 'Infantry', armType: 1, cost: 10, requirements: [] }
]
} as any, } as any,
nations: [mockNationA, mockNationB], nations: [mockNationA, mockNationB],
cities: [mockCityA, mockCityB], cities: [mockCityA, mockCityB],
@@ -70,7 +142,7 @@ describe('Diplomacy Scenario', () => {
troops: [], troops: [],
diplomacy: [], diplomacy: [],
events: [], events: [],
initialEvents: [] initialEvents: [],
}; };
const world = new InMemoryWorld(snapshot); const world = new InMemoryWorld(snapshot);
@@ -98,17 +170,19 @@ describe('Diplomacy Scenario', () => {
maxTechLevel: 10, maxTechLevel: 10,
baseGold: 1000, baseGold: 1000,
baseRice: 1000, baseRice: 1000,
maxResourceActionAmount: 1000 maxResourceActionAmount: 1000,
}; };
// 2. Declare War // 2. Declare War
const declareWarDef = declareWarSpec.createDefinition(systemEnv); const declareWarDef = declareWarSpec.createDefinition(systemEnv);
await runner.runTurn([{ await runner.runTurn([
generalId: 1, {
commandKey: 'che_선전포고', generalId: 1,
resolver: declareWarDef, commandKey: 'che_선전포고',
args: { destNationId: NATION_B_ID } resolver: declareWarDef,
}]); args: { destNationId: NATION_B_ID },
},
]);
const diplomacyAB = world.getDiplomacy(NATION_A_ID, NATION_B_ID); const diplomacyAB = world.getDiplomacy(NATION_A_ID, NATION_B_ID);
expect(diplomacyAB).toBeDefined(); expect(diplomacyAB).toBeDefined();
@@ -122,7 +196,7 @@ describe('Diplomacy Scenario', () => {
year: 200, year: 200,
month: 1, month: 1,
season: 0, season: 0,
turn: 1 turn: 1,
}; };
const seedBase = 'test_seed'; const seedBase = 'test_seed';
@@ -146,41 +220,42 @@ describe('Diplomacy Scenario', () => {
cities: world.getAllCities(), cities: world.getAllCities(),
nations: world.getAllNations(), nations: world.getAllNations(),
generals: world.getAllGenerals(), generals: world.getAllGenerals(),
diplomacy: world.snapshot.diplomacy diplomacy: world.snapshot.diplomacy,
}; };
}; };
// 3. Try to Deploy // 3. Try to Deploy
const deployDef = deploySpec.createDefinition(systemEnv); const deployDef = deploySpec.createDefinition(systemEnv);
await runner.runTurn([{ await runner.runTurn([
generalId: 1, {
commandKey: 'che_출병', generalId: 1,
resolver: deployDef, commandKey: 'che_출병',
args: { destCityId: 2 }, resolver: deployDef,
context: buildDispatchContext(2) args: { destCityId: 2 },
}]); context: buildDispatchContext(2),
},
]);
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++) {
const entries: DiplomacyEntry[] = world.snapshot.diplomacy.map(s => ({ const entries: DiplomacyEntry[] = world.snapshot.diplomacy.map((s) => ({
fromNationId: s.fromNationId, fromNationId: s.fromNationId,
toNationId: s.toNationId, toNationId: s.toNationId,
state: s.state, state: s.state,
term: s.durationMonths, term: s.durationMonths,
dead: 0, dead: 0,
meta: {} meta: {},
})); }));
const updatedEntries = processDiplomacyMonth(entries, new Map()); const updatedEntries = processDiplomacyMonth(entries, new Map());
world.snapshot.diplomacy = updatedEntries.map(e => ({ world.snapshot.diplomacy = updatedEntries.map((e) => ({
fromNationId: e.fromNationId, fromNationId: e.fromNationId,
toNationId: e.toNationId, toNationId: e.toNationId,
state: e.state, state: e.state,
durationMonths: e.term durationMonths: e.term,
})); }));
runner.currentDate.setMonth(runner.currentDate.getMonth() + 1); runner.currentDate.setMonth(runner.currentDate.getMonth() + 1);
@@ -190,13 +265,15 @@ describe('Diplomacy Scenario', () => {
expect(diplomacyAB_After?.state).toBe(DIPLOMACY_STATE.WAR); expect(diplomacyAB_After?.state).toBe(DIPLOMACY_STATE.WAR);
// 5. Try to Deploy (Should Succeed) // 5. Try to Deploy (Should Succeed)
await runner.runTurn([{ await runner.runTurn([
generalId: 1, {
commandKey: 'che_출병', generalId: 1,
resolver: deployDef, commandKey: 'che_출병',
args: { destCityId: 2 }, resolver: deployDef,
context: buildDispatchContext(2) args: { destCityId: 2 },
}]); context: buildDispatchContext(2),
},
]);
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}`);
+139 -41
View File
@@ -1,4 +1,3 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { MINIMAL_MAP } from '../fixtures/minimalMap.js'; import { MINIMAL_MAP } from '../fixtures/minimalMap.js';
import { InMemoryWorld, TestGameRunner } from '../testEnv.js'; import { InMemoryWorld, TestGameRunner } from '../testEnv.js';
@@ -11,32 +10,83 @@ 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 // 1. Setup World
const mockNation: Nation = { const mockNation: Nation = {
id: 1, name: 'Test Nation', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1, id: 1,
gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: {} name: 'Test Nation',
color: '#FF0000',
capitalCityId: 1,
chiefGeneralId: 1,
gold: 10000,
rice: 10000,
power: 0,
level: 5,
typeCode: 'test',
meta: {},
}; };
const cityDef = MINIMAL_MAP.cities[0]; const cityDef = MINIMAL_MAP.cities[0];
if (!cityDef) throw new Error('City definition missing'); if (!cityDef) throw new Error('City definition missing');
const mockCity: City = { const mockCity: City = {
id: 1, name: cityDef.name, nationId: 1, level: 1, state: 0, id: 1,
population: 10000, populationMax: 10000, agriculture: 500, agricultureMax: 1000, name: cityDef.name,
commerce: 500, commerceMax: 1000, security: 500, securityMax: 1000, nationId: 1,
defence: 500, defenceMax: 1000, wall: 500, wallMax: 1000, level: 1,
supplyState: 1, frontState: 0, meta: {} state: 0,
population: 10000,
populationMax: 10000,
agriculture: 500,
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 = { const mockGeneral: General = {
id: 1, name: 'Domestic Officer', nationId: 1, cityId: 1, troopId: 0, npcState: 0, id: 1,
experience: 100, dedication: 100, officerLevel: 5, gold: 1000, rice: 1000, crew: 0, crewTypeId: 0, name: 'Domestic Officer',
train: 100, atmos: 100, injury: 0, age: 30, 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 }, stats: { leadership: 50, strength: 50, intelligence: 100 },
role: { personality: null, specialDomestic: null, specialWar: null, items: { horse: null, weapon: null, book: null, item: null } }, role: {
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, meta: {} 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' }, unitSet: { id: 'default', name: 'default' },
nations: [mockNation], nations: [mockNation],
@@ -45,7 +95,7 @@ describe('Domestic Affairs Scenario', () => {
troops: [], troops: [],
diplomacy: [], diplomacy: [],
events: [], events: [],
initialEvents: [] initialEvents: [],
}; };
const world = new InMemoryWorld(snapshot); const world = new InMemoryWorld(snapshot);
@@ -74,18 +124,20 @@ describe('Domestic Affairs Scenario', () => {
maxTechLevel: 10, maxTechLevel: 10,
baseGold: 1000, baseGold: 1000,
baseRice: 1000, baseRice: 1000,
maxResourceActionAmount: 1000 maxResourceActionAmount: 1000,
}; };
const farmingDef = developAgricultureSpec.createDefinition(systemEnv); const farmingDef = developAgricultureSpec.createDefinition(systemEnv);
// 3. Execute // 3. Execute
await runner.runTurn([{ await runner.runTurn([
generalId: 1, {
commandKey: 'che_농지개간', generalId: 1,
resolver: farmingDef, commandKey: 'che_농지개간',
args: {} resolver: farmingDef,
}]); args: {},
},
]);
// 4. Verify // 4. Verify
const updatedCity = world.getCity(1)!; const updatedCity = world.getCity(1)!;
@@ -96,23 +148,67 @@ describe('Domestic Affairs Scenario', () => {
it('should not increase agriculture when city is already maxed', async () => { it('should not increase agriculture when city is already maxed', async () => {
// Setup with max agriculture // Setup with max agriculture
const mockNation: Nation = { const mockNation: Nation = {
id: 1, name: 'Test Nation', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1, id: 1,
gold: 10000, rice: 10000, power: 0, level: 5, typeCode: 'test', meta: {} name: 'Test Nation',
color: '#FF0000',
capitalCityId: 1,
chiefGeneralId: 1,
gold: 10000,
rice: 10000,
power: 0,
level: 5,
typeCode: 'test',
meta: {},
}; };
const mockCity: City = { const mockCity: City = {
id: 1, name: 'City A', nationId: 1, level: 1, state: 0, id: 1,
population: 10000, populationMax: 10000, agriculture: 1000, agricultureMax: 1000, name: 'City A',
commerce: 500, commerceMax: 1000, security: 500, securityMax: 1000, nationId: 1,
defence: 500, defenceMax: 1000, wall: 500, wallMax: 1000, level: 1,
supplyState: 1, frontState: 0, meta: {} 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 = { const mockGeneral: General = {
id: 1, name: 'Domestic Officer', nationId: 1, cityId: 1, troopId: 0, npcState: 0, id: 1,
experience: 100, dedication: 100, officerLevel: 5, gold: 1000, rice: 1000, crew: 0, crewTypeId: 0, name: 'Domestic Officer',
train: 100, atmos: 100, injury: 0, age: 30, 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 }, stats: { leadership: 50, strength: 50, intelligence: 100 },
role: { personality: null, specialDomestic: null, specialWar: null, items: { horse: null, weapon: null, book: null, item: null } }, role: {
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, meta: {} 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 = {
@@ -124,7 +220,7 @@ describe('Domestic Affairs Scenario', () => {
troops: [], troops: [],
diplomacy: [], diplomacy: [],
events: [], events: [],
initialEvents: [] initialEvents: [],
}; };
const world = new InMemoryWorld(snapshot); const world = new InMemoryWorld(snapshot);
const runner = new TestGameRunner(world, 200, 1); const runner = new TestGameRunner(world, 200, 1);
@@ -132,12 +228,14 @@ describe('Domestic Affairs Scenario', () => {
const systemEnv: TurnCommandEnv = { develCost: 50 } as any; const systemEnv: TurnCommandEnv = { develCost: 50 } as any;
const farmingDef = developAgricultureSpec.createDefinition(systemEnv); const farmingDef = developAgricultureSpec.createDefinition(systemEnv);
await runner.runTurn([{ await runner.runTurn([
generalId: 1, {
commandKey: 'che_농지개간', generalId: 1,
resolver: farmingDef, commandKey: 'che_농지개간',
args: {} resolver: farmingDef,
}]); args: {},
},
]);
const updatedCity = world.getCity(1)!; const updatedCity = world.getCity(1)!;
expect(updatedCity.agriculture).toBe(1000); expect(updatedCity.agriculture).toBe(1000);
+91 -37
View File
@@ -1,4 +1,3 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { MINIMAL_MAP } from '../fixtures/minimalMap.js'; import { MINIMAL_MAP } from '../fixtures/minimalMap.js';
import { InMemoryWorld, TestGameRunner } from '../testEnv.js'; import { InMemoryWorld, TestGameRunner } from '../testEnv.js';
@@ -13,39 +12,88 @@ 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 World // 1. Setup World
const mockNation: Nation = { const mockNation: Nation = {
id: 1, name: 'Militaristic Nation', color: '#FF0000', capitalCityId: 1, chiefGeneralId: 1, id: 1,
gold: 50000, rice: 50000, power: 0, level: 5, typeCode: 'test', meta: {} name: 'Militaristic Nation',
color: '#FF0000',
capitalCityId: 1,
chiefGeneralId: 1,
gold: 50000,
rice: 50000,
power: 0,
level: 5,
typeCode: 'test',
meta: {},
}; };
const cityDef = MINIMAL_MAP.cities[0]; const cityDef = MINIMAL_MAP.cities[0];
if (!cityDef) throw new Error('City definition missing'); if (!cityDef) throw new Error('City definition missing');
const mockCity: City = { const mockCity: City = {
id: 1, name: cityDef.name, nationId: 1, level: 1, state: 0, id: 1,
population: 50000, populationMax: 50000, agriculture: 500, agricultureMax: 1000, name: cityDef.name,
commerce: 500, commerceMax: 1000, security: 500, securityMax: 1000, nationId: 1,
defence: 500, defenceMax: 1000, wall: 500, wallMax: 1000, level: 1,
supplyState: 1, frontState: 0, meta: {} state: 0,
population: 50000,
populationMax: 50000,
agriculture: 500,
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 = { const mockGeneral: General = {
id: 1, name: 'General Lee', nationId: 1, cityId: 1, troopId: 0, npcState: 0, id: 1,
experience: 100, dedication: 100, officerLevel: 5, gold: 1000, rice: 1000, crew: 0, crewTypeId: 1, name: 'General Lee',
train: 10, atmos: 10, injury: 0, age: 30, nationId: 1,
cityId: 1,
troopId: 0,
npcState: 0,
experience: 100,
dedication: 100,
officerLevel: 5,
gold: 1000,
rice: 1000,
crew: 0,
crewTypeId: 1,
train: 10,
atmos: 10,
injury: 0,
age: 30,
stats: { leadership: 100, strength: 100, intelligence: 50 }, stats: { leadership: 100, strength: 100, intelligence: 50 },
role: { personality: null, specialDomestic: null, specialWar: null, items: { horse: null, weapon: null, book: null, item: null } }, role: {
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, meta: {} 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: { unitSet: {
id: 'default', id: 'default',
name: 'default', name: 'default',
crewTypes: [ crewTypes: [{ id: 1, name: 'Infantry', armType: 1, cost: 10, requirements: [] }],
{ id: 1, name: 'Infantry', armType: 1, cost: 10, requirements: [] }
]
} as any, } as any,
nations: [mockNation], nations: [mockNation],
cities: [mockCity], cities: [mockCity],
@@ -53,7 +101,7 @@ describe('Troop Management Scenario', () => {
troops: [], troops: [],
diplomacy: [], diplomacy: [],
events: [], events: [],
initialEvents: [] initialEvents: [],
}; };
const world = new InMemoryWorld(snapshot); const world = new InMemoryWorld(snapshot);
@@ -81,17 +129,19 @@ describe('Troop Management Scenario', () => {
maxTechLevel: 10, maxTechLevel: 10,
baseGold: 1000, baseGold: 1000,
baseRice: 1000, baseRice: 1000,
maxResourceActionAmount: 1000 maxResourceActionAmount: 1000,
}; };
// 2. Draft Troops // 2. Draft Troops
const recruitDef = recruitSpec.createDefinition(systemEnv); const recruitDef = recruitSpec.createDefinition(systemEnv);
await runner.runTurn([{ await runner.runTurn([
generalId: 1, {
commandKey: 'che_징병', generalId: 1,
resolver: recruitDef, commandKey: 'che_징병',
args: { crewType: 1, amount: 1000 } resolver: recruitDef,
}]); args: { crewType: 1, amount: 1000 },
},
]);
const generalAfterDraft = world.getGeneral(1)!; const generalAfterDraft = world.getGeneral(1)!;
console.log(`Drafted: ${generalAfterDraft.crew}`); console.log(`Drafted: ${generalAfterDraft.crew}`);
@@ -99,12 +149,14 @@ describe('Troop Management Scenario', () => {
// 3. Train // 3. Train
const trainDef = trainSpec.createDefinition(systemEnv); const trainDef = trainSpec.createDefinition(systemEnv);
await runner.runTurn([{ await runner.runTurn([
generalId: 1, {
commandKey: 'che_훈련', generalId: 1,
resolver: trainDef, commandKey: 'che_훈련',
args: {} resolver: trainDef,
}]); args: {},
},
]);
const generalAfterTrain = world.getGeneral(1)!; const generalAfterTrain = world.getGeneral(1)!;
console.log(`Train: 10 -> ${generalAfterTrain.train}`); console.log(`Train: 10 -> ${generalAfterTrain.train}`);
@@ -112,12 +164,14 @@ describe('Troop Management Scenario', () => {
// 4. Boost Morale // 4. Boost Morale
const atmosDef = atmosSpec.createDefinition(systemEnv); const atmosDef = atmosSpec.createDefinition(systemEnv);
await runner.runTurn([{ await runner.runTurn([
generalId: 1, {
commandKey: 'che_사기진작', generalId: 1,
resolver: atmosDef, commandKey: 'che_사기진작',
args: {} resolver: atmosDef,
}]); args: {},
},
]);
const generalAfterAtmos = world.getGeneral(1)!; const generalAfterAtmos = world.getGeneral(1)!;
console.log(`Atmos: 10 -> ${generalAfterAtmos.atmos}`); console.log(`Atmos: 10 -> ${generalAfterAtmos.atmos}`);
+34 -34
View File
@@ -1,8 +1,11 @@
import { enablePatches } from 'immer'; import { enablePatches } from 'immer';
import type { City, General, Nation, GeneralId, NationId, CityId } 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'; import type { ScenarioDiplomacy } from '../src/scenario/types.js';
@@ -44,8 +47,8 @@ export class InMemoryWorld {
// Apply patches to the snapshot // Apply patches to the snapshot
if (resolution.patches) { if (resolution.patches) {
if (resolution.patches.generals) { if (resolution.patches.generals) {
this.snapshot.generals = this.snapshot.generals.map(g => { this.snapshot.generals = this.snapshot.generals.map((g) => {
const patchItem = resolution.patches!.generals.find(p => p.id === g.id); const patchItem = resolution.patches!.generals.find((p) => p.id === g.id);
if (patchItem) { if (patchItem) {
return { ...g, ...patchItem.patch } as General; return { ...g, ...patchItem.patch } as General;
} }
@@ -53,8 +56,8 @@ export class InMemoryWorld {
}); });
} }
if (resolution.patches.cities) { if (resolution.patches.cities) {
this.snapshot.cities = this.snapshot.cities.map(c => { this.snapshot.cities = this.snapshot.cities.map((c) => {
const patchItem = resolution.patches!.cities.find(p => p.id === c.id); const patchItem = resolution.patches!.cities.find((p) => p.id === c.id);
if (patchItem) { if (patchItem) {
return { ...c, ...patchItem.patch } as City; return { ...c, ...patchItem.patch } as City;
} }
@@ -62,8 +65,8 @@ export class InMemoryWorld {
}); });
} }
if (resolution.patches.nations) { if (resolution.patches.nations) {
this.snapshot.nations = this.snapshot.nations.map(n => { this.snapshot.nations = this.snapshot.nations.map((n) => {
const patchItem = resolution.patches!.nations.find(p => p.id === n.id); const patchItem = resolution.patches!.nations.find((p) => p.id === n.id);
if (patchItem) { if (patchItem) {
return { ...n, ...patchItem.patch } as Nation; return { ...n, ...patchItem.patch } as Nation;
} }
@@ -93,14 +96,16 @@ export class InMemoryWorld {
const existing = this.getDiplomacy(srcId, destId); const existing = this.getDiplomacy(srcId, destId);
// Convert ScenarioDiplomacy to DiplomacyEntry for applying patch // Convert ScenarioDiplomacy to DiplomacyEntry for applying patch
const entry: DiplomacyEntry = existing ? { const entry: DiplomacyEntry = existing
fromNationId: existing.fromNationId, ? {
toNationId: existing.toNationId, fromNationId: existing.fromNationId,
state: existing.state, toNationId: existing.toNationId,
term: existing.durationMonths, state: existing.state,
dead: 0, term: existing.durationMonths,
meta: {} dead: 0,
} : buildDefaultDiplomacy(srcId, destId); meta: {},
}
: buildDefaultDiplomacy(srcId, destId);
const patched = applyDiplomacyPatch(entry, effect.patch); const patched = applyDiplomacyPatch(entry, effect.patch);
this.updateDiplomacy(patched); this.updateDiplomacy(patched);
@@ -110,7 +115,7 @@ export class InMemoryWorld {
} }
private updateGeneral(updated: General) { private updateGeneral(updated: General) {
const idx = this.snapshot.generals.findIndex(g => g.id === updated.id); const idx = this.snapshot.generals.findIndex((g) => g.id === updated.id);
if (idx >= 0) { if (idx >= 0) {
this.snapshot.generals[idx] = updated; this.snapshot.generals[idx] = updated;
} else { } else {
@@ -119,21 +124,21 @@ export class InMemoryWorld {
} }
private updateCity(updated: City) { private updateCity(updated: City) {
const idx = this.snapshot.cities.findIndex(c => c.id === updated.id); const idx = this.snapshot.cities.findIndex((c) => c.id === updated.id);
if (idx >= 0) { if (idx >= 0) {
this.snapshot.cities[idx] = updated; this.snapshot.cities[idx] = updated;
} }
} }
private updateNation(updated: Nation) { private updateNation(updated: Nation) {
const idx = this.snapshot.nations.findIndex(n => n.id === updated.id); const idx = this.snapshot.nations.findIndex((n) => n.id === updated.id);
if (idx >= 0) { if (idx >= 0) {
this.snapshot.nations[idx] = updated; this.snapshot.nations[idx] = updated;
} }
} }
getDiplomacy(srcId: number, destId: number): ScenarioDiplomacy | 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) {
@@ -141,10 +146,12 @@ export class InMemoryWorld {
fromNationId: entry.fromNationId, fromNationId: entry.fromNationId,
toNationId: entry.toNationId, toNationId: entry.toNationId,
state: entry.state, state: entry.state,
durationMonths: entry.term 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] = scenarioEntry; this.snapshot.diplomacy[idx] = scenarioEntry;
} else { } else {
@@ -172,9 +179,7 @@ export class TestGameRunner {
async runTurn(commands: TestCommand[]) { async runTurn(commands: TestCommand[]) {
const schedule: TurnSchedule = { const schedule: TurnSchedule = {
entries: [ entries: [{ startMinute: 0, tickMinutes: 60 }],
{ startMinute: 0, tickMinutes: 60 }
]
}; };
for (const cmd of commands) { for (const cmd of commands) {
@@ -194,7 +199,7 @@ export class TestGameRunner {
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, nextInt: (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min,
next: () => Math.random() next: () => Math.random(),
} as any, } as any,
year: this.currentDate.getFullYear(), year: this.currentDate.getFullYear(),
@@ -203,20 +208,15 @@ export class TestGameRunner {
map: this.world.snapshot.map, map: this.world.snapshot.map,
unitSet: this.world.snapshot.unitSet, unitSet: this.world.snapshot.unitSet,
cities: this.world.snapshot.cities, cities: this.world.snapshot.cities,
...cmd.context ...cmd.context,
}; };
const scheduleContext = { const scheduleContext = {
now: this.currentDate, now: this.currentDate,
schedule schedule,
}; };
const resolution = resolveGeneralAction( const resolution = resolveGeneralAction(cmd.resolver, inputContext as any, scheduleContext, cmd.args);
cmd.resolver,
inputContext as any,
scheduleContext,
cmd.args
);
await this.world.applyResolution(resolution); await this.world.applyResolution(resolution);
} }
+2 -1
View File
@@ -22,7 +22,8 @@
}, },
"include": [ "include": [
"src", "src",
"test" "test",
"*.ts"
], ],
"references": [ "references": [
{ {