Merge branch 'main' into feature/scenario2601-gui-186-20260802
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
|
||||
import { RANK_DATA_TYPES } from '@sammo-ts/common';
|
||||
import type { RedisConnector } from '@sammo-ts/infra';
|
||||
|
||||
import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js';
|
||||
@@ -32,7 +33,24 @@ const auth: GameSessionTokenPayload = {
|
||||
sanctions: {},
|
||||
};
|
||||
|
||||
const generalRows = [
|
||||
interface RankingGeneralRow {
|
||||
id: number;
|
||||
name: string;
|
||||
nationId: number;
|
||||
userId: string | null;
|
||||
npcState: number;
|
||||
picture: string | null;
|
||||
imageServer: number;
|
||||
meta: Record<string, string | number>;
|
||||
experience: number;
|
||||
dedication: number;
|
||||
horseCode: string;
|
||||
weaponCode: string;
|
||||
bookCode: string;
|
||||
itemCode: string;
|
||||
}
|
||||
|
||||
const generalRows: RankingGeneralRow[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: '유비',
|
||||
@@ -81,13 +99,16 @@ const generalRows = [
|
||||
bookCode: 'None',
|
||||
itemCode: 'None',
|
||||
},
|
||||
] as const;
|
||||
];
|
||||
|
||||
const buildContext = (options?: {
|
||||
authenticated?: boolean;
|
||||
isUnited?: boolean;
|
||||
includeOwnerDisplayName?: boolean;
|
||||
generals?: RankingGeneralRow[];
|
||||
rankRows?: Array<{ generalId: number; type: string; value: number }>;
|
||||
}): GameApiContext => {
|
||||
const selectedGeneralRows = options?.generals ?? generalRows;
|
||||
const db = {
|
||||
worldState: {
|
||||
findFirst: async () => ({
|
||||
@@ -112,21 +133,22 @@ const buildContext = (options?: {
|
||||
},
|
||||
general: {
|
||||
findMany: async (args: { where: { npcState: { lt?: number; gte?: number } } }) =>
|
||||
generalRows.filter((general) =>
|
||||
selectedGeneralRows.filter((general) =>
|
||||
args.where.npcState.gte !== undefined
|
||||
? general.npcState >= args.where.npcState.gte
|
||||
: general.npcState < (args.where.npcState.lt ?? Number.POSITIVE_INFINITY)
|
||||
),
|
||||
},
|
||||
rankData: {
|
||||
findMany: async () => [
|
||||
{ generalId: 1, type: 'firenum', value: 10 },
|
||||
{ generalId: 2, type: 'firenum', value: 20 },
|
||||
{ generalId: 3, type: 'firenum', value: 30 },
|
||||
{ generalId: 1, type: 'dex1', value: 999 },
|
||||
{ generalId: 2, type: 'dex1', value: 999 },
|
||||
{ generalId: 3, type: 'dex1', value: 999 },
|
||||
],
|
||||
findMany: async () =>
|
||||
options?.rankRows ?? [
|
||||
{ generalId: 1, type: 'firenum', value: 10 },
|
||||
{ generalId: 2, type: 'firenum', value: 20 },
|
||||
{ generalId: 3, type: 'firenum', value: 30 },
|
||||
{ generalId: 1, type: 'dex1', value: 999 },
|
||||
{ generalId: 2, type: 'dex1', value: 999 },
|
||||
{ generalId: 3, type: 'dex1', value: 999 },
|
||||
],
|
||||
},
|
||||
auction: {
|
||||
findMany: async () => [{ targetCode: 'che_명마_15_적토마' }],
|
||||
@@ -237,6 +259,58 @@ describe('ranking.getBestGeneral', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns positions one through ten for every populated ranking section', async () => {
|
||||
const generals = Array.from({ length: 12 }, (_, index) => {
|
||||
const id = index + 1;
|
||||
const value = id * 1_000;
|
||||
return {
|
||||
id,
|
||||
name: `상위${id}`,
|
||||
nationId: 1,
|
||||
userId: `top-${id}`,
|
||||
npcState: 0,
|
||||
picture: null,
|
||||
imageServer: 0,
|
||||
meta: { dex1: value, dex2: value, dex3: value, dex4: value, dex5: value },
|
||||
experience: value,
|
||||
dedication: value,
|
||||
horseCode: 'None',
|
||||
weaponCode: 'None',
|
||||
bookCode: 'None',
|
||||
itemCode: 'None',
|
||||
};
|
||||
});
|
||||
const rankRows = generals.flatMap((general) =>
|
||||
RANK_DATA_TYPES.filter(
|
||||
(type) => type !== 'experience' && type !== 'dedication' && !type.startsWith('dex')
|
||||
).map((type) => ({
|
||||
generalId: general.id,
|
||||
type,
|
||||
value:
|
||||
type === 'warnum' || type === 'deathcrew' || type === 'deathcrew_person'
|
||||
? 1_000
|
||||
: type === 'ttd' || type === 'ttl' || type === 'tld' || type === 'tll' ||
|
||||
type === 'tsd' || type === 'tsl' || type === 'tid' || type === 'til' ||
|
||||
type === 'betgold'
|
||||
? 1_000
|
||||
: general.id * 1_000,
|
||||
}))
|
||||
);
|
||||
const result = await appRouter
|
||||
.createCaller(buildContext({ isUnited: true, generals, rankRows }))
|
||||
.ranking.getBestGeneral({ view: 'user' });
|
||||
|
||||
expect(result.sections).toHaveLength(26);
|
||||
for (const section of result.sections) {
|
||||
expect(section.entries, section.title).toHaveLength(10);
|
||||
expect(new Set(section.entries.map((entry) => entry.id)).size, section.title).toBe(10);
|
||||
expect(section.entries.every((entry) => entry.value > 0), section.title).toBe(true);
|
||||
}
|
||||
expect(result.sections.find((section) => section.title === '계 략 성 공')?.entries.map((entry) => entry.id)).toEqual([
|
||||
12, 11, 10, 9, 8, 7, 6, 5, 4, 3,
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches PHP number_format rounding and the legacy fixed color table', () => {
|
||||
expect(formatLegacyRankingNumber(1.005, 2)).toBe('1.01');
|
||||
expect(formatLegacyRankingNumber(12345.6, 2)).toBe('12,345.60');
|
||||
|
||||
@@ -176,13 +176,14 @@ const runTournamentToCompletion = async (options: {
|
||||
store: TournamentStore;
|
||||
prisma: ReturnType<typeof createPrismaMock>;
|
||||
baseSeed: string;
|
||||
daemonTransport?: TurnDaemonTransport;
|
||||
}): Promise<TournamentState> => {
|
||||
let state = await options.store.getState();
|
||||
if (!state) {
|
||||
throw new Error('토너먼트 상태가 없습니다.');
|
||||
}
|
||||
|
||||
const daemonTransport = createNoopDaemonTransport();
|
||||
const daemonTransport = options.daemonTransport ?? createNoopDaemonTransport();
|
||||
|
||||
for (let i = 0; i < 2000; i += 1) {
|
||||
if (state.stage === 0) {
|
||||
@@ -198,7 +199,7 @@ const runTournamentToCompletion = async (options: {
|
||||
continue;
|
||||
}
|
||||
if (state.stage >= 7 && state.stage <= 10) {
|
||||
state = await applyBattle(options.store, state, options.baseSeed);
|
||||
state = await applyBattle(options.store, state, options.baseSeed, daemonTransport);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
@@ -270,6 +271,61 @@ describe('tournament worker (in-memory)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('runs all four tournament types and emits enough rank and NPC-betting commands for a top ten', async () => {
|
||||
for (const type of [
|
||||
TournamentType.TOTAL,
|
||||
TournamentType.LEADERSHIP,
|
||||
TournamentType.STRENGTH,
|
||||
TournamentType.INTEL,
|
||||
]) {
|
||||
const redis = new MemoryRedis();
|
||||
const store = new TournamentStore(redis, buildTournamentKeys(`ranking-audit-${type}`));
|
||||
const participants = createParticipants(16, 16, 32);
|
||||
await store.setParticipants(participants);
|
||||
await store.setState(createTournamentState({ stage: 1, type }));
|
||||
const npcBetting = participants.slice(0, 12).map((entry) => ({
|
||||
...entry,
|
||||
meta: {},
|
||||
npcState: 2,
|
||||
gold: 10_000,
|
||||
}));
|
||||
const commands: TurnDaemonCommand[] = [];
|
||||
const transport: TurnDaemonTransport = {
|
||||
sendCommand: async (command) => {
|
||||
commands.push(command);
|
||||
return 'ok';
|
||||
},
|
||||
requestCommand: async () => null,
|
||||
requestStatus: async () => null,
|
||||
};
|
||||
|
||||
await runTournamentToCompletion({
|
||||
store,
|
||||
prisma: createPrismaMock({ baseSeed: `ranking-audit-${type}`, npcBetting, currentYear: 10 }),
|
||||
baseSeed: `ranking-audit-${type}`,
|
||||
daemonTransport: transport,
|
||||
});
|
||||
|
||||
const matchCommands = commands.filter((command) => command.type === 'tournamentMatchResult');
|
||||
const rankedGeneralIds = new Set(
|
||||
matchCommands.flatMap((command) =>
|
||||
command.type === 'tournamentMatchResult' ? [command.attackerId, command.defenderId] : []
|
||||
)
|
||||
);
|
||||
expect(matchCommands.length).toBeGreaterThan(50);
|
||||
expect(rankedGeneralIds.size).toBeGreaterThanOrEqual(10);
|
||||
expect(commands).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: 'adjustGeneralMeta',
|
||||
reason: 'tournamentNpcBet',
|
||||
adjustments: expect.arrayContaining([
|
||||
expect.objectContaining({ metaDelta: { betgold: expect.any(Number) } }),
|
||||
]),
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('우승 결과에 따라 베팅 정산 명령이 생성된다', async () => {
|
||||
const redis = new MemoryRedis();
|
||||
const store = new TournamentStore(redis, buildTournamentKeys('test-bet'));
|
||||
|
||||
@@ -248,7 +248,7 @@ export const seedScenarioToDatabase = async (options: ScenarioSeedOptions): Prom
|
||||
blockGeneralCreate: install?.blockGeneralCreate,
|
||||
npcMode: install?.npcMode,
|
||||
showImgLevel: install?.showImgLevel,
|
||||
tournamentTrig: install?.tournamentTrig,
|
||||
tournamentTrig: install?.tournamentTrig ?? true,
|
||||
extendedGeneral: includeExtendedGeneral,
|
||||
turnTermMinutes: install?.turnTermMinutes,
|
||||
syncTurnTime: install?.sync,
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { RANK_DATA_TYPES, rankDataMetaKey } from '@sammo-ts/common';
|
||||
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
|
||||
import type { GeneralMeta } from '@sammo-ts/logic';
|
||||
|
||||
import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js';
|
||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||
|
||||
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
|
||||
const integration = describe.skipIf(!databaseUrl);
|
||||
const worldId = 992_400;
|
||||
const nationId = 992_400;
|
||||
const cityId = 992_400;
|
||||
const generalIds = Array.from({ length: 12 }, (_, index) => 992_401 + index);
|
||||
|
||||
const makeGeneral = (id: number): TurnGeneral => ({
|
||||
id,
|
||||
name: `랭킹감사${id}`,
|
||||
nationId,
|
||||
cityId,
|
||||
troopId: 0,
|
||||
stats: { leadership: 70, strength: 70, intelligence: 70 },
|
||||
turnTime: new Date('0190-01-01T00:10:00.000Z'),
|
||||
recentWarTime: null,
|
||||
role: {
|
||||
items: { horse: null, weapon: null, book: null, item: null },
|
||||
personality: null,
|
||||
specialDomestic: null,
|
||||
specialWar: null,
|
||||
},
|
||||
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
|
||||
meta: { killturn: 24 },
|
||||
penalty: {},
|
||||
officerLevel: 1,
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
injury: 0,
|
||||
gold: 1_000,
|
||||
rice: 1_000,
|
||||
crew: 100,
|
||||
crewTypeId: 1,
|
||||
train: 100,
|
||||
atmos: 100,
|
||||
age: 30,
|
||||
npcState: 2,
|
||||
});
|
||||
|
||||
integration('best-general rank persistence', () => {
|
||||
let db: GamePrismaClient;
|
||||
let closeDb: (() => Promise<void>) | undefined;
|
||||
|
||||
const cleanup = async () => {
|
||||
await db.rankData.deleteMany({ where: { generalId: { in: generalIds } } });
|
||||
await db.general.deleteMany({ where: { id: { in: generalIds } } });
|
||||
await db.city.deleteMany({ where: { id: cityId } });
|
||||
await db.nation.deleteMany({ where: { id: nationId } });
|
||||
await db.worldState.deleteMany({ where: { id: worldId } });
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
const connector = createGamePostgresConnector({ url: databaseUrl! });
|
||||
await connector.connect();
|
||||
db = connector.prisma;
|
||||
closeDb = () => connector.disconnect();
|
||||
await cleanup();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup();
|
||||
await closeDb?.();
|
||||
});
|
||||
|
||||
it('flushes every ranking field for twelve active NPCs and keeps the ordered top ten', async () => {
|
||||
await db.worldState.create({
|
||||
data: {
|
||||
id: worldId,
|
||||
scenarioCode: 'best-general-rank-persistence',
|
||||
currentYear: 190,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 600,
|
||||
config: {},
|
||||
meta: {},
|
||||
},
|
||||
});
|
||||
await db.nation.create({
|
||||
data: {
|
||||
id: nationId,
|
||||
name: '랭킹감사국',
|
||||
color: '#330000',
|
||||
level: 1,
|
||||
},
|
||||
});
|
||||
await db.city.create({
|
||||
data: {
|
||||
id: cityId,
|
||||
name: '랭킹감사성',
|
||||
level: 5,
|
||||
nationId,
|
||||
population: 10_000,
|
||||
populationMax: 20_000,
|
||||
agriculture: 1_000,
|
||||
agricultureMax: 2_000,
|
||||
commerce: 1_000,
|
||||
commerceMax: 2_000,
|
||||
security: 1_000,
|
||||
securityMax: 2_000,
|
||||
defence: 1_000,
|
||||
defenceMax: 2_000,
|
||||
wall: 1_000,
|
||||
wallMax: 2_000,
|
||||
region: 1,
|
||||
},
|
||||
});
|
||||
const initialGenerals = generalIds.map(makeGeneral);
|
||||
await db.general.createMany({
|
||||
data: initialGenerals.map((general) => ({
|
||||
id: general.id,
|
||||
name: general.name,
|
||||
nationId,
|
||||
cityId,
|
||||
npcState: general.npcState,
|
||||
leadership: general.stats.leadership,
|
||||
strength: general.stats.strength,
|
||||
intel: general.stats.intelligence,
|
||||
turnTime: general.turnTime,
|
||||
meta: general.meta,
|
||||
})),
|
||||
});
|
||||
|
||||
const state: TurnWorldState = {
|
||||
id: worldId,
|
||||
currentYear: 190,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 600,
|
||||
lastTurnTime: new Date('0190-01-01T00:00:00.000Z'),
|
||||
meta: {},
|
||||
};
|
||||
const snapshot: TurnWorldSnapshot = {
|
||||
generals: initialGenerals,
|
||||
cities: [],
|
||||
nations: [],
|
||||
troops: [],
|
||||
diplomacy: [],
|
||||
events: [],
|
||||
initialEvents: [],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: '랭킹 감사 지도',
|
||||
cities: [],
|
||||
},
|
||||
scenarioConfig: {
|
||||
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
|
||||
iconPath: '',
|
||||
map: {},
|
||||
const: {},
|
||||
environment: { mapName: 'test', unitSet: 'test' },
|
||||
},
|
||||
};
|
||||
const world = new InMemoryTurnWorld(state, snapshot, {
|
||||
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
|
||||
});
|
||||
for (const [index, generalId] of generalIds.entries()) {
|
||||
const value = index + 1;
|
||||
const meta: GeneralMeta = { killturn: 24 };
|
||||
for (const type of RANK_DATA_TYPES) {
|
||||
if (type !== 'experience' && type !== 'dedication') {
|
||||
meta[rankDataMetaKey(type)] = value;
|
||||
}
|
||||
}
|
||||
world.updateGeneral(generalId, {
|
||||
experience: value,
|
||||
dedication: value,
|
||||
meta,
|
||||
});
|
||||
}
|
||||
|
||||
const dbHooks = await createDatabaseTurnHooks(databaseUrl!, world);
|
||||
try {
|
||||
await dbHooks.hooks.flushChanges?.({
|
||||
lastTurnTime: state.lastTurnTime.toISOString(),
|
||||
processedGenerals: generalIds.length,
|
||||
processedTurns: generalIds.length,
|
||||
durationMs: 0,
|
||||
partial: false,
|
||||
});
|
||||
} finally {
|
||||
await dbHooks.close();
|
||||
}
|
||||
|
||||
const rows = await db.rankData.findMany({
|
||||
where: { generalId: { in: generalIds } },
|
||||
orderBy: [{ type: 'asc' }, { value: 'desc' }, { generalId: 'asc' }],
|
||||
});
|
||||
expect(rows).toHaveLength(generalIds.length * RANK_DATA_TYPES.length);
|
||||
for (const type of RANK_DATA_TYPES) {
|
||||
const topTen = rows.filter((row) => row.type === type).slice(0, 10);
|
||||
expect(topTen.map((row) => row.value)).toEqual([12, 11, 10, 9, 8, 7, 6, 5, 4, 3]);
|
||||
expect(topTen.map((row) => row.generalId)).toEqual(generalIds.slice(2).reverse());
|
||||
}
|
||||
|
||||
const persistedGenerals = await db.general.findMany({
|
||||
where: { id: { in: generalIds } },
|
||||
orderBy: { experience: 'desc' },
|
||||
select: { id: true, experience: true, dedication: true, meta: true },
|
||||
});
|
||||
expect(persistedGenerals.slice(0, 10).map((general) => general.id)).toEqual(generalIds.slice(2).reverse());
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { RANK_DATA_TYPES, rankDataMetaKey } from '@sammo-ts/common';
|
||||
import type { LogEntryDraft, TurnSchedule, UnitSetDefinition } from '@sammo-ts/logic';
|
||||
import { DIPLOMACY_STATE, LogCategory, LogFormat, LogScope } from '@sammo-ts/logic';
|
||||
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../src/turn/inMemoryWorld.js';
|
||||
@@ -153,6 +154,7 @@ const dumpWorldStatus = (world: InMemoryTurnWorld, label: string) => {
|
||||
describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
||||
it('건국, 선포, 출병, 점령과 장기 국가 감소가 안정적으로 진행되어야 한다', async () => {
|
||||
const memoryProfileEnabled = process.env.NPC_UNIFICATION_MEMORY_PROFILE === '1';
|
||||
const rankingAuditEnabled = process.env.NPC_RANKING_AUDIT === '1';
|
||||
const profileStartedAtMs = performance.now();
|
||||
const cities = buildLargeTestCities().map(maxCityStats);
|
||||
for (const city of cities) {
|
||||
@@ -206,7 +208,8 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
||||
};
|
||||
|
||||
const generals: TurnGeneral[] = [];
|
||||
for (let i = 0; i < 300; i += 1) {
|
||||
const initialGeneralCount = rankingAuditEnabled ? 150 : 300;
|
||||
for (let i = 0; i < initialGeneralCount; i += 1) {
|
||||
const cityId = cities[i % cities.length]!.id;
|
||||
const stats =
|
||||
i % 2 === 0
|
||||
@@ -580,6 +583,7 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
||||
}
|
||||
|
||||
if (
|
||||
(rankingAuditEnabled && sortieCount >= 50) ||
|
||||
world.getState().currentYear > 260 ||
|
||||
(world.getState().currentYear === 260 && world.getState().currentMonth >= 1)
|
||||
) {
|
||||
@@ -595,11 +599,85 @@ describe('NPC 건국/통일 장기 시뮬레이션', () => {
|
||||
expect(meta.isUnited).toBe(2);
|
||||
expect(hasUnificationLog).toBe(true);
|
||||
} else {
|
||||
expect(prevNationCount).toBeLessThan(foundedNationCount);
|
||||
if (!rankingAuditEnabled) {
|
||||
expect(prevNationCount).toBeLessThan(foundedNationCount);
|
||||
}
|
||||
expect(meta.isUnited ?? 0).toBe(0);
|
||||
}
|
||||
expect(sortieCount).toBeGreaterThan(0);
|
||||
|
||||
if (rankingAuditEnabled) {
|
||||
const rankingAudit = RANK_DATA_TYPES.map((type) => {
|
||||
const entries = world
|
||||
.listGenerals()
|
||||
.map((general) => {
|
||||
const rawValue =
|
||||
type === 'experience'
|
||||
? general.experience
|
||||
: type === 'dedication'
|
||||
? general.dedication
|
||||
: general.meta[rankDataMetaKey(type)];
|
||||
const value = typeof rawValue === 'number' && Number.isFinite(rawValue) ? rawValue : 0;
|
||||
return { generalId: general.id, name: general.name, value };
|
||||
})
|
||||
.filter((entry) => entry.value > 0)
|
||||
.sort((lhs, rhs) => rhs.value - lhs.value || lhs.generalId - rhs.generalId)
|
||||
.slice(0, 10);
|
||||
return { type, entries };
|
||||
});
|
||||
const byType = new Map(rankingAudit.map((entry) => [entry.type, entry.entries]));
|
||||
expect(byType.get('firenum')).toHaveLength(0);
|
||||
for (const type of [
|
||||
'experience',
|
||||
'dedication',
|
||||
'warnum',
|
||||
'killnum',
|
||||
'deathnum',
|
||||
'killcrew',
|
||||
'deathcrew',
|
||||
'killcrew_person',
|
||||
'deathcrew_person',
|
||||
'dex1',
|
||||
'dex2',
|
||||
'dex3',
|
||||
'dex4',
|
||||
'dex5',
|
||||
] as const) {
|
||||
expect(byType.get(type), type).toHaveLength(10);
|
||||
}
|
||||
const reportPath = resolve(
|
||||
process.env.NPC_RANKING_AUDIT_REPORT_PATH ?? 'test-results/npc-ranking-audit.json'
|
||||
);
|
||||
mkdirSync(dirname(reportPath), { recursive: true });
|
||||
writeFileSync(
|
||||
reportPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
year: world.getState().currentYear,
|
||||
month: world.getState().currentMonth,
|
||||
initialGeneralCount,
|
||||
finalGeneralCount: world.listGenerals().length,
|
||||
declarationCount,
|
||||
sortieCount,
|
||||
rankingAudit,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}\n`,
|
||||
'utf8'
|
||||
);
|
||||
console.log(
|
||||
`[NPC_RANKING_AUDIT]${JSON.stringify({
|
||||
reportPath,
|
||||
year: world.getState().currentYear,
|
||||
month: world.getState().currentMonth,
|
||||
declarationCount,
|
||||
sortieCount,
|
||||
topTenTypes: Array.from(byType.values()).filter((entries) => entries.length === 10).length,
|
||||
})}`
|
||||
);
|
||||
}
|
||||
|
||||
if (memoryProfiler) {
|
||||
expect(typeof globalThis.gc).toBe('function');
|
||||
expect(unifiedAt).not.toBeNull();
|
||||
|
||||
@@ -103,6 +103,7 @@ describeDb('scenario database seed', () => {
|
||||
await connector.connect();
|
||||
try {
|
||||
const prisma = connector.prisma as unknown as ScenarioSeederPrismaClient;
|
||||
const worldState = await prisma.worldState.findFirst();
|
||||
const [nationCount, cityCount, generalCount, diplomacyCount, eventCount] = await Promise.all([
|
||||
prisma.nation.count(),
|
||||
prisma.city.count(),
|
||||
@@ -116,6 +117,7 @@ describeDb('scenario database seed', () => {
|
||||
expect(generalCount).toBe(seed.generals.length);
|
||||
expect(diplomacyCount).toBe(seed.nations.length * Math.max(0, seed.nations.length - 1));
|
||||
expect(eventCount).toBe(seed.events.length);
|
||||
expect(worldState?.config).toMatchObject({ tournamentTrig: true });
|
||||
expect(generalCount).toBeGreaterThan(0);
|
||||
const seededGeneral = await prisma.general.findFirst();
|
||||
expect(seededGeneral?.startAge).toBe(seededGeneral?.age);
|
||||
@@ -201,7 +203,7 @@ describeDb('scenario database seed', () => {
|
||||
blockGeneralCreate: 2,
|
||||
npcMode: 0,
|
||||
showImgLevel: 3,
|
||||
tournamentTrig: true,
|
||||
tournamentTrig: false,
|
||||
joinMode: 'full',
|
||||
autorunUser: {
|
||||
limitMinutes: 60,
|
||||
@@ -234,6 +236,7 @@ describeDb('scenario database seed', () => {
|
||||
const config = (worldState.config ?? {}) as Record<string, unknown>;
|
||||
expect(config.extendedGeneral).toBe(false);
|
||||
expect(config.joinMode).toBe('full');
|
||||
expect(config.tournamentTrig).toBe(false);
|
||||
|
||||
const meta = (worldState.meta ?? {}) as Record<string, unknown>;
|
||||
const autorun = (meta.autorun_user ?? {}) as Record<string, unknown>;
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { TurnSchedule } from '@sammo-ts/logic';
|
||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
|
||||
import { buildPersistedRankRows } from '../src/turn/rankData.js';
|
||||
|
||||
const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] };
|
||||
|
||||
@@ -116,6 +117,46 @@ describe('tournament world commands', () => {
|
||||
expect(world.getGeneralById(1)?.meta).not.toHaveProperty('rank_betwin');
|
||||
});
|
||||
|
||||
it('records all four tournament types and NPC betting for at least ten generals', async () => {
|
||||
const generals = Array.from({ length: 12 }, (_, index) => buildGeneral(index + 1));
|
||||
const world = buildWorld(generals);
|
||||
const handler = createTurnDaemonCommandHandler({ world });
|
||||
|
||||
for (const tournamentType of [0, 1, 2, 3] as const) {
|
||||
for (const general of generals) {
|
||||
const result = await handler.handle({
|
||||
type: 'tournamentMatchResult',
|
||||
tournamentType,
|
||||
attackerId: general.id,
|
||||
defenderId: (general.id % generals.length) + 1,
|
||||
result: 'attacker',
|
||||
});
|
||||
expect(result).toMatchObject({ ok: true });
|
||||
}
|
||||
}
|
||||
await handler.handle({
|
||||
type: 'adjustGeneralMeta',
|
||||
reason: 'tournamentNpcBet',
|
||||
adjustments: generals.map((general) => ({
|
||||
generalId: general.id,
|
||||
metaDelta: { betgold: 1_000 },
|
||||
})),
|
||||
});
|
||||
await handler.handle({
|
||||
type: 'tournamentBettingPayout',
|
||||
bettingId: 1,
|
||||
payouts: generals.map((general) => ({ generalId: general.id, amount: 2_000 })),
|
||||
});
|
||||
|
||||
for (const type of ['ttw', 'tlw', 'tsw', 'tiw', 'betgold', 'betwin', 'betwingold'] as const) {
|
||||
const positiveRows = world
|
||||
.listGenerals()
|
||||
.flatMap(buildPersistedRankRows)
|
||||
.filter((row) => row.type === type && row.value > 0);
|
||||
expect(positiveRows, type).toHaveLength(12);
|
||||
}
|
||||
});
|
||||
|
||||
it('enforces a command-specific minimum remaining gold atomically', async () => {
|
||||
const world = buildWorld([buildGeneral(1)]);
|
||||
const handler = createTurnDaemonCommandHandler({ world });
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
|
||||
const frontendUrl = process.env.CHIEF_CENTER_LIVE_FRONTEND_URL ?? 'http://127.0.0.1:15160/hwe/';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: '.',
|
||||
testMatch: ['chiefCenterLive.spec.ts'],
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
timeout: 90_000,
|
||||
expect: { timeout: 15_000 },
|
||||
reporter: [['list']],
|
||||
outputDir: resolve(repositoryRoot, 'test-results/chief-center-live'),
|
||||
use: {
|
||||
baseURL: frontendUrl,
|
||||
trace: 'retain-on-failure',
|
||||
screenshot: 'only-on-failure',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import { expect, test, type Browser, type Page } from '@playwright/test';
|
||||
import { encryptGameSessionToken } from '../../../packages/common/dist/auth/gameToken.js';
|
||||
import { createGamePostgresConnector } from '../../../packages/infra/dist/index.js';
|
||||
|
||||
const databaseUrl = process.env.CHIEF_CENTER_LIVE_DATABASE_URL;
|
||||
const gameTokenSecret = process.env.CHIEF_CENTER_LIVE_GAME_SECRET;
|
||||
const profile = process.env.PLAYWRIGHT_GAME_PROFILE ?? 'hwe:1010';
|
||||
const hasLiveFixture = Boolean(databaseUrl && gameTokenSecret);
|
||||
const gameSchema = profile.split(':', 1)[0] ?? '';
|
||||
|
||||
const resolveGameDatabaseUrl = (): string => {
|
||||
const parsed = new URL(databaseUrl!);
|
||||
const sourceSchema = parsed.searchParams.get('schema');
|
||||
if (!gameSchema || (sourceSchema !== 'public' && sourceSchema !== gameSchema)) {
|
||||
throw new Error(`Refusing unexpected chief-center schema: ${sourceSchema ?? '(missing)'}`);
|
||||
}
|
||||
parsed.searchParams.set('schema', gameSchema);
|
||||
return parsed.toString();
|
||||
};
|
||||
|
||||
const installSession = async (page: Page, userId: string, displayName: string): Promise<void> => {
|
||||
const now = new Date();
|
||||
const token = encryptGameSessionToken(
|
||||
{
|
||||
version: 1,
|
||||
profile,
|
||||
issuedAt: now.toISOString(),
|
||||
expiresAt: new Date(now.getTime() + 3_600_000).toISOString(),
|
||||
sessionId: `chief-center-live-${randomUUID()}`,
|
||||
user: {
|
||||
id: userId,
|
||||
username: userId,
|
||||
displayName,
|
||||
roles: ['user'],
|
||||
canUseGeneralPicture: false,
|
||||
},
|
||||
sanctions: {},
|
||||
identity: {
|
||||
kakaoVerified: true,
|
||||
canCreateGeneral: true,
|
||||
requiresKakaoVerification: false,
|
||||
graceEndsAt: null,
|
||||
},
|
||||
},
|
||||
gameTokenSecret!
|
||||
);
|
||||
await page.addInitScript(
|
||||
({ gameToken, gameProfile }) => {
|
||||
localStorage.setItem('sammo-game-token', gameToken);
|
||||
localStorage.setItem('sammo-game-profile', gameProfile);
|
||||
},
|
||||
{ gameToken: token, gameProfile: profile }
|
||||
);
|
||||
};
|
||||
|
||||
const newPage = async (browser: Browser, userId: string, displayName: string): Promise<Page> => {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1365, height: 900 },
|
||||
deviceScaleFactor: 1,
|
||||
locale: 'ko-KR',
|
||||
timezoneId: 'Asia/Seoul',
|
||||
colorScheme: 'dark',
|
||||
});
|
||||
const page = await context.newPage();
|
||||
await installSession(page, userId, displayName);
|
||||
return page;
|
||||
};
|
||||
|
||||
test('persists one chief command and exposes it to a normal nation user and another chief', async ({
|
||||
browser,
|
||||
}, testInfo) => {
|
||||
test.skip(!hasLiveFixture, 'isolated chief-center PostgreSQL and token secret are required');
|
||||
test.setTimeout(90_000);
|
||||
|
||||
const connector = createGamePostgresConnector({ url: resolveGameDatabaseUrl() });
|
||||
await connector.connect();
|
||||
const db = connector.prisma;
|
||||
const editor = await db.general.findFirstOrThrow({ where: { name: 'GUI비교관리자' } });
|
||||
const candidates = await db.general.findMany({
|
||||
where: { nationId: editor.nationId, userId: null, id: { not: editor.id } },
|
||||
orderBy: { id: 'asc' },
|
||||
take: 2,
|
||||
});
|
||||
if (candidates.length !== 2) throw new Error('Two isolated visibility candidates are required.');
|
||||
const [viewer, otherChief] = candidates;
|
||||
const viewerUserId = `chief-center-viewer-${randomUUID()}`;
|
||||
const otherChiefUserId = `chief-center-peer-${randomUUID()}`;
|
||||
const originalTurns = await db.nationTurn.findMany({
|
||||
where: { nationId: editor.nationId, officerLevel: editor.officerLevel },
|
||||
orderBy: { turnIdx: 'asc' },
|
||||
});
|
||||
const originalRevision = await db.nationTurnRevision.findUnique({
|
||||
where: {
|
||||
nationId_officerLevel: { nationId: editor.nationId, officerLevel: editor.officerLevel },
|
||||
},
|
||||
});
|
||||
let selectedTargetId: number | undefined;
|
||||
|
||||
try {
|
||||
await db.$transaction([
|
||||
db.general.update({
|
||||
where: { id: viewer.id },
|
||||
data: {
|
||||
userId: viewerUserId,
|
||||
officerLevel: 1,
|
||||
npcState: 0,
|
||||
meta: { ...(viewer.meta as Record<string, unknown>), belong: 999 },
|
||||
penalty: {},
|
||||
},
|
||||
}),
|
||||
db.general.update({
|
||||
where: { id: otherChief.id },
|
||||
data: { userId: otherChiefUserId, officerLevel: 10, npcState: 0, penalty: {} },
|
||||
}),
|
||||
]);
|
||||
|
||||
const editorPage = await newPage(browser, editor.userId!, '사령부입력자');
|
||||
await editorPage.goto('chief-center');
|
||||
await expect(editorPage.getByRole('heading', { name: '사령부', exact: true })).toBeVisible();
|
||||
await editorPage.getByRole('button', { name: '1턴 명령 입력', exact: true }).click();
|
||||
const picker = editorPage.getByTestId('chief-command-picker');
|
||||
await expect(picker).toBeVisible();
|
||||
await picker.getByRole('button', { name: '인사', exact: true }).click();
|
||||
const reward = picker.getByRole('button', { name: /포상/ });
|
||||
await expect(reward).toBeEnabled();
|
||||
await reward.click();
|
||||
const argumentForm = picker.getByTestId('command-argument-form');
|
||||
await argumentForm.getByRole('button', { name: '쌀', exact: true }).click();
|
||||
await argumentForm.locator('input[type=number]').fill('1');
|
||||
const selectableGeneralIds = await argumentForm
|
||||
.locator('select option')
|
||||
.evaluateAll((options) =>
|
||||
options
|
||||
.map((option) => Number((option as HTMLOptionElement).value))
|
||||
.filter((value) => Number.isInteger(value) && value > 0)
|
||||
);
|
||||
selectedTargetId = selectableGeneralIds.find((generalId) => generalId !== editor.id);
|
||||
if (!selectedTargetId) throw new Error('No reward target is available in the live command table.');
|
||||
await argumentForm.locator('select').selectOption(String(selectedTargetId));
|
||||
await picker.getByRole('button', { name: '입력', exact: true }).click();
|
||||
await expect(
|
||||
editorPage.getByTestId('chief-command-editor').locator('.editor-turn-row strong').first()
|
||||
).toHaveText('포상');
|
||||
|
||||
const persisted = await db.nationTurn.findUniqueOrThrow({
|
||||
where: {
|
||||
nationId_officerLevel_turnIdx: {
|
||||
nationId: editor.nationId,
|
||||
officerLevel: editor.officerLevel,
|
||||
turnIdx: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(persisted.actionCode).toBe('che_포상');
|
||||
expect(persisted.arg).toEqual({ isGold: false, amount: 1, destGeneralId: selectedTargetId });
|
||||
await editorPage.screenshot({ path: testInfo.outputPath('chief-editor-command-entered.png'), fullPage: true });
|
||||
|
||||
const viewerPage = await newPage(browser, viewerUserId, '일반국가원');
|
||||
await viewerPage.goto('chief-center');
|
||||
await expect(viewerPage.getByRole('heading', { name: '사령부', exact: true })).toBeVisible();
|
||||
await expect(viewerPage.getByTestId('chief-command-editor')).toHaveCount(0);
|
||||
await expect(viewerPage.locator('.chief-grid-row').first().getByText('포상', { exact: true })).toBeVisible();
|
||||
await viewerPage.screenshot({ path: testInfo.outputPath('chief-normal-user-visible.png'), fullPage: true });
|
||||
|
||||
const peerPage = await newPage(browser, otherChiefUserId, '다른수뇌');
|
||||
await peerPage.goto('chief-center');
|
||||
await expect(peerPage.getByTestId('chief-command-editor')).toBeVisible();
|
||||
await expect(peerPage.locator('.chief-grid-row').first().getByText('포상', { exact: true })).toBeVisible();
|
||||
await peerPage.screenshot({ path: testInfo.outputPath('chief-peer-visible.png'), fullPage: true });
|
||||
} finally {
|
||||
await db.$transaction(async (transaction) => {
|
||||
await transaction.nationTurn.deleteMany({
|
||||
where: { nationId: editor.nationId, officerLevel: editor.officerLevel },
|
||||
});
|
||||
if (originalTurns.length) await transaction.nationTurn.createMany({ data: originalTurns });
|
||||
await transaction.nationTurnRevision.deleteMany({
|
||||
where: { nationId: editor.nationId, officerLevel: editor.officerLevel },
|
||||
});
|
||||
if (originalRevision) await transaction.nationTurnRevision.create({ data: originalRevision });
|
||||
await transaction.general.update({
|
||||
where: { id: viewer.id },
|
||||
data: {
|
||||
userId: viewer.userId,
|
||||
officerLevel: viewer.officerLevel,
|
||||
npcState: viewer.npcState,
|
||||
meta: viewer.meta,
|
||||
penalty: viewer.penalty,
|
||||
},
|
||||
});
|
||||
await transaction.general.update({
|
||||
where: { id: otherChief.id },
|
||||
data: {
|
||||
userId: otherChief.userId,
|
||||
officerLevel: otherChief.officerLevel,
|
||||
npcState: otherChief.npcState,
|
||||
meta: otherChief.meta,
|
||||
penalty: otherChief.penalty,
|
||||
},
|
||||
});
|
||||
});
|
||||
await connector.disconnect();
|
||||
}
|
||||
});
|
||||
@@ -211,6 +211,7 @@ const install = async (page: Page, rejectGeneral = false) => {
|
||||
requests.push(body);
|
||||
return response({
|
||||
ok: true,
|
||||
revision: 1,
|
||||
turns: [{ index: 0, action: 'che_포상', args: { isGold: false, amount: 300, destGeneralId: 2 } }],
|
||||
});
|
||||
}
|
||||
@@ -281,7 +282,7 @@ test('keeps the entered command visible and reports a server validation error',
|
||||
});
|
||||
|
||||
test('keeps the shared main and chief shell geometry and interaction states', async ({ page }) => {
|
||||
await install(page);
|
||||
const requests = await install(page);
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await page.goto('/');
|
||||
await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible();
|
||||
@@ -329,10 +330,23 @@ test('keeps the shared main and chief shell geometry and interaction states', as
|
||||
await page.locator('.main-nation-menu').first().locator('[data-navigation-id="chief-center"]').click();
|
||||
await expect(page).toHaveURL(/\/che\/chief-center$/);
|
||||
await expect(page.getByRole('heading', { name: '사령부', exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: '1턴 명령 입력', exact: true }).click();
|
||||
await expect(page.getByTestId('chief-command-picker')).toBeVisible();
|
||||
await page.getByTestId('chief-command-picker').getByRole('button', { name: /포상/ }).click();
|
||||
const chiefArgumentForm = page.getByTestId('chief-command-picker').getByTestId('command-argument-form');
|
||||
await chiefArgumentForm.getByRole('button', { name: '쌀' }).click();
|
||||
await chiefArgumentForm.locator('input[type=number]').fill('300');
|
||||
await chiefArgumentForm.locator('select').selectOption('2');
|
||||
await page.getByTestId('chief-command-picker').getByRole('button', { name: '입력', exact: true }).click();
|
||||
await expect(page.getByTestId('chief-command-editor').locator('.editor-turn-row strong').first()).toHaveText(
|
||||
'포상'
|
||||
);
|
||||
expect(JSON.stringify(requests)).toContain('"action":"che_포상"');
|
||||
expect(JSON.stringify(requests)).toContain('"destGeneralId":2');
|
||||
const chiefDesktop = await page.locator('.chief-page').evaluate((element) => ({
|
||||
width: element.getBoundingClientRect().width,
|
||||
padding: getComputedStyle(element).padding,
|
||||
headerWidth: element.querySelector<HTMLElement>('.game-shell__header')!.getBoundingClientRect().width,
|
||||
headerWidth: element.querySelector<HTMLElement>('.chief-top')!.getBoundingClientRect().width,
|
||||
}));
|
||||
expect(chiefDesktop).toEqual({ width: 1000, padding: '0px', headerWidth: 1000 });
|
||||
|
||||
@@ -340,7 +354,7 @@ test('keeps the shared main and chief shell geometry and interaction states', as
|
||||
const chiefMobile = await page.locator('.chief-page').evaluate((element) => ({
|
||||
width: element.getBoundingClientRect().width,
|
||||
padding: getComputedStyle(element).padding,
|
||||
headerWidth: element.querySelector<HTMLElement>('.game-shell__header')!.getBoundingClientRect().width,
|
||||
headerWidth: element.querySelector<HTMLElement>('.chief-top')!.getBoundingClientRect().width,
|
||||
}));
|
||||
expect(chiefMobile).toEqual({ width: 500, padding: '0px', headerWidth: 500 });
|
||||
});
|
||||
|
||||
@@ -25,6 +25,7 @@ export default defineConfig({
|
||||
'nationGeneralSecret.spec.ts',
|
||||
'npcPolicy.spec.ts',
|
||||
'auction.spec.ts',
|
||||
'tournamentBracket.spec.ts',
|
||||
'battleSimulator.spec.ts',
|
||||
'battleSimulatorRef.spec.ts',
|
||||
'commandArguments.spec.ts',
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
"./npcPossessionLive.spec.ts",
|
||||
"./npcPossession.live.playwright.config.mjs",
|
||||
"./dieOnPrestartLive.spec.ts",
|
||||
"./dieOnPrestart.live.playwright.config.mjs"
|
||||
"./dieOnPrestart.live.playwright.config.mjs",
|
||||
"./chiefCenterLive.spec.ts",
|
||||
"./chiefCenter.live.playwright.config.mjs"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { gameProfile, gameTrpcRoute } from './gameTestPaths.js';
|
||||
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
|
||||
const imageRoots = [
|
||||
...(process.env.FRONTEND_PARITY_IMAGE_ROOT ? [resolve(process.env.FRONTEND_PARITY_IMAGE_ROOT, 'game')] : []),
|
||||
resolve(repositoryRoot, '../image/game'),
|
||||
resolve(repositoryRoot, '../../image/game'),
|
||||
];
|
||||
const names = [
|
||||
'관우',
|
||||
'장료',
|
||||
'조운',
|
||||
'하후돈',
|
||||
'손책',
|
||||
'태사자',
|
||||
'마초',
|
||||
'황충',
|
||||
'여포',
|
||||
'전위',
|
||||
'감녕',
|
||||
'문추',
|
||||
'안량',
|
||||
'허저',
|
||||
'주태',
|
||||
'방덕',
|
||||
];
|
||||
const participants = names.map((name, index) => ({
|
||||
id: index + 1,
|
||||
name,
|
||||
leadership: 80,
|
||||
strength: 80,
|
||||
intel: 80,
|
||||
level: 10,
|
||||
groupId: 10 + (index % 8),
|
||||
groupNo: Math.floor(index / 8),
|
||||
win: 3 - (index % 2),
|
||||
draw: index % 2,
|
||||
lose: 0,
|
||||
gl: 12 - index,
|
||||
finalRank: Math.floor(index / 8) + 1,
|
||||
}));
|
||||
const matches = [
|
||||
...Array.from({ length: 8 }, (_, index) => ({
|
||||
id: index + 1,
|
||||
stage: 7,
|
||||
roundIndex: index,
|
||||
attackerId: index * 2 + 1,
|
||||
defenderId: index * 2 + 2,
|
||||
winnerId: index * 2 + 1,
|
||||
})),
|
||||
...Array.from({ length: 4 }, (_, index) => ({
|
||||
id: index + 9,
|
||||
stage: 8,
|
||||
roundIndex: index,
|
||||
attackerId: index * 4 + 1,
|
||||
defenderId: index * 4 + 3,
|
||||
winnerId: index * 4 + 1,
|
||||
})),
|
||||
...Array.from({ length: 2 }, (_, index) => ({
|
||||
id: index + 13,
|
||||
stage: 9,
|
||||
roundIndex: index,
|
||||
attackerId: index * 8 + 1,
|
||||
defenderId: index * 8 + 5,
|
||||
winnerId: index * 8 + 1,
|
||||
})),
|
||||
{ id: 15, stage: 10, roundIndex: 0, attackerId: 1, defenderId: 9, winnerId: 1 },
|
||||
];
|
||||
|
||||
const response = (data: unknown) => ({ result: { data } });
|
||||
const operationNames = (route: Route): string[] => {
|
||||
const url = new URL(route.request().url());
|
||||
return decodeURIComponent(url.pathname.slice(url.pathname.lastIndexOf('/trpc/') + 6)).split(',');
|
||||
};
|
||||
|
||||
const readReferenceImage = async (filename: string): Promise<Buffer> => {
|
||||
for (const imageRoot of imageRoots) {
|
||||
try {
|
||||
return await readFile(resolve(imageRoot, filename));
|
||||
} catch {
|
||||
// Worktrees can be nested at different depths.
|
||||
}
|
||||
}
|
||||
throw new Error(`Reference image not found: ${filename}`);
|
||||
};
|
||||
|
||||
const installFixture = async (page: Page) => {
|
||||
await page.addInitScript((profile) => {
|
||||
window.localStorage.setItem('sammo-game-token', 'ga_tournament_bracket_playwright');
|
||||
window.localStorage.setItem('sammo-game-profile', profile);
|
||||
}, gameProfile);
|
||||
for (const filename of ['back_walnut.jpg', 'back_green.jpg', 'back_blue.jpg']) {
|
||||
await page.route(`**/image/game/${filename}`, async (route) => {
|
||||
await route.fulfill({ status: 200, contentType: 'image/jpeg', body: await readReferenceImage(filename) });
|
||||
});
|
||||
}
|
||||
await page.route(gameTrpcRoute, async (route) => {
|
||||
const results = operationNames(route).map((operation) => {
|
||||
if (operation === 'auth.status') return response({ ok: true });
|
||||
if (operation === 'lobby.info') return response({ myGeneral: { id: 1, name: names[0] } });
|
||||
if (operation === 'join.getConfig') return response({});
|
||||
if (operation === 'general.me') return response({ general: { id: 1, name: names[0] } });
|
||||
if (operation === 'tournament.getAdminStatus') return response({ ok: false });
|
||||
if (operation === 'tournament.getSnapshot') {
|
||||
return response({
|
||||
state: {
|
||||
stage: 0,
|
||||
phase: 0,
|
||||
type: 0,
|
||||
auto: false,
|
||||
openYear: 184,
|
||||
openMonth: 1,
|
||||
termSeconds: 60,
|
||||
nextAt: '2026-08-02T00:00:00.000Z',
|
||||
winnerId: 1,
|
||||
},
|
||||
participants,
|
||||
matches,
|
||||
betCount: 16,
|
||||
});
|
||||
}
|
||||
if (operation === 'tournament.getBettingSummary') {
|
||||
return response({
|
||||
totals: Object.fromEntries(participants.map((participant, index) => [participant.id, 100 + index * 10])),
|
||||
myTotals: {},
|
||||
totalAmount: 2800,
|
||||
myAmount: 0,
|
||||
});
|
||||
}
|
||||
return response(null);
|
||||
});
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(results) });
|
||||
});
|
||||
};
|
||||
|
||||
const openTournament = async (page: Page) => {
|
||||
await installFixture(page);
|
||||
await page.goto('tournament');
|
||||
await expect(page.getByLabel('토너먼트 대진표')).toBeVisible();
|
||||
};
|
||||
|
||||
test('desktop bracket connects every real general slot to the next round', async ({ page }, testInfo) => {
|
||||
await page.setViewportSize({ width: 1365, height: 900 });
|
||||
await openTournament(page);
|
||||
|
||||
await expect(page.locator('.bracket-canvas .bracket-name[data-general-id]')).toHaveCount(31);
|
||||
await expect(page.locator('.bracket-canvas .connector-segment')).toHaveCount(15);
|
||||
await expect(page.locator('.bracket-canvas .bracket-name.advanced', { hasText: '관우' })).toHaveCount(5);
|
||||
|
||||
const geometry = await page.locator('.bracket-canvas').evaluate((canvas) => {
|
||||
const firstConnector = canvas.querySelector<HTMLElement>('.connector-segment')!.getBoundingClientRect();
|
||||
const champion = canvas.querySelector<HTMLElement>('.bracket-champion .bracket-name')!.getBoundingClientRect();
|
||||
const finalists = [...canvas.querySelectorAll<HTMLElement>('.bracket-round:nth-of-type(3) .bracket-name')].map(
|
||||
(element) => element.getBoundingClientRect()
|
||||
);
|
||||
return {
|
||||
canvasWidth: canvas.getBoundingClientRect().width,
|
||||
connectorCenter: firstConnector.x + firstConnector.width / 2,
|
||||
championCenter: champion.x + champion.width / 2,
|
||||
finalistCenters: finalists.map((rect) => rect.x + rect.width / 2),
|
||||
connectorQuarters: [firstConnector.x + firstConnector.width / 4, firstConnector.x + (firstConnector.width * 3) / 4],
|
||||
};
|
||||
});
|
||||
expect(geometry.canvasWidth).toBe(2000);
|
||||
expect(Math.abs(geometry.connectorCenter - geometry.championCenter)).toBeLessThan(1);
|
||||
expect(geometry.finalistCenters).toHaveLength(2);
|
||||
expect(Math.abs(geometry.finalistCenters[0]! - geometry.connectorQuarters[0]!)).toBeLessThan(1);
|
||||
expect(Math.abs(geometry.finalistCenters[1]! - geometry.connectorQuarters[1]!)).toBeLessThan(1);
|
||||
|
||||
await page.screenshot({ path: testInfo.outputPath('tournament-bracket-desktop.webp'), fullPage: true });
|
||||
});
|
||||
|
||||
test('mobile bracket shows every round and general within the handheld width', async ({ page }, testInfo) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await openTournament(page);
|
||||
|
||||
const bracket = page.locator('.mobile-bracket');
|
||||
await expect(bracket).toBeVisible();
|
||||
await expect(bracket.locator('.mobile-bracket-name')).toHaveCount(31);
|
||||
await expect(bracket.locator('.mobile-bracket-name', { hasText: '방덕' })).toBeVisible();
|
||||
await expect(bracket.locator('.mobile-bracket-name', { hasText: '관우' })).toHaveCount(5);
|
||||
const bounds = await bracket.evaluate((element) => {
|
||||
const names = [...element.querySelectorAll<HTMLElement>('.mobile-bracket-name')].map((name) =>
|
||||
name.getBoundingClientRect()
|
||||
);
|
||||
const own = element.getBoundingClientRect();
|
||||
return {
|
||||
width: own.width,
|
||||
minX: Math.min(...names.map((rect) => rect.left - own.left)),
|
||||
maxX: Math.max(...names.map((rect) => rect.right - own.left)),
|
||||
};
|
||||
});
|
||||
expect(bounds.width).toBe(390);
|
||||
expect(bounds.minX).toBeGreaterThanOrEqual(0);
|
||||
expect(bounds.maxX).toBeLessThanOrEqual(390);
|
||||
await page.screenshot({ path: testInfo.outputPath('tournament-bracket-mobile.webp'), fullPage: true });
|
||||
});
|
||||
@@ -259,13 +259,14 @@ test('renders the legacy desktop grid with matching computed geometry and states
|
||||
});
|
||||
|
||||
const kickButton = page.getByRole('button', { name: '부대원 추방...' }).first();
|
||||
expect(await kickButton.evaluate((button) => getComputedStyle(button).backgroundColor)).toBe('rgb(68, 68, 68)');
|
||||
await kickButton.hover();
|
||||
const hoverStyle = await kickButton.evaluate((button) => ({
|
||||
cursor: getComputedStyle(button).cursor,
|
||||
filter: getComputedStyle(button).filter,
|
||||
borderBottomWidth: getComputedStyle(button).borderBottomWidth,
|
||||
}));
|
||||
expect(hoverStyle.cursor).toBe('pointer');
|
||||
expect(hoverStyle.filter).not.toBe('none');
|
||||
expect(hoverStyle.borderBottomWidth).toBe('3px');
|
||||
|
||||
await page.locator('.troopMember').nth(1).hover();
|
||||
await expect(page.getByRole('tooltip')).toContainText('조운');
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"test:e2e:board": "playwright test board.spec.ts --config e2e/playwright.config.mjs",
|
||||
"test:e2e:directories": "playwright test directoryLists.spec.ts --config e2e/playwright.config.mjs",
|
||||
"test:e2e:auction": "playwright test auction.spec.ts --config e2e/playwright.config.mjs",
|
||||
"test:e2e:tournament-bracket": "playwright test tournamentBracket.spec.ts --config e2e/playwright.config.mjs",
|
||||
"test:e2e:battle-simulator": "playwright test battleSimulator.spec.ts --config e2e/playwright.config.mjs",
|
||||
"test:e2e:join-live": "playwright test --config e2e/joinGeneral.live.playwright.config.mjs --tsconfig e2e/playwright.live.tsconfig.json",
|
||||
"test:e2e:npc-possession": "playwright test npcPossession.spec.ts --config e2e/playwright.config.mjs",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
@import 'tailwindcss';
|
||||
@import './styles/tokens.css';
|
||||
@import './styles/legacy-controls.css';
|
||||
@import './styles/game-shell.css';
|
||||
@import './styles/ref-shell.css';
|
||||
|
||||
@@ -44,33 +45,3 @@ textarea {
|
||||
background-color: #172a52;
|
||||
background-image: var(--sammo-texture-blue);
|
||||
}
|
||||
|
||||
.legacy-button {
|
||||
display: inline-block;
|
||||
border: 1px solid #12195b;
|
||||
border-radius: 3px;
|
||||
background: #141c65;
|
||||
color: #fff;
|
||||
padding: 5px 10px;
|
||||
font-weight: 700;
|
||||
line-height: 1.5;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.legacy-button:hover,
|
||||
.legacy-button:focus,
|
||||
.legacy-button:active {
|
||||
border-color: #0f154c;
|
||||
background: #101651;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.legacy-button:focus-visible {
|
||||
outline: 2px solid #f39c12;
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.legacy-button:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
.legacy-button {
|
||||
display: inline-block;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--sammo-button-base1-border);
|
||||
border-radius: 3px;
|
||||
padding: 5px 10px;
|
||||
background: var(--sammo-button-base1-bg);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.legacy-button:hover,
|
||||
.legacy-button:focus,
|
||||
.legacy-button:active {
|
||||
border-color: var(--sammo-button-base1-hover-border);
|
||||
background: var(--sammo-button-base1-hover-bg);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.legacy-button:focus-visible {
|
||||
outline: 2px solid var(--sammo-color-accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.legacy-button:disabled,
|
||||
.legacy-button[aria-disabled='true'] {
|
||||
cursor: default;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
/*
|
||||
* Ref Bootstrap 5.2 + Lumen button family. The modifier describes the legacy
|
||||
* semantic role; width and placement remain in the owning scoped component.
|
||||
*/
|
||||
.legacy-button:is(
|
||||
.legacy-button--primary,
|
||||
.legacy-button--secondary,
|
||||
.legacy-button--danger,
|
||||
.legacy-button--info,
|
||||
.legacy-button--navigation
|
||||
) {
|
||||
--legacy-button-bg: var(--sammo-button-primary-bg);
|
||||
--legacy-button-border: var(--sammo-button-primary-border);
|
||||
min-height: 35.5px;
|
||||
margin-top: 0;
|
||||
border-color: var(--legacy-button-border);
|
||||
border-style: solid;
|
||||
border-width: 0 1px 4px;
|
||||
border-radius: 5.25px;
|
||||
padding: 5.25px 10.5px;
|
||||
background: var(--legacy-button-bg);
|
||||
color: #fff;
|
||||
line-height: 21px;
|
||||
}
|
||||
|
||||
.legacy-button.legacy-button--secondary {
|
||||
--legacy-button-bg: var(--sammo-button-secondary-bg);
|
||||
--legacy-button-border: var(--sammo-button-secondary-border);
|
||||
}
|
||||
|
||||
.legacy-button.legacy-button--danger {
|
||||
--legacy-button-bg: var(--sammo-button-danger-bg);
|
||||
--legacy-button-border: var(--sammo-button-danger-border);
|
||||
}
|
||||
|
||||
.legacy-button.legacy-button--info {
|
||||
--legacy-button-bg: var(--sammo-button-info-bg);
|
||||
--legacy-button-border: var(--sammo-button-info-border);
|
||||
}
|
||||
|
||||
.legacy-button.legacy-button--navigation {
|
||||
--legacy-button-bg: var(--sammo-button-navigation-bg);
|
||||
--legacy-button-border: var(--sammo-button-navigation-border);
|
||||
}
|
||||
|
||||
.legacy-button:is(
|
||||
.legacy-button--primary,
|
||||
.legacy-button--secondary,
|
||||
.legacy-button--danger,
|
||||
.legacy-button--info,
|
||||
.legacy-button--navigation
|
||||
):not(:disabled, [aria-disabled='true']):hover {
|
||||
margin-top: 1px;
|
||||
border-color: var(--legacy-button-border);
|
||||
border-bottom-width: 3px;
|
||||
background: var(--legacy-button-bg);
|
||||
}
|
||||
|
||||
.legacy-button:is(
|
||||
.legacy-button--primary,
|
||||
.legacy-button--secondary,
|
||||
.legacy-button--danger,
|
||||
.legacy-button--info,
|
||||
.legacy-button--navigation
|
||||
):not(:disabled, [aria-disabled='true']):active {
|
||||
margin-top: 2px;
|
||||
border-color: var(--legacy-button-border);
|
||||
border-bottom-width: 2px;
|
||||
background: var(--legacy-button-bg);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.legacy-button:is(
|
||||
.legacy-button--primary,
|
||||
.legacy-button--secondary,
|
||||
.legacy-button--danger,
|
||||
.legacy-button--info,
|
||||
.legacy-button--navigation
|
||||
):focus {
|
||||
border-color: var(--legacy-button-border);
|
||||
background: var(--legacy-button-bg);
|
||||
}
|
||||
@@ -6,6 +6,20 @@
|
||||
--sammo-color-border: rgba(201, 164, 90, 0.4);
|
||||
--sammo-color-action-bg: rgba(16, 16, 16, 0.6);
|
||||
--sammo-color-error: #f5b7b1;
|
||||
--sammo-button-base1-bg: #141c65;
|
||||
--sammo-button-base1-border: #12195b;
|
||||
--sammo-button-base1-hover-bg: #101651;
|
||||
--sammo-button-base1-hover-border: #0f154c;
|
||||
--sammo-button-primary-bg: #375a7f;
|
||||
--sammo-button-primary-border: #325172;
|
||||
--sammo-button-secondary-bg: #444;
|
||||
--sammo-button-secondary-border: #3d3d3d;
|
||||
--sammo-button-danger-bg: #e74c3c;
|
||||
--sammo-button-danger-border: #d04436;
|
||||
--sammo-button-info-bg: #3498db;
|
||||
--sammo-button-info-border: #2f89c5;
|
||||
--sammo-button-navigation-bg: #00582c;
|
||||
--sammo-button-navigation-border: #004f28;
|
||||
--sammo-texture-walnut: url('/image/game/back_walnut.jpg');
|
||||
--sammo-texture-green: url('/image/game/back_green.jpg');
|
||||
--sammo-texture-blue: url('/image/game/back_blue.jpg');
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import CommandArgumentForm from '../main/CommandArgumentForm.vue';
|
||||
import CommandSelectForm from '../main/CommandSelectForm.vue';
|
||||
import { getNpcColor } from '../../utils/npcColor';
|
||||
|
||||
type CommandOption = { value: string | number; label: string; color?: string };
|
||||
type CommandInputField = {
|
||||
key: string;
|
||||
label: string;
|
||||
kind: 'text' | 'number' | 'boolean' | 'select' | 'numberTuple' | 'hidden';
|
||||
required: boolean;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
constValue?: string | number;
|
||||
options?: CommandOption[];
|
||||
optionSource?: 'cities' | 'nations' | 'generals' | 'crewTypes' | 'armTypes' | 'nationTypes' | 'colors' | 'items';
|
||||
tupleLabels?: string[];
|
||||
};
|
||||
type CommandAvailability = {
|
||||
key: string;
|
||||
name: string;
|
||||
reqArg: boolean;
|
||||
status: 'available' | 'blocked' | 'needsInput' | 'unknown';
|
||||
possible: boolean;
|
||||
reason?: string;
|
||||
inputFields: CommandInputField[];
|
||||
};
|
||||
type CommandTable = {
|
||||
general: Array<{ category: string; values: CommandAvailability[] }>;
|
||||
nation: Array<{ category: string; values: CommandAvailability[] }>;
|
||||
inputOptions: {
|
||||
cities: CommandOption[];
|
||||
nations: CommandOption[];
|
||||
generals: CommandOption[];
|
||||
crewTypes: CommandOption[];
|
||||
armTypes: CommandOption[];
|
||||
nationTypes: CommandOption[];
|
||||
colors: CommandOption[];
|
||||
items: Record<string, CommandOption[]>;
|
||||
};
|
||||
};
|
||||
type TurnRow = { index: number; time: string; action: string; isRest: boolean };
|
||||
|
||||
const props = defineProps<{
|
||||
officerLevelText: string;
|
||||
name: string | null;
|
||||
npcState: number | null;
|
||||
rows: TurnRow[];
|
||||
commandTable: CommandTable | null;
|
||||
loading: boolean;
|
||||
mobile?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'reserve', payload: { index: number; action: string; args: Record<string, unknown> }): void;
|
||||
(event: 'shift', amount: number): void;
|
||||
(event: 'repeat', amount: number): void;
|
||||
}>();
|
||||
|
||||
const pickerTurnIndex = ref<number | null>(null);
|
||||
const selectedCommand = ref<CommandAvailability | null>(null);
|
||||
const commandArgs = ref<Record<string, unknown>>({});
|
||||
const commandArgsValid = ref(false);
|
||||
const editMode = ref(false);
|
||||
const repeatAmount = ref(0);
|
||||
|
||||
const nationCategoryOrder = ['휴식', '인사', '외교', '특수', '전략', '국가'];
|
||||
const nationOnlyTable = computed(() => {
|
||||
if (!props.commandTable) return null;
|
||||
const groupByCategory = new Map(props.commandTable.nation.map((group) => [group.category, group]));
|
||||
const orderedGroups = nationCategoryOrder.map(
|
||||
(category) => groupByCategory.get(category) ?? { category, values: [] }
|
||||
);
|
||||
const extraGroups = props.commandTable.nation.filter((group) => !nationCategoryOrder.includes(group.category));
|
||||
return { ...props.commandTable, general: [], nation: [...orderedGroups, ...extraGroups] };
|
||||
});
|
||||
const nameColor = computed(() => (props.npcState !== null ? getNpcColor(props.npcState) : undefined));
|
||||
|
||||
const closePicker = () => {
|
||||
pickerTurnIndex.value = null;
|
||||
selectedCommand.value = null;
|
||||
commandArgs.value = {};
|
||||
commandArgsValid.value = false;
|
||||
};
|
||||
|
||||
const openPicker = (turnIndex: number) => {
|
||||
pickerTurnIndex.value = turnIndex;
|
||||
selectedCommand.value = null;
|
||||
commandArgs.value = {};
|
||||
commandArgsValid.value = false;
|
||||
};
|
||||
|
||||
const selectCommand = (commandKey: string) => {
|
||||
const command =
|
||||
props.commandTable?.nation.flatMap((group) => group.values).find((entry) => entry.key === commandKey) ?? null;
|
||||
if (!command || pickerTurnIndex.value === null) return;
|
||||
selectedCommand.value = command;
|
||||
commandArgs.value = {};
|
||||
commandArgsValid.value = !command.reqArg;
|
||||
if (!command.reqArg) reserveSelected();
|
||||
};
|
||||
|
||||
const reserveSelected = () => {
|
||||
if (pickerTurnIndex.value === null || !selectedCommand.value || !commandArgsValid.value) return;
|
||||
emit('reserve', {
|
||||
index: pickerTurnIndex.value,
|
||||
action: selectedCommand.value.key,
|
||||
args: commandArgs.value,
|
||||
});
|
||||
closePicker();
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="chief-editor" :class="{ mobile: props.mobile }" data-testid="chief-command-editor">
|
||||
<header v-if="!props.mobile" class="editor-header legacy-bg1">
|
||||
<span>{{ props.officerLevelText }} :</span>
|
||||
<strong :style="{ color: nameColor }">{{ props.name ?? '-' }}</strong>
|
||||
</header>
|
||||
|
||||
<div class="editor-body">
|
||||
<aside class="editor-controls">
|
||||
<div v-if="props.mobile" class="mobile-identity legacy-bg1">
|
||||
<strong :style="{ color: nameColor }">{{ props.name ?? '-' }}</strong>
|
||||
<span>{{ props.officerLevelText }}</span>
|
||||
</div>
|
||||
<time>{{ props.rows[0]?.time ?? '--:--' }}</time>
|
||||
<button type="button" @click="editMode = !editMode">{{ editMode ? '일반 모드' : '고급 모드' }}</button>
|
||||
<select
|
||||
v-model.number="repeatAmount"
|
||||
class="repeat-control"
|
||||
aria-label="반복 턴 수"
|
||||
@change="repeatAmount > 0 && emit('repeat', repeatAmount)"
|
||||
>
|
||||
<option :value="0" disabled>반복⌄</option>
|
||||
<option v-for="amount in 6" :key="amount" :value="amount">{{ amount }}턴</option>
|
||||
</select>
|
||||
<button type="button" @click="emit('shift', -1)">당기기⌄</button>
|
||||
<button type="button" @click="emit('shift', 1)">미루기⌄</button>
|
||||
</aside>
|
||||
|
||||
<div class="editor-turns">
|
||||
<div v-for="row in props.rows" :key="row.index" class="editor-turn-row">
|
||||
<time>{{ row.time }}</time>
|
||||
<strong>{{ row.action }}</strong>
|
||||
<button
|
||||
type="button"
|
||||
class="edit-turn"
|
||||
:aria-label="`${row.index + 1}턴 명령 입력`"
|
||||
@click="openPicker(row.index)"
|
||||
>
|
||||
✎
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="pickerTurnIndex !== null"
|
||||
:class="['command-picker', { 'has-command': selectedCommand }]"
|
||||
data-testid="chief-command-picker"
|
||||
>
|
||||
<header>
|
||||
<strong>{{ pickerTurnIndex + 1 }}턴 명령 입력</strong>
|
||||
<button type="button" aria-label="명령 입력 닫기" @click="closePicker">×</button>
|
||||
</header>
|
||||
<CommandSelectForm
|
||||
v-if="!selectedCommand"
|
||||
:command-table="nationOnlyTable"
|
||||
:loading="props.loading"
|
||||
scope="nation"
|
||||
@select="selectCommand"
|
||||
/>
|
||||
<button v-if="!selectedCommand" type="button" class="picker-close" @click="closePicker">닫기</button>
|
||||
<template v-else>
|
||||
<div class="selected-command">{{ selectedCommand.name }}</div>
|
||||
<CommandArgumentForm
|
||||
v-if="selectedCommand.reqArg && props.commandTable"
|
||||
:command-key="selectedCommand.key"
|
||||
:fields="selectedCommand.inputFields"
|
||||
:options="props.commandTable.inputOptions"
|
||||
@update:args="commandArgs = $event"
|
||||
@update:valid="commandArgsValid = $event"
|
||||
/>
|
||||
<div class="picker-actions">
|
||||
<button type="button" @click="selectedCommand = null">명령 다시 선택</button>
|
||||
<button type="button" :disabled="!commandArgsValid" @click="reserveSelected">입력</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.chief-editor {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
color: #fff;
|
||||
background: #000;
|
||||
}
|
||||
.editor-header {
|
||||
box-sizing: border-box;
|
||||
height: 24px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
font-size: 16.8px;
|
||||
font-weight: 400;
|
||||
}
|
||||
.editor-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.editor-controls {
|
||||
order: 2;
|
||||
min-height: 85px;
|
||||
padding: 2px 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 3px;
|
||||
align-items: stretch;
|
||||
}
|
||||
.editor-controls > time {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 4px;
|
||||
background: #345c85;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.editor-controls button,
|
||||
.repeat-control {
|
||||
min-height: 36px;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: #444;
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
}
|
||||
.editor-controls button {
|
||||
cursor: pointer;
|
||||
}
|
||||
.repeat-control {
|
||||
padding: 0 8px;
|
||||
text-align: center;
|
||||
}
|
||||
.editor-turns {
|
||||
order: 1;
|
||||
display: grid;
|
||||
grid-template-rows: repeat(12, 30px);
|
||||
}
|
||||
.editor-turn-row {
|
||||
display: grid;
|
||||
grid-template-columns: 55px minmax(0, 1fr) 36px;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
.editor-turn-row > time {
|
||||
height: 30px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #000;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.editor-turn-row > strong {
|
||||
height: 30px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
background: #0d204d;
|
||||
font-weight: 400;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.editor-turn-row:nth-child(odd) > strong {
|
||||
background: #12295d;
|
||||
}
|
||||
.edit-turn {
|
||||
align-self: stretch;
|
||||
border: 0;
|
||||
background: #444;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
.command-picker {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
top: 54px;
|
||||
left: 0;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 344px;
|
||||
overflow: auto;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
background: #303030;
|
||||
}
|
||||
.command-picker > header {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
}
|
||||
.command-picker.has-command {
|
||||
padding: 8px;
|
||||
}
|
||||
.command-picker.has-command > header {
|
||||
position: static;
|
||||
width: auto;
|
||||
height: auto;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
clip: auto;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.command-picker.has-command > header button {
|
||||
width: 32px;
|
||||
height: 28px;
|
||||
}
|
||||
.command-picker :deep(.command-form) {
|
||||
gap: 4px;
|
||||
padding-top: 0;
|
||||
}
|
||||
.command-picker :deep(.category-list) {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 4px 2px;
|
||||
}
|
||||
.command-picker :deep(.category-btn) {
|
||||
min-width: 0;
|
||||
height: 35px;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
padding: 4px;
|
||||
background: #00a879;
|
||||
color: #fff;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.command-picker :deep(.category-btn.active) {
|
||||
background: #00bf91;
|
||||
}
|
||||
.command-picker :deep(.command-grid) {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.command-picker :deep(.command-item) {
|
||||
min-height: 39px;
|
||||
border: 1px solid #888;
|
||||
border-radius: 5px;
|
||||
padding: 5px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: transparent;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
font-size: 16px;
|
||||
}
|
||||
.command-picker :deep(.command-status) {
|
||||
display: none;
|
||||
}
|
||||
.picker-close {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 7px;
|
||||
width: 65px;
|
||||
height: 35px;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: #444;
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
}
|
||||
.selected-command {
|
||||
margin-bottom: 6px;
|
||||
padding: 6px 8px;
|
||||
background: #0d204d;
|
||||
font-weight: 700;
|
||||
}
|
||||
.picker-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.picker-actions button {
|
||||
min-height: 34px;
|
||||
}
|
||||
.mobile-identity {
|
||||
display: grid;
|
||||
grid-column: 1 / -1;
|
||||
min-height: 60px;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.chief-editor.mobile .editor-header {
|
||||
display: none;
|
||||
}
|
||||
.chief-editor.mobile {
|
||||
margin-top: 10px;
|
||||
}
|
||||
.chief-editor.mobile .editor-body {
|
||||
height: 360px;
|
||||
display: grid;
|
||||
grid-template-columns: 109px 391px;
|
||||
}
|
||||
.chief-editor.mobile .editor-controls {
|
||||
order: initial;
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
grid-template-columns: 1fr;
|
||||
align-content: start;
|
||||
}
|
||||
.chief-editor.mobile .editor-controls > time {
|
||||
min-height: 36px;
|
||||
}
|
||||
.chief-editor.mobile .editor-controls > button {
|
||||
min-height: 36px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.chief-editor.mobile .repeat-control {
|
||||
min-height: 36px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.chief-editor.mobile .editor-turns {
|
||||
order: initial;
|
||||
padding-top: 10px;
|
||||
}
|
||||
.chief-editor.mobile .editor-turn-row {
|
||||
grid-template-columns: 74px minmax(0, 1fr) 53px;
|
||||
}
|
||||
.chief-editor.mobile .command-picker {
|
||||
position: absolute;
|
||||
top: 30px;
|
||||
left: 130px;
|
||||
width: 370px;
|
||||
height: 327px;
|
||||
}
|
||||
</style>
|
||||
@@ -18,6 +18,7 @@ const props = defineProps<{
|
||||
compact?: boolean;
|
||||
isMe?: boolean;
|
||||
clickable?: boolean;
|
||||
turnTimeLabel?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -40,13 +41,26 @@ const handleClick = () => {
|
||||
@click="handleClick"
|
||||
>
|
||||
<header class="chief-header">
|
||||
<div class="chief-title">
|
||||
<span class="chief-level">{{ props.officerLevelText }}</span>
|
||||
<span class="chief-name" :style="{ color: nameColor }">
|
||||
{{ props.name ?? '-' }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-if="props.isMe" class="chief-me">ME</span>
|
||||
<template v-if="props.compact">
|
||||
<span
|
||||
class="compact-name"
|
||||
:style="{ color: nameColor, textDecoration: props.isMe ? 'underline' : undefined }"
|
||||
>{{ props.name ?? '-' }}</span
|
||||
>
|
||||
<span class="compact-meta"
|
||||
><span>{{ props.officerLevelText }}</span
|
||||
><time>{{ props.turnTimeLabel ?? '--:--' }}</time></span
|
||||
>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="chief-title">
|
||||
<span class="chief-level">{{ props.officerLevelText }}</span>
|
||||
<span class="chief-name" :style="{ color: nameColor }">
|
||||
{{ props.name ?? '-' }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-if="props.isMe" class="chief-me">ME</span>
|
||||
</template>
|
||||
</header>
|
||||
<div class="chief-rows">
|
||||
<div v-for="row in props.rows" :key="row.index" class="chief-row" :class="{ rest: row.isRest }">
|
||||
@@ -72,7 +86,9 @@ const handleClick = () => {
|
||||
|
||||
.chief-card.clickable {
|
||||
cursor: pointer;
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
transition:
|
||||
border-color 0.2s ease,
|
||||
box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.chief-card.clickable:hover {
|
||||
@@ -163,6 +179,28 @@ const handleClick = () => {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
|
||||
.compact-name,
|
||||
.compact-meta {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.compact-meta {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
.chief-card.compact .chief-header {
|
||||
height: 72px;
|
||||
grid-template-rows: 36px 36px;
|
||||
display: grid;
|
||||
padding: 0;
|
||||
}
|
||||
.chief-card.compact .chief-row {
|
||||
height: 46px;
|
||||
line-height: 46px;
|
||||
}
|
||||
|
||||
.chief-card.compact .chief-level,
|
||||
.chief-card.compact .chief-name {
|
||||
font-size: 0.6rem;
|
||||
|
||||
@@ -25,6 +25,7 @@ const props = defineProps<{
|
||||
commandTable: CommandTable | null;
|
||||
loading: boolean;
|
||||
activeCategory?: string;
|
||||
scope?: 'all' | 'general' | 'nation';
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -48,6 +49,10 @@ const categories = computed(() => {
|
||||
category: group.category,
|
||||
groupType: 'nation' as const,
|
||||
}));
|
||||
if (props.scope === 'general') return general;
|
||||
if (props.scope === 'nation') {
|
||||
return nation.map((entry) => ({ ...entry, label: entry.category === '국가' ? '기타' : entry.category }));
|
||||
}
|
||||
return [...general, ...nation];
|
||||
});
|
||||
|
||||
@@ -58,7 +63,10 @@ const selectedGroup = computed(() => {
|
||||
}
|
||||
const [scope, ...categoryParts] = selectedCategory.value.split(':');
|
||||
const category = categoryParts.join(':');
|
||||
return props.commandTable[scope === 'nation' ? 'nation' : 'general'].find((group) => group.category === category) ?? null;
|
||||
return (
|
||||
props.commandTable[scope === 'nation' ? 'nation' : 'general'].find((group) => group.category === category) ??
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
watch(
|
||||
@@ -109,9 +117,7 @@ const statusLabel = (command: CommandAvailability) => {
|
||||
<div v-if="props.loading">
|
||||
<SkeletonLines :lines="4" />
|
||||
</div>
|
||||
<div v-else-if="!props.commandTable" class="empty">
|
||||
명령 목록을 불러오지 못했습니다.
|
||||
</div>
|
||||
<div v-else-if="!props.commandTable" class="empty">명령 목록을 불러오지 못했습니다.</div>
|
||||
<div v-else>
|
||||
<div class="category-list">
|
||||
<button
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
buildTournamentBracket,
|
||||
type TournamentBracketMatch,
|
||||
type TournamentBracketParticipant,
|
||||
type TournamentBracketRound,
|
||||
type TournamentBracketSlot,
|
||||
} from '../../utils/tournamentBracket';
|
||||
|
||||
const props = defineProps<{
|
||||
participants: TournamentBracketParticipant[];
|
||||
matches: TournamentBracketMatch[];
|
||||
winnerId?: number;
|
||||
betTotals?: Record<number, number>;
|
||||
totalBet: number;
|
||||
}>();
|
||||
|
||||
const bracket = computed(() => buildTournamentBracket(props.participants, props.matches, props.winnerId));
|
||||
|
||||
const mobileColumns = computed(() => [
|
||||
bracket.value.top16.slots,
|
||||
bracket.value.quarter.slots,
|
||||
bracket.value.semi.slots,
|
||||
bracket.value.final.slots,
|
||||
[bracket.value.champion],
|
||||
]);
|
||||
const mobileX = [38, 118, 198, 278, 352];
|
||||
const mobileY = (columnIndex: number, slotIndex: number) => {
|
||||
const slotHeight = 32 * 2 ** columnIndex;
|
||||
return 16 + slotHeight / 2 + slotIndex * slotHeight;
|
||||
};
|
||||
const mobileConnections = computed(() =>
|
||||
mobileColumns.value.slice(0, -1).flatMap((column, columnIndex) => {
|
||||
const sourceX = mobileX[columnIndex]! + 32;
|
||||
const targetX = mobileX[columnIndex + 1]! - 32;
|
||||
const jointX = (sourceX + targetX) / 2;
|
||||
return Array.from({ length: column.length / 2 }, (_, pairIndex) => {
|
||||
const left = column[pairIndex * 2]!;
|
||||
const right = column[pairIndex * 2 + 1]!;
|
||||
const y1 = mobileY(columnIndex, pairIndex * 2);
|
||||
const y2 = mobileY(columnIndex, pairIndex * 2 + 1);
|
||||
return {
|
||||
id: `${columnIndex}-${pairIndex}`,
|
||||
sourceX,
|
||||
targetX,
|
||||
jointX,
|
||||
y1,
|
||||
y2,
|
||||
parentY: (y1 + y2) / 2,
|
||||
leftActive: left.advanced,
|
||||
rightActive: right.advanced,
|
||||
parentActive: left.advanced || right.advanced,
|
||||
};
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
const roundStyle = (round: TournamentBracketRound) => ({ '--slot-count': round.slots.length });
|
||||
const connectorGroups = (slots: TournamentBracketSlot[]) =>
|
||||
Array.from({ length: slots.length / 2 }, (_, index) => [slots[index * 2]!, slots[index * 2 + 1]!] as const);
|
||||
const odds = (id: number | null) => {
|
||||
if (id === null) return '0';
|
||||
const amount = props.betTotals?.[id] ?? 0;
|
||||
if (!amount) return '∞';
|
||||
return (props.totalBet / amount).toFixed(2);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="tournament-bracket" aria-label="토너먼트 대진표" tabindex="0">
|
||||
<div class="bracket-canvas">
|
||||
<div class="bracket-round bracket-champion" style="--slot-count: 1">
|
||||
<span
|
||||
class="bracket-name"
|
||||
:class="{ advanced: bracket.champion.advanced }"
|
||||
:data-general-id="bracket.champion.id ?? undefined"
|
||||
>
|
||||
{{ bracket.champion.name }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="connector-row" style="--connector-count: 1">
|
||||
<span class="connector-segment">
|
||||
<i class="stem" :class="{ active: bracket.champion.advanced }"></i>
|
||||
<i class="arm left" :class="{ active: bracket.final.slots[0]?.advanced }"></i>
|
||||
<i class="arm right" :class="{ active: bracket.final.slots[1]?.advanced }"></i>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<template v-for="round in [bracket.final, bracket.semi, bracket.quarter]" :key="round.stage">
|
||||
<div class="bracket-round" :style="roundStyle(round)">
|
||||
<span
|
||||
v-for="(slot, index) in round.slots"
|
||||
:key="`${round.stage}-${slot.id ?? 'empty'}-${index}`"
|
||||
class="bracket-name"
|
||||
:class="{ advanced: slot.advanced }"
|
||||
:data-general-id="slot.id ?? undefined"
|
||||
>
|
||||
{{ slot.name }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="connector-row" :style="{ '--connector-count': round.slots.length }">
|
||||
<span
|
||||
v-for="(pair, index) in connectorGroups(
|
||||
round.stage === 10
|
||||
? bracket.semi.slots
|
||||
: round.stage === 9
|
||||
? bracket.quarter.slots
|
||||
: bracket.top16.slots
|
||||
)"
|
||||
:key="`${round.stage}-connector-${index}`"
|
||||
class="connector-segment"
|
||||
>
|
||||
<i class="stem" :class="{ active: pair[0].advanced || pair[1].advanced }"></i>
|
||||
<i class="arm left" :class="{ active: pair[0].advanced }"></i>
|
||||
<i class="arm right" :class="{ active: pair[1].advanced }"></i>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="bracket-round" :style="roundStyle(bracket.top16)">
|
||||
<span
|
||||
v-for="(slot, index) in bracket.top16.slots"
|
||||
:key="`7-${slot.id ?? 'empty'}-${index}`"
|
||||
class="bracket-name"
|
||||
:class="{ advanced: slot.advanced }"
|
||||
:data-general-id="slot.id ?? undefined"
|
||||
>
|
||||
{{ slot.name }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="bracket-round bracket-odds" :style="roundStyle(bracket.top16)">
|
||||
<span
|
||||
v-for="(slot, index) in bracket.top16.slots"
|
||||
:key="`odds-${slot.id ?? 'empty'}-${index}`"
|
||||
:data-candidate="slot.name"
|
||||
>
|
||||
{{ odds(slot.id) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mobile-bracket" aria-label="모바일 토너먼트 대진">
|
||||
<svg viewBox="0 0 390 544" aria-hidden="true">
|
||||
<g v-for="connection in mobileConnections" :key="connection.id">
|
||||
<path
|
||||
class="mobile-connector"
|
||||
:d="`M ${connection.sourceX} ${connection.y1} H ${connection.jointX} V ${connection.y2} M ${connection.sourceX} ${connection.y2} H ${connection.jointX} M ${connection.jointX} ${connection.parentY} H ${connection.targetX}`"
|
||||
/>
|
||||
<path
|
||||
v-if="connection.leftActive"
|
||||
class="mobile-connector active"
|
||||
:d="`M ${connection.sourceX} ${connection.y1} H ${connection.jointX} V ${connection.parentY}`"
|
||||
/>
|
||||
<path
|
||||
v-if="connection.rightActive"
|
||||
class="mobile-connector active"
|
||||
:d="`M ${connection.sourceX} ${connection.y2} H ${connection.jointX} V ${connection.parentY}`"
|
||||
/>
|
||||
<path
|
||||
v-if="connection.parentActive"
|
||||
class="mobile-connector active"
|
||||
:d="`M ${connection.jointX} ${connection.parentY} H ${connection.targetX}`"
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
<template v-for="(column, columnIndex) in mobileColumns" :key="`mobile-column-${columnIndex}`">
|
||||
<span
|
||||
v-for="(slot, slotIndex) in column"
|
||||
:key="`mobile-${columnIndex}-${slot.id ?? 'empty'}-${slotIndex}`"
|
||||
class="mobile-bracket-name"
|
||||
:class="{ advanced: slot.advanced }"
|
||||
:style="{ left: `${mobileX[columnIndex]}px`, top: `${mobileY(columnIndex, slotIndex)}px` }"
|
||||
>
|
||||
{{ slot.name }}
|
||||
</span>
|
||||
</template>
|
||||
</div>
|
||||
<p>배당률이 낮을수록 베팅된 금액이 많고 유저들이 우승후보로 많이 선택한 장수입니다.</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tournament-bracket {
|
||||
overflow-x: auto;
|
||||
padding: 10px 0;
|
||||
scrollbar-color: #777 #24140e;
|
||||
}
|
||||
.bracket-canvas {
|
||||
width: 2000px;
|
||||
min-width: 2000px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.mobile-bracket {
|
||||
position: relative;
|
||||
display: none;
|
||||
width: 390px;
|
||||
height: 544px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.mobile-bracket svg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 390px;
|
||||
height: 544px;
|
||||
}
|
||||
.mobile-connector {
|
||||
fill: none;
|
||||
stroke: #fff;
|
||||
stroke-width: 1;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
.mobile-connector.active {
|
||||
stroke: #ff4b4b;
|
||||
}
|
||||
.mobile-bracket-name {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
width: 64px;
|
||||
overflow: hidden;
|
||||
transform: translate(-50%, -50%);
|
||||
border: 1px solid #555;
|
||||
background: rgb(58 33 24 / 92%);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
line-height: 22px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.mobile-bracket-name.advanced {
|
||||
border-color: #ff4b4b;
|
||||
color: #ff4b4b;
|
||||
}
|
||||
.bracket-round,
|
||||
.connector-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(var(--slot-count, var(--connector-count)), minmax(0, 1fr));
|
||||
align-items: center;
|
||||
}
|
||||
.bracket-round {
|
||||
min-height: 24px;
|
||||
}
|
||||
.bracket-name {
|
||||
overflow: hidden;
|
||||
padding: 0 3px;
|
||||
color: #fff;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.bracket-name.advanced {
|
||||
color: #ff4b4b;
|
||||
}
|
||||
.connector-row {
|
||||
min-height: 24px;
|
||||
}
|
||||
.connector-segment {
|
||||
position: relative;
|
||||
display: block;
|
||||
height: 24px;
|
||||
color: #fff;
|
||||
}
|
||||
.connector-segment i {
|
||||
position: absolute;
|
||||
display: block;
|
||||
color: inherit;
|
||||
font-style: normal;
|
||||
}
|
||||
.connector-segment .stem {
|
||||
top: 0;
|
||||
left: 50%;
|
||||
height: 13px;
|
||||
border-left: 1px solid currentColor;
|
||||
}
|
||||
.connector-segment .arm {
|
||||
top: 12px;
|
||||
width: 25%;
|
||||
height: 12px;
|
||||
border-top: 1px solid currentColor;
|
||||
}
|
||||
.connector-segment .arm.left {
|
||||
left: 25%;
|
||||
border-left: 1px solid currentColor;
|
||||
}
|
||||
.connector-segment .arm.right {
|
||||
right: 25%;
|
||||
border-right: 1px solid currentColor;
|
||||
}
|
||||
.connector-segment .active {
|
||||
color: #ff4b4b;
|
||||
}
|
||||
.bracket-odds {
|
||||
color: skyblue;
|
||||
}
|
||||
.tournament-bracket p {
|
||||
margin: 0;
|
||||
color: skyblue;
|
||||
font-size: 18px;
|
||||
}
|
||||
@media (max-width: 800px) {
|
||||
.tournament-bracket {
|
||||
width: 100vw;
|
||||
max-width: 100vw;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
.bracket-canvas {
|
||||
display: none;
|
||||
}
|
||||
.mobile-bracket {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,76 @@
|
||||
export interface TournamentBracketParticipant {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface TournamentBracketMatch {
|
||||
id: number;
|
||||
stage: number;
|
||||
roundIndex: number;
|
||||
attackerId: number;
|
||||
defenderId: number;
|
||||
winnerId?: number;
|
||||
}
|
||||
|
||||
export interface TournamentBracketSlot {
|
||||
id: number | null;
|
||||
name: string;
|
||||
advanced: boolean;
|
||||
}
|
||||
|
||||
export interface TournamentBracketRound {
|
||||
stage: number;
|
||||
slots: TournamentBracketSlot[];
|
||||
}
|
||||
|
||||
export interface TournamentBracketModel {
|
||||
champion: TournamentBracketSlot;
|
||||
final: TournamentBracketRound;
|
||||
semi: TournamentBracketRound;
|
||||
quarter: TournamentBracketRound;
|
||||
top16: TournamentBracketRound;
|
||||
}
|
||||
|
||||
const emptySlot = (): TournamentBracketSlot => ({ id: null, name: '-', advanced: false });
|
||||
|
||||
export const buildTournamentBracket = (
|
||||
participants: TournamentBracketParticipant[],
|
||||
matches: TournamentBracketMatch[],
|
||||
winnerId?: number
|
||||
): TournamentBracketModel => {
|
||||
const participantsById = new Map(participants.map((participant) => [participant.id, participant]));
|
||||
const nameOf = (id: number | null): string =>
|
||||
id === null ? '-' : (participantsById.get(id)?.name ?? `#${id}`);
|
||||
|
||||
const buildRound = (stage: number, slotCount: number): TournamentBracketRound => {
|
||||
const roundMatches = matches
|
||||
.filter((match) => match.stage === stage)
|
||||
.sort((lhs, rhs) => lhs.roundIndex - rhs.roundIndex || lhs.id - rhs.id);
|
||||
const slots: TournamentBracketSlot[] = roundMatches.flatMap((match) =>
|
||||
[match.attackerId, match.defenderId].map((id) => ({
|
||||
id,
|
||||
name: nameOf(id),
|
||||
advanced: match.winnerId === id,
|
||||
}))
|
||||
);
|
||||
while (slots.length < slotCount) {
|
||||
slots.push(emptySlot());
|
||||
}
|
||||
return { stage, slots: slots.slice(0, slotCount) };
|
||||
};
|
||||
|
||||
const final = buildRound(10, 2);
|
||||
const resolvedWinnerId = winnerId ?? matches.find((match) => match.stage === 10)?.winnerId ?? null;
|
||||
|
||||
return {
|
||||
champion: {
|
||||
id: resolvedWinnerId,
|
||||
name: nameOf(resolvedWinnerId),
|
||||
advanced: resolvedWinnerId !== null,
|
||||
},
|
||||
final,
|
||||
semi: buildRound(9, 4),
|
||||
quarter: buildRound(8, 8),
|
||||
top16: buildRound(7, 16),
|
||||
};
|
||||
};
|
||||
@@ -4,6 +4,7 @@ import { useMediaQuery } from '@vueuse/core';
|
||||
import { addMinutes, format } from 'date-fns';
|
||||
import SkeletonLines from '../components/ui/SkeletonLines.vue';
|
||||
import ChiefTurnCard from '../components/chief/ChiefTurnCard.vue';
|
||||
import ChiefCommandEditor from '../components/chief/ChiefCommandEditor.vue';
|
||||
import { trpc } from '../utils/trpc';
|
||||
import { formatOfficerLevelText } from '../utils/nationFormat';
|
||||
|
||||
@@ -260,7 +261,7 @@ const selectedChiefRows = computed(() => {
|
||||
return buildTurnRows(selectedChief.value);
|
||||
});
|
||||
|
||||
const updateMyTurns = (turns: ChiefEntry['turns'], revision: number) => {
|
||||
const updateMyTurns = (turns: Array<{ index: number; action: string; args?: unknown }>, revision: number) => {
|
||||
if (!data.value) {
|
||||
return;
|
||||
}
|
||||
@@ -269,29 +270,10 @@ const updateMyTurns = (turns: ChiefEntry['turns'], revision: number) => {
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
entry.turns = turns;
|
||||
entry.turns = turns.map((turn) => ({ ...turn, args: turn.args ?? {} }));
|
||||
entry.revision = revision;
|
||||
};
|
||||
|
||||
const clearTurn = async (turnIndex: number) => {
|
||||
if (!data.value || !isEditingAllowed.value) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await trpc.turns.reserved.setNation.mutate({
|
||||
generalId: data.value.me.id,
|
||||
turnIndex,
|
||||
action: '휴식',
|
||||
args: {},
|
||||
expectedRevision: selectedChief.value?.revision ?? 0,
|
||||
});
|
||||
updateMyTurns(result.turns, result.revision);
|
||||
} catch (err) {
|
||||
await loadChiefCenter();
|
||||
error.value = resolveErrorMessage(err);
|
||||
}
|
||||
};
|
||||
|
||||
const shiftTurns = async (amount: number) => {
|
||||
if (!data.value || !isEditingAllowed.value) {
|
||||
return;
|
||||
@@ -308,6 +290,38 @@ const shiftTurns = async (amount: number) => {
|
||||
error.value = resolveErrorMessage(err);
|
||||
}
|
||||
};
|
||||
|
||||
const reserveTurn = async (payload: { index: number; action: string; args: Record<string, unknown> }) => {
|
||||
if (!data.value || !isEditingAllowed.value) return;
|
||||
try {
|
||||
const result = await trpc.turns.reserved.setNation.mutate({
|
||||
generalId: data.value.me.id,
|
||||
turnIndex: payload.index,
|
||||
action: payload.action,
|
||||
args: payload.args,
|
||||
expectedRevision: selectedChief.value?.revision ?? 0,
|
||||
});
|
||||
updateMyTurns(result.turns, result.revision);
|
||||
} catch (err) {
|
||||
await loadChiefCenter();
|
||||
error.value = resolveErrorMessage(err);
|
||||
}
|
||||
};
|
||||
|
||||
const repeatTurns = async (amount: number) => {
|
||||
if (!data.value || !isEditingAllowed.value) return;
|
||||
try {
|
||||
const result = await trpc.turns.reserved.repeatNation.mutate({
|
||||
generalId: data.value.me.id,
|
||||
amount,
|
||||
expectedRevision: selectedChief.value?.revision ?? 0,
|
||||
});
|
||||
updateMyTurns(result.turns, result.revision);
|
||||
} catch (err) {
|
||||
await loadChiefCenter();
|
||||
error.value = resolveErrorMessage(err);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -316,7 +330,8 @@ const shiftTurns = async (amount: number) => {
|
||||
<RouterLink class="chief-nav" to="/">돌아가기</RouterLink>
|
||||
<button class="chief-nav" @click="loadChiefCenter">갱신</button>
|
||||
<h1>사령부</h1>
|
||||
<div></div><div></div>
|
||||
<div></div>
|
||||
<div></div>
|
||||
</header>
|
||||
|
||||
<div v-if="error" class="game-feedback game-feedback--error" role="alert">{{ error }}</div>
|
||||
@@ -324,47 +339,80 @@ const shiftTurns = async (amount: number) => {
|
||||
<section v-if="loading && !data" class="loading-panel"><SkeletonLines :lines="5" /></section>
|
||||
|
||||
<section v-else-if="data && isMobile" class="layout-mobile">
|
||||
<div class="mobile-editor">
|
||||
<aside class="mobile-controls legacy-bg1">
|
||||
<strong>{{ selectedChief?.name ?? '-' }}</strong>
|
||||
<span>{{ selectedChief ? formatOfficerLevelText(selectedChief.officerLevel, data.nation.level) : '-' }}</span>
|
||||
<time>{{ selectedChiefRows[0]?.time ?? '--:--' }}</time>
|
||||
<button>고급 모드</button><button>반복⌄</button>
|
||||
<button @click="shiftTurns(-1)">당기기⌄</button><button @click="shiftTurns(1)">미루기⌄</button>
|
||||
</aside>
|
||||
<div class="mobile-turns">
|
||||
<div v-for="row in selectedChiefRows" :key="row.index" class="mobile-turn-row">
|
||||
<time>{{ row.time }}</time><strong>{{ row.action }}</strong>
|
||||
<button :disabled="!isEditingAllowed" @click="clearTurn(row.index)">✎</button>
|
||||
</div>
|
||||
</div>
|
||||
<ChiefCommandEditor
|
||||
v-if="isEditingAllowed && selectedChief"
|
||||
:officer-level-text="formatOfficerLevelText(selectedChief.officerLevel, data.nation.level)"
|
||||
:name="selectedChief.name"
|
||||
:npc-state="selectedChief.npcState"
|
||||
:rows="selectedChiefRows"
|
||||
:command-table="commandTable"
|
||||
:loading="commandLoading"
|
||||
:mobile="true"
|
||||
@reserve="reserveTurn"
|
||||
@shift="shiftTurns"
|
||||
@repeat="repeatTurns"
|
||||
/>
|
||||
<div v-else-if="selectedChief" class="mobile-readonly">
|
||||
<ChiefTurnCard
|
||||
:officer-level-text="formatOfficerLevelText(selectedChief.officerLevel, data.nation.level)"
|
||||
:name="selectedChief.name"
|
||||
:npc-state="selectedChief.npcState"
|
||||
:rows="selectedChiefRows"
|
||||
/>
|
||||
</div>
|
||||
<div class="chief-overview">
|
||||
<ChiefTurnCard v-for="chief in chiefViews" :key="chief.officerLevel"
|
||||
:officer-level-text="chief.officerLevelText" :name="chief.name" :npc-state="chief.npcState"
|
||||
:rows="chief.rows" :compact="true" :selected="chief.officerLevel === selectedChief?.officerLevel"
|
||||
:is-me="chief.officerLevel === data.me.officerLevel" :clickable="true"
|
||||
@select="selectedChiefLevel = chief.officerLevel" />
|
||||
<div class="chief-overview-frame">
|
||||
<div class="chief-overview">
|
||||
<ChiefTurnCard
|
||||
v-for="chief in chiefViews"
|
||||
:key="chief.officerLevel"
|
||||
:officer-level-text="chief.officerLevelText"
|
||||
:name="chief.name"
|
||||
:npc-state="chief.npcState"
|
||||
:rows="chief.rows"
|
||||
:compact="true"
|
||||
:selected="chief.officerLevel === selectedChief?.officerLevel"
|
||||
:is-me="chief.officerLevel === data.me.officerLevel"
|
||||
:clickable="true"
|
||||
:turn-time-label="chief.rows[0]?.time"
|
||||
@select="selectedChiefLevel = chief.officerLevel"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-else-if="data" class="layout-desktop">
|
||||
<div class="chief-grid">
|
||||
<ChiefTurnCard
|
||||
v-for="chief in chiefViews"
|
||||
:key="chief.officerLevel"
|
||||
:officer-level-text="chief.officerLevelText"
|
||||
:name="chief.name"
|
||||
:npc-state="chief.npcState"
|
||||
:rows="chief.rows"
|
||||
:selected="chief.officerLevel === selectedChief?.officerLevel"
|
||||
:is-me="chief.officerLevel === data.me.officerLevel"
|
||||
:clickable="true"
|
||||
@select="selectedChiefLevel = chief.officerLevel"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="isEditingAllowed" class="desktop-actions legacy-bg0">
|
||||
<button @click="shiftTurns(-1)">당기기</button><button @click="shiftTurns(1)">미루기</button>
|
||||
<div
|
||||
v-for="(rowChiefs, rowIndex) in [chiefViews.slice(0, 4), chiefViews.slice(4, 8)]"
|
||||
:key="rowIndex"
|
||||
class="chief-grid-row"
|
||||
>
|
||||
<div class="turn-index-gutter legacy-bg0">
|
||||
<span></span><span v-for="idx in data.maxTurns" :key="idx">{{ idx }}</span>
|
||||
</div>
|
||||
<template v-for="chief in rowChiefs" :key="chief.officerLevel">
|
||||
<ChiefCommandEditor
|
||||
v-if="chief.officerLevel === data.me.officerLevel && data.me.officerLevel >= 5"
|
||||
:officer-level-text="chief.officerLevelText"
|
||||
:name="chief.name"
|
||||
:npc-state="chief.npcState"
|
||||
:rows="chief.rows"
|
||||
:command-table="commandTable"
|
||||
:loading="commandLoading"
|
||||
@reserve="reserveTurn"
|
||||
@shift="shiftTurns"
|
||||
@repeat="repeatTurns"
|
||||
/>
|
||||
<ChiefTurnCard
|
||||
v-else
|
||||
:officer-level-text="chief.officerLevelText"
|
||||
:name="chief.name"
|
||||
:npc-state="chief.npcState"
|
||||
:rows="chief.rows"
|
||||
/>
|
||||
</template>
|
||||
<div class="turn-index-gutter legacy-bg0">
|
||||
<span></span><span v-for="idx in data.maxTurns" :key="idx">{{ idx }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<footer class="chief-footer legacy-bg0"><RouterLink class="chief-nav" to="/">돌아가기</RouterLink></footer>
|
||||
@@ -580,66 +628,165 @@ const shiftTurns = async (amount: number) => {
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.layout-desktop { display: block; }
|
||||
.chief-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
.layout-desktop {
|
||||
display: block;
|
||||
}
|
||||
.chief-grid :deep(.chief-header) { height: 24px; min-height: 24px; }
|
||||
.chief-grid :deep(.chief-row) { box-sizing: border-box; min-height: 30px; }
|
||||
.chief-grid :deep(.chief-card) { border-color: transparent; box-shadow: none; }
|
||||
.desktop-actions { padding: 2px 24px; }
|
||||
.desktop-actions button,
|
||||
.mobile-controls button {
|
||||
min-height: 35px;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: #444;
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
.chief-footer {
|
||||
min-height: 56px;
|
||||
padding-top: 20px;
|
||||
}
|
||||
.chief-footer { min-height: 56px; padding-top: 20px; }
|
||||
.chief-footer .chief-nav { width: 70px; }
|
||||
.mobile-editor {
|
||||
height: 371px;
|
||||
display: grid;
|
||||
grid-template-columns: 109px 1fr;
|
||||
background: #000;
|
||||
.chief-footer .chief-nav {
|
||||
width: 70px;
|
||||
}
|
||||
.mobile-controls {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
align-content: start;
|
||||
text-align: center;
|
||||
}
|
||||
.mobile-controls strong,
|
||||
.mobile-controls span,
|
||||
.mobile-controls time { grid-column: 1 / -1; min-height: 30px; line-height: 30px; }
|
||||
.mobile-controls time { border-radius: 5px; background: #345c85; }
|
||||
.mobile-controls button { grid-column: 1 / -1; margin-top: 5px; }
|
||||
.mobile-turns { display: grid; grid-template-rows: repeat(12, 30px); padding-top: 10px; }
|
||||
.mobile-turn-row {
|
||||
display: grid;
|
||||
grid-template-columns: 74px 1fr 53px;
|
||||
align-items: center;
|
||||
background: #071638;
|
||||
text-align: center;
|
||||
}
|
||||
.mobile-turn-row:nth-child(even) { background: #0d214e; }
|
||||
.mobile-turn-row button { height: 30px; border: 0; background: #3d3d3d; color: #fff; }
|
||||
.chief-overview {
|
||||
width: 445px;
|
||||
margin-top: 56px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 111.25px);
|
||||
}
|
||||
.chief-overview :deep(.chief-card) { border-color: transparent; box-shadow: none; }
|
||||
.chief-overview :deep(.chief-row) { height: 12px; line-height: 10px; }
|
||||
.chief-overview :deep(.chief-header) { height: 28px; }
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.chief-page { width: 500px; min-width: 500px; }
|
||||
.chief-top { grid-template-columns: 89px 89px 1fr 0 0; }
|
||||
.chief-overview { grid-template-columns: repeat(4, 111.25px); }
|
||||
.chief-page {
|
||||
width: 500px;
|
||||
min-width: 500px;
|
||||
}
|
||||
.chief-top {
|
||||
grid-template-columns: 89px 89px 1fr 0 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Ref PageChiefCenter의 24 + 4×238 + 24 행렬과 500px 축소 overview 계약입니다. */
|
||||
.layout-desktop {
|
||||
display: block;
|
||||
}
|
||||
.chief-grid-row {
|
||||
display: grid;
|
||||
grid-template-columns: 24px repeat(4, 238px) 24px;
|
||||
align-items: start;
|
||||
}
|
||||
.turn-index-gutter {
|
||||
display: grid;
|
||||
grid-template-rows: 24px repeat(12, 30px);
|
||||
text-align: center;
|
||||
}
|
||||
.turn-index-gutter span {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
.chief-grid-row :deep(.chief-card) {
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
.chief-grid-row :deep(.chief-header) {
|
||||
box-sizing: border-box;
|
||||
height: 24px;
|
||||
min-height: 24px;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
}
|
||||
.chief-grid-row :deep(.chief-title) {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
}
|
||||
.chief-grid-row :deep(.chief-level),
|
||||
.chief-grid-row :deep(.chief-name) {
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
color: inherit;
|
||||
}
|
||||
.chief-grid-row :deep(.chief-level)::after {
|
||||
content: ':';
|
||||
}
|
||||
.chief-grid-row :deep(.chief-row) {
|
||||
box-sizing: border-box;
|
||||
min-height: 30px;
|
||||
height: 30px;
|
||||
grid-template-columns: 55px minmax(0, 1fr);
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
}
|
||||
.chief-grid-row :deep(.row-index) {
|
||||
display: none;
|
||||
}
|
||||
.chief-grid-row :deep(.row-time),
|
||||
.chief-grid-row :deep(.row-action) {
|
||||
height: 30px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
.chief-grid-row :deep(.row-time) {
|
||||
background: #000;
|
||||
}
|
||||
.chief-grid-row :deep(.chief-row:nth-child(odd) .row-action) {
|
||||
background-color: rgba(18, 41, 93, 0.88);
|
||||
}
|
||||
.chief-grid-row :deep(.chief-row:nth-child(even) .row-action) {
|
||||
background-color: rgba(7, 22, 56, 0.88);
|
||||
}
|
||||
|
||||
.layout-mobile {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
.chief-overview-frame {
|
||||
width: 500px;
|
||||
height: 320px;
|
||||
margin-top: 56px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.chief-overview {
|
||||
width: 890px;
|
||||
height: 1248px;
|
||||
margin-top: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 222.5px);
|
||||
transform: scale(0.5);
|
||||
transform-origin: left top;
|
||||
}
|
||||
.chief-overview :deep(.chief-card) {
|
||||
width: 222.5px;
|
||||
height: 624px;
|
||||
border: 0;
|
||||
border-left: 1px solid #fff;
|
||||
box-shadow: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.chief-overview :deep(.row-index) {
|
||||
display: none;
|
||||
}
|
||||
.chief-overview :deep(.chief-row) {
|
||||
grid-template-columns: 74px minmax(0, 1fr);
|
||||
padding: 0;
|
||||
gap: 0;
|
||||
text-align: center;
|
||||
font-size: 20px;
|
||||
}
|
||||
.chief-overview :deep(.row-time),
|
||||
.chief-overview :deep(.row-action) {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
.mobile-readonly {
|
||||
width: 308px;
|
||||
min-height: 394px;
|
||||
margin: 10px auto 16px;
|
||||
}
|
||||
.mobile-readonly :deep(.chief-header) {
|
||||
height: 24px;
|
||||
min-height: 24px;
|
||||
}
|
||||
.mobile-readonly :deep(.chief-row) {
|
||||
height: 30px;
|
||||
grid-template-columns: 55px 1fr;
|
||||
padding: 0;
|
||||
}
|
||||
.mobile-readonly :deep(.row-index) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.chief-overview {
|
||||
grid-template-columns: repeat(4, 222.5px);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -427,9 +427,16 @@ onMounted(() => {
|
||||
|
||||
<template>
|
||||
<header class="top-back-bar legacy-bg0">
|
||||
<RouterLink class="top-button legacy-button" to="/">돌아가기</RouterLink>
|
||||
<RouterLink class="top-button legacy-button legacy-button--navigation" to="/">돌아가기</RouterLink>
|
||||
<strong>유산 관리</strong>
|
||||
<button class="top-button legacy-button" type="button" :disabled="loading" @click="loadStatus">갱신</button>
|
||||
<button
|
||||
class="top-button legacy-button legacy-button--navigation"
|
||||
type="button"
|
||||
:disabled="loading"
|
||||
@click="loadStatus"
|
||||
>
|
||||
갱신
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<main id="container" class="inherit-page legacy-bg0">
|
||||
@@ -490,7 +497,7 @@ onMounted(() => {
|
||||
></small
|
||||
>
|
||||
<button
|
||||
class="legacy-button buy-button"
|
||||
class="legacy-button legacy-button--primary buy-button"
|
||||
:disabled="isUnited || actionBusy"
|
||||
@click="reserveSpecialWar"
|
||||
>
|
||||
@@ -524,7 +531,7 @@ onMounted(() => {
|
||||
}}</small
|
||||
>
|
||||
<button
|
||||
class="legacy-button buy-button"
|
||||
class="legacy-button legacy-button--primary buy-button"
|
||||
:disabled="isUnited || actionBusy"
|
||||
@click="openUniqueAuction"
|
||||
>
|
||||
@@ -539,7 +546,11 @@ onMounted(() => {
|
||||
<article class="shop-item simple-item">
|
||||
<div class="control-row">
|
||||
<span>랜덤 턴 초기화</span
|
||||
><button class="legacy-button" :disabled="isUnited || actionBusy" @click="resetTurnTime">
|
||||
><button
|
||||
class="legacy-button legacy-button--primary"
|
||||
:disabled="isUnited || actionBusy"
|
||||
@click="resetTurnTime"
|
||||
>
|
||||
구입
|
||||
</button>
|
||||
</div>
|
||||
@@ -552,7 +563,11 @@ onMounted(() => {
|
||||
<article class="shop-item simple-item">
|
||||
<div class="control-row">
|
||||
<span>랜덤 유니크 획득</span
|
||||
><button class="legacy-button" :disabled="isUnited || actionBusy" @click="buyRandomUnique">
|
||||
><button
|
||||
class="legacy-button legacy-button--primary"
|
||||
:disabled="isUnited || actionBusy"
|
||||
@click="buyRandomUnique"
|
||||
>
|
||||
구입
|
||||
</button>
|
||||
</div>
|
||||
@@ -565,7 +580,11 @@ onMounted(() => {
|
||||
<article class="shop-item simple-item">
|
||||
<div class="control-row">
|
||||
<span>즉시 전투 특기 초기화</span
|
||||
><button class="legacy-button" :disabled="isUnited || actionBusy" @click="resetSpecialWar">
|
||||
><button
|
||||
class="legacy-button legacy-button--primary"
|
||||
:disabled="isUnited || actionBusy"
|
||||
@click="resetSpecialWar"
|
||||
>
|
||||
구입
|
||||
</button>
|
||||
</div>
|
||||
@@ -596,14 +615,14 @@ onMounted(() => {
|
||||
>
|
||||
<div class="dual-buttons">
|
||||
<button
|
||||
class="legacy-button secondary"
|
||||
class="legacy-button legacy-button--secondary"
|
||||
:disabled="actionBusy"
|
||||
@click="buffTargets[key] = status.buffLevels[key] ?? 0"
|
||||
>
|
||||
리셋
|
||||
</button>
|
||||
<button
|
||||
class="legacy-button"
|
||||
class="legacy-button legacy-button--primary"
|
||||
:disabled="isUnited || actionBusy"
|
||||
@click="buyHiddenBuff(key)"
|
||||
>
|
||||
@@ -635,7 +654,11 @@ onMounted(() => {
|
||||
>필요 포인트: {{ status.inheritConst.inheritCheckOwnerPoint }}</b
|
||||
></small
|
||||
>
|
||||
<button class="legacy-button buy-button" :disabled="isUnited || actionBusy" @click="checkOwner">
|
||||
<button
|
||||
class="legacy-button legacy-button--primary buy-button"
|
||||
:disabled="isUnited || actionBusy"
|
||||
@click="checkOwner"
|
||||
>
|
||||
소유자 찾기
|
||||
</button>
|
||||
<p v-if="ownerResult" class="owner-result">
|
||||
@@ -689,7 +712,7 @@ onMounted(() => {
|
||||
><br /><span v-if="resetStatErrors.length">{{ resetStatErrors[0] }}</span></small
|
||||
>
|
||||
<button
|
||||
class="legacy-button buy-button"
|
||||
class="legacy-button legacy-button--primary buy-button"
|
||||
:disabled="isUnited || actionBusy || resetStatErrors.length > 0"
|
||||
@click="resetStats"
|
||||
>
|
||||
@@ -707,7 +730,11 @@ onMounted(() => {
|
||||
<small>[{{ new Date(entry.createdAt).toLocaleString('ko-KR') }}]</small>
|
||||
<span>{{ entry.text }}</span>
|
||||
</div>
|
||||
<button class="legacy-button more-button" :disabled="logLoading || logEnd" @click="loadLogs()">
|
||||
<button
|
||||
class="legacy-button legacy-button--secondary more-button"
|
||||
:disabled="logLoading || logEnd"
|
||||
@click="loadLogs()"
|
||||
>
|
||||
더 가져오기
|
||||
</button>
|
||||
</section>
|
||||
@@ -872,11 +899,6 @@ onMounted(() => {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.legacy-button.secondary {
|
||||
border-color: #51585e;
|
||||
background: #5c636a;
|
||||
}
|
||||
|
||||
.bottom-actions .shop-item:first-child {
|
||||
grid-column: 1;
|
||||
}
|
||||
|
||||
@@ -213,8 +213,13 @@ onMounted(() => {
|
||||
<template>
|
||||
<main id="container" class="pageVote bg0">
|
||||
<header class="back_bar bg0">
|
||||
<RouterLink class="btn btn-sammo-base2 back_btn" to="/">창 닫기</RouterLink>
|
||||
<button class="btn btn-sammo-base2 reload_btn" type="button" :disabled="loading" @click="reloadVote">
|
||||
<RouterLink class="legacy-button legacy-button--navigation back_btn" to="/">창 닫기</RouterLink>
|
||||
<button
|
||||
class="legacy-button legacy-button--navigation reload_btn"
|
||||
type="button"
|
||||
:disabled="loading"
|
||||
@click="reloadVote"
|
||||
>
|
||||
갱신
|
||||
</button>
|
||||
<h2 class="title"></h2>
|
||||
@@ -305,7 +310,9 @@ onMounted(() => {
|
||||
<template v-if="canVote">
|
||||
<td class="text-center">투표</td>
|
||||
<td colspan="2">
|
||||
<button class="btn btn-primary vote-submit" @click="submitVote">투표</button>
|
||||
<button class="legacy-button legacy-button--secondary vote-submit" @click="submitVote">
|
||||
투표
|
||||
</button>
|
||||
</td>
|
||||
</template>
|
||||
<td v-else colspan="3" class="text-center">결산</td>
|
||||
@@ -348,7 +355,11 @@ onMounted(() => {
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td></td>
|
||||
<td><button class="btn btn-primary comment-submit" type="submit">댓글 달기</button></td>
|
||||
<td>
|
||||
<button class="legacy-button legacy-button--secondary comment-submit" type="submit">
|
||||
댓글 달기
|
||||
</button>
|
||||
</td>
|
||||
<td colspan="2">
|
||||
<input v-model="myComment" class="form-control" maxlength="200" aria-label="댓글" />
|
||||
</td>
|
||||
@@ -395,13 +406,15 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-submit">
|
||||
<button class="btn btn-primary" type="button" @click="submitNewVote">제출</button>
|
||||
<button class="legacy-button legacy-button--secondary" type="button" @click="submitNewVote">
|
||||
제출
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<footer class="bottom_bar bg0">
|
||||
<RouterLink class="btn btn-sammo-base2 back_btn" to="/">창 닫기</RouterLink>
|
||||
<RouterLink class="legacy-button legacy-button--navigation back_btn" to="/">창 닫기</RouterLink>
|
||||
</footer>
|
||||
</main>
|
||||
</template>
|
||||
@@ -438,54 +451,19 @@ onMounted(() => {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.btn {
|
||||
min-height: 35.5px;
|
||||
padding: 5.25px 10.5px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5.25px;
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
filter: brightness(1.15);
|
||||
}
|
||||
|
||||
.btn:focus-visible {
|
||||
outline: 2px solid #8ab4f8;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.btn:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.65;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.btn-sammo-base2 {
|
||||
.back_btn,
|
||||
.reload_btn {
|
||||
height: 32px;
|
||||
min-height: 32px;
|
||||
margin-right: 2px;
|
||||
border-color: #004f28;
|
||||
background: #00582c;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.back_bar .btn-sammo-base2 {
|
||||
.back_bar .back_btn,
|
||||
.back_bar .reload_btn {
|
||||
width: 88px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
border-color: #0d6efd;
|
||||
background: #0d6efd;
|
||||
}
|
||||
|
||||
#vote-title {
|
||||
font-size: 1.8em;
|
||||
line-height: 1.5;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import TournamentBracket from '../components/tournament/TournamentBracket.vue';
|
||||
import { trpc } from '../utils/trpc';
|
||||
|
||||
type Snapshot = Awaited<ReturnType<typeof trpc.tournament.getSnapshot.query>>;
|
||||
@@ -60,27 +61,8 @@ const matchesAt = (stage: number) =>
|
||||
.filter((match) => match.stage === stage)
|
||||
.sort((a, b) => a.roundIndex - b.roundIndex);
|
||||
const nameOf = (id?: number) => (id ? (participantsById.value.get(id)?.name ?? `#${id}`) : '-');
|
||||
const roundNames = (stage: number, count: number) => {
|
||||
const matches = matchesAt(stage);
|
||||
const ids = matches.flatMap((match) => [match.attackerId, match.defenderId]);
|
||||
return Array.from({ length: count }, (_, index) => nameOf(ids[index]));
|
||||
};
|
||||
const champion = computed(() => {
|
||||
const winner = snapshot.value?.state?.winnerId ?? matchesAt(10)[0]?.winnerId;
|
||||
return nameOf(winner);
|
||||
});
|
||||
const finalists = computed(() => roundNames(10, 2));
|
||||
const semiFinalists = computed(() => roundNames(9, 4));
|
||||
const quarterFinalists = computed(() => roundNames(8, 8));
|
||||
const top16 = computed(() => roundNames(7, 16));
|
||||
const totalBet = computed(() => betting.value?.totalAmount ?? 0);
|
||||
const odds = (id?: number) => {
|
||||
if (!id) return '0';
|
||||
const totals = betting.value?.totals as Record<number, number> | undefined;
|
||||
const amount = totals?.[id] ?? 0;
|
||||
if (!amount) return '∞';
|
||||
return (totalBet.value / amount).toFixed(2);
|
||||
};
|
||||
const betTotals = computed(() => betting.value?.totals as Record<number, number> | undefined);
|
||||
const isParticipant = computed(() =>
|
||||
(snapshot.value?.participants ?? []).some((participant) => participant.id === myGeneralId.value)
|
||||
);
|
||||
@@ -172,33 +154,14 @@ const start = async () => {
|
||||
</section>
|
||||
<section class="section-title bg2">16강 승자전</section>
|
||||
|
||||
<section class="bracket bg0" aria-label="토너먼트 대진표">
|
||||
<div class="round champion">
|
||||
<span>{{ champion }}</span>
|
||||
</div>
|
||||
<div class="connector">┻</div>
|
||||
<div class="round final">
|
||||
<span v-for="(name, index) in finalists" :key="index">{{ name }}</span>
|
||||
</div>
|
||||
<div class="connector">┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓</div>
|
||||
<div class="round semi">
|
||||
<span v-for="(name, index) in semiFinalists" :key="index">{{ name }}</span>
|
||||
</div>
|
||||
<div class="connector">┏━━━━━━━━━━┻━━━━━━━━━━┓ ┏━━━━━━━━━━┻━━━━━━━━━━┓</div>
|
||||
<div class="round quarter">
|
||||
<span v-for="(name, index) in quarterFinalists" :key="index">{{ name }}</span>
|
||||
</div>
|
||||
<div class="connector">┏━━━━┻━━━━┓ ┏━━━━┻━━━━┓ ┏━━━━┻━━━━┓ ┏━━━━┻━━━━┓</div>
|
||||
<div class="round top16">
|
||||
<span v-for="(name, index) in top16" :key="index">{{ name }}</span>
|
||||
</div>
|
||||
<div class="round odds">
|
||||
<span v-for="(matchName, index) in top16" :key="index" :data-candidate="matchName">
|
||||
{{ odds(matchesAt(7).flatMap((match) => [match.attackerId, match.defenderId])[index]) }}
|
||||
</span>
|
||||
</div>
|
||||
<p>배당률이 낮을수록 베팅된 금액이 많고 유저들이 우승후보로 많이 선택한 장수입니다.</p>
|
||||
</section>
|
||||
<TournamentBracket
|
||||
class="bg0"
|
||||
:participants="snapshot?.participants ?? []"
|
||||
:matches="snapshot?.matches ?? []"
|
||||
:winner-id="snapshot?.state?.winnerId"
|
||||
:bet-totals="betTotals"
|
||||
:total-bet="totalBet"
|
||||
/>
|
||||
|
||||
<section v-if="currentMatch" class="fight bg0">
|
||||
<h2>{{ nameOf(currentMatch.attackerId) }} vs {{ nameOf(currentMatch.defenderId) }}</h2>
|
||||
@@ -353,42 +316,6 @@ button:focus-visible {
|
||||
color: magenta;
|
||||
font-size: 24px;
|
||||
}
|
||||
.bracket {
|
||||
padding: 10px 0;
|
||||
}
|
||||
.round {
|
||||
display: grid;
|
||||
align-items: center;
|
||||
min-height: 24px;
|
||||
}
|
||||
.champion {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.final {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
.semi {
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
}
|
||||
.quarter {
|
||||
grid-template-columns: repeat(8, 1fr);
|
||||
}
|
||||
.top16,
|
||||
.odds {
|
||||
grid-template-columns: repeat(16, 125px);
|
||||
}
|
||||
.connector {
|
||||
min-height: 24px;
|
||||
white-space: pre;
|
||||
color: #fff;
|
||||
}
|
||||
.odds {
|
||||
color: skyblue;
|
||||
}
|
||||
.bracket p {
|
||||
color: skyblue;
|
||||
font-size: 18px;
|
||||
}
|
||||
.fight {
|
||||
padding: 8px;
|
||||
text-align: left;
|
||||
|
||||
@@ -177,8 +177,15 @@ onMounted(() => {
|
||||
<template>
|
||||
<main id="container" class="legacy-troop-page">
|
||||
<header class="topBackBar bg0">
|
||||
<RouterLink class="btn legacyNavButton backLink" to="/">돌아가기</RouterLink>
|
||||
<button class="btn legacyNavButton reloadButton" type="button" :disabled="loading" @click="refresh">
|
||||
<RouterLink class="legacy-button legacy-button--navigation legacyNavButton backLink" to="/"
|
||||
>돌아가기</RouterLink
|
||||
>
|
||||
<button
|
||||
class="legacy-button legacy-button--navigation legacyNavButton reloadButton"
|
||||
type="button"
|
||||
:disabled="loading"
|
||||
@click="refresh"
|
||||
>
|
||||
갱신
|
||||
</button>
|
||||
<h2>부대 편성</h2>
|
||||
@@ -242,25 +249,33 @@ onMounted(() => {
|
||||
|
||||
<div class="troopAction">
|
||||
<div v-if="dialogKind === null || dialogTroopId !== troop.id" class="actionButtons">
|
||||
<button v-if="data.me.troopId === 0" class="btn btn-primary" @click="joinTroop(troop)">
|
||||
<button
|
||||
v-if="data.me.troopId === 0"
|
||||
class="legacy-button legacy-button--primary"
|
||||
@click="joinTroop(troop)"
|
||||
>
|
||||
부대 탑승
|
||||
</button>
|
||||
<button
|
||||
v-if="data.me.troopId === troop.id"
|
||||
class="btn"
|
||||
:class="data.me.id === data.me.troopId ? 'btn-danger' : 'btn-primary'"
|
||||
class="legacy-button"
|
||||
:class="data.me.id === data.me.troopId ? 'legacy-button--danger' : 'legacy-button--primary'"
|
||||
@click="exitTroop(troop)"
|
||||
>
|
||||
{{ data.me.id === data.me.troopId ? '부대 해산' : '부대 탈퇴' }}
|
||||
</button>
|
||||
<button
|
||||
v-if="data.me.troopId === troop.id && data.me.id === data.me.troopId"
|
||||
class="btn btn-secondary"
|
||||
class="legacy-button legacy-button--secondary"
|
||||
@click="openKick(troop)"
|
||||
>
|
||||
부대원 추방...
|
||||
</button>
|
||||
<button v-if="data.permission >= 4" class="btn btn-info" @click="openRename(troop)">
|
||||
<button
|
||||
v-if="data.permission >= 4"
|
||||
class="legacy-button legacy-button--info"
|
||||
@click="openRename(troop)"
|
||||
>
|
||||
부대명 변경...
|
||||
</button>
|
||||
</div>
|
||||
@@ -270,10 +285,12 @@ onMounted(() => {
|
||||
<input v-model.trim="editName" class="formControl" type="text" aria-label="새 부대명" />
|
||||
</div>
|
||||
<div class="subBtnCancel">
|
||||
<button class="btn btn-secondary" @click="closeDialog">취소</button>
|
||||
<button class="legacy-button legacy-button--secondary" @click="closeDialog">취소</button>
|
||||
</div>
|
||||
<div class="subBtnOK">
|
||||
<button class="btn btn-primary" @click="renameTroop(troop)">변경</button>
|
||||
<button class="legacy-button legacy-button--primary" @click="renameTroop(troop)">
|
||||
변경
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="subDialog kickDialog">
|
||||
@@ -290,10 +307,12 @@ onMounted(() => {
|
||||
</select>
|
||||
</div>
|
||||
<div class="subBtnCancel">
|
||||
<button class="btn btn-secondary" @click="closeDialog">취소</button>
|
||||
<button class="legacy-button legacy-button--secondary" @click="closeDialog">취소</button>
|
||||
</div>
|
||||
<div class="subBtnOK">
|
||||
<button class="btn btn-primary" @click="kickMember(troop)">추방</button>
|
||||
<button class="legacy-button legacy-button--primary" @click="kickMember(troop)">
|
||||
추방
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -305,12 +324,16 @@ onMounted(() => {
|
||||
<div v-if="data.me.troopId === 0" class="makeNewTroop">
|
||||
<div class="makeTitle bg1 center">부대 창설</div>
|
||||
<input v-model.trim="createName" class="formControl troopNameField" type="text" aria-label="부대명" />
|
||||
<button class="btn btn-secondary createButton" @click="makeTroop">부대 창설</button>
|
||||
<button class="legacy-button legacy-button--secondary createButton" @click="makeTroop">
|
||||
부대 창설
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="bottomBar bg0">
|
||||
<RouterLink class="btn legacyNavButton backLink" to="/">돌아가기</RouterLink>
|
||||
<RouterLink class="legacy-button legacy-button--navigation legacyNavButton backLink" to="/"
|
||||
>돌아가기</RouterLink
|
||||
>
|
||||
<div></div>
|
||||
</footer>
|
||||
<div v-if="popupMember" id="generalPopup" :style="{ top: `${popupTop}px` }" role="tooltip">
|
||||
@@ -359,14 +382,11 @@ onMounted(() => {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.btn.legacyNavButton {
|
||||
.legacyNavButton {
|
||||
height: 32px;
|
||||
min-height: 32px;
|
||||
margin-right: 2px;
|
||||
border-color: #004f28;
|
||||
color: #fff;
|
||||
background: #00582c;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.notice {
|
||||
@@ -490,51 +510,6 @@ onMounted(() => {
|
||||
grid-row: 1/3;
|
||||
}
|
||||
|
||||
.btn {
|
||||
min-height: 31px;
|
||||
padding: 0.2em 0.75em;
|
||||
border: 1px solid #777;
|
||||
border-radius: 4px;
|
||||
color: #eee;
|
||||
background: #555;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
filter: brightness(1.15);
|
||||
}
|
||||
|
||||
.btn:focus-visible {
|
||||
outline: 2px solid #8ab4f8;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.btn:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
border-color: #0d6efd;
|
||||
background: #0d6efd;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
border-color: #dc3545;
|
||||
background: #dc3545;
|
||||
}
|
||||
|
||||
.btn-info {
|
||||
border-color: #0dcaf0;
|
||||
color: #111;
|
||||
background: #0dcaf0;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
border-color: #6c757d;
|
||||
background: #6c757d;
|
||||
}
|
||||
|
||||
.formControl {
|
||||
width: 100%;
|
||||
min-height: 31px;
|
||||
@@ -561,6 +536,9 @@ onMounted(() => {
|
||||
.bottomBar .legacyNavButton {
|
||||
width: 70px;
|
||||
margin: 0;
|
||||
padding-right: 5px;
|
||||
padding-left: 5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (min-width: 501px) {
|
||||
@@ -624,7 +602,7 @@ onMounted(() => {
|
||||
|
||||
@media (max-width: 500px) {
|
||||
.legacy-troop-page {
|
||||
width: 511px;
|
||||
width: 500px;
|
||||
}
|
||||
|
||||
#generalPopup {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
|
||||
import { buildTournamentBracket } from '../src/utils/tournamentBracket.ts';
|
||||
|
||||
const participants = Array.from({ length: 16 }, (_, index) => ({ id: index + 1, name: `장수${index + 1}` }));
|
||||
const matches = [
|
||||
...Array.from({ length: 8 }, (_, index) => ({
|
||||
id: index + 1,
|
||||
stage: 7,
|
||||
roundIndex: index,
|
||||
attackerId: index * 2 + 1,
|
||||
defenderId: index * 2 + 2,
|
||||
winnerId: index * 2 + 1,
|
||||
})),
|
||||
...Array.from({ length: 4 }, (_, index) => ({
|
||||
id: 9 + index,
|
||||
stage: 8,
|
||||
roundIndex: index,
|
||||
attackerId: index * 4 + 1,
|
||||
defenderId: index * 4 + 3,
|
||||
winnerId: index * 4 + 1,
|
||||
})),
|
||||
...Array.from({ length: 2 }, (_, index) => ({
|
||||
id: 13 + index,
|
||||
stage: 9,
|
||||
roundIndex: index,
|
||||
attackerId: index * 8 + 1,
|
||||
defenderId: index * 8 + 5,
|
||||
winnerId: index * 8 + 1,
|
||||
})),
|
||||
{ id: 15, stage: 10, roundIndex: 0, attackerId: 1, defenderId: 9, winnerId: 1 },
|
||||
];
|
||||
|
||||
void describe('tournament bracket', () => {
|
||||
void it('keeps every general in the worker roundIndex order and marks the actual winner path', () => {
|
||||
const bracket = buildTournamentBracket(participants, matches, 1);
|
||||
|
||||
assert.equal(bracket.champion.name, '장수1');
|
||||
assert.deepEqual(
|
||||
bracket.top16.slots.map((slot) => slot.name),
|
||||
participants.map((participant) => participant.name)
|
||||
);
|
||||
assert.deepEqual(
|
||||
bracket.top16.slots.filter((slot) => slot.advanced).map((slot) => slot.id),
|
||||
[1, 3, 5, 7, 9, 11, 13, 15]
|
||||
);
|
||||
assert.deepEqual(
|
||||
bracket.final.slots.map((slot) => slot.id),
|
||||
[1, 9]
|
||||
);
|
||||
});
|
||||
|
||||
void it('renders missing future rounds as stable empty slots without inventing generals', () => {
|
||||
const bracket = buildTournamentBracket(participants, matches.filter((match) => match.stage === 7));
|
||||
|
||||
assert.equal(bracket.champion.name, '-');
|
||||
assert.deepEqual(bracket.final.slots.map((slot) => slot.name), ['-', '-']);
|
||||
assert.equal(bracket.top16.slots[0]?.name, '장수1');
|
||||
assert.equal(bracket.top16.slots[15]?.name, '장수16');
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,12 @@ import path from 'node:path';
|
||||
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
||||
|
||||
import { type ScenarioInstallOptions } from '@sammo-ts/game-engine';
|
||||
import { createGamePostgresConnector, resolvePostgresConfigFromEnv } from '@sammo-ts/infra';
|
||||
import {
|
||||
createGamePostgresConnector,
|
||||
createRedisConnector,
|
||||
resolvePostgresConfigFromEnv,
|
||||
resolveRedisConfigFromEnv,
|
||||
} from '@sammo-ts/infra';
|
||||
import { isRecord } from '@sammo-ts/common';
|
||||
|
||||
import type { BuildCommand, BuildRunner } from './buildRunner.js';
|
||||
@@ -41,6 +46,7 @@ export interface GatewayOrchestratorOptions {
|
||||
profileReadinessTimeoutMs?: number;
|
||||
now?: () => Date;
|
||||
fetchImpl?: typeof fetch;
|
||||
clearTournamentRuntimeState?: (profileName: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface ProfileRuntimeState {
|
||||
@@ -150,6 +156,18 @@ class OperationLeaseLostError extends Error {}
|
||||
|
||||
const normalizeMeta = (value: unknown): Record<string, unknown> => (isRecord(value) ? value : {});
|
||||
|
||||
export const buildTournamentRuntimeKeys = (profileName: string): string[] => [
|
||||
`sammo:${profileName}:tournament:state`,
|
||||
`sammo:${profileName}:tournament:participants`,
|
||||
`sammo:${profileName}:tournament:matches`,
|
||||
`sammo:${profileName}:tournament:betting`,
|
||||
];
|
||||
|
||||
export const clearTournamentRuntimeKeys = async (
|
||||
redis: { del(keys: string[]): Promise<number> },
|
||||
profileName: string
|
||||
): Promise<number> => redis.del(buildTournamentRuntimeKeys(profileName));
|
||||
|
||||
const buildServerId = (profileName: string, now: Date, installOperationId?: string): string => {
|
||||
const year = String(now.getFullYear()).slice(-2);
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
@@ -545,6 +563,7 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
||||
private readonly profileReadinessTimeoutMs: number;
|
||||
private readonly now: () => Date;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly clearTournamentRuntimeState: (profileName: string) => Promise<void>;
|
||||
private reconcileTimer?: NodeJS.Timeout;
|
||||
private scheduleTimer?: NodeJS.Timeout;
|
||||
private buildTimer?: NodeJS.Timeout;
|
||||
@@ -573,6 +592,9 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
||||
this.profileReadinessTimeoutMs = options.profileReadinessTimeoutMs ?? 30_000;
|
||||
this.now = options.now ?? (() => new Date());
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
this.clearTournamentRuntimeState =
|
||||
options.clearTournamentRuntimeState ??
|
||||
((profileName) => this.clearTournamentRuntimeStateFromRedis(profileName));
|
||||
}
|
||||
|
||||
start(): void {
|
||||
@@ -1383,6 +1405,8 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
||||
if (!seedResult.ok) {
|
||||
throw new Error(`Selected profile seed failed: ${seedResult.output.slice(-4000)}`);
|
||||
}
|
||||
await this.clearTournamentRuntimeState(profile.profileName);
|
||||
await assertLease?.();
|
||||
const completedAt = this.now().toISOString();
|
||||
const now = this.now();
|
||||
const shouldPreopen = openAt ? openAt.getTime() > now.getTime() : false;
|
||||
@@ -1590,6 +1614,18 @@ export class GatewayOrchestrator implements GatewayOrchestratorHandle {
|
||||
}).url;
|
||||
}
|
||||
|
||||
private async clearTournamentRuntimeStateFromRedis(profileName: string): Promise<void> {
|
||||
const connector = createRedisConnector(
|
||||
resolveRedisConfigFromEnv(this.processConfig.baseEnv ?? process.env)
|
||||
);
|
||||
await connector.connect();
|
||||
try {
|
||||
await clearTournamentRuntimeKeys(connector.client, profileName);
|
||||
} finally {
|
||||
await connector.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
async cleanupStaleWorkspaces(): Promise<{ removed: string[]; skipped: string[] }> {
|
||||
const profiles = await this.repository.listProfiles();
|
||||
const cutoff = this.computeCutoffDate(6);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
buildTournamentRuntimeKeys,
|
||||
clearTournamentRuntimeKeys,
|
||||
} from '../src/orchestrator/gatewayOrchestrator.js';
|
||||
|
||||
describe('tournament reset state', () => {
|
||||
it('targets every season-owned tournament key for the selected profile only', () => {
|
||||
expect(buildTournamentRuntimeKeys('che:1010')).toEqual([
|
||||
'sammo:che:1010:tournament:state',
|
||||
'sammo:che:1010:tournament:participants',
|
||||
'sammo:che:1010:tournament:matches',
|
||||
'sammo:che:1010:tournament:betting',
|
||||
]);
|
||||
expect(buildTournamentRuntimeKeys('hwe:915')).not.toContain('sammo:che:1010:tournament:state');
|
||||
});
|
||||
|
||||
it('deletes the tournament state as one profile-scoped reset operation', async () => {
|
||||
const calls: string[][] = [];
|
||||
const deleted = await clearTournamentRuntimeKeys(
|
||||
{
|
||||
del: async (keys) => {
|
||||
calls.push(keys);
|
||||
return keys.length;
|
||||
},
|
||||
},
|
||||
'che:1010'
|
||||
);
|
||||
|
||||
expect(deleted).toBe(4);
|
||||
expect(calls).toEqual([buildTournamentRuntimeKeys('che:1010')]);
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,39 @@ loads the following layers:
|
||||
4. Scoped SFC styles: page-specific grids, fixed table dimensions, selectors,
|
||||
and state styling. These remain closest to the DOM contract they implement.
|
||||
|
||||
`styles/legacy-controls.css` is the shared control layer between tokens and the
|
||||
two shell layers. It owns only control geometry and state rules that are proven
|
||||
identical in the Ref Bootstrap/Lumen family. A page still owns control width,
|
||||
grid placement, and any visual family that is not Bootstrap/Lumen.
|
||||
|
||||
## Button composition
|
||||
|
||||
Choose the Ref visual family before choosing a semantic color. Buttons from
|
||||
different historical families are not made identical merely because they have
|
||||
the same label.
|
||||
|
||||
| Ref family | Core composition | Use |
|
||||
| ---------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
| Bootstrap/Lumen primary | `.legacy-button.legacy-button--primary` | commit, purchase, submit, or another affirmative mutation |
|
||||
| Bootstrap/Lumen secondary | `.legacy-button.legacy-button--secondary` | reset, cancel, neutral toggle, or load-more |
|
||||
| Bootstrap/Lumen danger | `.legacy-button.legacy-button--danger` | destructive action only when Ref uses `variant="danger"` |
|
||||
| Bootstrap/Lumen info | `.legacy-button.legacy-button--info` | informational or edit action only when Ref uses `variant="info"` |
|
||||
| `btn-sammo-base2` navigation | `.legacy-button.legacy-button--navigation` | page back/close and paired reload controls |
|
||||
| page-specific/native control | feature-namespaced scoped class | only when Ref computed geometry or interaction differs from the Bootstrap/Lumen family |
|
||||
|
||||
The base class supplies accessible link/button normalization and the historical
|
||||
`base1` fallback used by already measured screens. New Bootstrap/Lumen controls
|
||||
must add an explicit semantic modifier; do not infer a mutation role from a
|
||||
label such as `구입` in page CSS. A disabled control keeps its semantic color
|
||||
and uses the shared opacity/cursor state. Hover and active use the Ref Lumen
|
||||
bottom-border movement rather than an unrelated brightness filter.
|
||||
|
||||
Only layout belongs in the SFC: width, grid column, margins required by the
|
||||
page, and breakpoint-specific placement. Color, border, font weight,
|
||||
hover/focus/active, and disabled presentation belong in
|
||||
`legacy-controls.css` when the Ref family is shared. Generic `.btn`, `button`,
|
||||
or `.primary` rules must not be promoted globally.
|
||||
|
||||
## Class naming
|
||||
|
||||
- `.game-shell`, `.game-shell__header`, `.game-shell__actions`: flexible
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import type { City, General, Nation } from '../src/domain/entities.js';
|
||||
import { commandSpec as fireSpec } from '../src/actions/turn/general/che_화계.js';
|
||||
import type { TurnCommandEnv } from '../src/actions/turn/commandEnv.js';
|
||||
import type { WorldSnapshot } from '../src/world/types.js';
|
||||
import { MINIMAL_MAP } from './fixtures/minimalMap.js';
|
||||
import { InMemoryWorld, TestGameRunner } from './testEnv.js';
|
||||
|
||||
const commandEnv: TurnCommandEnv = {
|
||||
develCost: 100,
|
||||
trainDelta: 35,
|
||||
atmosDelta: 35,
|
||||
maxTrainByCommand: 100,
|
||||
maxAtmosByCommand: 100,
|
||||
sabotageDefaultProb: 0.5,
|
||||
sabotageProbCoefByStat: 0.1,
|
||||
sabotageDefenceCoefByGeneralCount: 0.1,
|
||||
sabotageDamageMin: 10,
|
||||
sabotageDamageMax: 30,
|
||||
openingPartYear: 180,
|
||||
maxGeneral: 10,
|
||||
defaultNpcGold: 1_000,
|
||||
defaultNpcRice: 1_000,
|
||||
defaultCrewTypeId: 1,
|
||||
defaultSpecialDomestic: null,
|
||||
defaultSpecialWar: null,
|
||||
initialNationGenLimit: 10,
|
||||
maxTechLevel: 10,
|
||||
baseGold: 1_000,
|
||||
baseRice: 1_000,
|
||||
maxResourceActionAmount: 1_000,
|
||||
};
|
||||
|
||||
const makeNation = (id: number): Nation => ({
|
||||
id,
|
||||
name: `계략감사국${id}`,
|
||||
color: '#330000',
|
||||
capitalCityId: id,
|
||||
chiefGeneralId: id,
|
||||
gold: 10_000,
|
||||
rice: 10_000,
|
||||
power: 0,
|
||||
level: 1,
|
||||
typeCode: 'che_중립',
|
||||
meta: {},
|
||||
});
|
||||
|
||||
const makeCity = (id: number, nationId: number): City => ({
|
||||
id,
|
||||
name: `계략감사성${id}`,
|
||||
nationId,
|
||||
level: 1,
|
||||
state: 0,
|
||||
population: 10_000,
|
||||
populationMax: 20_000,
|
||||
agriculture: 2_000,
|
||||
agricultureMax: 2_000,
|
||||
commerce: 2_000,
|
||||
commerceMax: 2_000,
|
||||
security: 1_000,
|
||||
securityMax: 2_000,
|
||||
defence: 500,
|
||||
defenceMax: 500,
|
||||
wall: 500,
|
||||
wallMax: 500,
|
||||
supplyState: 1,
|
||||
frontState: 0,
|
||||
meta: { trust: 50 },
|
||||
});
|
||||
|
||||
const makeGeneral = (id: number, nationId: number, cityId: number): General => ({
|
||||
id,
|
||||
name: `계략감사장${id}`,
|
||||
nationId,
|
||||
cityId,
|
||||
troopId: 0,
|
||||
npcState: 0,
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
officerLevel: 5,
|
||||
gold: 100_000,
|
||||
rice: 100_000,
|
||||
crew: 1_000,
|
||||
crewTypeId: 1,
|
||||
train: 100,
|
||||
atmos: 100,
|
||||
injury: 0,
|
||||
age: 30,
|
||||
stats: { leadership: 70, strength: 70, intelligence: 70 },
|
||||
role: {
|
||||
personality: null,
|
||||
specialDomestic: null,
|
||||
specialWar: null,
|
||||
items: { horse: null, weapon: null, book: null, item: null },
|
||||
},
|
||||
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
|
||||
meta: { killturn: 24 },
|
||||
});
|
||||
|
||||
describe('best-general sabotage audit', () => {
|
||||
it('repeats real fire-attack turns until one succeeds and increments firenum', async () => {
|
||||
const attackerNation = makeNation(1);
|
||||
const defenderNation = makeNation(2);
|
||||
const attackerCity = makeCity(1, 1);
|
||||
const defenderCity = makeCity(2, 2);
|
||||
const attacker = makeGeneral(1, 1, 1);
|
||||
const defender = makeGeneral(2, 2, 2);
|
||||
const snapshot: WorldSnapshot = {
|
||||
scenarioConfig: { environment: { mapName: 'minimal_map', unitSet: 'default' } } as never,
|
||||
scenarioMeta: { startYear: 180 } as never,
|
||||
map: MINIMAL_MAP,
|
||||
unitSet: { id: 'default', name: 'default', crewTypes: [] },
|
||||
nations: [attackerNation, defenderNation],
|
||||
cities: [attackerCity, defenderCity],
|
||||
generals: [attacker, defender],
|
||||
troops: [],
|
||||
diplomacy: [],
|
||||
events: [],
|
||||
initialEvents: [],
|
||||
};
|
||||
const world = new InMemoryWorld(snapshot);
|
||||
const runner = new TestGameRunner(world, 180, 1, 'best-general-sabotage-audit-2');
|
||||
const fire = fireSpec.createDefinition(commandEnv);
|
||||
let attempts = 0;
|
||||
|
||||
while ((world.getGeneral(attacker.id)?.meta.firenum ?? 0) === 0 && attempts < 20) {
|
||||
attempts += 1;
|
||||
await runner.runTurn([
|
||||
{
|
||||
generalId: attacker.id,
|
||||
commandKey: 'che_화계',
|
||||
resolver: fire,
|
||||
args: { destCityId: defenderCity.id },
|
||||
context: {
|
||||
destCity: world.getCity(defenderCity.id),
|
||||
destNation: defenderNation,
|
||||
destGenerals: [world.getGeneral(defender.id)],
|
||||
distance: 1,
|
||||
env: commandEnv,
|
||||
map: MINIMAL_MAP,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
expect(attempts).toBe(3);
|
||||
expect(world.getGeneral(attacker.id)?.meta.firenum).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -167,6 +167,8 @@ test.describe('inheritance management legacy parity', () => {
|
||||
const container = getComputedStyle(document.querySelector<HTMLElement>('#container')!);
|
||||
const title = getComputedStyle(document.querySelector<HTMLElement>('.section-title')!);
|
||||
const button = getComputedStyle(document.querySelector<HTMLElement>('.buy-button')!);
|
||||
const navigation = getComputedStyle(document.querySelector<HTMLElement>('.top-button')!);
|
||||
const secondary = getComputedStyle(document.querySelector<HTMLElement>('.dual-buttons button')!);
|
||||
return {
|
||||
container: rect('#container'),
|
||||
firstPoint: rect('#inherit_sum'),
|
||||
@@ -175,6 +177,9 @@ test.describe('inheritance management legacy parity', () => {
|
||||
backgroundImage: container.backgroundImage,
|
||||
titleBackgroundImage: title.backgroundImage,
|
||||
buttonBackground: button.backgroundColor,
|
||||
buttonBorderBottomWidth: button.borderBottomWidth,
|
||||
navigationBackground: navigation.backgroundColor,
|
||||
secondaryBackground: secondary.backgroundColor,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -185,14 +190,42 @@ test.describe('inheritance management legacy parity', () => {
|
||||
expect(desktop.fontSize).toBe('14px');
|
||||
expect(desktop.backgroundImage).toContain('back_walnut.jpg');
|
||||
expect(desktop.titleBackgroundImage).toContain('back_green.jpg');
|
||||
expect(desktop.buttonBackground).toBe('rgb(55, 90, 127)');
|
||||
expect(desktop.buttonBorderBottomWidth).toBe('4px');
|
||||
expect(desktop.navigationBackground).toBe('rgb(0, 88, 44)');
|
||||
expect(desktop.secondaryBackground).toBe('rgb(68, 68, 68)');
|
||||
|
||||
const buyButton = page.locator('.buy-button').first();
|
||||
const beforeHover = await buyButton.evaluate((element) => getComputedStyle(element).backgroundColor);
|
||||
const beforeHover = await buyButton.evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return { background: style.backgroundColor, borderBottomWidth: style.borderBottomWidth };
|
||||
});
|
||||
await buyButton.hover();
|
||||
const afterHover = await buyButton.evaluate((element) => getComputedStyle(element).backgroundColor);
|
||||
expect(afterHover).not.toBe(beforeHover);
|
||||
const afterHover = await buyButton.evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return { background: style.backgroundColor, borderBottomWidth: style.borderBottomWidth };
|
||||
});
|
||||
expect(afterHover.background).toBe(beforeHover.background);
|
||||
expect(afterHover.borderBottomWidth).toBe('3px');
|
||||
|
||||
await buyButton.hover({ position: { x: 70, y: 20 } });
|
||||
await page.mouse.down();
|
||||
await expect
|
||||
.poll(() => buyButton.evaluate((element) => getComputedStyle(element).borderBottomWidth))
|
||||
.toBe('2px');
|
||||
await page.mouse.up();
|
||||
|
||||
await buyButton.focus();
|
||||
await expect(buyButton).toBeFocused();
|
||||
await page.keyboard.press('Tab');
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expect(buyButton).toBeFocused();
|
||||
await expect.poll(() => buyButton.evaluate((element) => getComputedStyle(element).outlineStyle)).toBe('solid');
|
||||
|
||||
await buyButton.evaluate((element) => element.setAttribute('disabled', ''));
|
||||
await expect.poll(() => buyButton.evaluate((element) => getComputedStyle(element).opacity)).toBe('0.65');
|
||||
await buyButton.evaluate((element) => element.removeAttribute('disabled'));
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
|
||||
|
||||
if (artifactRoot) {
|
||||
await page.screenshot({ path: resolve(artifactRoot, 'inherit-core-desktop.png'), fullPage: true });
|
||||
@@ -214,6 +247,10 @@ test.describe('inheritance management legacy parity', () => {
|
||||
expect(mobile.containerWidth).toBe(500);
|
||||
expect(mobile.firstWidth).toBeCloseTo(482, 0);
|
||||
expect(mobile.stacked).toBe(true);
|
||||
|
||||
if (artifactRoot) {
|
||||
await page.screenshot({ path: resolve(artifactRoot, 'inherit-core-mobile.png'), fullPage: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('submits a legacy buff purchase and refreshes status and logs', async ({ page }) => {
|
||||
|
||||
@@ -1014,6 +1014,12 @@ test.describe('survey legacy parity', () => {
|
||||
fontSize: getComputedStyle(title).fontSize,
|
||||
backgroundImage: getComputedStyle(title).backgroundImage,
|
||||
},
|
||||
voteButton: {
|
||||
backgroundColor: getComputedStyle(document.querySelector<HTMLElement>('.vote-submit')!)
|
||||
.backgroundColor,
|
||||
borderBottomWidth: getComputedStyle(document.querySelector<HTMLElement>('.vote-submit')!)
|
||||
.borderBottomWidth,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1027,6 +1033,10 @@ test.describe('survey legacy parity', () => {
|
||||
expect(geometry.title.height).toBeCloseTo(37.8, 0);
|
||||
expect(geometry.title.fontSize).toBe('25.2px');
|
||||
expect(geometry.title.backgroundImage).toContain('back_blue.jpg');
|
||||
expect(geometry.voteButton).toEqual({
|
||||
backgroundColor: 'rgb(68, 68, 68)',
|
||||
borderBottomWidth: '4px',
|
||||
});
|
||||
|
||||
const secondOption = page.locator('#v-vote-1');
|
||||
await secondOption.check();
|
||||
@@ -1035,9 +1045,9 @@ test.describe('survey legacy parity', () => {
|
||||
await expect(secondOption).toBeFocused();
|
||||
|
||||
const voteButton = page.getByRole('button', { name: '투표', exact: true });
|
||||
const beforeHover = await voteButton.evaluate((element) => getComputedStyle(element).filter);
|
||||
const beforeHover = await voteButton.evaluate((element) => getComputedStyle(element).borderBottomWidth);
|
||||
await voteButton.hover();
|
||||
const afterHover = await voteButton.evaluate((element) => getComputedStyle(element).filter);
|
||||
const afterHover = await voteButton.evaluate((element) => getComputedStyle(element).borderBottomWidth);
|
||||
expect(afterHover).not.toBe(beforeHover);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
|
||||
import { sealGatewayPassword } from '../src/passwordEnvelope.js';
|
||||
|
||||
import type { AppRouter as GatewayAppRouter } from '@sammo-ts/gateway-api';
|
||||
import { createGatewayApiServer } from '@sammo-ts/gateway-api';
|
||||
import { clearTournamentRuntimeKeys, createGatewayApiServer } from '@sammo-ts/gateway-api';
|
||||
import type { AppRouter as GameAppRouter } from '@sammo-ts/game-api';
|
||||
import {
|
||||
buildTournamentKeys,
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
processTournamentTick,
|
||||
TournamentStore,
|
||||
} from '@sammo-ts/game-api';
|
||||
import { createTurnDaemonRuntime } from '@sammo-ts/game-engine';
|
||||
import { createTurnDaemonRuntime, seedScenarioToDatabase } from '@sammo-ts/game-engine';
|
||||
import {
|
||||
createGamePostgresConnector,
|
||||
createGatewayPostgresConnector,
|
||||
@@ -92,7 +92,8 @@ const truncateSchema = async (schema: string): Promise<void> => {
|
||||
await connector.connect();
|
||||
try {
|
||||
const rows = (await connector.prisma.$queryRawUnsafe(
|
||||
`SELECT tablename FROM pg_tables WHERE schemaname = '${schema}'`
|
||||
`SELECT tablename FROM pg_tables
|
||||
WHERE schemaname = '${schema}' AND tablename <> '_prisma_migrations'`
|
||||
)) as Array<{ tablename: string }>;
|
||||
if (rows.length === 0) {
|
||||
return;
|
||||
@@ -168,6 +169,7 @@ describe('actual tournament lifecycle', () => {
|
||||
|
||||
gatewayServer = await createGatewayApiServer();
|
||||
await gatewayServer.app.listen({ host: gatewayServer.config.host, port: gatewayServer.config.port });
|
||||
process.env.GATEWAY_INTERNAL_API_URL = `http://127.0.0.1:${gatewayServer.config.port}`;
|
||||
gameServer = await createGameApiServer();
|
||||
await gameServer.app.listen({ host: gameServer.config.host, port: gameServer.config.port });
|
||||
|
||||
@@ -210,10 +212,23 @@ describe('actual tournament lifecycle', () => {
|
||||
localAccountGeneralCreationGraceDays: 7,
|
||||
},
|
||||
});
|
||||
await gatewayClient.admin.profiles.installNow.mutate({
|
||||
profileName: 'che:908',
|
||||
install: {
|
||||
scenarioId: 908,
|
||||
const staleTournamentRedis = createRedisConnector(resolveRedisConfigFromEnv());
|
||||
await staleTournamentRedis.connect();
|
||||
const staleTournamentKeys = buildTournamentKeys('che:908');
|
||||
try {
|
||||
await staleTournamentRedis.client.mSet({
|
||||
[staleTournamentKeys.stateKey]: JSON.stringify({ stage: 6, auto: true }),
|
||||
[staleTournamentKeys.participantsKey]: '[{"id":99999}]',
|
||||
[staleTournamentKeys.matchesKey]: '[{"id":99999}]',
|
||||
[staleTournamentKeys.bettingKey]: '[{"generalId":99999}]',
|
||||
});
|
||||
} finally {
|
||||
await staleTournamentRedis.disconnect();
|
||||
}
|
||||
await seedScenarioToDatabase({
|
||||
scenarioId: 908,
|
||||
databaseUrl: resolvePostgresConfigFromEnv({ schema: 'che' }).url,
|
||||
installOptions: {
|
||||
turnTermMinutes: 1,
|
||||
sync: false,
|
||||
fiction: 0,
|
||||
@@ -227,6 +242,41 @@ describe('actual tournament lifecycle', () => {
|
||||
},
|
||||
});
|
||||
|
||||
const resetTournamentRedis = createRedisConnector(resolveRedisConfigFromEnv());
|
||||
await resetTournamentRedis.connect();
|
||||
try {
|
||||
await clearTournamentRuntimeKeys(resetTournamentRedis.client, 'che:908');
|
||||
expect(
|
||||
await resetTournamentRedis.client.mGet([
|
||||
staleTournamentKeys.stateKey,
|
||||
staleTournamentKeys.participantsKey,
|
||||
staleTournamentKeys.matchesKey,
|
||||
staleTournamentKeys.bettingKey,
|
||||
])
|
||||
).toEqual([null, null, null, null]);
|
||||
} finally {
|
||||
await resetTournamentRedis.disconnect();
|
||||
}
|
||||
|
||||
const gameDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'che' }).url;
|
||||
const gatewayDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'public' }).url;
|
||||
gameConnector = createGamePostgresConnector({ url: gameDatabaseUrl });
|
||||
await gameConnector.connect();
|
||||
redisConnector = createRedisConnector(resolveRedisConfigFromEnv());
|
||||
await redisConnector.connect();
|
||||
store = new TournamentStore(redisConnector.client, buildTournamentKeys('che:908'));
|
||||
transport = new DatabaseTurnDaemonTransport(gameConnector.prisma, 30_000);
|
||||
turnDaemon = await createTurnDaemonRuntime({
|
||||
profile: 'che',
|
||||
profileName: 'che:908',
|
||||
databaseUrl: gameDatabaseUrl,
|
||||
gatewayDatabaseUrl,
|
||||
redisUrl: resolveRedisConfigFromEnv().url,
|
||||
});
|
||||
turnDaemonLoop = turnDaemon.lifecycle.start();
|
||||
const status = await transport.requestStatus(10_000);
|
||||
expect(status).not.toBeNull();
|
||||
|
||||
for (const [username, displayName] of users) {
|
||||
const login = await gatewayClient.auth.login.mutate({
|
||||
username,
|
||||
@@ -255,10 +305,6 @@ describe('actual tournament lifecycle', () => {
|
||||
}
|
||||
}
|
||||
|
||||
const gameDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'che' }).url;
|
||||
const gatewayDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'public' }).url;
|
||||
gameConnector = createGamePostgresConnector({ url: gameDatabaseUrl });
|
||||
await gameConnector.connect();
|
||||
await gameConnector.prisma.general.updateMany({
|
||||
where: { id: { in: [...generalIds.values()] } },
|
||||
data: { gold: 10_000 },
|
||||
@@ -296,19 +342,6 @@ describe('actual tournament lifecycle', () => {
|
||||
})),
|
||||
});
|
||||
|
||||
redisConnector = createRedisConnector(resolveRedisConfigFromEnv());
|
||||
await redisConnector.connect();
|
||||
store = new TournamentStore(redisConnector.client, buildTournamentKeys('che:908'));
|
||||
transport = new DatabaseTurnDaemonTransport(gameConnector.prisma, 30_000);
|
||||
|
||||
turnDaemon = await createTurnDaemonRuntime({
|
||||
profile: 'che',
|
||||
profileName: 'che:908',
|
||||
databaseUrl: gameDatabaseUrl,
|
||||
gatewayDatabaseUrl,
|
||||
redisUrl: resolveRedisConfigFromEnv().url,
|
||||
});
|
||||
|
||||
for (let attempt = 0; attempt < 36; attempt += 1) {
|
||||
const current = turnDaemon.world.getState().lastTurnTime;
|
||||
const next = new Date(current.getTime());
|
||||
@@ -319,10 +352,6 @@ describe('actual tournament lifecycle', () => {
|
||||
}
|
||||
}
|
||||
expect(await store.getState()).toMatchObject({ stage: 1, auto: true });
|
||||
|
||||
turnDaemonLoop = turnDaemon.lifecycle.start();
|
||||
const status = await transport.requestStatus(10_000);
|
||||
expect(status).not.toBeNull();
|
||||
}, 120_000);
|
||||
|
||||
afterAll(async () => {
|
||||
|
||||
Reference in New Issue
Block a user