feat: add double elimination match mode
This commit is contained in:
1 parent
b9aaf55193
commit
e12f182e7f
19 files changed
+3415
-58
No files matched your search
@@ -28,10 +28,11 @@ function createService() {
|
||||
|
||||
interface MatchOverrides {
|
||||
gameCount?: number;
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination';
|
||||
roundRobinMaxRounds?: number;
|
||||
participants?: Array<{ excluded?: boolean }>;
|
||||
teams?: Array<{ teamIndex: number }>;
|
||||
doubleElimination?: MatchDocument['doubleElimination'];
|
||||
gameSchedule?: Array<{
|
||||
gameNumber: number;
|
||||
roundNumber?: number;
|
||||
@@ -51,6 +52,7 @@ function createMatch(overrides: MatchOverrides): MatchDocument {
|
||||
tournamentCodeIds: [],
|
||||
gameSchedule: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
markModified: jest.fn(),
|
||||
...overrides,
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
@@ -206,6 +208,35 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
expect(pair.gameSchedule).toEqual([]);
|
||||
});
|
||||
|
||||
it('creates a double-elimination bracket from built teams', () => {
|
||||
const service = createService();
|
||||
const match = createMatch({
|
||||
gameMode: 'double-elimination',
|
||||
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||
teamIndex: index + 1,
|
||||
})),
|
||||
doubleElimination: {
|
||||
teamCount: 4,
|
||||
resetFinalEnabled: true,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
});
|
||||
|
||||
service.ensureGameSchedule(match);
|
||||
|
||||
expect(match.doubleElimination?.seeds).toHaveLength(4);
|
||||
expect(match.doubleElimination?.bracketMatches).toHaveLength(6);
|
||||
expect(
|
||||
match.doubleElimination?.bracketMatches.filter(
|
||||
(bracketMatch) => bracketMatch.state === 'ready',
|
||||
),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('creates a limited round-robin schedule grouped by playable rounds', () => {
|
||||
const service = createService();
|
||||
const roundRobin = createMatch({
|
||||
|
||||
@@ -4,8 +4,13 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
buildDoubleEliminationBracket,
|
||||
findNextReadyDoubleEliminationBracketMatches,
|
||||
} from '../double-elimination/double-elimination.util';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
DoubleEliminationBracketMatch,
|
||||
MatchGameAssignment,
|
||||
MatchDocument,
|
||||
TournamentCode,
|
||||
@@ -239,8 +244,12 @@ export class TournamentCodeService {
|
||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||
this.ensureGameSchedule(match);
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.reserveForDoubleEliminationMatch(match, TournamentCodeModel);
|
||||
}
|
||||
const shouldSaveMetadata =
|
||||
match.isModified('gameCount') || match.isModified('gameSchedule');
|
||||
this.isMatchModified(match, 'gameCount') ||
|
||||
this.isMatchModified(match, 'gameSchedule');
|
||||
const requiredSlots = this.resolveRequiredSlots(match);
|
||||
const need = requiredSlots - match.tournamentCodeIds.length;
|
||||
if (need <= 0) {
|
||||
@@ -309,6 +318,13 @@ export class TournamentCodeService {
|
||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||
this.ensureGameSchedule(match);
|
||||
const doubleEliminationBracketMatch =
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? this.resolveDoubleEliminationBracketMatchByGameNumber(
|
||||
match,
|
||||
params.gameNumber,
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const requiredSlots = this.resolveRequiredSlots(match);
|
||||
if (
|
||||
@@ -320,7 +336,11 @@ export class TournamentCodeService {
|
||||
}
|
||||
if (
|
||||
(match.result?.games ?? []).some(
|
||||
(game) => game.gameNumber === params.gameNumber,
|
||||
(game) =>
|
||||
game.gameNumber === params.gameNumber ||
|
||||
(doubleEliminationBracketMatch?.bracketMatchId &&
|
||||
game.bracketMatchId ===
|
||||
doubleEliminationBracketMatch.bracketMatchId),
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
@@ -331,7 +351,9 @@ export class TournamentCodeService {
|
||||
const currentCode = await TournamentCodeModel.findOne({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
matchId: match._id,
|
||||
gameNumber: params.gameNumber,
|
||||
...(doubleEliminationBracketMatch
|
||||
? { bracketMatchId: doubleEliminationBracketMatch.bracketMatchId }
|
||||
: { gameNumber: params.gameNumber }),
|
||||
}).exec();
|
||||
if (!currentCode) {
|
||||
throw new NotFoundException('Assigned tournament code not found.');
|
||||
@@ -358,6 +380,11 @@ export class TournamentCodeService {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: params.gameNumber,
|
||||
...(doubleEliminationBracketMatch
|
||||
? {
|
||||
bracketMatchId: doubleEliminationBracketMatch.bracketMatchId,
|
||||
}
|
||||
: {}),
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
@@ -373,6 +400,7 @@ export class TournamentCodeService {
|
||||
currentCode.state = 'released';
|
||||
currentCode.matchId = undefined;
|
||||
currentCode.gameNumber = undefined;
|
||||
currentCode.bracketMatchId = undefined;
|
||||
currentCode.reservedAt = undefined;
|
||||
currentCode.releasedAt = new Date();
|
||||
currentCode.riotMatchId = undefined;
|
||||
@@ -386,6 +414,9 @@ export class TournamentCodeService {
|
||||
|
||||
return {
|
||||
gameNumber: params.gameNumber,
|
||||
...(doubleEliminationBracketMatch
|
||||
? this.toDoubleEliminationSlotBase(doubleEliminationBracketMatch)
|
||||
: {}),
|
||||
roundNumber: this.resolveRoundNumberForGameNumber(
|
||||
match,
|
||||
params.gameNumber,
|
||||
@@ -415,7 +446,12 @@ export class TournamentCodeService {
|
||||
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
|
||||
{
|
||||
$set: { state: 'released', releasedAt: new Date() },
|
||||
$unset: { matchId: 1, gameNumber: 1, reservedAt: 1 },
|
||||
$unset: {
|
||||
matchId: 1,
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 1,
|
||||
reservedAt: 1,
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
|
||||
@@ -483,6 +519,9 @@ export class TournamentCodeService {
|
||||
public async buildSlots(
|
||||
match: MatchDocument,
|
||||
): Promise<TournamentCodeSlotView[]> {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.buildDoubleEliminationSlots(match);
|
||||
}
|
||||
if (
|
||||
(match.gameMode ?? 'pair') === 'round-robin' &&
|
||||
(match.gameSchedule?.length ?? 0) === 0 &&
|
||||
@@ -550,10 +589,130 @@ export class TournamentCodeService {
|
||||
return next;
|
||||
}
|
||||
|
||||
private async reserveForDoubleEliminationMatch(
|
||||
match: MatchDocument,
|
||||
TournamentCodeModel: mongoose.Model<TournamentCode>,
|
||||
): Promise<MatchDocument> {
|
||||
const readyBracketMatches = findNextReadyDoubleEliminationBracketMatches(
|
||||
match.doubleElimination,
|
||||
);
|
||||
const existingCodes =
|
||||
match.tournamentCodeIds.length > 0
|
||||
? await TournamentCodeModel.find({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
}).exec()
|
||||
: [];
|
||||
const byBracketMatchId = new Map(
|
||||
existingCodes
|
||||
.filter(
|
||||
(code) =>
|
||||
code.bracketMatchId &&
|
||||
(code.state === 'reserved' || code.state === 'used'),
|
||||
)
|
||||
.map((code) => [code.bracketMatchId as string, code]),
|
||||
);
|
||||
const expiresAfter = new Date(
|
||||
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||
);
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
|
||||
for (const bracketMatch of readyBracketMatches) {
|
||||
if (byBracketMatchId.has(bracketMatch.bracketMatchId)) continue;
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
region: DEFAULT_REGION,
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
expiresAt: { $gt: expiresAfter },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: bracketMatch.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
byBracketMatchId.set(bracketMatch.bracketMatchId, code);
|
||||
}
|
||||
|
||||
if (reservedIds.length > 0) {
|
||||
match.tournamentCodeIds.push(...reservedIds);
|
||||
}
|
||||
if (
|
||||
reservedIds.length > 0 ||
|
||||
this.isMatchModified(match, 'doubleElimination')
|
||||
) {
|
||||
await match.save();
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
private async buildDoubleEliminationSlots(
|
||||
match: MatchDocument,
|
||||
): Promise<TournamentCodeSlotView[]> {
|
||||
this.ensureGameSchedule(match);
|
||||
const bracketMatches = match.doubleElimination?.bracketMatches ?? [];
|
||||
if (bracketMatches.length === 0) return [];
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const ids = match.tournamentCodeIds ?? [];
|
||||
const codes =
|
||||
ids.length > 0
|
||||
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
|
||||
: [];
|
||||
const byBracketMatchId = new Map(
|
||||
codes
|
||||
.filter(
|
||||
(code) =>
|
||||
code.bracketMatchId &&
|
||||
code.state !== 'released' &&
|
||||
code.state !== 'voided',
|
||||
)
|
||||
.map((code) => [code.bracketMatchId as string, code]),
|
||||
);
|
||||
|
||||
return bracketMatches.map((bracketMatch) => {
|
||||
const code = byBracketMatchId.get(bracketMatch.bracketMatchId);
|
||||
return {
|
||||
...this.toDoubleEliminationSlotBase(bracketMatch),
|
||||
code: code?.code ?? null,
|
||||
expiresAt: code?.expiresAt.toISOString() ?? null,
|
||||
state: code?.state ?? 'pending',
|
||||
riotMatchId: code?.riotMatchId ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private toDoubleEliminationSlotBase(
|
||||
bracketMatch: DoubleEliminationBracketMatch,
|
||||
): Omit<TournamentCodeSlotView, 'code' | 'expiresAt' | 'state' | 'riotMatchId'> {
|
||||
return {
|
||||
gameNumber: bracketMatch.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
bracketSide: bracketMatch.bracketSide,
|
||||
roundNumber: bracketMatch.roundNumber,
|
||||
matchNumber: bracketMatch.matchNumber,
|
||||
teamAIndex: bracketMatch.teamAIndex,
|
||||
teamBIndex: bracketMatch.teamBIndex,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveRequiredSlots(match: MatchDocument): number {
|
||||
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
return match.doubleElimination?.bracketMatches.length ?? 0;
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||
return match.gameSchedule.length;
|
||||
@@ -577,6 +736,17 @@ export class TournamentCodeService {
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
const bracketMatch = this.resolveDoubleEliminationBracketMatchByGameNumber(
|
||||
match,
|
||||
gameNumber,
|
||||
);
|
||||
return {
|
||||
teamAIndex: bracketMatch?.teamAIndex ?? 1,
|
||||
teamBIndex: bracketMatch?.teamBIndex ?? 2,
|
||||
};
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
const persisted = match.gameSchedule?.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
@@ -611,6 +781,10 @@ export class TournamentCodeService {
|
||||
}
|
||||
|
||||
private ensureGameSchedule(match: MatchDocument): void {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
this.ensureDoubleEliminationBracket(match);
|
||||
return;
|
||||
}
|
||||
if ((match.gameMode ?? 'pair') !== 'round-robin') return;
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) return;
|
||||
|
||||
@@ -620,6 +794,48 @@ export class TournamentCodeService {
|
||||
match.gameSchedule = this.buildRoundRobinGameSchedule(match);
|
||||
}
|
||||
|
||||
private ensureDoubleEliminationBracket(match: MatchDocument): void {
|
||||
if ((match.doubleElimination?.bracketMatches.length ?? 0) > 0) return;
|
||||
const teamIndexes = [...(match.teams ?? [])]
|
||||
.map((team) => team.teamIndex)
|
||||
.sort((left, right) => left - right);
|
||||
if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return;
|
||||
const shuffledTeamIndexes = this.shuffleTeamIndexes(teamIndexes);
|
||||
match.doubleElimination = buildDoubleEliminationBracket(
|
||||
shuffledTeamIndexes,
|
||||
{
|
||||
resetFinalEnabled:
|
||||
match.doubleElimination?.resetFinalEnabled ?? false,
|
||||
},
|
||||
);
|
||||
match.markModified?.('doubleElimination');
|
||||
}
|
||||
|
||||
private resolveDoubleEliminationBracketMatchByGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): DoubleEliminationBracketMatch | undefined {
|
||||
return match.doubleElimination?.bracketMatches.find(
|
||||
(bracketMatch) => bracketMatch.gameNumber === gameNumber,
|
||||
);
|
||||
}
|
||||
|
||||
private shuffleTeamIndexes(teamIndexes: number[]): number[] {
|
||||
const shuffled = [...teamIndexes];
|
||||
for (let index = shuffled.length - 1; index > 0; index -= 1) {
|
||||
const swapIndex = Math.floor(Math.random() * (index + 1));
|
||||
[shuffled[index], shuffled[swapIndex]] = [
|
||||
shuffled[swapIndex],
|
||||
shuffled[index],
|
||||
];
|
||||
}
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
private isMatchModified(match: MatchDocument, path: string): boolean {
|
||||
return typeof match.isModified === 'function' && match.isModified(path);
|
||||
}
|
||||
|
||||
private resolveRoundNumberForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
|
||||
@@ -24,9 +24,12 @@ export interface BulkUploadTournamentCodesResponse {
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
bracketSide?: string;
|
||||
roundNumber?: number;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
matchNumber?: number;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeState | 'pending';
|
||||
|
||||
Reference in new issue
Block a user