랜덤 임관에서 이전 소속국을 제외하고 후보 소진 시 다시 순환한다

This commit is contained in:
Hide_D committed 2026-11-19 10:57:32 +09:00
1 parent 6a4f170fd9
commit 0ae14d5ee0
10 files changed
+221 -8

No files matched your search

@@ -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']);
});
});