Implement nation betting lifecycle

This commit is contained in:
2026-07-25 20:16:11 +00:00
parent 06ab6c3565
commit 25e67e15ae
15 changed files with 1750 additions and 0 deletions
@@ -0,0 +1,120 @@
export interface NationBettingStake {
generalId: number;
userId: string | null;
selection: number[];
amount: number;
}
export interface NationBettingReward {
generalId: number;
userId: string | null;
amount: number;
matchPoint: number;
}
export const purifyNationBettingSelection = (
selection: readonly number[],
selectCount: number
): number[] => {
const purified = [...selection].sort((left, right) => left - right);
const unique = purified.filter((value, index) => index === 0 || value !== purified[index - 1]);
if (unique.length !== selectCount) {
throw new Error('중복된 값이 있습니다.');
}
return unique;
};
export const calculateNationBettingRewards = (options: {
selectCount: number;
isExclusive: boolean | null;
winner: readonly number[];
stakes: readonly NationBettingStake[];
}): NationBettingReward[] => {
const winner = purifyNationBettingSelection(options.winner, options.selectCount);
const totalAmount = options.stakes.reduce((sum, stake) => sum + stake.amount, 0);
if (totalAmount === 0) {
return [];
}
if (options.selectCount === 1 || options.isExclusive === true) {
const winnerKey = JSON.stringify(winner);
const winnerList = options.stakes.filter(
(stake) => stake.generalId > 0 && JSON.stringify(stake.selection) === winnerKey
);
const winnerAmount = winnerList.reduce((sum, stake) => sum + stake.amount, 0);
// Legacy creates a refundList here but accidentally returns an empty
// result. Preserve that observable no-winner behavior.
if (winnerAmount === 0) {
return [];
}
const multiplier = totalAmount / winnerAmount;
return winnerList.map((stake) => ({
generalId: stake.generalId,
userId: stake.userId,
amount: stake.amount * multiplier,
matchPoint: options.selectCount,
}));
}
const winnerSet = new Set(winner);
const stakesByMatch = new Map<number, NationBettingStake[]>();
const amountByMatch = new Map<number, number>();
for (let matchPoint = 0; matchPoint <= options.selectCount; matchPoint += 1) {
stakesByMatch.set(matchPoint, []);
amountByMatch.set(matchPoint, 0);
}
for (const stake of options.stakes) {
const matchPoint = stake.selection.reduce(
(count, selected) => count + (winnerSet.has(selected) ? 1 : 0),
0
);
if (stake.generalId === 0) {
continue;
}
stakesByMatch.get(matchPoint)?.push(stake);
amountByMatch.set(matchPoint, (amountByMatch.get(matchPoint) ?? 0) + stake.amount);
}
let remainingReward = totalAmount;
let accumulatedReward = 0;
let givenReward = totalAmount;
const rewardByMatch = new Map<number, number>();
for (let matchPoint = options.selectCount; matchPoint >= 1; matchPoint -= 1) {
givenReward /= 2;
accumulatedReward += givenReward;
if ((stakesByMatch.get(matchPoint)?.length ?? 0) === 0 || (amountByMatch.get(matchPoint) ?? 0) === 0) {
continue;
}
rewardByMatch.set(matchPoint, accumulatedReward);
remainingReward -= accumulatedReward;
accumulatedReward = 0;
}
for (let matchPoint = options.selectCount; matchPoint >= 0; matchPoint -= 1) {
const reward = rewardByMatch.get(matchPoint);
if (reward === undefined) {
continue;
}
rewardByMatch.set(matchPoint, reward + remainingReward);
break;
}
const result: NationBettingReward[] = [];
for (let matchPoint = options.selectCount; matchPoint >= 1; matchPoint -= 1) {
const reward = rewardByMatch.get(matchPoint);
const staked = amountByMatch.get(matchPoint) ?? 0;
if (!reward || staked === 0) {
continue;
}
const multiplier = reward / staked;
for (const stake of stakesByMatch.get(matchPoint) ?? []) {
result.push({
generalId: stake.generalId,
userId: stake.userId,
amount: stake.amount * multiplier,
matchPoint,
});
}
}
return result;
};
+235
View File
@@ -16,6 +16,7 @@ import {
import {
finalizeLogEntry,
LogCategory,
LogFormat,
LogScope,
sendMessage,
type LogEntryDraft,
@@ -30,6 +31,12 @@ import { buildDiplomacyMeta } from '@sammo-ts/logic';
import { ensureItemInventory, withSerializedItemInventory } from '@sammo-ts/logic/items/index.js';
import { persistGeneralLifecycleEvents } from './generalTurnLifecyclePersistence.js';
import type { DatabaseTurnDaemonLease } from '../lifecycle/databaseTurnDaemonLease.js';
import { calculateNationBettingRewards } from '../betting/nationBettingSettlement.js';
import type {
NationBettingCandidate,
PendingNationBettingFinish,
PendingNationBettingOpen,
} from './types.js';
export interface DatabaseTurnHooks {
hooks: TurnDaemonHooks;
@@ -37,6 +44,225 @@ export interface DatabaseTurnHooks {
}
const asJson = (value: unknown): InputJsonValue => value as InputJsonValue;
const formatLegacyNumber = (value: number): string => Math.round(value).toLocaleString('en-US');
const readBettingCandidates = (value: unknown): NationBettingCandidate[] => {
if (!Array.isArray(value)) {
return [];
}
return value.flatMap((candidate) => {
const item = asRecord(candidate);
const aux = asRecord(item.aux);
if (
typeof item.title !== 'string' ||
typeof aux.nation !== 'number' ||
!Number.isInteger(aux.nation)
) {
return [];
}
return [
{
title: item.title,
info: typeof item.info === 'string' ? item.info : '',
isHtml: true as const,
aux: {
nation: aux.nation,
name: typeof aux.name === 'string' ? aux.name : item.title,
color: typeof aux.color === 'string' ? aux.color : '#000000',
type: typeof aux.type === 'string' ? aux.type : '',
level: typeof aux.level === 'number' ? aux.level : 0,
capital: typeof aux.capital === 'number' ? aux.capital : null,
gennum: typeof aux.gennum === 'number' ? aux.gennum : 0,
power: typeof aux.power === 'number' ? aux.power : 0,
city_cnt: typeof aux.city_cnt === 'number' ? aux.city_cnt : 0,
},
},
];
});
};
const persistNationBettingOpen = async (
prisma: GamePrisma.TransactionClient,
betting: PendingNationBettingOpen
): Promise<void> => {
await prisma.nationBetting.create({
data: {
id: betting.id,
type: 'bettingNation',
name: betting.name,
finished: false,
selectCount: betting.selectCount,
isExclusive: betting.isExclusive,
requiresInheritancePoint: betting.requiresInheritancePoint,
openYearMonth: betting.openYearMonth,
closeYearMonth: betting.closeYearMonth,
candidates: asJson(betting.candidates),
},
});
if (betting.bonusPoint > 0) {
await prisma.nationBet.create({
data: {
bettingId: betting.id,
generalId: 0,
userId: null,
selection: [-1],
selectionKey: '[-1]',
amount: betting.bonusPoint,
},
});
}
};
const persistNationBettingFinish = async (
prisma: GamePrisma.TransactionClient,
finish: PendingNationBettingFinish
): Promise<void> => {
await prisma.$queryRaw`
SELECT id
FROM nation_betting
WHERE id = ${finish.id}
FOR UPDATE
`;
const betting = await prisma.nationBetting.findUnique({
where: { id: finish.id },
include: { bets: { orderBy: { id: 'asc' } } },
});
if (!betting || betting.type !== 'bettingNation' || betting.finished) {
return;
}
if (finish.winnerNationIds.length !== betting.selectCount) {
return;
}
const candidates = readBettingCandidates(betting.candidates);
const candidateIndexByNation = new Map(candidates.map((candidate, index) => [candidate.aux.nation, index]));
let newNationOffset = 0;
const winner = finish.winnerNationIds.map((nationId) => {
const candidateIndex = candidateIndexByNation.get(nationId);
if (candidateIndex !== undefined) {
return candidateIndex;
}
const result = candidates.length + newNationOffset;
newNationOffset += 1;
return result;
});
const purifiedWinner = [...new Set(winner)].sort((left, right) => left - right);
if (purifiedWinner.length !== betting.selectCount) {
return;
}
const rewards = calculateNationBettingRewards({
selectCount: betting.selectCount,
isExclusive: betting.isExclusive,
winner: purifiedWinner,
stakes: betting.bets.map((bet) => ({
generalId: bet.generalId,
userId: bet.userId,
selection: Array.isArray(bet.selection)
? bet.selection.filter((value): value is number => typeof value === 'number')
: [],
amount: bet.amount,
})),
});
for (const reward of rewards) {
if (!reward.userId) {
continue;
}
const existing = await prisma.inheritancePoint.findUnique({
where: { userId_key: { userId: reward.userId, key: 'previous' } },
select: { value: true },
});
const previousPoint = existing?.value ?? 0;
const nextPoint = previousPoint + reward.amount;
await prisma.inheritancePoint.upsert({
where: { userId_key: { userId: reward.userId, key: 'previous' } },
update: { value: nextPoint },
create: { userId: reward.userId, key: 'previous', value: nextPoint },
});
await prisma.rankData.upsert({
where: {
generalId_type: {
generalId: reward.generalId,
type: 'inherit_earned_act',
},
},
update: { value: { increment: Math.trunc(reward.amount) } },
create: {
generalId: reward.generalId,
nationId:
(
await prisma.general.findUnique({
where: { id: reward.generalId },
select: { nationId: true },
})
)?.nationId ?? 0,
type: 'inherit_earned_act',
value: Math.trunc(reward.amount),
},
});
const partialText =
reward.matchPoint === betting.selectCount
? '베팅 당첨'
: `베팅 부분 당첨(${reward.matchPoint}/${betting.selectCount})`;
await prisma.inheritanceLog.createMany({
data: [
{
userId: reward.userId,
year: finish.year,
month: finish.month,
text: `${betting.name} ${partialText} 보상으로 ${formatLegacyNumber(reward.amount)} 포인트 획득.`,
},
{
userId: reward.userId,
year: finish.year,
month: finish.month,
text: `포인트 ${formatLegacyNumber(previousPoint)} => ${formatLegacyNumber(nextPoint)}`,
},
],
});
}
await prisma.nationBetting.update({
where: { id: finish.id },
data: {
finished: true,
winner: purifiedWinner,
},
});
const openYear = Math.floor(betting.openYearMonth / 12);
const openMonth = (betting.openYearMonth % 12) + 1;
const finishLog = finalizeLogEntry(
{
scope: LogScope.SYSTEM,
category: LogCategory.HISTORY,
format: LogFormat.YEAR_MONTH,
text: `<B><b>【내기】</b></> ${openYear}${openMonth}월에 열렸던 ${betting.name} 내기의 결과가 나왔습니다!`,
},
{
year: finish.year,
month: finish.month,
at: finish.turnTime,
}
);
if (finishLog) {
await prisma.logEntry.create({
data: {
scope: finishLog.scope,
category: finishLog.category,
subType: finishLog.subType ?? null,
year: finishLog.year,
month: finishLog.month,
text: finishLog.text,
generalId: finishLog.generalId ?? null,
nationId: finishLog.nationId ?? null,
userId: finishLog.userId ?? null,
meta: asJson(finishLog.meta ?? {}),
createdAt: finishLog.createdAt,
},
});
}
};
const toCode = (value: string | null | undefined): string => (value && value !== 'None' ? value : 'None');
@@ -399,6 +625,8 @@ export const createDatabaseTurnHooks = async (
lifecycleEvents,
pendingNeutralAuctions,
inheritancePointAdjustments,
pendingNationBettingOpens,
pendingNationBettingFinishes,
} = changes;
const reservedTurnChanges = options?.reservedTurns?.peekDirtyState();
@@ -440,6 +668,13 @@ export const createDatabaseTurnHooks = async (
data: worldStateUpdate,
});
for (const betting of pendingNationBettingOpens) {
await persistNationBettingOpen(prisma, betting);
}
for (const finish of pendingNationBettingFinishes) {
await persistNationBettingFinish(prisma, finish);
}
const meta = asRecord(state.meta);
const serverId =
typeof meta.serverId === 'string' && meta.serverId.trim() ? meta.serverId.trim() : 'default';
+44
View File
@@ -4,6 +4,8 @@ import { getNextTurnAt } from '@sammo-ts/logic';
import type { TurnCheckpoint } from '../lifecycle/types.js';
import type {
PendingNeutralAuction,
PendingNationBettingFinish,
PendingNationBettingOpen,
TurnDiplomacy,
TurnEvent,
TurnGeneral,
@@ -112,6 +114,8 @@ export interface TurnWorldChanges {
lifecycleEvents: GeneralLifecycleEvent[];
pendingNeutralAuctions: PendingNeutralAuction[];
inheritancePointAdjustments: Array<{ userId: string; key: string; amount: number }>;
pendingNationBettingOpens: PendingNationBettingOpen[];
pendingNationBettingFinishes: PendingNationBettingFinish[];
}
const compareTurnOrder = (left: TurnGeneral, right: TurnGeneral): number => {
@@ -283,6 +287,8 @@ export class InMemoryTurnWorld {
private readonly lifecycleEvents: GeneralLifecycleEvent[] = [];
private readonly pendingNeutralAuctions: PendingNeutralAuction[] = [];
private readonly inheritancePointAdjustments: Array<{ userId: string; key: string; amount: number }> = [];
private readonly pendingNationBettingOpens: PendingNationBettingOpen[] = [];
private readonly pendingNationBettingFinishes: PendingNationBettingFinish[] = [];
private readonly scenarioConfig: ScenarioConfig;
private checkpoint?: TurnCheckpoint;
private state: TurnWorldState;
@@ -366,6 +372,10 @@ export class InMemoryTurnWorld {
this.logs.push(entry);
}
queueMessage(draft: MessageDraft): void {
this.messages.push(draft);
}
queueNeutralAuction(auction: PendingNeutralAuction): void {
this.pendingNeutralAuctions.push({
...auction,
@@ -381,6 +391,24 @@ export class InMemoryTurnWorld {
this.inheritancePointAdjustments.push({ userId, key, amount });
}
queueNationBettingOpen(betting: PendingNationBettingOpen): void {
this.pendingNationBettingOpens.push({
...betting,
candidates: betting.candidates.map((candidate) => ({
...candidate,
aux: { ...candidate.aux },
})),
});
}
queueNationBettingFinish(finish: PendingNationBettingFinish): void {
this.pendingNationBettingFinishes.push({
...finish,
winnerNationIds: [...finish.winnerNationIds],
turnTime: new Date(finish.turnTime.getTime()),
});
}
getScenarioConfig(): ScenarioConfig {
return this.scenarioConfig;
}
@@ -918,6 +946,18 @@ export class InMemoryTurnWorld {
closeAt: new Date(auction.closeAt.getTime()),
}));
const inheritancePointAdjustments = this.inheritancePointAdjustments.map((entry) => ({ ...entry }));
const pendingNationBettingOpens = this.pendingNationBettingOpens.map((entry) => ({
...entry,
candidates: entry.candidates.map((candidate) => ({
...candidate,
aux: { ...candidate.aux },
})),
}));
const pendingNationBettingFinishes = this.pendingNationBettingFinishes.map((entry) => ({
...entry,
winnerNationIds: [...entry.winnerNationIds],
turnTime: new Date(entry.turnTime.getTime()),
}));
return {
generals,
@@ -940,6 +980,8 @@ export class InMemoryTurnWorld {
lifecycleEvents,
pendingNeutralAuctions,
inheritancePointAdjustments,
pendingNationBettingOpens,
pendingNationBettingFinishes,
};
}
@@ -968,6 +1010,8 @@ export class InMemoryTurnWorld {
this.lifecycleEvents.splice(0, changes.lifecycleEvents.length);
this.pendingNeutralAuctions.splice(0, changes.pendingNeutralAuctions.length);
this.inheritancePointAdjustments.splice(0, changes.inheritancePointAdjustments.length);
this.pendingNationBettingOpens.splice(0, changes.pendingNationBettingOpens.length);
this.pendingNationBettingFinishes.splice(0, changes.pendingNationBettingFinishes.length);
}
consumeDirtyState(): TurnWorldChanges {
@@ -0,0 +1,165 @@
import { LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
import type { MonthlyEventActionHandler } from './monthlyEventHandler.js';
import type { NationBettingCandidate } from './types.js';
const joinYearMonth = (year: number, month: number): number => year * 12 + month - 1;
const readIntegerArg = (value: unknown, fallback: number, label: string): number => {
if (value === undefined) {
return fallback;
}
if (typeof value !== 'number' || !Number.isInteger(value)) {
throw new Error(`${label} must be an integer.`);
}
return value;
};
export const createOpenNationBettingHandler = (options: {
getWorld: () => InMemoryTurnWorld | null;
}): MonthlyEventActionHandler => {
return (args, environment) => {
const world = options.getWorld();
if (!world) {
return;
}
const nationCount = readIntegerArg(args[0], 1, 'OpenNationBetting nation count');
const bonusPoint = readIntegerArg(args[1], 0, 'OpenNationBetting bonus point');
if (nationCount < 1) {
throw new Error('OpenNationBetting nation count must be at least 1.');
}
if (bonusPoint < 0) {
throw new Error('OpenNationBetting bonus point must not be negative.');
}
const generals = world.listGenerals();
const cities = world.listCities();
const candidates: NationBettingCandidate[] = world
.listNations()
.filter((nation) => nation.id > 0)
.sort((left, right) => right.power - left.power)
.map((nation) => {
const generalCount = generals.filter((general) => general.nationId === nation.id).length;
const cityCount = cities.filter((city) => city.nationId === nation.id).length;
return {
title: nation.name,
info: `국력: ${nation.power}<br>장수 수: ${generalCount}<br>도시 수: ${cityCount}`,
isHtml: true,
aux: {
nation: nation.id,
name: nation.name,
color: nation.color,
type: nation.typeCode,
level: nation.level,
capital: nation.capitalCityId,
gennum: generalCount,
power: nation.power,
city_cnt: cityCount,
},
};
});
const currentLastId = world.getState().meta.lastBettingId;
const bettingId =
(typeof currentLastId === 'number' && Number.isFinite(currentLastId)
? Math.trunc(currentLastId)
: 0) + 1;
world.updateWorldMeta({ lastBettingId: bettingId });
const shortName = nationCount === 1 ? '천통국' : `최후 ${nationCount}`;
const openYearMonth = joinYearMonth(environment.year, environment.month);
world.queueNationBettingOpen({
id: bettingId,
name: `${shortName} 예상`,
selectCount: nationCount,
isExclusive: null,
requiresInheritancePoint: true,
openYearMonth,
closeYearMonth: openYearMonth + 24,
candidates,
bonusPoint,
});
const eventId = world.getNextEventId();
if (
!world.addEvent({
id: eventId,
targetCode: 'DESTROY_NATION',
priority: 1_000,
condition: ['RemainNation', '<=', nationCount],
action: [
['FinishNationBetting', bettingId],
['DeleteEvent'],
],
meta: {},
})
) {
throw new Error(`Failed to add FinishNationBetting event: ${eventId}`);
}
world.pushLog({
scope: LogScope.SYSTEM,
category: LogCategory.HISTORY,
format: LogFormat.YEAR_MONTH,
text:
nationCount > 1
? '<B><b>【내기】</b></>중원의 강자를 점치는 <C>내기</>가 진행중입니다! 호사가의 참여를 기다립니다!'
: '<B><b>【내기】</b></>천하통일 후보를 점치는 <C>내기</>가 진행중입니다! 호사가의 참여를 기다립니다!',
});
const text = `새로운 ${shortName} 내기가 열렸습니다. 천통국 베팅란을 확인해주세요.`;
const now = new Date();
for (const general of generals.filter((entry) => entry.npcState <= 1)) {
const nation = world.getNationById(general.nationId);
world.queueMessage({
msgType: 'private',
src: {
generalId: 0,
generalName: '',
nationId: 0,
nationName: 'System',
color: '#000000',
icon: '',
},
dest: {
generalId: general.id,
generalName: general.name,
nationId: general.nationId,
nationName: nation?.name ?? '재야',
color: nation?.color ?? '#000000',
icon: general.picture ?? '',
},
text,
time: now,
validUntil: new Date('9999-12-31T00:00:00.000Z'),
option: {},
});
}
};
};
export const createFinishNationBettingHandler = (options: {
getWorld: () => InMemoryTurnWorld | null;
}): MonthlyEventActionHandler => {
return (args, environment) => {
const world = options.getWorld();
if (!world) {
return;
}
const bettingId = readIntegerArg(args[0], 0, 'FinishNationBetting betting ID');
if (bettingId <= 0) {
throw new Error('FinishNationBetting betting ID must be positive.');
}
world.queueNationBettingFinish({
id: bettingId,
winnerNationIds: world
.listNations()
.filter((nation) => nation.level > 0)
.map((nation) => nation.id),
year: environment.year,
month: environment.month,
turnTime: environment.turnTime,
});
};
};
+16
View File
@@ -61,6 +61,10 @@ import {
} from './monthlyInvaderAction.js';
import { createChangeCityHandler } from './monthlyChangeCityAction.js';
import { createProvideNpcTroopLeaderHandler } from './monthlyProvideNpcTroopLeaderAction.js';
import {
createFinishNationBettingHandler,
createOpenNationBettingHandler,
} from './monthlyNationBettingAction.js';
import { buildCommandEnv } from './reservedTurnCommands.js';
import { DatabaseTurnDaemonLease, TurnDaemonLeaseUnavailableError } from '../lifecycle/databaseTurnDaemonLease.js';
@@ -332,6 +336,18 @@ const createTurnDaemonRuntimeWithLease = async (
getWorld: () => worldRef,
})
);
eventActions.set(
'OpenNationBetting',
createOpenNationBettingHandler({
getWorld: () => worldRef,
})
);
eventActions.set(
'FinishNationBetting',
createFinishNationBettingHandler({
getWorld: () => worldRef,
})
);
eventActions.set('ProcessIncome', async (_args, environment) => {
await incomeHandler.onMonthChanged?.({
previousYear: environment.month === 1 ? environment.year - 1 : environment.year,
+37
View File
@@ -60,6 +60,43 @@ export interface PendingNeutralAuction {
closeAt: Date;
}
export interface NationBettingCandidate {
title: string;
info: string;
isHtml: true;
aux: {
nation: number;
name: string;
color: string;
type: string;
level: number;
capital: number | null;
gennum: number;
power: number;
city_cnt: number;
};
}
export interface PendingNationBettingOpen {
id: number;
name: string;
selectCount: number;
isExclusive: boolean | null;
requiresInheritancePoint: true;
openYearMonth: number;
closeYearMonth: number;
candidates: NationBettingCandidate[];
bonusPoint: number;
}
export interface PendingNationBettingFinish {
id: number;
winnerNationIds: number[];
year: number;
month: number;
turnTime: Date;
}
export interface TurnWorldSnapshot extends Omit<
WorldSnapshot,
'generals' | 'cities' | 'nations' | 'troops' | 'diplomacy'