diff --git a/app/game-api/src/router/join/index.ts b/app/game-api/src/router/join/index.ts index af6371b..a086c0c 100644 --- a/app/game-api/src/router/join/index.ts +++ b/app/game-api/src/router/join/index.ts @@ -30,6 +30,28 @@ const DEFAULT_JOIN_STAT = { bonusMax: 5, }; +const buildSpecialityAge = ( + retirementYear: number, + age: number, + relativeYear: number, + divisor: number +): number => Math.max(Math.round((retirementYear - age) / divisor - relativeYear / 2), 3) + age; + +export const resolveJoinSpecialityAges = (options: { + retirementYear: number; + age: number; + relativeYear: number; + scenarioId: number; +}): { domestic: number; war: number } => { + if (Number.isFinite(options.scenarioId) && options.scenarioId >= 1000) { + return { domestic: options.age + 3, war: options.age + 3 }; + } + return { + domestic: buildSpecialityAge(options.retirementYear, options.age, options.relativeYear, 12), + war: buildSpecialityAge(options.retirementYear, options.age, options.relativeYear, 6), + }; +}; + const resolveJoinStat = (worldState: WorldStateRow) => { const config = asRecord(worldState.config); const stat = asRecord(config.stat); @@ -456,6 +478,27 @@ export const joinRouter = router({ typeof configConst.defaultSpecialDomestic === 'string' ? configConst.defaultSpecialDomestic : 'None'; const defaultSpecialWar = typeof configConst.defaultSpecialWar === 'string' ? configConst.defaultSpecialWar : 'None'; + const retirementYear = + typeof configConst.retirementYear === 'number' && Number.isFinite(configConst.retirementYear) + ? configConst.retirementYear + : 80; + const worldMeta = asRecord(worldState.meta); + const scenarioMeta = asRecord(worldMeta.scenarioMeta); + const startYear = + typeof scenarioMeta.startYear === 'number' && Number.isFinite(scenarioMeta.startYear) + ? scenarioMeta.startYear + : worldState.currentYear; + const relativeYear = Math.max( + worldState.currentYear - startYear, + 0 + ); + const scenarioId = Number(worldMeta.scenarioId ?? worldState.scenarioCode); + const specialityAges = resolveJoinSpecialityAges({ + retirementYear, + age, + relativeYear, + scenarioId, + }); const specialWar = input.inheritSpecial && isWarTraitKey(input.inheritSpecial) ? input.inheritSpecial : defaultSpecialWar; @@ -515,6 +558,8 @@ export const joinRouter = router({ createdBy: 'join', ownerName: ctx.auth?.user.displayName ?? '', killturn: 24, + specage: specialityAges.domestic, + specage2: specialityAges.war, }, }, }); diff --git a/app/game-api/test/joinSpecialityAge.test.ts b/app/game-api/test/joinSpecialityAge.test.ts new file mode 100644 index 0000000..233771b --- /dev/null +++ b/app/game-api/test/joinSpecialityAge.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; + +import { resolveJoinSpecialityAges } from '../src/router/join/index.js'; + +describe('join speciality ages', () => { + it('uses the legacy retirement formula outside custom scenarios', () => { + expect( + resolveJoinSpecialityAges({ + retirementYear: 80, + age: 20, + relativeYear: 0, + scenarioId: 910, + }) + ).toEqual({ domestic: 25, war: 30 }); + expect( + resolveJoinSpecialityAges({ + retirementYear: 80, + age: 30, + relativeYear: 4, + scenarioId: 910, + }) + ).toEqual({ domestic: 33, war: 36 }); + }); + + it('forces both speciality ages to age plus three for scenario 1000 and above', () => { + expect( + resolveJoinSpecialityAges({ + retirementYear: 80, + age: 26, + relativeYear: 7, + scenarioId: 2220, + }) + ).toEqual({ domestic: 29, war: 29 }); + }); +}); diff --git a/app/game-engine/src/scenario/scenarioSeeder.ts b/app/game-engine/src/scenario/scenarioSeeder.ts index 93e4b61..d9e1dd0 100644 --- a/app/game-engine/src/scenario/scenarioSeeder.ts +++ b/app/game-engine/src/scenario/scenarioSeeder.ts @@ -427,6 +427,7 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom itemCode: general.item ?? 'None', turnTime: now, age: resolveGeneralAge(scenario.startYear ?? null, general.birthYear), + startAge: resolveGeneralAge(scenario.startYear ?? null, general.birthYear), personalCode: general.personality ?? 'None', specialCode: general.special ?? 'None', special2Code: general.specialWar ?? 'None', diff --git a/app/game-engine/src/turn/monthlySpecialityBetrayAction.ts b/app/game-engine/src/turn/monthlySpecialityBetrayAction.ts new file mode 100644 index 0000000..830ed0f --- /dev/null +++ b/app/game-engine/src/turn/monthlySpecialityBetrayAction.ts @@ -0,0 +1,262 @@ +import { JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common'; +import { + LogCategory, + LogFormat, + LogScope, + TraitSelector, + WAR_TRAIT_KEYS, + loadDomesticTraitModules, + loadWarTraitModules, + type TraitModule, +} from '@sammo-ts/logic'; +import { simpleSerialize } from '@sammo-ts/logic/war/utils.js'; + +import type { InMemoryTurnWorld } from './inMemoryWorld.js'; +import type { MonthlyEventActionHandler, MonthlyEventEnvironment } from './monthlyEventHandler.js'; +import type { TurnGeneral } from './types.js'; + +const LEGACY_DOMESTIC_SELECTION_KEYS = [ + 'che_경작', + 'che_상재', + 'che_발명', + 'che_축성', + 'che_수비', + 'che_통찰', + 'che_인덕', + 'che_귀모', +] as const; + +const normalizeCode = (value: unknown): string | null => + typeof value === 'string' && value !== '' && value !== 'None' ? value : null; + +const readFiniteNumber = (source: Record, keys: readonly string[]): number | null => { + for (const key of keys) { + const value = source[key]; + if (typeof value === 'number' && Number.isFinite(value)) { + return value; + } + } + return null; +}; + +const readStringList = (source: Record, key: string): string[] => { + const value = source[key]; + return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []; +}; + +const resolveHiddenSeed = (world: InMemoryTurnWorld): string | number => { + const state = world.getState(); + const value = state.meta.hiddenSeed ?? state.meta.seed ?? state.id; + return typeof value === 'string' || typeof value === 'number' ? value : String(value); +}; + +const readRuntimeNumber = (world: InMemoryTurnWorld, key: string, fallback: number): number => { + const value = world.getScenarioConfig().const[key]; + return typeof value === 'number' && Number.isFinite(value) ? value : fallback; +}; + +const buildSpecialityAge = ( + retirementYear: number, + age: number, + relativeYear: number, + divisor: number +): number => Math.max(Math.round((retirementYear - age) / divisor - relativeYear / 2), 3) + age; + +const resolveSpecialityAge = ( + general: TurnGeneral, + environment: MonthlyEventEnvironment, + retirementYear: number, + kind: 'domestic' | 'war' +): number => { + const stored = readFiniteNumber( + general.meta, + kind === 'domestic' ? ['specage', 'specAge'] : ['specage2', 'specAge2'] + ); + if (stored !== null) { + return stored; + } + + const currentRelativeYear = Math.max(environment.year - environment.startyear, 0); + const startAge = + typeof general.startAge === 'number' && Number.isFinite(general.startAge) + ? general.startAge + : general.age - currentRelativeYear; + const yearsSinceCreation = Math.max(general.age - startAge, 0); + const creationRelativeYear = Math.max(currentRelativeYear - yearsSinceCreation, 0); + return buildSpecialityAge(retirementYear, startAge, creationRelativeYear, kind === 'domestic' ? 12 : 6); +}; + +const pushSpecialityLogs = ( + world: InMemoryTurnWorld, + general: TurnGeneral, + traitName: string, + environment: MonthlyEventEnvironment +): void => { + const josaUl = JosaUtil.pick(traitName, '을'); + world.pushLog({ + scope: LogScope.GENERAL, + category: LogCategory.HISTORY, + generalId: general.id, + text: `특기 【${traitName}】${josaUl} 습득`, + format: LogFormat.YEAR_MONTH, + year: environment.year, + month: environment.month, + }); + world.pushLog({ + scope: LogScope.GENERAL, + category: LogCategory.ACTION, + generalId: general.id, + text: `특기 【${traitName}】${josaUl} 익혔습니다!`, + format: LogFormat.PLAIN, + year: environment.year, + month: environment.month, + }); +}; + +const resolveTrait = (modules: readonly TraitModule[], key: string, label: string): TraitModule => { + const module = modules.find((candidate) => candidate.key === key); + if (!module) { + throw new Error(`Unknown ${label} speciality: ${key}`); + } + return module; +}; + +export const createAssignGeneralSpecialityHandler = (options: { + getWorld: () => InMemoryTurnWorld | null; +}): MonthlyEventActionHandler => { + let modulePromise: + | Promise<{ domesticModules: TraitModule[]; warModules: TraitModule[] }> + | undefined; + const loadModules = () => { + modulePromise ??= Promise.all([ + loadDomesticTraitModules([...LEGACY_DOMESTIC_SELECTION_KEYS]), + loadWarTraitModules([...WAR_TRAIT_KEYS]), + ]).then(([domesticModules, warModules]) => ({ domesticModules, warModules })); + return modulePromise; + }; + + return async (_args, environment) => { + const world = options.getWorld(); + if (!world || environment.year < environment.startyear + 3) { + return; + } + const { domesticModules, warModules } = await loadModules(); + const rng = new RandUtil( + new LiteHashDRBG( + simpleSerialize(resolveHiddenSeed(world), 'assignGeneralSpeciality', environment.year, environment.month) + ) + ); + const defaultDomestic = normalizeCode(world.getScenarioConfig().const.defaultSpecialDomestic); + const defaultWar = normalizeCode(world.getScenarioConfig().const.defaultSpecialWar); + const retirementYear = readRuntimeNumber(world, 'retirementYear', 80); + const scenarioStat = world.getScenarioConfig().stat; + // ref SQL에 ORDER BY가 없으므로 loader가 보존한 DB scan 순서를 두 + // domestic/war pass에서 그대로 재사용한다. + const generals = world.listGenerals(); + + for (const general of generals) { + if ( + general.role.specialDomestic !== defaultDomestic || + resolveSpecialityAge(general, environment, retirementYear, 'domestic') > general.age + ) { + continue; + } + const key = TraitSelector.pickDomesticTrait( + rng, + general.stats, + domesticModules, + readStringList(general.meta, 'prev_types_special'), + scenarioStat + ); + if (!key) { + throw new Error(`Unable to assign domestic speciality (generalId=${general.id}).`); + } + const trait = resolveTrait(domesticModules, key, 'domestic'); + world.updateGeneral(general.id, { + role: { ...general.role, specialDomestic: key }, + }); + pushSpecialityLogs(world, general, trait.name, environment); + } + + for (const general of generals) { + const currentGeneral = world.getGeneralById(general.id) ?? general; + if ( + currentGeneral.role.specialWar !== defaultWar || + resolveSpecialityAge(currentGeneral, environment, retirementYear, 'war') > currentGeneral.age + ) { + continue; + } + const inherited = currentGeneral.meta.inheritSpecificSpecialWar; + let key: string | null; + let meta = currentGeneral.meta; + let removeInherited = false; + if (Object.prototype.hasOwnProperty.call(currentGeneral.meta, 'inheritSpecificSpecialWar')) { + if (typeof inherited !== 'string') { + throw new Error(`Invalid inherited war speciality (generalId=${currentGeneral.id}).`); + } + key = inherited; + removeInherited = true; + } else { + key = TraitSelector.pickWarTrait( + rng, + currentGeneral.stats, + [ + readFiniteNumber(currentGeneral.meta, ['dex1']) ?? 0, + readFiniteNumber(currentGeneral.meta, ['dex2']) ?? 0, + readFiniteNumber(currentGeneral.meta, ['dex3']) ?? 0, + readFiniteNumber(currentGeneral.meta, ['dex4']) ?? 0, + readFiniteNumber(currentGeneral.meta, ['dex5']) ?? 0, + ], + warModules, + readStringList(currentGeneral.meta, 'prev_types_special2'), + scenarioStat + ); + } + if (!key) { + throw new Error(`Unable to assign war speciality (generalId=${currentGeneral.id}).`); + } + const trait = resolveTrait(warModules, key, 'war'); + if (removeInherited) { + delete currentGeneral.meta.inheritSpecificSpecialWar; + meta = { ...currentGeneral.meta }; + } + world.updateGeneral(currentGeneral.id, { + role: { ...currentGeneral.role, specialWar: key }, + meta, + }); + pushSpecialityLogs(world, currentGeneral, trait.name, environment); + } + }; +}; + +const readOptionalInteger = (value: unknown, fallback: number, label: string): number => { + if (value === undefined) { + return fallback; + } + if (typeof value !== 'number' || !Number.isInteger(value)) { + throw new Error(`${label} must be an integer.`); + } + return value; +}; + +export const createAddGlobalBetrayHandler = (options: { + getWorld: () => InMemoryTurnWorld | null; +}): MonthlyEventActionHandler => { + return (args) => { + const world = options.getWorld(); + if (!world) { + return; + } + const count = readOptionalInteger(args[0], 1, 'AddGlobalBetray count'); + const maximum = readOptionalInteger(args[1], 0, 'AddGlobalBetray maximum'); + for (const general of world.listGenerals()) { + const betray = readFiniteNumber(general.meta, ['betray']) ?? 0; + if (betray > maximum) { + continue; + } + world.updateGeneral(general.id, { + meta: { ...general.meta, betray: betray + count }, + }); + } + }; +}; diff --git a/app/game-engine/src/turn/turnDaemon.ts b/app/game-engine/src/turn/turnDaemon.ts index 27955dd..0ff3cd6 100644 --- a/app/game-engine/src/turn/turnDaemon.ts +++ b/app/game-engine/src/turn/turnDaemon.ts @@ -66,6 +66,10 @@ import { createOpenNationBettingHandler, } from './monthlyNationBettingAction.js'; import { createScoutBlockHandler } from './monthlyScoutBlockAction.js'; +import { + createAddGlobalBetrayHandler, + createAssignGeneralSpecialityHandler, +} from './monthlySpecialityBetrayAction.js'; import { buildCommandEnv } from './reservedTurnCommands.js'; import { DatabaseTurnDaemonLease, TurnDaemonLeaseUnavailableError } from '../lifecycle/databaseTurnDaemonLease.js'; @@ -358,6 +362,18 @@ const createTurnDaemonRuntimeWithLease = async ( }) ); } + eventActions.set( + 'AssignGeneralSpeciality', + createAssignGeneralSpecialityHandler({ + getWorld: () => worldRef, + }) + ); + eventActions.set( + 'AddGlobalBetray', + createAddGlobalBetrayHandler({ + getWorld: () => worldRef, + }) + ); eventActions.set('ProcessIncome', async (_args, environment) => { await incomeHandler.onMonthChanged?.({ previousYear: environment.month === 1 ? environment.year - 1 : environment.year, diff --git a/app/game-engine/src/turn/types.ts b/app/game-engine/src/turn/types.ts index 87e7c74..957a5b4 100644 --- a/app/game-engine/src/turn/types.ts +++ b/app/game-engine/src/turn/types.ts @@ -22,6 +22,7 @@ export interface TurnWorldState { export interface TurnGeneral extends General { userId?: string | null; + startAge?: number; bornYear?: number; deadYear?: number; affinity?: number | null; diff --git a/app/game-engine/src/turn/worldLoader.ts b/app/game-engine/src/turn/worldLoader.ts index e7229e6..0567674 100644 --- a/app/game-engine/src/turn/worldLoader.ts +++ b/app/game-engine/src/turn/worldLoader.ts @@ -200,6 +200,7 @@ const mapGeneralRow = (row: TurnEngineGeneralRow): TurnGeneral => { train: row.train, atmos: row.atmos, age: row.age, + startAge: row.startAge, npcState: row.npcState, bornYear: row.bornYear, deadYear: row.deadYear, diff --git a/app/game-engine/test/monthlySpecialityBetrayAction.test.ts b/app/game-engine/test/monthlySpecialityBetrayAction.test.ts new file mode 100644 index 0000000..04b5d4e --- /dev/null +++ b/app/game-engine/test/monthlySpecialityBetrayAction.test.ts @@ -0,0 +1,273 @@ +import { describe, expect, it } from 'vitest'; +import { LogCategory, LogFormat } from '@sammo-ts/logic'; + +import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js'; +import { + createAddGlobalBetrayHandler, + createAssignGeneralSpecialityHandler, +} from '../src/turn/monthlySpecialityBetrayAction.js'; +import type { TurnEvent, TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js'; + +const event: TurnEvent = { + id: 1, + targetCode: 'month', + priority: 9_000, + condition: true, + action: [], + meta: {}, +}; + +const buildGeneral = (options: { + id: number; + name: string; + nationId: number; + stats: [number, number, number]; + specialDomestic: string | null; + specialWar: string | null; + meta: Record; +}): TurnGeneral => ({ + id: options.id, + userId: null, + name: options.name, + nationId: options.nationId, + cityId: options.id === 1 ? 1 : 2, + troopId: 0, + stats: { + leadership: options.stats[0], + strength: options.stats[1], + intelligence: options.stats[2], + }, + experience: 0, + dedication: 0, + officerLevel: 1, + role: { + personality: null, + specialDomestic: options.specialDomestic, + specialWar: options.specialWar, + items: { horse: null, weapon: null, book: null, item: null }, + }, + injury: 0, + gold: 1_000, + rice: 1_000, + crew: 0, + crewTypeId: 0, + train: 0, + atmos: 0, + age: 30, + startAge: 20, + npcState: 2, + triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, + meta: { ...options.meta, killturn: 24 }, + lastTurn: { command: '휴식' }, + turnTime: new Date('0200-01-01T00:00:00.000Z'), +}); + +const buildWorld = (hiddenSeed = 'monthly-speciality-fixture') => { + const state: TurnWorldState = { + id: 1, + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + lastTurnTime: new Date('0200-01-01T00:00:00.000Z'), + meta: { hiddenSeed }, + }; + const scenarioConfig: TurnWorldSnapshot['scenarioConfig'] = { + stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 75, npcMin: 10, chiefMin: 70 }, + iconPath: '.', + map: {}, + const: { + defaultSpecialDomestic: 'None', + defaultSpecialWar: 'None', + retirementYear: 80, + }, + environment: { mapName: 'test', unitSet: 'default' }, + }; + const domesticGeneral = buildGeneral({ + id: 1, + name: '내정대상', + nationId: 1, + stats: [40, 45, 80], + specialDomestic: null, + specialWar: 'che_신산', + meta: { specage: 30, specage2: 99, prev_types_special: ['che_경작'] }, + }); + const warGeneral = buildGeneral({ + id: 2, + name: '전투대상', + nationId: 1, + stats: [80, 75, 40], + specialDomestic: 'che_인덕', + specialWar: null, + meta: { + specage: 99, + specage2: 30, + prev_types_special2: ['che_돌격'], + dex1: 200, + dex2: 10, + dex3: 10, + dex4: 10, + dex5: 10, + }, + }); + const inheritedGeneral = buildGeneral({ + id: 3, + name: '계승대상', + nationId: 2, + stats: [50, 50, 50], + specialDomestic: 'che_경작', + specialWar: null, + meta: { specage: 99, specage2: 30, inheritSpecificSpecialWar: 'che_의술', marker: 3 }, + }); + // The isolated Aria fixture scans eligible war rows as 3, 2 because the + // legacy query has no ORDER BY. Preserve that input order in this trace. + const generals = [domesticGeneral, inheritedGeneral, warGeneral]; + return new InMemoryTurnWorld( + state, + { + scenarioConfig, + map: { id: 'test', name: 'test', cities: [] }, + generals, + cities: [], + nations: [], + troops: [], + diplomacy: [], + events: [event], + initialEvents: [], + }, + { schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] } } + ); +}; + +const environment = { + year: 200, + month: 1, + startyear: 190, + currentEventID: 1, + turnTime: new Date('0200-01-01T00:00:00.000Z'), +}; + +describe('monthly speciality and betrayal actions', () => { + it('assigns eligible traits, consumes inherited war choice without RNG, and writes legacy logs', async () => { + const world = buildWorld(); + await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], environment, event); + + expect(world.getGeneralById(1)?.role.specialDomestic).not.toBeNull(); + expect(world.getGeneralById(1)?.role.specialDomestic).not.toBe('che_경작'); + expect(world.getGeneralById(2)?.role.specialWar).not.toBeNull(); + expect(world.getGeneralById(2)?.role.specialWar).not.toBe('che_돌격'); + expect(world.getGeneralById(3)?.role.specialWar).toBe('che_의술'); + expect(world.getGeneralById(3)?.meta).toEqual(expect.objectContaining({ marker: 3, killturn: 24 })); + expect(world.getGeneralById(3)?.meta).not.toHaveProperty('inheritSpecificSpecialWar'); + + const logs = world.peekDirtyState().logs; + expect(logs).toHaveLength(6); + expect(logs.slice(2, 4)).toEqual([ + expect.objectContaining({ + generalId: 3, + category: LogCategory.HISTORY, + format: LogFormat.YEAR_MONTH, + text: '특기 【의술】을 습득', + }), + expect.objectContaining({ + generalId: 3, + category: LogCategory.ACTION, + format: LogFormat.PLAIN, + text: '특기 【의술】을 익혔습니다!', + }), + ]); + }); + + it('does nothing before the three-year opening period ends', async () => { + const world = buildWorld(); + await createAssignGeneralSpecialityHandler({ getWorld: () => world })( + [], + { ...environment, year: 192 }, + event + ); + expect(world.peekDirtyState().generals).toEqual([]); + expect(world.peekDirtyState().logs).toEqual([]); + }); + + it('preserves a domestic trait when the same general also receives a war trait', async () => { + const world = buildWorld(); + const general = world.getGeneralById(1)!; + world.updateGeneral(1, { + role: { ...general.role, specialWar: null }, + meta: { ...general.meta, specage2: 30 }, + }); + world.acknowledgeDirtyState(world.peekDirtyState()); + + await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], environment, event); + + expect(world.getGeneralById(1)?.role.specialDomestic).not.toBeNull(); + expect(world.getGeneralById(1)?.role.specialWar).not.toBeNull(); + }); + + it('applies the two default scenario betrayal steps only to values within each threshold', async () => { + const world = buildWorld(); + world.updateGeneral(1, { meta: { ...world.getGeneralById(1)!.meta, betray: 0 } }); + world.updateGeneral(2, { meta: { ...world.getGeneralById(2)!.meta, betray: 1 } }); + world.updateGeneral(3, { meta: { ...world.getGeneralById(3)!.meta, betray: 2 } }); + world.acknowledgeDirtyState(world.peekDirtyState()); + const handler = createAddGlobalBetrayHandler({ getWorld: () => world }); + + await handler([1, 0], environment, event); + await handler([1, 1], environment, event); + + expect(world.listGenerals().map((general) => general.meta.betray)).toEqual([2, 2, 2]); + }); + + it.skipIf(!process.env.REF_HIDDEN_SEED)('matches the isolated legacy fixed-seed trait choices', async () => { + const world = buildWorld(process.env.REF_HIDDEN_SEED); + await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], environment, event); + + expect(world.getGeneralById(1)?.role.specialDomestic).toBe('che_상재'); + expect(world.getGeneralById(2)?.role.specialWar).toBe('che_필살'); + expect(world.getGeneralById(3)?.role.specialWar).toBe('che_의술'); + expect( + world.peekDirtyState().logs.map((log) => ({ + generalId: log.generalId, + category: log.category, + text: log.text, + format: log.format, + })) + ).toEqual([ + { + generalId: 1, + category: LogCategory.HISTORY, + text: '특기 【상재】를 습득', + format: LogFormat.YEAR_MONTH, + }, + { + generalId: 1, + category: LogCategory.ACTION, + text: '특기 【상재】를 익혔습니다!', + format: LogFormat.PLAIN, + }, + { + generalId: 3, + category: LogCategory.HISTORY, + text: '특기 【의술】을 습득', + format: LogFormat.YEAR_MONTH, + }, + { + generalId: 3, + category: LogCategory.ACTION, + text: '특기 【의술】을 익혔습니다!', + format: LogFormat.PLAIN, + }, + { + generalId: 2, + category: LogCategory.HISTORY, + text: '특기 【필살】을 습득', + format: LogFormat.YEAR_MONTH, + }, + { + generalId: 2, + category: LogCategory.ACTION, + text: '특기 【필살】을 익혔습니다!', + format: LogFormat.PLAIN, + }, + ]); + }); +}); diff --git a/app/game-engine/test/monthlySpecialityBetrayPersistence.integration.test.ts b/app/game-engine/test/monthlySpecialityBetrayPersistence.integration.test.ts new file mode 100644 index 0000000..12c3913 --- /dev/null +++ b/app/game-engine/test/monthlySpecialityBetrayPersistence.integration.test.ts @@ -0,0 +1,221 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { Nation } from '@sammo-ts/logic'; +import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra'; + +import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js'; +import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js'; +import { + createAddGlobalBetrayHandler, + createAssignGeneralSpecialityHandler, +} from '../src/turn/monthlySpecialityBetrayAction.js'; +import type { TurnEvent, TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js'; + +const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL; +const integration = describe.skipIf(!databaseUrl); +const nationId = 990_091; +const generalIds = [990_091, 990_092] as const; + +const event: TurnEvent = { + id: 1, + targetCode: 'month', + priority: 9_000, + condition: true, + action: [], + meta: {}, +}; + +const nation: Nation = { + id: nationId, + name: '특기검증국', + color: '#777777', + capitalCityId: null, + chiefGeneralId: null, + gold: 0, + rice: 0, + power: 0, + level: 2, + typeCode: 'che_중립', + meta: {}, +}; + +const buildGeneral = ( + id: number, + options: { domestic: string | null; war: string | null; meta: Record } +): TurnGeneral => ({ + id, + userId: null, + name: id === generalIds[0] ? '영속내정대상' : '영속계승대상', + nationId, + cityId: 0, + troopId: 0, + stats: { leadership: 40, strength: 45, intelligence: 80 }, + experience: 0, + dedication: 0, + officerLevel: 1, + role: { + personality: null, + specialDomestic: options.domestic, + specialWar: options.war, + items: { horse: null, weapon: null, book: null, item: null }, + }, + injury: 0, + gold: 1_000, + rice: 1_000, + crew: 0, + crewTypeId: 0, + train: 0, + atmos: 0, + age: 30, + startAge: 20, + npcState: 2, + triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} }, + meta: { ...options.meta, killturn: 24 }, + lastTurn: { command: '휴식' }, + turnTime: new Date('2026-07-25T00:00:00.000Z'), +}); + +integration('monthly speciality and betrayal persistence', () => { + let db: GamePrismaClient; + let closeDb: (() => Promise) | undefined; + + beforeAll(async () => { + const connector = createGamePostgresConnector({ url: databaseUrl! }); + await connector.connect(); + db = connector.prisma; + closeDb = () => connector.disconnect(); + await db.logEntry.deleteMany({ where: { generalId: { in: [...generalIds] } } }); + await db.general.deleteMany({ where: { id: { in: [...generalIds] } } }); + await db.nation.deleteMany({ where: { id: nationId } }); + }); + + afterAll(async () => { + await db.logEntry.deleteMany({ where: { generalId: { in: [...generalIds] } } }); + await db.general.deleteMany({ where: { id: { in: [...generalIds] } } }); + await db.nation.deleteMany({ where: { id: nationId } }); + await closeDb?.(); + }); + + it('flushes trait columns, inherited aux removal, betrayal, and four general logs', async () => { + const generals = [ + buildGeneral(generalIds[0], { + domestic: null, + war: 'che_신산', + meta: { specage: 30, specage2: 99, betray: 0 }, + }), + buildGeneral(generalIds[1], { + domestic: 'che_경작', + war: null, + meta: { + specage: 99, + specage2: 30, + betray: 1, + inheritSpecificSpecialWar: 'che_의술', + marker: 2, + }, + }), + ]; + await db.nation.create({ + data: { + id: nation.id, + name: nation.name, + color: nation.color, + level: nation.level, + typeCode: nation.typeCode, + meta: {}, + }, + }); + await db.general.createMany({ + data: generals.map((general) => ({ + id: general.id, + name: general.name, + nationId: general.nationId, + cityId: general.cityId, + leadership: general.stats.leadership, + strength: general.stats.strength, + intel: general.stats.intelligence, + age: general.age, + startAge: general.startAge, + specialCode: general.role.specialDomestic ?? 'None', + special2Code: general.role.specialWar ?? 'None', + turnTime: general.turnTime, + meta: general.meta, + })), + }); + const row = await db.worldState.create({ + data: { + scenarioCode: 'monthly-speciality-betray-persistence', + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + config: {}, + meta: { hiddenSeed: 'monthly-speciality-persistence' }, + }, + }); + const state: TurnWorldState = { + id: row.id, + currentYear: 200, + currentMonth: 1, + tickSeconds: 600, + lastTurnTime: new Date('2026-07-25T00:00:00.000Z'), + meta: { hiddenSeed: 'monthly-speciality-persistence' }, + }; + const snapshot: TurnWorldSnapshot = { + scenarioConfig: { + stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 75, npcMin: 10, chiefMin: 70 }, + iconPath: '.', + map: {}, + const: { + defaultSpecialDomestic: 'None', + defaultSpecialWar: 'None', + retirementYear: 80, + }, + environment: { mapName: 'test', unitSet: 'default' }, + }, + map: { id: 'test', name: 'test', cities: [] }, + generals, + cities: [], + nations: [nation], + troops: [], + diplomacy: [], + events: [event], + initialEvents: [], + }; + const world = new InMemoryTurnWorld(state, snapshot, { + schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] }, + }); + const hooks = await createDatabaseTurnHooks(databaseUrl!, world); + const environment = { + year: 200, + month: 1, + startyear: 190, + currentEventID: 1, + turnTime: state.lastTurnTime, + }; + + try { + await createAssignGeneralSpecialityHandler({ getWorld: () => world })([], environment, event); + await createAddGlobalBetrayHandler({ getWorld: () => world })([2, 1], environment, event); + await hooks.hooks.flushChanges?.({ + lastTurnTime: state.lastTurnTime.toISOString(), + processedGenerals: 0, + processedTurns: 2, + durationMs: 0, + partial: false, + }); + + const rows = await db.general.findMany({ + where: { id: { in: [...generalIds] } }, + orderBy: { id: 'asc' }, + }); + expect(rows[0]?.specialCode).not.toBe('None'); + expect(rows[0]?.meta).toMatchObject({ betray: 2 }); + expect(rows[1]).toMatchObject({ special2Code: 'che_의술' }); + expect(rows[1]?.meta).toMatchObject({ betray: 3, marker: 2 }); + expect(rows[1]?.meta).not.toHaveProperty('inheritSpecificSpecialWar'); + expect(await db.logEntry.count({ where: { generalId: { in: [...generalIds] } } })).toBe(4); + } finally { + await hooks.close(); + await db.worldState.deleteMany({ where: { id: row.id } }); + } + }); +}); diff --git a/app/game-engine/test/scenarioSeeder.test.ts b/app/game-engine/test/scenarioSeeder.test.ts index e453fc5..1a09c8c 100644 --- a/app/game-engine/test/scenarioSeeder.test.ts +++ b/app/game-engine/test/scenarioSeeder.test.ts @@ -28,6 +28,7 @@ type ScenarioSeederPrismaClient = { }; general: { count(): Promise; + findFirst(): Promise<{ age: number; startAge: number; meta: unknown } | null>; }; diplomacy: { count(): Promise; @@ -116,6 +117,14 @@ describeDb('scenario database seed', () => { expect(diplomacyCount).toBe(seed.nations.length * Math.max(0, seed.nations.length - 1)); expect(eventCount).toBe(seed.events.length); expect(generalCount).toBeGreaterThan(0); + const seededGeneral = await prisma.general.findFirst(); + expect(seededGeneral?.startAge).toBe(seededGeneral?.age); + expect(seededGeneral?.meta).toEqual( + expect.objectContaining({ + specage: expect.any(Number), + specage2: expect.any(Number), + }) + ); const freeCity = seed.cities.find((city) => city.nationId === 0); const occupiedCity = seed.cities.find((city) => city.nationId !== 0); diff --git a/packages/infra/src/turnEngineDb.ts b/packages/infra/src/turnEngineDb.ts index 0502eac..18d3429 100644 --- a/packages/infra/src/turnEngineDb.ts +++ b/packages/infra/src/turnEngineDb.ts @@ -42,6 +42,7 @@ export interface TurnEngineGeneralRow { train: number; atmos: number; age: number; + startAge: number; npcState: number; lastTurn: JsonValue; bornYear: number; diff --git a/packages/logic/src/actions/turn/general/che_내정특기초기화.ts b/packages/logic/src/actions/turn/general/che_내정특기초기화.ts index e01eec7..34f68e3 100644 --- a/packages/logic/src/actions/turn/general/che_내정특기초기화.ts +++ b/packages/logic/src/actions/turn/general/che_내정특기초기화.ts @@ -83,7 +83,8 @@ export class ActionDefinition< ? [general.role.specialDomestic!] : nextPreviousTypes; general.role.specialDomestic = null; - setMetaNumber(general.meta, 'specAge', general.age + 1); + delete general.meta.specAge; + setMetaNumber(general.meta, 'specage', general.age + 1); context.addLog('새로운 내정 특기를 가질 준비가 되었습니다.'); return { effects: [] }; } diff --git a/packages/logic/src/actions/turn/general/che_전투특기초기화.ts b/packages/logic/src/actions/turn/general/che_전투특기초기화.ts index 7f5b6ad..f9dbe1c 100644 --- a/packages/logic/src/actions/turn/general/che_전투특기초기화.ts +++ b/packages/logic/src/actions/turn/general/che_전투특기초기화.ts @@ -82,7 +82,8 @@ export class ActionDefinition< general.meta.prev_types_special2 = nextPreviousTypes.length === WAR_TRAIT_KEYS.length ? [general.role.specialWar!] : nextPreviousTypes; general.role.specialWar = null; - setMetaNumber(general.meta, 'specAge2', general.age + 1); + delete general.meta.specAge2; + setMetaNumber(general.meta, 'specage2', general.age + 1); const specialName = ACTION_NAME.replace(' 초기화', ''); context.addLog(`새로운 ${specialName}를 가질 준비가 되었습니다.`); tryApplyUniqueLottery(context, { acquireType: '아이템', reason: ACTION_NAME }); diff --git a/packages/logic/src/triggers/special/selector.ts b/packages/logic/src/triggers/special/selector.ts index 39a0199..d9031e9 100644 --- a/packages/logic/src/triggers/special/selector.ts +++ b/packages/logic/src/triggers/special/selector.ts @@ -15,7 +15,17 @@ export class TraitSelector { const chiefMin = scenarioStat.chiefMin; let myCond = 0; - if (leadership < chiefMin || strength < chiefMin || intelligence < chiefMin) { + if (leadership > chiefMin) { + myCond |= TraitRequirement.STAT_LEADERSHIP; + } + if (strength >= intelligence * 0.95 && strength > chiefMin) { + myCond |= TraitRequirement.STAT_STRENGTH; + } + if (intelligence >= strength * 0.95 && intelligence > chiefMin) { + myCond |= TraitRequirement.STAT_INTEL; + } + + if (myCond !== 0) { if (leadership < chiefMin) myCond |= TraitRequirement.STAT_NOT_LEADERSHIP; if (strength < chiefMin) myCond |= TraitRequirement.STAT_NOT_STRENGTH; if (intelligence < chiefMin) myCond |= TraitRequirement.STAT_NOT_INTEL; @@ -48,7 +58,7 @@ export class TraitSelector { const dexSum = Object.values(dexMap).reduce((a, b) => a + b, 0); // 루트(합)/4 확률 기반 로직 (Legacy: sqrt(dexSum)/4) - const dexProb = Math.sqrt(dexSum) / 4; + const dexBase = Math.round(Math.sqrt(dexSum) / 4); // Legacy: 80% 확률로 0 반환 (이전 연도에 이미 얻었거나 기타 이유로 제한하는 인지) // 실제로는 pickSpecialWar에서 이 메서드 호출 전후에 별도 확률을 둘 수도 있으나, @@ -57,12 +67,12 @@ export class TraitSelector { return 0; } - if (rng.nextRangeInt(0, 99) < dexProb) { + if (rng.nextRangeInt(0, 99) < dexBase) { return 0; } if (dexSum === 0) { - return Number(rng.choice(Object.keys(dexMap))); + return rng.choice(Object.values(dexMap)); } const maxDex = Math.max(...Object.values(dexMap)); @@ -76,42 +86,59 @@ export class TraitSelector { /** * 사용 가능한 특기 목록에서 하나를 무작위로 선택 (pickTrait) */ - static pickTrait(rng: RandUtil, myCond: number, traits: TraitModule[], prevTraitKeys: string[]): string | null { - const normPool: Record = {}; - const percentPool: { key: string; weight: number }[] = []; + private static pickTraitOnce( + rng: RandUtil, + myCond: number, + traits: TraitModule[], + prevTraitKeys: string[], + preferDexterity: boolean + ): string | null { + const dexterityPool: Array<[string, number]> = []; + const normPool: Array<[string, number]> = []; + const percentPool: Array<[string | null, number]> = []; for (const trait of traits) { if (!trait.selection) continue; if (prevTraitKeys.includes(trait.key)) continue; - let valid = false; + let matchedRequirement: number | null = null; for (const req of trait.selection.requirements) { if (req === (req & myCond)) { - valid = true; + matchedRequirement = req; break; } } - if (!valid) continue; + if (matchedRequirement === null) continue; - if (trait.selection.weightType === TraitWeightType.PERCENT) { - percentPool.push({ key: trait.key, weight: trait.selection.weight }); + if (preferDexterity && (matchedRequirement & TraitRequirement.REQ_DEXTERITY) !== 0) { + dexterityPool.push([trait.key, trait.selection.weight]); + } else if (trait.selection.weightType === TraitWeightType.PERCENT) { + percentPool.push([trait.key, trait.selection.weight]); } else { - normPool[trait.key] = trait.selection.weight; + normPool.push([trait.key, trait.selection.weight]); } } - // PERCENT 타입 특기 먼저 우선권 확인 - for (const item of percentPool) { - if (rng.nextBool(item.weight / 100)) { - return item.key; + if (dexterityPool.length > 0) { + return rng.choiceUsingWeightPair(dexterityPool); + } + + if (percentPool.length > 0) { + if (normPool.length > 0) { + const totalPercent = percentPool.reduce((sum, [, weight]) => sum + weight, 0); + percentPool.push([null, Math.max(0, 100 - totalPercent)]); + } + const selected = rng.choiceUsingWeightPair(percentPool); + if (selected !== null) { + return selected; } } - // NORM 타입 특기들 중 가중치 기반 선택 - if (Object.keys(normPool).length === 0) return null; - - return String(rng.choiceUsingWeight(normPool)); + if (normPool.length > 0) { + return rng.choiceUsingWeightPair(normPool); + } + return null; } /** @@ -125,13 +152,18 @@ export class TraitSelector { prevTraitKeys: string[], scenarioStat: ScenarioStatBlock ): string | null { - let myCond = this.calcCondGeneric(stats, scenarioStat); - const dexCond = this.calcCondDexterity(rng, dex); - if (dexCond) { - myCond |= dexCond | TraitRequirement.REQ_DEXTERITY; + const myCond = + this.calcCondGeneric(stats, scenarioStat) | + this.calcCondDexterity(rng, dex) | + TraitRequirement.REQ_DEXTERITY; + const selected = this.pickTraitOnce(rng, myCond, traits, prevTraitKeys, true); + if (selected !== null) { + return selected; } - - return this.pickTrait(rng, myCond, traits, prevTraitKeys); + if (prevTraitKeys.length > 0) { + return this.pickWarTrait(rng, stats, dex, traits, [], scenarioStat); + } + return null; } /** @@ -145,6 +177,13 @@ export class TraitSelector { scenarioStat: ScenarioStatBlock ): string | null { const myCond = this.calcCondGeneric(stats, scenarioStat); - return this.pickTrait(rng, myCond, traits, prevTraitKeys); + const selected = this.pickTraitOnce(rng, myCond, traits, prevTraitKeys, false); + if (selected !== null) { + return selected; + } + if (prevTraitKeys.length > 0) { + return this.pickDomesticTrait(rng, stats, traits, [], scenarioStat); + } + return null; } } diff --git a/packages/logic/src/world/bootstrap.ts b/packages/logic/src/world/bootstrap.ts index 0b37bcd..7ef2e92 100644 --- a/packages/logic/src/world/bootstrap.ts +++ b/packages/logic/src/world/bootstrap.ts @@ -161,6 +161,9 @@ const resolveAge = (startYear: number | null, birthYear: number): number => { return Math.max(startYear - birthYear, 0); }; +const buildSpecialityAge = (retirementYear: number, age: number, divisor: number): number => + Math.max(Math.round((retirementYear - age) / divisor), 3) + age; + const ADULT_GENERAL_AGE = 14; type GeneralBootstrapDisposition = 'active' | 'delayed' | 'expired'; @@ -294,6 +297,9 @@ const buildGeneralSeeds = ( const defaultGold = options?.defaultGeneralGold ?? DEFAULT_GENERAL_GOLD; const defaultRice = options?.defaultGeneralRice ?? DEFAULT_GENERAL_RICE; + const rawRetirementYear = scenario.config.const.retirementYear; + const retirementYear = + typeof rawRetirementYear === 'number' && Number.isFinite(rawRetirementYear) ? rawRetirementYear : 80; for (const row of rows) { const id = nextId; @@ -313,6 +319,8 @@ const buildGeneralSeeds = ( const seedMeta: Record = { source: contextLabel, + specage: buildSpecialityAge(retirementYear, age, 12), + specage2: buildSpecialityAge(retirementYear, age, 6), }; if (row.affinity !== null) { seedMeta.affinity = row.affinity; @@ -374,6 +382,8 @@ const buildGeneralSeeds = ( killturn: resolveKillturnFromDeathYear(scenario.startYear, 1, deathYear, DEFAULT_GENERAL_KILLTURN), npcType, crewTypeId: defaultCrewTypeId, + specage: buildSpecialityAge(retirementYear, age, 12), + specage2: buildSpecialityAge(retirementYear, age, 6), }; addTriggerMeta(generalMeta, 'affinity', row.affinity); addTriggerMeta(generalMeta, 'personality', row.personality ?? undefined); diff --git a/packages/logic/test/specialTraitSelectorParity.test.ts b/packages/logic/test/specialTraitSelectorParity.test.ts new file mode 100644 index 0000000..2faeff7 --- /dev/null +++ b/packages/logic/test/specialTraitSelectorParity.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest'; +import { RandUtil, type RNG } from '@sammo-ts/common'; + +import { TraitRequirement, TraitWeightType } from '../src/triggers/special/requirements.js'; +import { TraitSelector } from '../src/triggers/special/selector.js'; +import type { TraitModule } from '../src/triggers/special/types.js'; + +class ScriptedRng implements RNG { + public floatCalls = 0; + public intCalls = 0; + + constructor( + private readonly floats: number[], + private readonly ints: number[] + ) {} + + getMaxInt(): number { + return 0x7fff_ffff; + } + + nextBytes(bytes: number): Uint8Array { + return new Uint8Array(bytes); + } + + nextBits(bits: number): Uint8Array { + return new Uint8Array(Math.ceil(bits / 8)); + } + + nextInt(max = 0x7fff_ffff): number { + const value = this.ints[this.intCalls++] ?? 0; + return Math.max(0, Math.min(value, max)); + } + + nextFloat1(): number { + return this.floats[this.floatCalls++] ?? 0; + } +} + +const scenarioStat = { + total: 300, + min: 10, + max: 100, + npcTotal: 150, + npcMax: 75, + npcMin: 10, + chiefMin: 70, +}; + +const trait = ( + key: string, + requirement: TraitRequirement, + weightType = TraitWeightType.NORM, + weight = 1 +): TraitModule => + ({ + key, + name: key, + info: '', + kind: 'domestic', + selection: { requirements: [requirement], weightType, weight }, + }) as TraitModule; + +describe('legacy speciality selector parity', () => { + it('sets positive and negative stat bits in the legacy order', () => { + expect( + TraitSelector.calcCondGeneric( + { leadership: 80, strength: 75, intelligence: 40 }, + scenarioStat + ) + ).toBe( + TraitRequirement.STAT_LEADERSHIP | + TraitRequirement.STAT_STRENGTH | + TraitRequirement.STAT_NOT_INTEL + ); + expect( + TraitSelector.calcCondGeneric( + { leadership: 70, strength: 70, intelligence: 70 }, + scenarioStat + ) + ).toBe(TraitRequirement.STAT_STRENGTH); + }); + + it('rounds the dex threshold and still consumes a value choice when every dex is zero', () => { + const source = new ScriptedRng([0.9], [99, 4]); + const result = TraitSelector.calcCondDexterity(new RandUtil(source), [0, 0, 0, 0, 0]); + expect(result).toBe(0); + expect(source.floatCalls).toBe(1); + expect(source.intCalls).toBe(2); + }); + + it('uses one weighted absolute draw with a relative sentinel before the norm pool', () => { + const source = new ScriptedRng([0.5, 0.1], []); + const result = TraitSelector.pickDomesticTrait( + new RandUtil(source), + { leadership: 40, strength: 40, intelligence: 80 }, + [ + trait('rare', TraitRequirement.STAT_INTEL, TraitWeightType.PERCENT, 2.5), + trait('normal-a', TraitRequirement.STAT_INTEL), + trait('normal-b', TraitRequirement.STAT_INTEL), + ], + [], + scenarioStat + ); + expect(result).toBe('normal-a'); + expect(source.floatCalls).toBe(2); + }); + + it('retries without previous traits and reruns the war dex RNG path', () => { + const source = new ScriptedRng([0.9, 0.9, 0.1], [99, 0, 99, 0]); + const result = TraitSelector.pickWarTrait( + new RandUtil(source), + { leadership: 80, strength: 75, intelligence: 40 }, + [200, 10, 10, 10, 10], + [ + trait( + 'footman', + (TraitRequirement.STAT_LEADERSHIP | + TraitRequirement.REQ_DEXTERITY | + TraitRequirement.ARMY_FOOTMAN | + TraitRequirement.STAT_NOT_INTEL) as TraitRequirement + ), + ], + ['footman'], + scenarioStat + ); + expect(result).toBe('footman'); + expect(source.floatCalls).toBe(3); + expect(source.intCalls).toBe(4); + }); +}); diff --git a/packages/logic/test/worldBootstrap.test.ts b/packages/logic/test/worldBootstrap.test.ts index 00d87f8..e47362a 100644 --- a/packages/logic/test/worldBootstrap.test.ts +++ b/packages/logic/test/worldBootstrap.test.ts @@ -119,6 +119,8 @@ describe('scenario bootstrap', () => { expect(result.snapshot.generals[0]?.crewTypeId).toBe(1200); expect(result.snapshot.generals[0]?.role.specialDomestic).toBe('Special'); expect(result.snapshot.generals[0]?.role.specialWar).toBeNull(); + expect(result.snapshot.generals[0]?.meta).toMatchObject({ specage: 25, specage2: 30 }); + expect(result.seed.generals[0]?.meta).toMatchObject({ specage: 25, specage2: 30 }); expect(result.seed.generals[0]?.npcType).toBe(2); expect(result.snapshot.scenarioMeta?.title).toBe('Test Scenario'); });