랜덤 임관에서 이전 소속국을 제외하고 후보 소진 시 다시 순환한다
This commit is contained in:
1 parent
6a4f170fd9
commit
0ae14d5ee0
10 files changed
+221
-8
No files matched your search
@@ -39,6 +39,7 @@ import {
|
||||
type TurnCommandProfile,
|
||||
} from '@sammo-ts/logic';
|
||||
import { resolveLegacyCompatibleUniqueConfig } from '@sammo-ts/logic/rewards/legacyUniqueItemPool.js';
|
||||
import { appendJoinedNationIds } from '@sammo-ts/logic/actions/turn/general/joinedNations.js';
|
||||
import { round as roundLegacyInteger, simpleSerialize } from '@sammo-ts/logic/war/utils.js';
|
||||
import {
|
||||
cloneItemInventory,
|
||||
@@ -2034,6 +2035,7 @@ async function handleKick(
|
||||
const targetMeta = target.meta;
|
||||
const nextMeta: TurnGeneral['meta'] = {
|
||||
...targetMeta,
|
||||
joinedNations: appendJoinedNationIds(targetMeta, target.nationId),
|
||||
officerCity: 0,
|
||||
officer_city: 0,
|
||||
belong: 0,
|
||||
|
||||
@@ -378,7 +378,7 @@ describe('nation personnel world commands', () => {
|
||||
rice: 1_000,
|
||||
experience: 850,
|
||||
dedication: 1_700,
|
||||
meta: expect.objectContaining({ belong: 0, permission: 'normal', betray: 2 }),
|
||||
meta: expect.objectContaining({ belong: 0, permission: 'normal', betray: 2, joinedNations: [1] }),
|
||||
});
|
||||
expect(fixture.world.getGeneralById(4)?.troopId).toBe(0);
|
||||
expect(fixture.world.getTroopById(3)).toBeNull();
|
||||
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
type RandomAppointmentResolveContext,
|
||||
} from '@sammo-ts/logic/actions/turn/general/che_랜덤임관.js';
|
||||
import type { ActionContextWorldRef } from '@sammo-ts/logic/actions/turn/actionContext.js';
|
||||
import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js';
|
||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||
import { createMonthlyBoundaryPreHandler } from '../src/turn/monthlyBoundaryPreHandler.js';
|
||||
import { InMemoryReservedTurnStore } from '../src/turn/reservedTurnStore.js';
|
||||
import { createReservedTurnHandler } from '../src/turn/reservedTurnHandler.js';
|
||||
import { buildCommandEnv } from '../src/turn/reservedTurnCommands.js';
|
||||
@@ -320,6 +322,104 @@ describeDb('scenario database seed', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('persists and reloads random appointment history across reserved joins and resignations', async () => {
|
||||
await seedScenarioToDatabase({
|
||||
scenarioId: 1031,
|
||||
databaseUrl,
|
||||
resetTables: true,
|
||||
now: new Date('2030-01-01T00:00:00.000Z'),
|
||||
installOptions: { fiction: 1 },
|
||||
});
|
||||
const connector = createGamePostgresConnector({ url: databaseUrl });
|
||||
try {
|
||||
await connector.connect();
|
||||
const db = connector.prisma;
|
||||
const loaded = await loadTurnWorldFromDatabase({ databaseUrl });
|
||||
const [visited, unvisited] = loaded.snapshot.nations.filter((nation) => nation.id > 0).slice(0, 2);
|
||||
const actor = loaded.snapshot.generals.find((general) => general.nationId === 0);
|
||||
if (!visited || !unvisited || !actor) throw new Error('Expected two nations and a neutral general.');
|
||||
for (const nation of loaded.snapshot.nations.filter((nation) => nation.id > 0)) {
|
||||
const eligible = nation.id === visited.id || nation.id === unvisited.id;
|
||||
await db.nation.update({
|
||||
where: { id: nation.id },
|
||||
data: { meta: { ...nation.meta, scout: !eligible, gennum: 1 } },
|
||||
});
|
||||
}
|
||||
const eligibleIds = [visited.id, unvisited.id];
|
||||
await db.general.update({
|
||||
where: { id: actor.id },
|
||||
data: { npcState: 0, meta: { ...actor.meta, killturn: 100, joinedNations: [visited.id] } },
|
||||
});
|
||||
|
||||
const executeAndReload = async (action: 'che_랜덤임관' | 'che_하야', waitMonths = 0) => {
|
||||
const { state, snapshot } = await loadTurnWorldFromDatabase({ databaseUrl });
|
||||
const store = new InMemoryReservedTurnStore(db, { maxGeneralTurns: 30, maxNationTurns: 12 });
|
||||
await store.loadAll();
|
||||
let world: InMemoryTurnWorld | null = null;
|
||||
const handler = await createReservedTurnHandler({
|
||||
reservedTurns: store,
|
||||
scenarioConfig: snapshot.scenarioConfig,
|
||||
scenarioMeta: snapshot.scenarioMeta,
|
||||
map: snapshot.map,
|
||||
unitSet: snapshot.unitSet,
|
||||
getWorld: () => world,
|
||||
});
|
||||
world = new InMemoryTurnWorld(state, snapshot, {
|
||||
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
|
||||
generalTurnHandler: handler,
|
||||
calendarHandler: createMonthlyBoundaryPreHandler({
|
||||
getWorld: () => world,
|
||||
startYear: snapshot.scenarioMeta?.startYear ?? state.currentYear,
|
||||
commandEnv: buildCommandEnv(snapshot.scenarioConfig, snapshot.unitSet),
|
||||
}),
|
||||
});
|
||||
for (let month = 0; month < waitMonths; month++) {
|
||||
const next = new Date(world.getState().lastTurnTime.getTime() + state.tickSeconds * 1000);
|
||||
await world.advanceMonth(next);
|
||||
}
|
||||
store.setGeneralTurn(actor.id, 0, { action, args: {} });
|
||||
world.executeGeneralTurn(world.getGeneralById(actor.id)!);
|
||||
const hooks = await createDatabaseTurnHooks(databaseUrl, world, { reservedTurns: store });
|
||||
try {
|
||||
await hooks.hooks.flushChanges?.({
|
||||
lastTurnTime: world.getState().lastTurnTime.toISOString(),
|
||||
processedGenerals: 1,
|
||||
processedTurns: 1,
|
||||
durationMs: 0,
|
||||
partial: false,
|
||||
});
|
||||
} finally {
|
||||
await hooks.close();
|
||||
}
|
||||
const reloaded = await loadTurnWorldFromDatabase({ databaseUrl });
|
||||
return reloaded.snapshot.generals.find(({ id }) => id === actor.id)!;
|
||||
};
|
||||
|
||||
expect(await executeAndReload('che_랜덤임관')).toMatchObject({
|
||||
nationId: unvisited.id,
|
||||
meta: { joinedNations: eligibleIds },
|
||||
});
|
||||
expect(await executeAndReload('che_하야')).toMatchObject({
|
||||
nationId: 0,
|
||||
meta: { joinedNations: eligibleIds, makelimit: 12 },
|
||||
});
|
||||
const reset = await executeAndReload('che_랜덤임관', 12);
|
||||
expect(eligibleIds).toContain(reset.nationId);
|
||||
expect(reset.meta.joinedNations).toEqual([reset.nationId]);
|
||||
expect(await executeAndReload('che_하야')).toMatchObject({
|
||||
nationId: 0,
|
||||
meta: { joinedNations: [reset.nationId], makelimit: 12 },
|
||||
});
|
||||
const otherId = eligibleIds.find((id) => id !== reset.nationId);
|
||||
expect(await executeAndReload('che_랜덤임관', 12)).toMatchObject({
|
||||
nationId: otherId,
|
||||
meta: { joinedNations: [reset.nationId, otherId] },
|
||||
});
|
||||
} finally {
|
||||
await connector.disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ sync: true, turnMinutes: 60, hour: 10, month: 10, yearOffset: -1 },
|
||||
{ sync: true, turnMinutes: 60, hour: 1, month: 1, yearOffset: 0 },
|
||||
|
||||
@@ -25,6 +25,7 @@ import { z } from 'zod';
|
||||
import type { TurnCommandEnv } from '@sammo-ts/logic/actions/turn/commandEnv.js';
|
||||
import type { ActionContextBuilder } from '@sammo-ts/logic/actions/turn/actionContext.js';
|
||||
import type { GeneralTurnCommandSpec } from './index.js';
|
||||
import { appendJoinedNationIds } from './joinedNations.js';
|
||||
import { parseArgsWithSchema } from '../parseArgs.js';
|
||||
import { LEGACY_DEFAULT_MAX_LEVEL } from '@sammo-ts/logic/scenario/constants.js';
|
||||
|
||||
@@ -263,6 +264,7 @@ export class ActionResolver<
|
||||
meta: {
|
||||
...general.meta,
|
||||
belong: 1,
|
||||
joinedNations: appendJoinedNationIds(general.meta, general.nationId, destNation.id),
|
||||
permission: 'normal',
|
||||
officer_city: 0,
|
||||
betray: newBetray,
|
||||
|
||||
@@ -17,6 +17,7 @@ import type { ActionContextBuilder } from '@sammo-ts/logic/actions/turn/actionCo
|
||||
import { resolveStartYear } from '@sammo-ts/logic/actions/turn/actionContextHelpers.js';
|
||||
import { GeneralActionPipeline } from '@sammo-ts/logic/actionModules/general.js';
|
||||
import type { TurnCommandEnv } from '@sammo-ts/logic/actions/turn/commandEnv.js';
|
||||
import { readJoinedNationIds } from './joinedNations.js';
|
||||
|
||||
export interface RandomAppointmentArgs {}
|
||||
|
||||
@@ -167,10 +168,10 @@ export class ActionDefinition<
|
||||
context: RandomAppointmentResolveContext<TriggerState>,
|
||||
_args: RandomAppointmentArgs
|
||||
): GeneralActionOutcome<TriggerState> {
|
||||
const { general, rng, candidateNations } = context;
|
||||
const { general, rng, candidateNations: eligibleNations } = context;
|
||||
const effects: Array<GeneralActionEffect<TriggerState>> = [];
|
||||
|
||||
if (candidateNations.length === 0) {
|
||||
if (eligibleNations.length === 0) {
|
||||
effects.push(
|
||||
createLogEffect('임관 가능한 국가가 없습니다.', {
|
||||
scope: LogScope.GENERAL,
|
||||
@@ -181,6 +182,12 @@ export class ActionDefinition<
|
||||
return { effects, alternative: { commandKey: 'che_인재탐색', args: {} } };
|
||||
}
|
||||
|
||||
const joinedNationIds = readJoinedNationIds(general.meta);
|
||||
const unvisitedNations = eligibleNations.filter(({ nation }) => !joinedNationIds.has(nation.id));
|
||||
// 이번 턴에 임관 가능한 국가를 모두 방문했으면 같은 실행에서 새 순환을 시작한다.
|
||||
const restartCycle = unvisitedNations.length === 0;
|
||||
const candidateNations = restartCycle ? eligibleNations : unvisitedNations;
|
||||
|
||||
let picked: CandidateNation<TriggerState> | null;
|
||||
if (context.historicalNpcAffinityMode) {
|
||||
const totalGenerals = candidateNations.reduce((sum, candidate) => sum + candidate.generalCount, 0);
|
||||
@@ -235,6 +242,7 @@ export class ActionDefinition<
|
||||
belong: 1,
|
||||
officer_city: 0,
|
||||
officerCity: 0,
|
||||
joinedNations: restartCycle ? [destNation.id] : [...joinedNationIds, destNation.id],
|
||||
};
|
||||
|
||||
const expGain =
|
||||
|
||||
@@ -21,6 +21,7 @@ import type {
|
||||
} from '@sammo-ts/logic/actions/turn/actionContext.js';
|
||||
import { tryApplyUniqueLottery } from '@sammo-ts/logic/rewards/uniqueLottery.js';
|
||||
import type { GeneralTurnCommandSpec } from './index.js';
|
||||
import { appendJoinedNationIds } from './joinedNations.js';
|
||||
import { parseArgsWithSchema } from '../parseArgs.js';
|
||||
import { JosaUtil } from '@sammo-ts/common';
|
||||
import { GeneralActionPipeline } from '@sammo-ts/logic/actionModules/general.js';
|
||||
@@ -130,6 +131,7 @@ export class ActionDefinition<
|
||||
...context.general.meta,
|
||||
officer_city: 0,
|
||||
belong: 1,
|
||||
joinedNations: appendJoinedNationIds(context.general.meta, args.destNationId),
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { ActionContextBuilder } from '@sammo-ts/logic/actions/turn/actionCo
|
||||
import type { TurnCommandEnv } from '@sammo-ts/logic/actions/turn/commandEnv.js';
|
||||
import { tryApplyUniqueLottery } from '@sammo-ts/logic/rewards/uniqueLottery.js';
|
||||
import type { GeneralTurnCommandSpec } from './index.js';
|
||||
import { appendJoinedNationIds } from './joinedNations.js';
|
||||
import { parseArgsWithSchema } from '../parseArgs.js';
|
||||
|
||||
const ACTION_NAME = '장수를 따라 임관';
|
||||
@@ -207,6 +208,7 @@ export class ActionDefinition<
|
||||
meta: {
|
||||
...general.meta,
|
||||
belong: 1,
|
||||
joinedNations: appendJoinedNationIds(general.meta, destNation.id),
|
||||
officer_city: 0,
|
||||
officerCity: 0,
|
||||
},
|
||||
|
||||
@@ -12,6 +12,7 @@ import { LogCategory, LogFormat, LogScope } from '@sammo-ts/logic/logging/types.
|
||||
import type { TurnCommandEnv } from '@sammo-ts/logic/actions/turn/commandEnv.js';
|
||||
import type { ActionContextBuilder } from '@sammo-ts/logic/actions/turn/actionContext.js';
|
||||
import type { GeneralTurnCommandSpec } from './index.js';
|
||||
import { appendJoinedNationIds } from './joinedNations.js';
|
||||
import { JosaUtil } from '@sammo-ts/common';
|
||||
|
||||
export interface ResignArgs {}
|
||||
@@ -100,6 +101,7 @@ export class ActionResolver<
|
||||
...general.meta,
|
||||
betray: Math.min(9, betrayal + 1),
|
||||
belong: 0,
|
||||
joinedNations: appendJoinedNationIds(general.meta, nation.id),
|
||||
// Ref resets belong before max_belong is refreshed here.
|
||||
// Preserve that ordering, including its legacy behavior.
|
||||
...(general.npcState < 2 ? { max_belong: Math.max(0, maxBelong) } : {}),
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { GeneralMeta, NationId } from '../../../domain/entities.js';
|
||||
|
||||
// Ref의 aux.joinedNations가 이관된 경우 숫자 문자열로 저장된 ID도 읽는다.
|
||||
export const readJoinedNationIds = (meta: GeneralMeta): Set<NationId> => {
|
||||
const ids = new Set<NationId>();
|
||||
if (!Array.isArray(meta.joinedNations)) return ids;
|
||||
|
||||
for (const value of meta.joinedNations) {
|
||||
const id = typeof value === 'string' && /^\d+$/u.test(value) ? Number(value) : value;
|
||||
if (typeof id === 'number' && Number.isSafeInteger(id) && id > 0) {
|
||||
ids.add(id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
};
|
||||
|
||||
export const appendJoinedNationIds = (meta: GeneralMeta, ...nationIds: NationId[]): NationId[] => {
|
||||
const ids = readJoinedNationIds(meta);
|
||||
for (const id of nationIds) {
|
||||
if (id > 0) ids.add(id);
|
||||
}
|
||||
return [...ids];
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { General, Nation } from '../../../src/domain/entities.js';
|
||||
import type { General, GeneralMeta, Nation } from '../../../src/domain/entities.js';
|
||||
import type { GeneralActionResolveContext } from '../../../src/actions/engine.js';
|
||||
import { finalizeLogEntry } from '../../../src/logging/entries.js';
|
||||
import { LogCategory, type LogEntryDraft, LogFormat, LogScope } from '../../../src/logging/types.js';
|
||||
@@ -24,7 +24,7 @@ const actor = {
|
||||
specialWar: null,
|
||||
items: { horse: null, weapon: null, book: null, item: null },
|
||||
},
|
||||
meta: {},
|
||||
meta: { killturn: 70 },
|
||||
} as General;
|
||||
|
||||
const nation = {
|
||||
@@ -57,7 +57,7 @@ describe('appointment global summary log format', () => {
|
||||
const logs: LogEntryDraft[] = [];
|
||||
const action = new AppointmentAction({} as TurnCommandEnv);
|
||||
|
||||
action.resolve(
|
||||
const result = action.resolve(
|
||||
{
|
||||
general: actor,
|
||||
destNation: nation,
|
||||
@@ -69,6 +69,12 @@ describe('appointment global summary log format', () => {
|
||||
);
|
||||
|
||||
expectMonthlySummary(logs);
|
||||
expect(result.effects).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: 'general:patch',
|
||||
patch: expect.objectContaining({ meta: expect.objectContaining({ joinedNations: [2] }) }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('adds the legacy month prefix to random appointment', () => {
|
||||
@@ -104,7 +110,7 @@ describe('appointment global summary log format', () => {
|
||||
const logs: LogEntryDraft[] = [];
|
||||
const action = new FollowAppointmentAction();
|
||||
|
||||
action.resolve(
|
||||
const result = action.resolve(
|
||||
{
|
||||
general: actor,
|
||||
destNation: nation,
|
||||
@@ -116,8 +122,74 @@ describe('appointment global summary log format', () => {
|
||||
);
|
||||
|
||||
expectMonthlySummary(logs);
|
||||
expect(result.effects).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: 'general:patch',
|
||||
patch: expect.objectContaining({ meta: expect.objectContaining({ joinedNations: [2] }) }),
|
||||
})
|
||||
);
|
||||
expect(
|
||||
logs.find((entry) => entry.scope === LogScope.GENERAL && entry.category === LogCategory.HISTORY)?.format
|
||||
).toBe(LogFormat.YEAR_MONTH);
|
||||
});
|
||||
});
|
||||
|
||||
describe('random appointment nation history', () => {
|
||||
const action = new RandomAppointmentAction({} as TurnCommandEnv);
|
||||
const resolve = (meta: GeneralMeta, eligibleIds: number[], historicalNpcAffinityMode = false) => {
|
||||
const rng = { nextFloat1: vi.fn(() => 0.42), nextInt: vi.fn(() => 0) };
|
||||
const candidateNations = eligibleIds.map((id) => ({
|
||||
nation: { ...nation, id },
|
||||
generals: [],
|
||||
generalCount: 1,
|
||||
monarchCityId: 2,
|
||||
monarchAffinity: 0,
|
||||
}));
|
||||
const result = action.resolve(
|
||||
{
|
||||
general: { ...actor, meta },
|
||||
rng,
|
||||
candidateNations,
|
||||
relYear: 4,
|
||||
initialNationGenLimit: 10,
|
||||
historicalNpcAffinityMode,
|
||||
} as unknown as Parameters<typeof action.resolve>[0],
|
||||
{}
|
||||
);
|
||||
return { ...result, rng, actorPatch: result.effects.find((effect) => effect.type === 'general:patch')?.patch };
|
||||
};
|
||||
|
||||
it.each([false, true])(
|
||||
'excludes visited nations and resets only when the eligible pool is exhausted (affinity: %s)',
|
||||
(affinity) => {
|
||||
const first = resolve(actor.meta, [2, 3], affinity);
|
||||
expect(first.actorPatch).toMatchObject({ nationId: 2, meta: { joinedNations: [2] } });
|
||||
expect(first.rng.nextFloat1).toHaveBeenCalledTimes(affinity ? 2 : 1);
|
||||
|
||||
const second = resolve(first.actorPatch!.meta!, [2, 3], affinity);
|
||||
expect(second.actorPatch).toMatchObject({ nationId: 3, meta: { joinedNations: [2, 3] } });
|
||||
expect(second.rng.nextFloat1).toHaveBeenCalledTimes(1);
|
||||
expect(second.rng.nextInt).toHaveBeenCalledTimes(1);
|
||||
|
||||
const third = resolve(second.actorPatch!.meta!, [2, 3], affinity);
|
||||
expect(third.actorPatch).toMatchObject({ nationId: 2, meta: { joinedNations: [2] } });
|
||||
expect(third.rng.nextFloat1).toHaveBeenCalledTimes(affinity ? 2 : 1);
|
||||
}
|
||||
);
|
||||
|
||||
it('reads legacy IDs, resets for one eligible visited nation, and retains history when the pool is empty', () => {
|
||||
const meta = { ...actor.meta, joinedNations: ['2', 4, 4, 0, 'invalid'] };
|
||||
const unvisited = resolve(meta, [2, 3]);
|
||||
expect(unvisited.actorPatch).toMatchObject({ nationId: 3, meta: { joinedNations: [2, 4, 3] } });
|
||||
|
||||
const restarted = resolve(meta, [2]);
|
||||
expect(restarted.actorPatch).toMatchObject({ nationId: 2, meta: { joinedNations: [2] } });
|
||||
expect(restarted.rng.nextFloat1).toHaveBeenCalledTimes(1);
|
||||
|
||||
const unavailable = resolve(meta, []);
|
||||
expect(unavailable.actorPatch).toBeUndefined();
|
||||
expect(unavailable.alternative).toEqual({ commandKey: 'che_인재탐색', args: {} });
|
||||
expect(unavailable.rng.nextFloat1).not.toHaveBeenCalled();
|
||||
expect(meta.joinedNations).toEqual(['2', 4, 4, 0, 'invalid']);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user