feat(game-engine): port city changes and NPC troop leaders
This commit is contained in:
@@ -8,6 +8,7 @@ import type { ScenarioLoaderOptions } from './scenarioLoader.js';
|
||||
import { loadScenarioDefinitionById } from './scenarioLoader.js';
|
||||
import type { UnitSetLoaderOptions } from './unitSetLoader.js';
|
||||
import { loadUnitSetDefinitionByName } from './unitSetLoader.js';
|
||||
import { applyInitialChangeCityEvents } from '../turn/monthlyChangeCityAction.js';
|
||||
|
||||
const DEFAULT_TICK_SECONDS = 120 * 60;
|
||||
const DEFAULT_GENERAL_GOLD = 1000;
|
||||
@@ -75,7 +76,7 @@ const resolveSchemaName = (databaseUrl: string): string => {
|
||||
const hasEventTable = async (prisma: RawQueryClient, schema: string): Promise<boolean> => {
|
||||
try {
|
||||
const result = await prisma.$queryRawUnsafe<Array<{ regclass: string | null }>>(
|
||||
`SELECT to_regclass('${schema}.event') as regclass`
|
||||
`SELECT to_regclass('${schema}.event')::text as regclass`
|
||||
);
|
||||
return Array.isArray(result) && result.length > 0 && result[0]?.regclass !== null;
|
||||
} catch {
|
||||
@@ -211,6 +212,7 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
||||
includeNeutralNationInSeed: options.includeNeutralNationInSeed ?? true,
|
||||
},
|
||||
});
|
||||
seed.cities = applyInitialChangeCityEvents(seed.cities, seed.initialEvents);
|
||||
|
||||
const connector = createGamePostgresConnector({ url: options.databaseUrl });
|
||||
const now = options.now ?? new Date();
|
||||
@@ -513,7 +515,7 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
||||
});
|
||||
}
|
||||
|
||||
const eventRows = [...buildEventRows(seed.events), ...buildEventRows(seed.initialEvents, 'initial')];
|
||||
const eventRows = buildEventRows(seed.events);
|
||||
if (eventRows.length > 0 && eventTableReady) {
|
||||
await prisma.event.createMany({
|
||||
data: eventRows,
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import type { City, CitySeed } from '@sammo-ts/logic';
|
||||
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
import type { MonthlyEventActionHandler } from './monthlyEventHandler.js';
|
||||
|
||||
type MutableCity = City | CitySeed;
|
||||
type CityNumericKey =
|
||||
| 'population'
|
||||
| 'agriculture'
|
||||
| 'commerce'
|
||||
| 'security'
|
||||
| 'defence'
|
||||
| 'wall';
|
||||
type CityMaximumKey =
|
||||
| 'populationMax'
|
||||
| 'agricultureMax'
|
||||
| 'commerceMax'
|
||||
| 'securityMax'
|
||||
| 'defenceMax'
|
||||
| 'wallMax';
|
||||
type ChangeCityKey = CityNumericKey | CityMaximumKey | 'trust' | 'trade';
|
||||
|
||||
const KEY_MAP: Readonly<Record<string, ChangeCityKey>> = {
|
||||
pop: 'population',
|
||||
agri: 'agriculture',
|
||||
comm: 'commerce',
|
||||
secu: 'security',
|
||||
trust: 'trust',
|
||||
def: 'defence',
|
||||
wall: 'wall',
|
||||
trade: 'trade',
|
||||
pop_max: 'populationMax',
|
||||
agri_max: 'agricultureMax',
|
||||
comm_max: 'commerceMax',
|
||||
secu_max: 'securityMax',
|
||||
def_max: 'defenceMax',
|
||||
wall_max: 'wallMax',
|
||||
};
|
||||
const MAX_KEY_MAP: Readonly<Record<CityNumericKey, CityMaximumKey>> = {
|
||||
population: 'populationMax',
|
||||
agriculture: 'agricultureMax',
|
||||
commerce: 'commerceMax',
|
||||
security: 'securityMax',
|
||||
defence: 'defenceMax',
|
||||
wall: 'wallMax',
|
||||
};
|
||||
const PERCENT_PATTERN = /^(\d+(?:\.\d+)?)%$/;
|
||||
const MATH_PATTERN = /^([+\-/*])(\d+(?:\.\d+)?)$/;
|
||||
|
||||
const legacyRound = (value: number): number =>
|
||||
value >= 0 ? Math.floor(value + 0.5) : Math.ceil(value - 0.5);
|
||||
|
||||
const clamp = (value: number, minimum: number, maximum: number): number =>
|
||||
Math.min(maximum, Math.max(minimum, value));
|
||||
|
||||
const readCityTrust = (city: MutableCity): number => {
|
||||
if ('trust' in city && typeof city.trust === 'number') {
|
||||
return city.trust;
|
||||
}
|
||||
const value = city.meta.trust;
|
||||
return typeof value === 'number' ? value : 0;
|
||||
};
|
||||
|
||||
const applyOperator = (current: number, operator: string, operand: number): number => {
|
||||
switch (operator) {
|
||||
case '+':
|
||||
return current + operand;
|
||||
case '-':
|
||||
return current - operand;
|
||||
case '*':
|
||||
return current * operand;
|
||||
case '/':
|
||||
if (operand === 0) {
|
||||
throw new Error('ChangeCity cannot divide by zero.');
|
||||
}
|
||||
return current / operand;
|
||||
default:
|
||||
throw new Error(`Unsupported ChangeCity operator: ${operator}`);
|
||||
}
|
||||
};
|
||||
|
||||
const resolveTargets = (cities: readonly MutableCity[], rawTarget: unknown): MutableCity[] => {
|
||||
if (!rawTarget) {
|
||||
return [...cities];
|
||||
}
|
||||
const targetType =
|
||||
typeof rawTarget === 'string'
|
||||
? rawTarget
|
||||
: Array.isArray(rawTarget) && typeof rawTarget[0] === 'string'
|
||||
? rawTarget[0]
|
||||
: null;
|
||||
const targetArgs = Array.isArray(rawTarget) ? rawTarget.slice(1) : [];
|
||||
if (targetType === 'all') {
|
||||
return [...cities];
|
||||
}
|
||||
if (targetType === 'free') {
|
||||
return cities.filter((city) => city.nationId === 0);
|
||||
}
|
||||
if (targetType === 'occupied') {
|
||||
return cities.filter((city) => city.nationId !== 0);
|
||||
}
|
||||
if (targetType === 'cities') {
|
||||
// ref는 is_numeric(array)를 검사하므로 이 경로의 인자는 항상 도시명
|
||||
// 목록으로 SQL에 전달된다.
|
||||
const names = new Set(targetArgs.map(String));
|
||||
return cities.filter((city) => names.has(city.name));
|
||||
}
|
||||
throw new Error('ChangeCity target type is invalid.');
|
||||
};
|
||||
|
||||
const resolveChangedValue = (
|
||||
city: MutableCity,
|
||||
key: ChangeCityKey,
|
||||
rawValue: unknown
|
||||
): number => {
|
||||
if (typeof rawValue !== 'number' && typeof rawValue !== 'string') {
|
||||
throw new Error('ChangeCity values must be numbers or strings.');
|
||||
}
|
||||
if (key === 'trade') {
|
||||
const value = Number(rawValue);
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error('ChangeCity trade must be numeric.');
|
||||
}
|
||||
return clamp(value, 95, 105);
|
||||
}
|
||||
if (key === 'trust') {
|
||||
if (typeof rawValue === 'number') {
|
||||
if (!Number.isInteger(rawValue)) {
|
||||
if (rawValue < 0) {
|
||||
throw new Error('ChangeCity cannot multiply trust by a negative number.');
|
||||
}
|
||||
return Math.min(100, readCityTrust(city) * rawValue);
|
||||
}
|
||||
return clamp(rawValue, 0, 100);
|
||||
}
|
||||
const percent = rawValue.match(PERCENT_PATTERN);
|
||||
if (percent) {
|
||||
return clamp(legacyRound(Number(percent[1])), 0, 100);
|
||||
}
|
||||
const math = rawValue.match(MATH_PATTERN);
|
||||
if (math) {
|
||||
return clamp(applyOperator(readCityTrust(city), math[1]!, Number(math[2])), 0, 100);
|
||||
}
|
||||
throw new Error('ChangeCity trust pattern is invalid.');
|
||||
}
|
||||
|
||||
const current = city[key];
|
||||
if (typeof rawValue === 'number') {
|
||||
if (!Number.isInteger(rawValue)) {
|
||||
if (rawValue < 0) {
|
||||
throw new Error('ChangeCity cannot multiply a city value by a negative number.');
|
||||
}
|
||||
const maximumKey = MAX_KEY_MAP[key as CityNumericKey];
|
||||
if (!maximumKey) {
|
||||
throw new Error(`ChangeCity float operation is invalid for ${key}.`);
|
||||
}
|
||||
return Math.min(city[maximumKey], legacyRound(current * rawValue));
|
||||
}
|
||||
const maximumKey = MAX_KEY_MAP[key as CityNumericKey];
|
||||
if (!maximumKey) {
|
||||
throw new Error(`ChangeCity integer operation is invalid for ${key}.`);
|
||||
}
|
||||
return Math.min(city[maximumKey], Math.max(0, rawValue));
|
||||
}
|
||||
|
||||
const percent = rawValue.match(PERCENT_PATTERN);
|
||||
if (percent) {
|
||||
const maximumKey = MAX_KEY_MAP[key as CityNumericKey];
|
||||
if (!maximumKey) {
|
||||
throw new Error(`ChangeCity percent operation is invalid for ${key}.`);
|
||||
}
|
||||
return legacyRound(city[maximumKey] * (legacyRound(Number(percent[1])) / 100));
|
||||
}
|
||||
const math = rawValue.match(MATH_PATTERN);
|
||||
if (!math) {
|
||||
throw new Error('ChangeCity value pattern is invalid.');
|
||||
}
|
||||
const result = legacyRound(applyOperator(current, math[1]!, Number(math[2])));
|
||||
if (key.endsWith('Max')) {
|
||||
return Math.max(0, result);
|
||||
}
|
||||
const maximumKey = MAX_KEY_MAP[key as CityNumericKey];
|
||||
if (!maximumKey) {
|
||||
throw new Error(`ChangeCity math operation is invalid for ${key}.`);
|
||||
}
|
||||
return Math.min(city[maximumKey], Math.max(0, result));
|
||||
};
|
||||
|
||||
export const applyChangeCity = <T extends MutableCity>(
|
||||
cities: readonly T[],
|
||||
rawTarget: unknown,
|
||||
rawActions: unknown
|
||||
): T[] => {
|
||||
if (!rawActions || typeof rawActions !== 'object' || Array.isArray(rawActions)) {
|
||||
throw new Error('ChangeCity actions must be an object.');
|
||||
}
|
||||
const targets = resolveTargets(cities, rawTarget);
|
||||
return targets.map((city) => {
|
||||
const next = { ...city, meta: { ...city.meta } } as T & MutableCity;
|
||||
for (const [rawKey, rawValue] of Object.entries(rawActions)) {
|
||||
const key = KEY_MAP[rawKey];
|
||||
if (!key) {
|
||||
throw new Error(`Unsupported ChangeCity key: ${rawKey}`);
|
||||
}
|
||||
const value = resolveChangedValue(next, key, rawValue);
|
||||
if (key === 'trust' || key === 'trade') {
|
||||
if (key in next) {
|
||||
(next as CitySeed)[key] = value;
|
||||
} else {
|
||||
next.meta[key] = value;
|
||||
}
|
||||
} else {
|
||||
next[key] = value;
|
||||
}
|
||||
}
|
||||
return next as T;
|
||||
});
|
||||
};
|
||||
|
||||
export const createChangeCityHandler = (options: {
|
||||
getWorld: () => InMemoryTurnWorld | null;
|
||||
}): MonthlyEventActionHandler => {
|
||||
return (args) => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
}
|
||||
for (const city of applyChangeCity(world.listCities(), args[0], args[1])) {
|
||||
world.updateCity(city.id, city);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export const applyInitialChangeCityEvents = <T extends CitySeed>(
|
||||
cities: readonly T[],
|
||||
initialEvents: readonly unknown[]
|
||||
): T[] => {
|
||||
let result = cities.map((city) => ({ ...city }));
|
||||
for (const rawEvent of initialEvents) {
|
||||
if (!Array.isArray(rawEvent) || rawEvent[0] !== true) {
|
||||
throw new Error('Only unconditional initial events are supported.');
|
||||
}
|
||||
for (const rawAction of rawEvent.slice(1)) {
|
||||
if (!Array.isArray(rawAction) || rawAction[0] !== 'ChangeCity') {
|
||||
throw new Error('Only ChangeCity initial actions are supported.');
|
||||
}
|
||||
const changed = applyChangeCity(result, rawAction[1], rawAction[2]);
|
||||
const changedById = new Map(changed.map((city) => [city.id, city]));
|
||||
result = result.map((city) => changedById.get(city.id) ?? city);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
import { LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||
import type { TurnCommandEnv } 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 { InMemoryReservedTurnStore } from './reservedTurnStore.js';
|
||||
import type { TurnGeneral } from './types.js';
|
||||
|
||||
const NPC_TYPE = 5;
|
||||
const NPC_PREFIX = '㉥';
|
||||
const MAX_LEADERS_BY_NATION_LEVEL: Readonly<Record<number, number>> = {
|
||||
1: 0,
|
||||
2: 1,
|
||||
3: 3,
|
||||
4: 4,
|
||||
5: 6,
|
||||
6: 7,
|
||||
7: 9,
|
||||
};
|
||||
|
||||
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 createTurnTime = (
|
||||
rng: RandUtil,
|
||||
environment: MonthlyEventEnvironment,
|
||||
tickSeconds: number
|
||||
): Date => {
|
||||
const turnMinutes = tickSeconds / 60;
|
||||
if (!(turnMinutes > 0) || !Number.isInteger(turnMinutes)) {
|
||||
throw new Error('ProvideNPCTroopLeader requires a positive integer turn term.');
|
||||
}
|
||||
const seconds = rng.nextRangeInt(0, turnMinutes * 60 - 1);
|
||||
const fraction = rng.nextRangeInt(0, 999_999);
|
||||
return new Date(environment.turnTime.getTime() + seconds * 1_000 + Math.floor(fraction / 1_000));
|
||||
};
|
||||
|
||||
export const createProvideNpcTroopLeaderHandler = (options: {
|
||||
getWorld: () => InMemoryTurnWorld | null;
|
||||
reservedTurns: InMemoryReservedTurnStore;
|
||||
env: TurnCommandEnv;
|
||||
}): MonthlyEventActionHandler => {
|
||||
return (_args, environment) => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
}
|
||||
const currentLastId = world.getState().meta.lastNPCTroopLeaderID;
|
||||
let lastNpcTroopLeaderId =
|
||||
typeof currentLastId === 'number' && Number.isFinite(currentLastId)
|
||||
? Math.trunc(currentLastId)
|
||||
: 0;
|
||||
|
||||
for (const nation of world.listNations().sort((left, right) => left.id - right.id)) {
|
||||
const maximum = MAX_LEADERS_BY_NATION_LEVEL[nation.level] ?? 0;
|
||||
let current = world
|
||||
.listGenerals()
|
||||
.filter((general) => general.nationId === nation.id && general.npcState === NPC_TYPE).length;
|
||||
if (current >= maximum) {
|
||||
continue;
|
||||
}
|
||||
const rng = new RandUtil(
|
||||
new LiteHashDRBG(
|
||||
simpleSerialize(
|
||||
resolveHiddenSeed(world),
|
||||
'troopLeader',
|
||||
environment.year,
|
||||
environment.month,
|
||||
nation.id
|
||||
)
|
||||
)
|
||||
);
|
||||
while (current < maximum) {
|
||||
lastNpcTroopLeaderId += 1;
|
||||
const allCities = world.listCities().sort((left, right) => left.id - right.id);
|
||||
const cityCandidates = allCities.filter((city) => city.nationId === nation.id);
|
||||
const cityPool = cityCandidates.length > 0 ? cityCandidates : allCities;
|
||||
if (cityPool.length === 0) {
|
||||
throw new Error('ProvideNPCTroopLeader requires at least one city.');
|
||||
}
|
||||
const city = rng.choice(cityPool);
|
||||
const id = world.getNextGeneralId();
|
||||
const age = 20;
|
||||
const general: TurnGeneral = {
|
||||
id,
|
||||
userId: null,
|
||||
name: `${NPC_PREFIX}부대장${String(lastNpcTroopLeaderId).padStart(4, ' ')}`,
|
||||
nationId: nation.id,
|
||||
cityId: city.id,
|
||||
troopId: id,
|
||||
stats: { leadership: 10, strength: 10, intelligence: 10 },
|
||||
experience: age * 100,
|
||||
dedication: age * 100,
|
||||
officerLevel: 1,
|
||||
role: {
|
||||
personality: 'che_은둔',
|
||||
specialDomestic: options.env.defaultSpecialDomestic,
|
||||
specialWar: options.env.defaultSpecialWar,
|
||||
items: { horse: null, weapon: null, book: null, item: null },
|
||||
},
|
||||
injury: 0,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
crew: 0,
|
||||
crewTypeId: options.env.defaultCrewTypeId,
|
||||
train: 0,
|
||||
atmos: 0,
|
||||
age,
|
||||
npcState: NPC_TYPE,
|
||||
bornYear: environment.year - 20,
|
||||
deadYear: environment.year + 60,
|
||||
affinity: 999,
|
||||
picture: 'default.jpg',
|
||||
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
|
||||
lastTurn: { command: '휴식' },
|
||||
turnTime: createTurnTime(rng, environment, world.getState().tickSeconds),
|
||||
recentWarTime: null,
|
||||
meta: {
|
||||
killturn: 70,
|
||||
npcType: NPC_TYPE,
|
||||
npc_org: NPC_TYPE,
|
||||
belong: 0,
|
||||
dedlevel: 1,
|
||||
specage: 999,
|
||||
specage2: 999,
|
||||
dex1: 0,
|
||||
dex2: 0,
|
||||
dex3: 0,
|
||||
dex4: 0,
|
||||
dex5: 0,
|
||||
},
|
||||
};
|
||||
if (!world.addGeneral(general)) {
|
||||
throw new Error(`ProvideNPCTroopLeader generated duplicate general id ${id}.`);
|
||||
}
|
||||
if (
|
||||
!world.createTroop({
|
||||
id,
|
||||
nationId: nation.id,
|
||||
name: general.name,
|
||||
})
|
||||
) {
|
||||
throw new Error(`ProvideNPCTroopLeader generated duplicate troop id ${id}.`);
|
||||
}
|
||||
options.reservedTurns.replaceGeneralTurns(id, {
|
||||
action: 'che_집합',
|
||||
args: {},
|
||||
});
|
||||
current += 1;
|
||||
world.updateWorldMeta({ lastNPCTroopLeaderID: lastNpcTroopLeaderId });
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -59,6 +59,8 @@ import {
|
||||
createInvaderEndingHandler,
|
||||
createRaiseInvaderHandler,
|
||||
} from './monthlyInvaderAction.js';
|
||||
import { createChangeCityHandler } from './monthlyChangeCityAction.js';
|
||||
import { createProvideNpcTroopLeaderHandler } from './monthlyProvideNpcTroopLeaderAction.js';
|
||||
import { buildCommandEnv } from './reservedTurnCommands.js';
|
||||
import { DatabaseTurnDaemonLease, TurnDaemonLeaseUnavailableError } from '../lifecycle/databaseTurnDaemonLease.js';
|
||||
|
||||
@@ -183,7 +185,8 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
hasEventAction('RegNeutralNPC') ||
|
||||
hasEventAction('RaiseNPCNation') ||
|
||||
hasEventAction('RaiseInvader') ||
|
||||
hasEventAction('AutoDeleteInvader');
|
||||
hasEventAction('AutoDeleteInvader') ||
|
||||
hasEventAction('ProvideNPCTroopLeader');
|
||||
const reservedTurnStoreHandle =
|
||||
options.generalTurnHandler && !eventRequiresReservedTurns
|
||||
? null
|
||||
@@ -299,6 +302,14 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
reservedTurns: reservedTurnStoreHandle.store,
|
||||
})
|
||||
);
|
||||
eventActions.set(
|
||||
'ProvideNPCTroopLeader',
|
||||
createProvideNpcTroopLeaderHandler({
|
||||
getWorld: () => worldRef,
|
||||
reservedTurns: reservedTurnStoreHandle.store,
|
||||
env: monthlyCommandEnv,
|
||||
})
|
||||
);
|
||||
eventActions.set(
|
||||
'UpdateNationLevel',
|
||||
createUpdateNationLevelHandler({
|
||||
@@ -315,6 +326,12 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
getWorld: () => worldRef,
|
||||
})
|
||||
);
|
||||
eventActions.set(
|
||||
'ChangeCity',
|
||||
createChangeCityHandler({
|
||||
getWorld: () => worldRef,
|
||||
})
|
||||
);
|
||||
eventActions.set('ProcessIncome', async (_args, environment) => {
|
||||
await incomeHandler.onMonthChanged?.({
|
||||
previousYear: environment.month === 1 ? environment.year - 1 : environment.year,
|
||||
|
||||
Reference in New Issue
Block a user