feat: add unification handler and inheritance system
- Implemented `unificationHandler.ts` to manage nation unification logic, including inheritance point calculations and logging. - Created `InheritView.vue` for frontend management of inheritance points, buffs, and logs. - Added database migration for new inheritance tables: `inheritance_point`, `inheritance_log`, `inheritance_result`, and `inheritance_user_state`. - Developed inheritance buff logic in `inheritBuff.ts` to apply buffs during domestic and war actions.
This commit is contained in:
@@ -210,6 +210,20 @@ export class InMemoryTurnWorld {
|
||||
return { ...this.state };
|
||||
}
|
||||
|
||||
updateWorldMeta(patch: Record<string, unknown>): void {
|
||||
this.state = {
|
||||
...this.state,
|
||||
meta: {
|
||||
...this.state.meta,
|
||||
...patch,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
pushLog(entry: LogEntryDraft): void {
|
||||
this.logs.push(entry);
|
||||
}
|
||||
|
||||
getScenarioConfig(): ScenarioConfig {
|
||||
return this.scenarioConfig;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
createItemModuleRegistry,
|
||||
ITEM_KEYS,
|
||||
loadItemModules,
|
||||
createInheritBuffModules,
|
||||
} from '@sammo-ts/logic';
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
|
||||
@@ -107,8 +108,11 @@ export const buildReservedTurnDefinitions = async (options: {
|
||||
const itemModules = await loadItemModules([...ITEM_KEYS]);
|
||||
const itemRegistry = createItemModuleRegistry(itemModules);
|
||||
const itemActionModules = createItemActionModules(itemRegistry);
|
||||
const inheritBuffModules = createInheritBuffModules();
|
||||
options.env.generalActionModules = [...(options.env.generalActionModules ?? []), ...itemActionModules.general];
|
||||
options.env.warActionModules = [...(options.env.warActionModules ?? []), ...itemActionModules.war];
|
||||
options.env.generalActionModules.push(inheritBuffModules.general);
|
||||
options.env.warActionModules.push(inheritBuffModules.war);
|
||||
|
||||
const generalSpecs = await loadGeneralTurnCommandSpecs(options.commandProfile.general);
|
||||
const nationSpecs = await loadNationTurnCommandSpecs(options.commandProfile.nation);
|
||||
|
||||
@@ -468,7 +468,7 @@ export const createReservedTurnHandler = async (options: {
|
||||
fallbackDefinition: GeneralActionDefinition,
|
||||
command: ReservedTurnEntry,
|
||||
applyNextTurnAt: boolean
|
||||
): Date | undefined => {
|
||||
): { nextTurnAt?: Date; actionKey: string } => {
|
||||
const resolvedDefinition = resolveDefinition(command.action, definitionMap, fallbackDefinition);
|
||||
const rawArgs = extractArgsRecord(command.args);
|
||||
const parsedArgs = resolvedDefinition.parseArgs(rawArgs);
|
||||
@@ -658,7 +658,7 @@ export const createReservedTurnHandler = async (options: {
|
||||
}
|
||||
}
|
||||
|
||||
return applyNextTurnAt ? resolution.nextTurnAt : undefined;
|
||||
return { nextTurnAt: applyNextTurnAt ? resolution.nextTurnAt : undefined, actionKey };
|
||||
};
|
||||
|
||||
if (currentNation && currentGeneral.officerLevel >= 5) {
|
||||
@@ -718,9 +718,25 @@ export const createReservedTurnHandler = async (options: {
|
||||
generalCommand = { action: candidate.action, args: candidate.args };
|
||||
}
|
||||
}
|
||||
const nextTurnAt = runAction(generalDefinitions, generalFallback, generalCommand, true);
|
||||
const generalResult = runAction(generalDefinitions, generalFallback, generalCommand, true);
|
||||
const nextTurnAt = generalResult.nextTurnAt;
|
||||
options.reservedTurns.shiftGeneralTurns(currentGeneral.id, -1);
|
||||
|
||||
const worldMeta = asRecord(context.world.meta);
|
||||
if (currentGeneral.npcState < 2 && !(typeof worldMeta.isUnited === 'number' && worldMeta.isUnited !== 0)) {
|
||||
const meta = { ...currentGeneral.meta };
|
||||
const lived = typeof meta.inherit_lived_month === 'number' ? meta.inherit_lived_month : 0;
|
||||
const active = typeof meta.inherit_active_action === 'number' ? meta.inherit_active_action : 0;
|
||||
meta.inherit_lived_month = lived + 1;
|
||||
if (generalResult.actionKey !== DEFAULT_ACTION) {
|
||||
meta.inherit_active_action = active + 1;
|
||||
} else {
|
||||
meta.inherit_active_action = active;
|
||||
}
|
||||
currentGeneral = { ...currentGeneral, meta };
|
||||
worldOverlay?.syncGeneral(currentGeneral);
|
||||
}
|
||||
|
||||
const result: GeneralTurnResult = {
|
||||
general: currentGeneral,
|
||||
city: currentCity,
|
||||
|
||||
@@ -22,6 +22,7 @@ import { createTurnDaemonCommandHandler } from './worldCommandHandler.js';
|
||||
import { loadTurnCommandProfile } from './turnCommandProfile.js';
|
||||
import { loadTurnWorldFromDatabase } from './worldLoader.js';
|
||||
import { shouldUseAi } from './ai/generalAi.js';
|
||||
import { createUnificationHandler } from './unificationHandler.js';
|
||||
|
||||
export interface TurnDaemonRuntimeOptions {
|
||||
profile: string;
|
||||
@@ -99,6 +100,13 @@ export const createTurnDaemonRuntime = async (options: TurnDaemonRuntimeOptions)
|
||||
})
|
||||
: await loadTurnCommandProfile());
|
||||
let worldRef: InMemoryTurnWorld | null = null;
|
||||
const unification = options.calendarHandler
|
||||
? null
|
||||
: createUnificationHandler({
|
||||
databaseUrl: options.databaseUrl,
|
||||
profileName: options.profileName ?? options.profile,
|
||||
getWorld: () => worldRef,
|
||||
});
|
||||
const worldOptions: InMemoryTurnWorldOptions = {
|
||||
schedule,
|
||||
generalTurnHandler:
|
||||
@@ -112,7 +120,7 @@ export const createTurnDaemonRuntime = async (options: TurnDaemonRuntimeOptions)
|
||||
getWorld: () => worldRef,
|
||||
commandProfile,
|
||||
})),
|
||||
calendarHandler: options.calendarHandler,
|
||||
calendarHandler: options.calendarHandler ?? unification?.handler,
|
||||
};
|
||||
const world = new InMemoryTurnWorld(resolvedState, snapshot, worldOptions);
|
||||
worldRef = world;
|
||||
@@ -250,6 +258,9 @@ export const createTurnDaemonRuntime = async (options: TurnDaemonRuntimeOptions)
|
||||
const baseClose = close;
|
||||
close = async () => {
|
||||
await baseClose();
|
||||
if (unification) {
|
||||
await unification.close();
|
||||
}
|
||||
if (redisConnector) {
|
||||
await redisConnector.disconnect();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import { createGamePostgresConnector } from '@sammo-ts/infra';
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import type { LogEntryDraft } from '@sammo-ts/logic';
|
||||
import { LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
|
||||
|
||||
import type { TurnCalendarHandler } from './inMemoryWorld.js';
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
|
||||
const UNIFIER_POINT = 2000;
|
||||
|
||||
const readMetaNumber = (meta: Record<string, unknown>, key: string): number => {
|
||||
const value = meta[key];
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const computeDexPoint = (meta: Record<string, unknown>): number => {
|
||||
let total = 0;
|
||||
for (const [key, value] of Object.entries(meta)) {
|
||||
if (!key.startsWith('dex')) {
|
||||
continue;
|
||||
}
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
total += value;
|
||||
}
|
||||
}
|
||||
return total * 0.001;
|
||||
};
|
||||
|
||||
const buildUnificationLog = (nationName: string): LogEntryDraft => ({
|
||||
scope: LogScope.SYSTEM,
|
||||
category: LogCategory.HISTORY,
|
||||
format: LogFormat.YEAR_MONTH,
|
||||
text: `<C>●</><Y><b>【통일】</b></><D><b>${nationName}</b></>이 전토를 통일하였습니다.`,
|
||||
meta: {},
|
||||
});
|
||||
|
||||
export const createUnificationHandler = (options: {
|
||||
databaseUrl: string;
|
||||
profileName: string;
|
||||
getWorld: () => InMemoryTurnWorld | null;
|
||||
}): { handler: TurnCalendarHandler; close: () => Promise<void> } => {
|
||||
const connector = createGamePostgresConnector({ url: options.databaseUrl });
|
||||
const ready = connector.connect();
|
||||
|
||||
const settleInheritance = async (winnerNationId: number, year: number, month: number): Promise<void> => {
|
||||
await ready;
|
||||
const prisma = connector.prisma;
|
||||
|
||||
const generals = await prisma.general.findMany({
|
||||
where: {
|
||||
userId: { not: null },
|
||||
npcState: { lt: 2 },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
nationId: true,
|
||||
officerLevel: true,
|
||||
meta: true,
|
||||
},
|
||||
});
|
||||
|
||||
const userIds = Array.from(new Set(generals.map((general) => general.userId).filter(Boolean))) as string[];
|
||||
if (userIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pointRows = await prisma.inheritancePoint.findMany({
|
||||
where: {
|
||||
userId: { in: userIds },
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
key: true,
|
||||
value: true,
|
||||
},
|
||||
});
|
||||
const pointMap = new Map<string, Map<string, number>>();
|
||||
for (const row of pointRows) {
|
||||
const bucket = pointMap.get(row.userId) ?? new Map();
|
||||
bucket.set(row.key, row.value);
|
||||
pointMap.set(row.userId, bucket);
|
||||
}
|
||||
|
||||
for (const general of generals) {
|
||||
if (!general.userId) {
|
||||
continue;
|
||||
}
|
||||
const meta = asRecord(general.meta);
|
||||
const livedMonth = readMetaNumber(meta, 'inherit_lived_month');
|
||||
const maxDomestic = readMetaNumber(meta, 'max_domestic_critical');
|
||||
const activeAction = readMetaNumber(meta, 'inherit_active_action');
|
||||
const combat = readMetaNumber(meta, 'rank_warnum') * 5;
|
||||
const sabotage = readMetaNumber(meta, 'firenum') * 20;
|
||||
const dex = computeDexPoint(meta);
|
||||
|
||||
const points = pointMap.get(general.userId) ?? new Map();
|
||||
const previous = points.get('previous') ?? 0;
|
||||
const unifier = points.get('unifier') ?? 0;
|
||||
const earned =
|
||||
livedMonth +
|
||||
maxDomestic +
|
||||
activeAction * 3 +
|
||||
combat +
|
||||
sabotage +
|
||||
dex +
|
||||
unifier +
|
||||
(general.nationId === winnerNationId && general.officerLevel > 4 ? UNIFIER_POINT : 0);
|
||||
|
||||
const total = previous + earned;
|
||||
|
||||
await prisma.inheritancePoint.upsert({
|
||||
where: {
|
||||
userId_key: {
|
||||
userId: general.userId,
|
||||
key: 'previous',
|
||||
},
|
||||
},
|
||||
update: { value: total },
|
||||
create: { userId: general.userId, key: 'previous', value: total },
|
||||
});
|
||||
|
||||
await prisma.inheritancePoint.deleteMany({
|
||||
where: {
|
||||
userId: general.userId,
|
||||
key: { not: 'previous' },
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.inheritanceResult.create({
|
||||
data: {
|
||||
serverId: options.profileName,
|
||||
owner: general.userId,
|
||||
generalId: general.id,
|
||||
year,
|
||||
month,
|
||||
value: {
|
||||
previous,
|
||||
lived_month: livedMonth,
|
||||
max_domestic_critical: maxDomestic,
|
||||
active_action: activeAction,
|
||||
combat,
|
||||
sabotage,
|
||||
dex,
|
||||
unifier,
|
||||
unifierAward: general.nationId === winnerNationId && general.officerLevel > 4 ? UNIFIER_POINT : 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.inheritanceLog.create({
|
||||
data: {
|
||||
userId: general.userId,
|
||||
year,
|
||||
month,
|
||||
text: `천하 통일 정산: ${Math.floor(total).toLocaleString()} 포인트`,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handler: TurnCalendarHandler = {
|
||||
onMonthChanged: (context) => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
}
|
||||
const state = world.getState();
|
||||
const meta = asRecord(state.meta);
|
||||
if (typeof meta.isUnited === 'number' && meta.isUnited !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeNations = world.listNations().filter((nation) => nation.level > 0);
|
||||
if (activeNations.length !== 1) {
|
||||
return;
|
||||
}
|
||||
const winner = activeNations[0];
|
||||
const cities = world.listCities();
|
||||
const ownedCount = cities.filter((city) => city.nationId === winner.id).length;
|
||||
if (ownedCount !== cities.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
world.updateWorldMeta({ isUnited: 2 });
|
||||
world.pushLog(buildUnificationLog(winner.name));
|
||||
void settleInheritance(winner.id, context.currentYear, context.currentMonth);
|
||||
},
|
||||
};
|
||||
|
||||
const close = async (): Promise<void> => {
|
||||
await ready;
|
||||
await connector.disconnect();
|
||||
};
|
||||
|
||||
return { handler, close };
|
||||
};
|
||||
Reference in New Issue
Block a user