fix: align legacy speciality selection

This commit is contained in:
2026-07-25 20:55:27 +00:00
parent 4fa91439d5
commit 80d7f264af
13 changed files with 306 additions and 30 deletions
+45
View File
@@ -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,
},
},
});
@@ -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 });
});
});
@@ -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',
+1
View File
@@ -22,6 +22,7 @@ export interface TurnWorldState {
export interface TurnGeneral extends General {
userId?: string | null;
startAge?: number;
bornYear?: number;
deadYear?: number;
affinity?: number | null;
+1
View File
@@ -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,
@@ -28,6 +28,7 @@ type ScenarioSeederPrismaClient = {
};
general: {
count(): Promise<number>;
findFirst(): Promise<{ age: number; startAge: number; meta: unknown } | null>;
};
diplomacy: {
count(): Promise<number>;
@@ -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);
+1
View File
@@ -42,6 +42,7 @@ export interface TurnEngineGeneralRow {
train: number;
atmos: number;
age: number;
startAge: number;
npcState: number;
lastTurn: JsonValue;
bornYear: number;
@@ -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: [] };
}
@@ -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 });
+67 -28
View File
@@ -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<string, number> = {};
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;
}
}
+10
View File
@@ -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<string, unknown> = {
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);
@@ -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<ArrayBuffer> {
return new Uint8Array(bytes);
}
nextBits(bits: number): Uint8Array<ArrayBuffer> {
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);
});
});
@@ -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');
});