feat: add ranking and hall of fame features
- Implemented new routes for Best General and Hall of Fame views in the frontend. - Created BestGeneralView and HallOfFameView components to display rankings based on game data. - Added new database models for RankData and HallOfFame to store ranking information. - Introduced ranking types and hall of fame types in common types for better type safety. - Developed ranking router to handle fetching of best general and hall of fame data. - Updated database schema with migrations to include new tables for rank data and hall of fame. - Enhanced the main view with links to the new ranking features.
This commit is contained in:
@@ -35,6 +35,7 @@ export interface ScenarioInstallOptions {
|
||||
autorunUser?: ScenarioAutorunOptions | null;
|
||||
preopenAt?: Date | null;
|
||||
season?: number;
|
||||
serverId?: string;
|
||||
}
|
||||
|
||||
export interface ScenarioSeedOptions {
|
||||
@@ -258,6 +259,9 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
||||
if (typeof install?.season === 'number' && Number.isFinite(install.season)) {
|
||||
worldMeta.season = Math.floor(install.season);
|
||||
}
|
||||
if (typeof install?.serverId === 'string' && install.serverId.trim()) {
|
||||
worldMeta.serverId = install.serverId.trim();
|
||||
}
|
||||
|
||||
const integrationSeed = process.env[INTEGRATION_WORLD_SEED_ENV];
|
||||
if (typeof integrationSeed === 'string' && integrationSeed.trim().length > 0) {
|
||||
@@ -304,6 +308,43 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
||||
},
|
||||
});
|
||||
|
||||
if (typeof worldMeta.serverId === 'string' && worldMeta.serverId) {
|
||||
await prisma.gameHistory.upsert({
|
||||
where: { serverId: worldMeta.serverId },
|
||||
create: {
|
||||
serverId: worldMeta.serverId,
|
||||
date: now,
|
||||
winnerNation: null,
|
||||
map: scenario.config.environment.mapName ?? null,
|
||||
season:
|
||||
typeof worldMeta.season === 'number' && Number.isFinite(worldMeta.season)
|
||||
? Math.floor(worldMeta.season)
|
||||
: 1,
|
||||
scenario: options.scenarioId,
|
||||
scenarioName: String(seed.scenarioMeta?.title ?? ''),
|
||||
env: asJson({
|
||||
config: scenarioConfig,
|
||||
meta: worldMeta,
|
||||
}),
|
||||
},
|
||||
update: {
|
||||
date: now,
|
||||
winnerNation: null,
|
||||
map: scenario.config.environment.mapName ?? null,
|
||||
season:
|
||||
typeof worldMeta.season === 'number' && Number.isFinite(worldMeta.season)
|
||||
? Math.floor(worldMeta.season)
|
||||
: 1,
|
||||
scenario: options.scenarioId,
|
||||
scenarioName: String(seed.scenarioMeta?.title ?? ''),
|
||||
env: asJson({
|
||||
config: scenarioConfig,
|
||||
meta: worldMeta,
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (seed.nations.length > 0) {
|
||||
await prisma.nation.createMany({
|
||||
data: seed.nations.map((nation) => ({
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
type TurnEngineWorldStateUpdateInput,
|
||||
} from '@sammo-ts/infra';
|
||||
import { finalizeLogEntry, type LogEntryDraft } from '@sammo-ts/logic';
|
||||
import { asRecord, type RankDataType } from '@sammo-ts/common';
|
||||
|
||||
import type { TurnDaemonHooks } from '../lifecycle/types.js';
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
@@ -33,6 +34,79 @@ const readMetaNumber = (meta: Record<string, unknown>, key: string): number | nu
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
||||
};
|
||||
|
||||
const readRankMetaNumber = (meta: Record<string, unknown>, key: string): number => {
|
||||
const value = meta[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return Math.floor(value);
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) {
|
||||
return Math.floor(parsed);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
const buildRankRows = (
|
||||
general: ReturnType<InMemoryTurnWorld['consumeDirtyState']>['generals'][number]
|
||||
): Array<{ generalId: number; nationId: number; type: string; value: number }> => {
|
||||
const meta = asRecord(general.meta);
|
||||
const readMeta = (key: string) => readRankMetaNumber(meta, key);
|
||||
const readRank = (key: string) => readRankMetaNumber(meta, `rank_${key}`);
|
||||
|
||||
const entries: Array<[RankDataType, number]> = [
|
||||
['experience', Math.floor(general.experience)],
|
||||
['dedication', Math.floor(general.dedication)],
|
||||
['firenum', readMeta('firenum')],
|
||||
['warnum', readRank('warnum')],
|
||||
['killnum', readRank('killnum')],
|
||||
['deathnum', readRank('deathnum')],
|
||||
['occupied', readRank('occupied')],
|
||||
['killcrew', readRank('killcrew')],
|
||||
['deathcrew', readRank('deathcrew')],
|
||||
['killcrew_person', readRank('killcrew_person')],
|
||||
['deathcrew_person', readRank('deathcrew_person')],
|
||||
['dex1', readMeta('dex1')],
|
||||
['dex2', readMeta('dex2')],
|
||||
['dex3', readMeta('dex3')],
|
||||
['dex4', readMeta('dex4')],
|
||||
['dex5', readMeta('dex5')],
|
||||
['ttw', readMeta('ttw')],
|
||||
['ttd', readMeta('ttd')],
|
||||
['ttl', readMeta('ttl')],
|
||||
['ttg', readMeta('ttg')],
|
||||
['ttp', readMeta('ttp')],
|
||||
['tlw', readMeta('tlw')],
|
||||
['tld', readMeta('tld')],
|
||||
['tll', readMeta('tll')],
|
||||
['tlg', readMeta('tlg')],
|
||||
['tlp', readMeta('tlp')],
|
||||
['tsw', readMeta('tsw')],
|
||||
['tsd', readMeta('tsd')],
|
||||
['tsl', readMeta('tsl')],
|
||||
['tsg', readMeta('tsg')],
|
||||
['tsp', readMeta('tsp')],
|
||||
['tiw', readMeta('tiw')],
|
||||
['tid', readMeta('tid')],
|
||||
['til', readMeta('til')],
|
||||
['tig', readMeta('tig')],
|
||||
['tip', readMeta('tip')],
|
||||
['betgold', readMeta('betgold')],
|
||||
['betwin', readMeta('betwin')],
|
||||
['betwingold', readMeta('betwingold')],
|
||||
['inherit_earned', readMeta('inherit_earned')],
|
||||
['inherit_spent', readMeta('inherit_spent')],
|
||||
];
|
||||
|
||||
return entries.map(([type, value]) => ({
|
||||
generalId: general.id,
|
||||
nationId: general.nationId,
|
||||
type,
|
||||
value,
|
||||
}));
|
||||
};
|
||||
|
||||
const buildGeneralUpdate = (
|
||||
general: ReturnType<InMemoryTurnWorld['consumeDirtyState']>['generals'][number]
|
||||
): TurnEngineGeneralUpdateInput => ({
|
||||
@@ -308,6 +382,9 @@ export const createDatabaseTurnHooks = async (
|
||||
await prisma.general.deleteMany({
|
||||
where: { id: { in: deletedGenerals } },
|
||||
});
|
||||
await prisma.rankData.deleteMany({
|
||||
where: { generalId: { in: deletedGenerals } },
|
||||
});
|
||||
}
|
||||
|
||||
if (deletedNations.length > 0) {
|
||||
@@ -377,6 +454,28 @@ export const createDatabaseTurnHooks = async (
|
||||
),
|
||||
]);
|
||||
|
||||
const rankTargets = [...createdGenerals, ...generals];
|
||||
if (rankTargets.length > 0) {
|
||||
const rankRows = rankTargets.flatMap(buildRankRows);
|
||||
await Promise.all(
|
||||
rankRows.map((row) =>
|
||||
prisma.rankData.upsert({
|
||||
where: {
|
||||
generalId_type: {
|
||||
generalId: row.generalId,
|
||||
type: row.type,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
nationId: row.nationId,
|
||||
value: row.value,
|
||||
},
|
||||
create: row,
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (logs.length > 0) {
|
||||
const logContext = {
|
||||
year: state.currentYear,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createGamePostgresConnector } from '@sammo-ts/infra';
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import { asRecord, HALL_OF_FAME_TYPES, type HallOfFameType } from '@sammo-ts/common';
|
||||
import type { LogEntryDraft } from '@sammo-ts/logic';
|
||||
import { LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
|
||||
|
||||
@@ -16,6 +16,27 @@ const readMetaNumber = (meta: Record<string, unknown>, key: string): number => {
|
||||
return value;
|
||||
};
|
||||
|
||||
const readMetaNumberOrNull = (meta: Record<string, unknown>, key: string): number | null => {
|
||||
const value = meta[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return Math.floor(value);
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) {
|
||||
return Math.floor(parsed);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const computeHallRate = (numerator: number, denominator: number): number => {
|
||||
if (denominator <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return numerator / denominator;
|
||||
};
|
||||
|
||||
const computeDexPoint = (meta: Record<string, unknown>): number => {
|
||||
let total = 0;
|
||||
for (const [key, value] of Object.entries(meta)) {
|
||||
@@ -162,6 +183,203 @@ export const createUnificationHandler = (options: {
|
||||
}
|
||||
};
|
||||
|
||||
const settleHallOfFame = async (winnerNationId: number): Promise<void> => {
|
||||
const world = options.getWorld();
|
||||
if (!world) {
|
||||
return;
|
||||
}
|
||||
await ready;
|
||||
const prisma = connector.prisma;
|
||||
const state = world.getState();
|
||||
const meta = asRecord(state.meta);
|
||||
|
||||
const serverId =
|
||||
typeof meta.serverId === 'string' && meta.serverId.trim()
|
||||
? meta.serverId.trim()
|
||||
: options.profileName;
|
||||
const season = readMetaNumberOrNull(meta, 'season') ?? 1;
|
||||
const scenario = readMetaNumberOrNull(meta, 'scenarioId') ?? 0;
|
||||
const scenarioName =
|
||||
typeof asRecord(meta.scenarioMeta).title === 'string'
|
||||
? String(asRecord(meta.scenarioMeta).title)
|
||||
: '';
|
||||
const startTime = typeof meta.starttime === 'string' ? meta.starttime : null;
|
||||
const unitedTime = new Date().toISOString();
|
||||
|
||||
const [serverCount, nationRows, generalRows, rankRows] = await Promise.all([
|
||||
prisma.gameHistory.count(),
|
||||
prisma.nation.findMany({ select: { id: true, name: true, color: true } }),
|
||||
prisma.general.findMany({
|
||||
where: { npcState: { lt: 2 } },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
nationId: true,
|
||||
name: true,
|
||||
picture: true,
|
||||
imageServer: true,
|
||||
experience: true,
|
||||
dedication: true,
|
||||
},
|
||||
}),
|
||||
prisma.rankData.findMany({
|
||||
where: { generalId: { gt: 0 } },
|
||||
select: { generalId: true, type: true, value: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const nationMap = new Map<number, { name: string; color: string }>();
|
||||
for (const nation of nationRows) {
|
||||
nationMap.set(nation.id, { name: nation.name, color: nation.color });
|
||||
}
|
||||
|
||||
const rankMap = new Map<number, Record<string, number>>();
|
||||
for (const row of rankRows) {
|
||||
const entry = rankMap.get(row.generalId) ?? {};
|
||||
entry[row.type] = row.value;
|
||||
rankMap.set(row.generalId, entry);
|
||||
}
|
||||
|
||||
const hallTypes: Array<[HallOfFameType, 'natural' | 'rank' | 'calc']> = HALL_OF_FAME_TYPES.map((type) => {
|
||||
if (type === 'experience' || type === 'dedication' || type.startsWith('dex')) {
|
||||
return [type, 'natural'];
|
||||
}
|
||||
if (type.endsWith('rate')) {
|
||||
return [type, 'calc'];
|
||||
}
|
||||
return [type, 'rank'];
|
||||
});
|
||||
|
||||
for (const general of generalRows) {
|
||||
const ranks = rankMap.get(general.id) ?? {};
|
||||
const warnum = ranks.warnum ?? 0;
|
||||
const killnum = ranks.killnum ?? 0;
|
||||
const killcrew = ranks.killcrew ?? 0;
|
||||
const deathcrew = ranks.deathcrew ?? 0;
|
||||
const killcrewPerson = ranks.killcrew_person ?? 0;
|
||||
const deathcrewPerson = ranks.deathcrew_person ?? 0;
|
||||
const ttw = ranks.ttw ?? 0;
|
||||
const ttd = ranks.ttd ?? 0;
|
||||
const ttl = ranks.ttl ?? 0;
|
||||
const tlw = ranks.tlw ?? 0;
|
||||
const tld = ranks.tld ?? 0;
|
||||
const tll = ranks.tll ?? 0;
|
||||
const tsw = ranks.tsw ?? 0;
|
||||
const tsd = ranks.tsd ?? 0;
|
||||
const tsl = ranks.tsl ?? 0;
|
||||
const tiw = ranks.tiw ?? 0;
|
||||
const tid = ranks.tid ?? 0;
|
||||
const til = ranks.til ?? 0;
|
||||
const betGold = ranks.betgold ?? 0;
|
||||
const betWinGold = ranks.betwingold ?? 0;
|
||||
|
||||
const ttTotal = ttw + ttd + ttl;
|
||||
const tlTotal = tlw + tld + tll;
|
||||
const tsTotal = tsw + tsd + tsl;
|
||||
const tiTotal = tiw + tid + til;
|
||||
|
||||
const calcValues: Record<string, number> = {
|
||||
winrate: computeHallRate(killnum, warnum),
|
||||
killrate: computeHallRate(killcrew, Math.max(1, deathcrew)),
|
||||
killrate_person: computeHallRate(killcrewPerson, Math.max(1, deathcrewPerson)),
|
||||
ttrate: computeHallRate(ttw, Math.max(1, ttTotal)),
|
||||
tlrate: computeHallRate(tlw, Math.max(1, tlTotal)),
|
||||
tsrate: computeHallRate(tsw, Math.max(1, tsTotal)),
|
||||
tirate: computeHallRate(tiw, Math.max(1, tiTotal)),
|
||||
betrate: computeHallRate(betWinGold, Math.max(1, betGold)),
|
||||
};
|
||||
|
||||
const nation = nationMap.get(general.nationId) ?? { name: '재야', color: '#000000' };
|
||||
const aux = {
|
||||
name: general.name,
|
||||
nationName: nation.name,
|
||||
bgColor: nation.color,
|
||||
fgColor: nation.color,
|
||||
picture: general.picture,
|
||||
imgsvr: general.imageServer,
|
||||
startTime,
|
||||
unitedTime,
|
||||
ownerName: general.userId ?? null,
|
||||
serverID: serverId,
|
||||
serverIdx: serverCount,
|
||||
serverName: options.profileName,
|
||||
scenarioName,
|
||||
};
|
||||
|
||||
for (const [typeName, valueType] of hallTypes) {
|
||||
let value = 0;
|
||||
if (valueType === 'natural') {
|
||||
value = typeName === 'experience' ? general.experience : typeName === 'dedication' ? general.dedication : ranks[typeName] ?? 0;
|
||||
} else if (valueType === 'rank') {
|
||||
value = ranks[typeName] ?? 0;
|
||||
} else {
|
||||
value = calcValues[typeName] ?? 0;
|
||||
}
|
||||
|
||||
if ((typeName === 'winrate' || typeName === 'killrate') && warnum < 10) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'ttrate' && ttTotal < 50) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'tlrate' && tlTotal < 50) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'tsrate' && tsTotal < 50) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'tirate' && tiTotal < 50) {
|
||||
continue;
|
||||
}
|
||||
if (typeName === 'betrate' && betGold < 1000) {
|
||||
continue;
|
||||
}
|
||||
if (value <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = await prisma.hallOfFame.findUnique({
|
||||
where: {
|
||||
serverId_type_generalNo: {
|
||||
serverId,
|
||||
type: typeName,
|
||||
generalNo: general.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!existing) {
|
||||
await prisma.hallOfFame.create({
|
||||
data: {
|
||||
serverId,
|
||||
season,
|
||||
scenario,
|
||||
generalNo: general.id,
|
||||
type: typeName,
|
||||
value,
|
||||
owner: general.userId ?? null,
|
||||
aux,
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (value > existing.value) {
|
||||
await prisma.hallOfFame.update({
|
||||
where: { id: existing.id },
|
||||
data: { value, aux },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.gameHistory.update({
|
||||
where: { serverId },
|
||||
data: {
|
||||
winnerNation: winnerNationId,
|
||||
date: new Date(),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handler: TurnCalendarHandler = {
|
||||
onMonthChanged: (context) => {
|
||||
const world = options.getWorld();
|
||||
@@ -188,6 +406,7 @@ export const createUnificationHandler = (options: {
|
||||
world.updateWorldMeta({ isUnited: 2 });
|
||||
world.pushLog(buildUnificationLog(winner.name));
|
||||
void settleInheritance(winner.id, context.currentYear, context.currentMonth);
|
||||
void settleHallOfFame(winner.id);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user