merge: 최신 main을 비용 기반 갱신 점수에 통합
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { isAvailableNationTraitKey } from '@sammo-ts/logic';
|
||||
|
||||
import type { BattleSimRequestPayload } from './types.js';
|
||||
|
||||
const zBattleSimGeneral = z.object({
|
||||
@@ -71,7 +73,7 @@ const zBattleSimCity = z.object({
|
||||
});
|
||||
|
||||
const zBattleSimNation = z.object({
|
||||
type: z.string().min(1),
|
||||
type: z.string().refine(isAvailableNationTraitKey),
|
||||
tech: z.number().min(0),
|
||||
level: z.number().int().min(0),
|
||||
capital: z.number().int().min(0),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
AVAILABLE_NATION_TRAIT_KEYS,
|
||||
ITEM_KEYS,
|
||||
EVENT_DOMESTIC_TRAIT_KEYS,
|
||||
loadEventDomesticTraitModules,
|
||||
@@ -6,7 +7,6 @@ import {
|
||||
loadNationTraitModules,
|
||||
loadPersonalityTraitModules,
|
||||
loadWarTraitModules,
|
||||
NATION_TRAIT_KEYS,
|
||||
PERSONALITY_TRAIT_KEYS,
|
||||
WAR_TRAIT_KEYS,
|
||||
type ItemModule,
|
||||
@@ -110,7 +110,7 @@ export const loadBattleSimTraitOptions = async (): Promise<{
|
||||
}> => {
|
||||
if (!cachedTraitOptions) {
|
||||
cachedTraitOptions = Promise.all([
|
||||
loadNationTraitModules([...NATION_TRAIT_KEYS]),
|
||||
loadNationTraitModules([...AVAILABLE_NATION_TRAIT_KEYS]),
|
||||
loadEventDomesticTraitModules([...EVENT_DOMESTIC_TRAIT_KEYS]),
|
||||
loadWarTraitModules([...WAR_TRAIT_KEYS]),
|
||||
loadPersonalityTraitModules([...PERSONALITY_TRAIT_KEYS]),
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { TournamentState } from '../../tournament/types.js';
|
||||
|
||||
import { TournamentStore } from '../../tournament/store.js';
|
||||
import { buildTournamentKeys } from '../../tournament/keys.js';
|
||||
import { assignManualApplicantGroup } from '../../tournament/workerHelpers.js';
|
||||
import { accessAuthedProcedure, authedProcedure, router } from '../../trpc.js';
|
||||
import { getMyGeneral } from '../shared/general.js';
|
||||
import { loadCurrentGameTime } from '../../services/gameClock.js';
|
||||
@@ -412,52 +413,31 @@ export const tournamentRouter = router({
|
||||
});
|
||||
}
|
||||
|
||||
const settingResult = await ctx.turnDaemon.requestCommand({
|
||||
type: 'setMySetting',
|
||||
generalId: general.id,
|
||||
settings: { tnmt: 1 },
|
||||
const meta = asRecord(general.meta);
|
||||
const level = typeof meta.explevel === 'number' ? meta.explevel : 0;
|
||||
const applicant = assignManualApplicantGroup({
|
||||
state,
|
||||
baseSeed: String(asRecord(worldState?.meta).hiddenSeed ?? 'tournament'),
|
||||
current: participants,
|
||||
applicant: {
|
||||
id: general.id,
|
||||
name: general.name,
|
||||
leadership: general.leadership,
|
||||
strength: general.strength,
|
||||
intel: general.intel,
|
||||
level,
|
||||
},
|
||||
});
|
||||
if (!settingResult || settingResult.type !== 'setMySetting' || !settingResult.ok) {
|
||||
const next = participants.concat(applicant);
|
||||
|
||||
try {
|
||||
await store.setParticipants(next);
|
||||
} catch (error) {
|
||||
await ctx.turnDaemon.requestCommand({
|
||||
type: 'adjustGeneralResources',
|
||||
reason: 'tournamentJoinRollback',
|
||||
adjustments: [{ generalId: general.id, goldDelta: develCost }],
|
||||
});
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message:
|
||||
settingResult && settingResult.type === 'setMySetting'
|
||||
? (settingResult.reason ?? '요청에 실패했습니다.')
|
||||
: 'Unexpected response',
|
||||
});
|
||||
}
|
||||
|
||||
const meta = asRecord(general.meta);
|
||||
const level = typeof meta.explevel === 'number' ? meta.explevel : 0;
|
||||
const next = participants.concat({
|
||||
id: general.id,
|
||||
name: general.name,
|
||||
leadership: general.leadership,
|
||||
strength: general.strength,
|
||||
intel: general.intel,
|
||||
level,
|
||||
});
|
||||
|
||||
try {
|
||||
await store.setParticipants(next);
|
||||
} catch (error) {
|
||||
await Promise.all([
|
||||
ctx.turnDaemon.requestCommand({
|
||||
type: 'adjustGeneralResources',
|
||||
reason: 'tournamentJoinRollback',
|
||||
adjustments: [{ generalId: general.id, goldDelta: develCost }],
|
||||
}),
|
||||
ctx.turnDaemon.requestCommand({
|
||||
type: 'setMySetting',
|
||||
generalId: general.id,
|
||||
settings: { tnmt: 0 },
|
||||
}),
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
return { ok: true, count: next.length };
|
||||
|
||||
@@ -28,13 +28,14 @@ import {
|
||||
repeatNationTurns,
|
||||
setGeneralTurn,
|
||||
setGeneralTurns,
|
||||
setNationTurn,
|
||||
setNationTurns,
|
||||
setNationTurnAtCurrentPosition,
|
||||
setNationTurnsAtCurrentPositions,
|
||||
shiftGeneralTurns,
|
||||
shiftNationTurns,
|
||||
} from '../../turns/reservedTurns.js';
|
||||
import { getOwnedGeneral } from '../shared/general.js';
|
||||
import type { GameApiContext, GeneralRow, WorldStateRow } from '../../context.js';
|
||||
import { buildRefGeneralTargetOptions } from '../../turns/commandTargets.js';
|
||||
|
||||
const zPushAmount = z
|
||||
.number()
|
||||
@@ -181,9 +182,15 @@ export const getTurnCommandTable = async (ctx: GameApiContext, generalId: number
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
ctx.db.general.findMany({
|
||||
where: { npcState: { lt: 2 } },
|
||||
select: { id: true, name: true, nationId: true, cityId: true },
|
||||
orderBy: { id: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
nationId: true,
|
||||
cityId: true,
|
||||
npcState: true,
|
||||
officerLevel: true,
|
||||
},
|
||||
orderBy: [{ npcState: 'asc' }, { name: 'asc' }, { id: 'asc' }],
|
||||
}),
|
||||
environmentPromise,
|
||||
loadBattleSimTraitOptions(),
|
||||
@@ -192,7 +199,13 @@ export const getTurnCommandTable = async (ctx: GameApiContext, generalId: number
|
||||
]);
|
||||
|
||||
const nationById = new Map(nations.map((entry) => [entry.id, entry]));
|
||||
const cityById = new Map(cities.map((entry) => [entry.id, entry]));
|
||||
const generalTargetOptions = buildRefGeneralTargetOptions({
|
||||
actorId: general.id,
|
||||
actorNationId: general.nationId,
|
||||
generals,
|
||||
nationNames: new Map(nations.map((entry) => [entry.id, entry.name])),
|
||||
cityNames: new Map(cities.map((entry) => [entry.id, entry.name])),
|
||||
});
|
||||
const items: TurnCommandInputOptions['items'] = {
|
||||
horse: [{ value: 'None', label: '판매/해제' }],
|
||||
weapon: [{ value: 'None', label: '판매/해제' }],
|
||||
@@ -226,12 +239,8 @@ export const getTurnCommandTable = async (ctx: GameApiContext, generalId: number
|
||||
label: entry.name,
|
||||
color: entry.color,
|
||||
})),
|
||||
generals: generals.map((entry) => ({
|
||||
value: entry.id,
|
||||
label: `${entry.name} (${nationById.get(entry.nationId)?.name ?? '무소속'} · ${
|
||||
cityById.get(entry.cityId)?.name ?? '재야'
|
||||
})`,
|
||||
})),
|
||||
generals: generalTargetOptions.generals,
|
||||
generalTargets: generalTargetOptions.generalTargets,
|
||||
crewTypes: (environment.unitSet.crewTypes ?? [])
|
||||
.filter((entry) => !entry.requirements.some((requirement) => requirement.type === 'Impossible'))
|
||||
.map((entry) => ({ value: entry.id, label: entry.name })),
|
||||
@@ -446,7 +455,7 @@ export const turnsRouter = router({
|
||||
await assertReservedTurnPermission(worldState, general, 'nation', input.action, args);
|
||||
|
||||
const snapshot = await mutateReservedTurns(() =>
|
||||
setNationTurn(
|
||||
setNationTurnAtCurrentPosition(
|
||||
ctx.db,
|
||||
general.nationId,
|
||||
general.officerLevel,
|
||||
@@ -559,7 +568,13 @@ export const turnsRouter = router({
|
||||
await assertReservedTurnPermission(worldState, general, 'nation', update.action, update.args);
|
||||
}
|
||||
const snapshot = await mutateReservedTurns(() =>
|
||||
setNationTurns(ctx.db, general.nationId, general.officerLevel, updates, input.expectedRevision)
|
||||
setNationTurnsAtCurrentPositions(
|
||||
ctx.db,
|
||||
general.nationId,
|
||||
general.officerLevel,
|
||||
updates,
|
||||
input.expectedRevision
|
||||
)
|
||||
);
|
||||
return { ok: true, ...snapshot };
|
||||
}),
|
||||
|
||||
@@ -155,6 +155,60 @@ export const assignGroupSlots = (
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Ref assigns a manual applicant to one uniformly selected non-full preliminary
|
||||
* group as part of the join request. Keeping that assignment in the persisted
|
||||
* participant projection lets the applicant see the group immediately while
|
||||
* the later participant-fill pass can still balance automatic applicants.
|
||||
*/
|
||||
export const assignManualApplicantGroup = (options: {
|
||||
state: TournamentState;
|
||||
baseSeed: string;
|
||||
current: TournamentParticipantEntry[];
|
||||
applicant: TournamentParticipantEntry;
|
||||
groupCount?: number;
|
||||
groupSize?: number;
|
||||
}): TournamentParticipantEntry => {
|
||||
const groupCount = options.groupCount ?? 8;
|
||||
const groupSize = options.groupSize ?? 8;
|
||||
const groupCounts = Array.from({ length: groupCount }, () => 0);
|
||||
|
||||
for (const participant of options.current) {
|
||||
const groupId = participant.groupId;
|
||||
if (groupId !== undefined && groupId >= 0 && groupId < groupCount) {
|
||||
groupCounts[groupId] = (groupCounts[groupId] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const openGroupIds = groupCounts.flatMap((count, groupId) => (count < groupSize ? [groupId] : []));
|
||||
if (openGroupIds.length === 0) {
|
||||
throw new Error('참가 인원이 가득 찼습니다.');
|
||||
}
|
||||
|
||||
const rng = createTournamentRng(options.baseSeed, {
|
||||
openYear: options.state.openYear,
|
||||
openMonth: options.state.openMonth,
|
||||
stage: 1,
|
||||
phase: options.state.phase,
|
||||
matchIndex: options.applicant.id,
|
||||
participantIndex: options.current.length,
|
||||
extraSeed: `manual-group:${options.current.map((entry) => entry.id).join('-')}:${openGroupIds.join('-')}`,
|
||||
});
|
||||
const groupId = rng.choice(openGroupIds);
|
||||
|
||||
return {
|
||||
...options.applicant,
|
||||
groupId,
|
||||
groupNo: groupCounts[groupId] ?? 0,
|
||||
win: 0,
|
||||
draw: 0,
|
||||
lose: 0,
|
||||
gl: 0,
|
||||
seedRank: 0,
|
||||
finalRank: 0,
|
||||
};
|
||||
};
|
||||
|
||||
const selectWeighted = <T>(rng: ReturnType<typeof createTournamentRng>, pool: Array<{ item: T; weight: number }>): T =>
|
||||
rng.choiceUsingWeightPair(pool.map((entry) => [entry.item, entry.weight]));
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ export interface TurnCommandInputOptions {
|
||||
cities: TurnCommandOption[];
|
||||
nations: TurnCommandOption[];
|
||||
generals: TurnCommandOption[];
|
||||
generalTargets?: Record<string, TurnCommandOption[]>;
|
||||
crewTypes: TurnCommandOption[];
|
||||
armTypes: TurnCommandOption[];
|
||||
nationTypes: TurnCommandOption[];
|
||||
|
||||
@@ -771,6 +771,7 @@ export const buildTurnCommandTable = async (options: {
|
||||
cities: [],
|
||||
nations: [],
|
||||
generals: [],
|
||||
generalTargets: {},
|
||||
crewTypes: [],
|
||||
armTypes: [],
|
||||
nationTypes: [],
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { TurnCommandOption } from './commandInput.js';
|
||||
|
||||
export interface GeneralTargetSource {
|
||||
id: number;
|
||||
name: string;
|
||||
nationId: number;
|
||||
cityId: number;
|
||||
npcState: number;
|
||||
officerLevel: number;
|
||||
}
|
||||
|
||||
export interface RefGeneralTargetOptions {
|
||||
generals: TurnCommandOption[];
|
||||
generalTargets: Record<string, TurnCommandOption[]>;
|
||||
}
|
||||
|
||||
const SAME_NATION_GENERAL_COMMANDS = ['che_증여'] as const;
|
||||
const SAME_NATION_NATION_COMMANDS = ['che_발령', 'che_포상', 'che_몰수', 'che_부대탈퇴지시'] as const;
|
||||
|
||||
/** Ref 각 처리 화면의 SELECT 조건을 공통 command table의 명령별 option으로 투영한다. */
|
||||
export const buildRefGeneralTargetOptions = (options: {
|
||||
actorId: number;
|
||||
actorNationId: number;
|
||||
generals: readonly GeneralTargetSource[];
|
||||
nationNames: ReadonlyMap<number, string>;
|
||||
cityNames: ReadonlyMap<number, string>;
|
||||
}): RefGeneralTargetOptions => {
|
||||
const toOption = (entry: GeneralTargetSource): TurnCommandOption => ({
|
||||
value: entry.id,
|
||||
label: `${entry.name} (${options.nationNames.get(entry.nationId) ?? '무소속'} · ${
|
||||
options.cityNames.get(entry.cityId) ?? '재야'
|
||||
})`,
|
||||
});
|
||||
const project = (predicate: (entry: GeneralTargetSource) => boolean): TurnCommandOption[] =>
|
||||
options.generals.filter(predicate).map(toOption);
|
||||
|
||||
const sameNation = project((entry) => entry.nationId === options.actorNationId);
|
||||
const generalTargets: Record<string, TurnCommandOption[]> = {};
|
||||
for (const action of SAME_NATION_GENERAL_COMMANDS) generalTargets[action] = sameNation;
|
||||
for (const action of SAME_NATION_NATION_COMMANDS) generalTargets[action] = sameNation;
|
||||
|
||||
generalTargets.che_선양 = project(
|
||||
(entry) => entry.nationId !== 0 && entry.nationId === options.actorNationId && entry.id !== options.actorId
|
||||
);
|
||||
generalTargets.che_등용 = project(
|
||||
(entry) => entry.npcState < 2 && entry.officerLevel !== 12 && entry.id !== options.actorId
|
||||
);
|
||||
generalTargets.che_장수대상임관 = project((entry) => entry.id !== options.actorId);
|
||||
|
||||
return {
|
||||
// 기존 profile의 공통 fallback은 유저장 목록을 유지한다.
|
||||
generals: project((entry) => entry.npcState < 2),
|
||||
generalTargets,
|
||||
};
|
||||
};
|
||||
@@ -165,20 +165,22 @@ const loadGeneralTurns = async (db: DatabaseClient, generalId: number): Promise<
|
||||
return buildTurnListFromRows(rows, MAX_GENERAL_TURNS);
|
||||
};
|
||||
|
||||
const loadGeneralAutorunLimit = async (db: DatabaseClient, generalId: number): Promise<number | null> => {
|
||||
const general = await db.general.findUnique({ where: { id: generalId }, select: { meta: true } });
|
||||
const rawAutorunLimit = isRecord(general?.meta) ? general.meta.autorun_limit : undefined;
|
||||
return typeof rawAutorunLimit === 'number' && Number.isFinite(rawAutorunLimit) ? Math.trunc(rawAutorunLimit) : null;
|
||||
};
|
||||
|
||||
export const getGeneralTurnSnapshot = async (db: DatabaseClient, generalId: number): Promise<ReservedTurnSnapshot> => {
|
||||
const [turns, revisionRow, general] = await Promise.all([
|
||||
const [turns, revisionRow, autorunLimit] = await Promise.all([
|
||||
loadGeneralTurns(db, generalId),
|
||||
db.generalTurnRevision.findUnique({ where: { generalId } }),
|
||||
db.general.findUnique({ where: { id: generalId }, select: { meta: true } }),
|
||||
loadGeneralAutorunLimit(db, generalId),
|
||||
]);
|
||||
const rawAutorunLimit = isRecord(general?.meta) ? general.meta.autorun_limit : undefined;
|
||||
return {
|
||||
revision: revisionRow?.revision ?? 0,
|
||||
turns: serializeTurnList(turns),
|
||||
autorunLimit:
|
||||
typeof rawAutorunLimit === 'number' && Number.isFinite(rawAutorunLimit)
|
||||
? Math.trunc(rawAutorunLimit)
|
||||
: null,
|
||||
autorunLimit,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -331,7 +333,7 @@ export const setGeneralTurns = async (
|
||||
}
|
||||
}
|
||||
await persistGeneralTurns(db, generalId, turns);
|
||||
return { revision, turns: serializeTurnList(turns) };
|
||||
return { revision, turns: serializeTurnList(turns), autorunLimit: await loadGeneralAutorunLimit(db, generalId) };
|
||||
};
|
||||
|
||||
export const setGeneralTurn = async (
|
||||
@@ -357,7 +359,7 @@ export const shiftGeneralTurns = async (
|
||||
const turns = await loadGeneralTurns(db, generalId);
|
||||
const shifted = applyShift(turns, amount);
|
||||
await persistGeneralTurns(db, generalId, shifted);
|
||||
return { revision, turns: serializeTurnList(shifted) };
|
||||
return { revision, turns: serializeTurnList(shifted), autorunLimit: await loadGeneralAutorunLimit(db, generalId) };
|
||||
};
|
||||
|
||||
export const repeatGeneralTurns = async (
|
||||
@@ -372,7 +374,7 @@ export const repeatGeneralTurns = async (
|
||||
const revision = await claimGeneralRevision(db, generalId, expectedRevision);
|
||||
const turns = applyRepeat(await loadGeneralTurns(db, generalId), amount);
|
||||
await persistGeneralTurns(db, generalId, turns);
|
||||
return { revision, turns: serializeTurnList(turns) };
|
||||
return { revision, turns: serializeTurnList(turns), autorunLimit: await loadGeneralAutorunLimit(db, generalId) };
|
||||
};
|
||||
|
||||
export const setNationTurns = async (
|
||||
@@ -396,6 +398,32 @@ export const setNationTurns = async (
|
||||
return { revision, turns: serializeTurnList(turns) };
|
||||
};
|
||||
|
||||
/**
|
||||
* 국가 턴 입력은 화면을 연 뒤 daemon이 선두 턴을 소비했더라도 사용자가 고른
|
||||
* 슬롯 번호를 현재 큐에 적용한다. 큐 lease가 실제로 잡혀 있는 충돌은 그대로
|
||||
* 거절하고, revision이 앞으로 진행한 경우에만 새 revision으로 재기준화한다.
|
||||
*/
|
||||
export const setNationTurnsAtCurrentPositions = async (
|
||||
db: DatabaseClient,
|
||||
nationId: number,
|
||||
officerLevel: number,
|
||||
updates: readonly ReservedTurnUpdate[],
|
||||
expectedRevision: number
|
||||
): Promise<ReservedTurnSnapshot> => {
|
||||
let revision = expectedRevision;
|
||||
for (let attempt = 0; attempt < 8; attempt += 1) {
|
||||
try {
|
||||
return await setNationTurns(db, nationId, officerLevel, updates, revision);
|
||||
} catch (error) {
|
||||
if (!(error instanceof ReservedTurnRevisionConflictError) || error.currentRevision === revision) {
|
||||
throw error;
|
||||
}
|
||||
revision = error.currentRevision;
|
||||
}
|
||||
}
|
||||
throw new ReservedTurnRevisionConflictError(revision, revision);
|
||||
};
|
||||
|
||||
export const setNationTurn = async (
|
||||
db: DatabaseClient,
|
||||
nationId: number,
|
||||
@@ -407,6 +435,23 @@ export const setNationTurn = async (
|
||||
): Promise<ReservedTurnSnapshot> =>
|
||||
setNationTurns(db, nationId, officerLevel, [{ turnIndices: [turnIndex], action, args }], expectedRevision);
|
||||
|
||||
export const setNationTurnAtCurrentPosition = async (
|
||||
db: DatabaseClient,
|
||||
nationId: number,
|
||||
officerLevel: number,
|
||||
turnIndex: number,
|
||||
action: string,
|
||||
args: unknown,
|
||||
expectedRevision: number
|
||||
): Promise<ReservedTurnSnapshot> =>
|
||||
setNationTurnsAtCurrentPositions(
|
||||
db,
|
||||
nationId,
|
||||
officerLevel,
|
||||
[{ turnIndices: [turnIndex], action, args }],
|
||||
expectedRevision
|
||||
);
|
||||
|
||||
export const shiftNationTurns = async (
|
||||
db: DatabaseClient,
|
||||
nationId: number,
|
||||
|
||||
Reference in New Issue
Block a user