Better bracket logic
This commit is contained in:
@@ -1,22 +1,11 @@
|
||||
# backend/app/core/brackets.py
|
||||
|
||||
import math
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class Match:
|
||||
def __init__(self, match_id: int, name: str):
|
||||
self.id = match_id
|
||||
self.name = name
|
||||
self.next_win: Optional["Match"] = None
|
||||
self.next_loss: Optional["Match"] = None
|
||||
self.players: list[Optional[int]] = [None, None]
|
||||
self.is_bye: bool = False
|
||||
self.ghost_count: int = 0
|
||||
from ..constants import BracketTypes
|
||||
from .structures import Match
|
||||
|
||||
|
||||
class BracketGenerator:
|
||||
|
||||
def __init__(self):
|
||||
self.matches_dict = {}
|
||||
self.match_counter = 1
|
||||
@@ -30,23 +19,24 @@ class BracketGenerator:
|
||||
size = 2 ** math.ceil(math.log2(num_players))
|
||||
seeds = self._generate_seeding_indices(num_players)
|
||||
|
||||
bracket = self._create_tree_bracket(size, "WB")
|
||||
# Create Winners Bracket
|
||||
bracket = self._create_tree_bracket(size)
|
||||
|
||||
for i, match in enumerate(bracket[0]):
|
||||
match.players = [seeds[i * 2], seeds[i * 2 + 1]]
|
||||
match.teams = [seeds[i * 2], seeds[i * 2 + 1]]
|
||||
|
||||
lb_rounds = []
|
||||
if double_elimination:
|
||||
lb_rounds = self._create_strict_lb(size, bracket)
|
||||
|
||||
if double_elimination:
|
||||
self._create_de_finals(bracket, lb_rounds)
|
||||
else:
|
||||
self._create_se_third_place(bracket)
|
||||
|
||||
self._apply_ghost_logic(bracket[0], num_players)
|
||||
# Propagate ghosts (this marks matches as is_bye=True)
|
||||
self._resolve_byes(num_players)
|
||||
|
||||
all_matches = sorted(self.matches_dict.values(), key=lambda x: x.id)
|
||||
# Filter out byes so they don't become DB rows
|
||||
return [m for m in all_matches if not m.is_bye]
|
||||
|
||||
def _generate_seeding_indices(self, num_players: int) -> list[int]:
|
||||
@@ -58,7 +48,7 @@ class BracketGenerator:
|
||||
curr *= 2
|
||||
return seeds
|
||||
|
||||
def _create_tree_bracket(self, size: int, prefix: str) -> list[list[Match]]:
|
||||
def _create_tree_bracket(self, size: int) -> list[list[Match]]:
|
||||
rounds: list[list[Match]] = []
|
||||
current_size = size // 2
|
||||
r_num = 1
|
||||
@@ -66,8 +56,7 @@ class BracketGenerator:
|
||||
while current_size >= 1:
|
||||
round_matches: list[Match] = []
|
||||
for _ in range(current_size):
|
||||
name = f"{prefix} Round {r_num}"
|
||||
m = Match(self.match_counter, name)
|
||||
m = Match(self.match_counter, BracketTypes.WB, r_num)
|
||||
self.matches_dict[m.id] = m
|
||||
round_matches.append(m)
|
||||
self.match_counter += 1
|
||||
@@ -75,15 +64,10 @@ class BracketGenerator:
|
||||
current_size //= 2
|
||||
r_num += 1
|
||||
|
||||
if rounds:
|
||||
rounds[-1][0].name = "Grand Final"
|
||||
if len(rounds) > 1:
|
||||
for m in rounds[-2]:
|
||||
m.name = f"{prefix} Semifinal"
|
||||
|
||||
for r in range(len(rounds) - 1):
|
||||
for i, match in enumerate(rounds[r]):
|
||||
match.next_win = rounds[r + 1][i // 2]
|
||||
match.next_win_slot = i % 2
|
||||
|
||||
return rounds
|
||||
|
||||
@@ -104,102 +88,129 @@ class BracketGenerator:
|
||||
|
||||
round_matches = []
|
||||
for _ in range(current_lb_size):
|
||||
m = Match(self.match_counter, f"LB Round {r}")
|
||||
m = Match(self.match_counter, BracketTypes.LB, r)
|
||||
self.matches_dict[m.id] = m
|
||||
round_matches.append(m)
|
||||
self.match_counter += 1
|
||||
lb_rounds.append(round_matches)
|
||||
|
||||
if lb_rounds:
|
||||
lb_rounds[-1][0].name = "Losers Final (3rd Place Match)"
|
||||
|
||||
# Link LB rounds
|
||||
for r in range(len(lb_rounds) - 1):
|
||||
curr = lb_rounds[r]
|
||||
next_r = lb_rounds[r + 1]
|
||||
for i, match in enumerate(curr):
|
||||
if len(curr) == len(next_r):
|
||||
# 1-to-1 Mapping case (e.g. 4 matches -> 4 matches)
|
||||
match.next_win = next_r[i]
|
||||
# FIX: Always use slot 1 (Slot 0 is taken by WB Drop-down)
|
||||
match.next_win_slot = 1
|
||||
else:
|
||||
# 2-to-1 Mapping case (e.g. 4 matches -> 2 matches)
|
||||
match.next_win = next_r[i // 2]
|
||||
match.next_win_slot = i % 2
|
||||
|
||||
# Link WB Losers -> LB
|
||||
for r in range(num_wb_rounds):
|
||||
wb_round = wb_rounds[r]
|
||||
|
||||
if r == 0:
|
||||
lb_target_idx = 0
|
||||
else:
|
||||
lb_target_idx = (r * 2) - 1
|
||||
lb_target_idx = 0 if r == 0 else (r * 2) - 1
|
||||
|
||||
if lb_target_idx >= len(lb_rounds):
|
||||
break
|
||||
|
||||
lb_round = lb_rounds[lb_target_idx]
|
||||
|
||||
for i, wb_match in enumerate(wb_round):
|
||||
if r == 0:
|
||||
target = lb_round[i // 2]
|
||||
wb_match.next_loss_slot = i % 2
|
||||
else:
|
||||
# Drop-in round
|
||||
target = lb_round[i] if i < len(lb_round) else lb_round[0]
|
||||
|
||||
# Drop-ins take Slot 0
|
||||
wb_match.next_loss_slot = 0
|
||||
wb_match.next_loss = target
|
||||
|
||||
return lb_rounds
|
||||
|
||||
def _create_se_third_place(self, wb_rounds: list[list[Match]]) -> None:
|
||||
"""Creates a standalone 3rd place match for Single Elim"""
|
||||
if len(wb_rounds) < 2:
|
||||
return
|
||||
|
||||
semis = wb_rounds[-2]
|
||||
third_place_match = Match(self.match_counter, "3rd Place Match")
|
||||
final_round_idx = wb_rounds[-1][0].round_number
|
||||
third_place_match = Match(
|
||||
self.match_counter, BracketTypes.FINALS, final_round_idx
|
||||
)
|
||||
self.matches_dict[third_place_match.id] = third_place_match
|
||||
self.match_counter += 1
|
||||
|
||||
for m in semis:
|
||||
m.next_loss = third_place_match
|
||||
for i, sm in enumerate(semis):
|
||||
sm.next_loss = third_place_match
|
||||
sm.next_loss_slot = i % 2
|
||||
|
||||
def _create_de_finals(
|
||||
self, wb_rounds: list[list[Match]], lb_rounds: list[list[Match]]
|
||||
) -> None:
|
||||
"""Links Double Elim Grand Final"""
|
||||
wb_final = wb_rounds[-1][0]
|
||||
wb_final.name = "Winners Final"
|
||||
final_round_idx = wb_final.round_number + 1
|
||||
|
||||
gf = Match(self.match_counter, "Grand Final")
|
||||
gf = Match(self.match_counter, BracketTypes.FINALS, final_round_idx)
|
||||
self.matches_dict[gf.id] = gf
|
||||
self.match_counter += 1
|
||||
|
||||
wb_final.next_win = gf
|
||||
wb_final.next_win_slot = 0
|
||||
|
||||
if lb_rounds:
|
||||
lb_rounds[-1][0].next_win = gf
|
||||
reset = Match(self.match_counter, "Grand Final Reset")
|
||||
lb_rounds[-1][0].next_win_slot = 1
|
||||
|
||||
reset = Match(self.match_counter, BracketTypes.FINALS, final_round_idx + 1)
|
||||
self.matches_dict[reset.id] = reset
|
||||
self.match_counter += 1
|
||||
gf.next_loss = reset
|
||||
gf.next_loss_slot = 0
|
||||
|
||||
def _apply_ghost_logic(
|
||||
self, round_one_matches: list[Match], num_players: int
|
||||
) -> None:
|
||||
def _resolve_byes(self, num_players: int) -> None:
|
||||
"""
|
||||
Injects ghosts into WB Round 1 and lets them flow recursively.
|
||||
Iterates through all matches to identify 'Ghost' players (seeds > num_players).
|
||||
If a match has a ghost, it is marked as a Bye, and the real player is
|
||||
automatically pushed to the next match.
|
||||
"""
|
||||
for m in round_one_matches:
|
||||
p1, p2 = m.players
|
||||
if p1 and p1 > num_players:
|
||||
self._add_ghost(m)
|
||||
if p2 and p2 > num_players:
|
||||
self._add_ghost(m)
|
||||
all_matches: list[Match] = sorted(
|
||||
self.matches_dict.values(), key=lambda x: x.id
|
||||
)
|
||||
|
||||
def _add_ghost(self, match: Match) -> None:
|
||||
"""
|
||||
Recursively propagates a ghost through the bracket.
|
||||
"""
|
||||
match.ghost_count += 1
|
||||
match.is_bye = True
|
||||
for m in all_matches:
|
||||
if m.is_bye:
|
||||
continue
|
||||
|
||||
if match.next_loss:
|
||||
self._add_ghost(match.next_loss)
|
||||
p1, p2 = m.teams
|
||||
|
||||
if match.ghost_count == 2:
|
||||
if match.next_win:
|
||||
self._add_ghost(match.next_win)
|
||||
p1_is_ghost = p1 is not None and p1 > num_players
|
||||
p2_is_ghost = p2 is not None and p2 > num_players
|
||||
|
||||
if p1_is_ghost or p2_is_ghost:
|
||||
m.is_bye = True
|
||||
|
||||
winner = None
|
||||
loser = None # Ghost
|
||||
|
||||
if p1_is_ghost and p2_is_ghost:
|
||||
winner = None
|
||||
loser = None
|
||||
elif p1_is_ghost:
|
||||
winner = p2
|
||||
loser = p1
|
||||
elif p2_is_ghost:
|
||||
winner = p1
|
||||
loser = p2
|
||||
|
||||
# Propagate Winner (Advance to next round)
|
||||
if m.next_win:
|
||||
m.next_win.teams[m.next_win_slot] = winner
|
||||
|
||||
# Propagate Loser (Drop to LB)
|
||||
# Important: We push the GHOST to the LB.
|
||||
# When the loop reaches that LB match later, it will see the ghost
|
||||
# and mark THAT match as a bye too, recursively cleaning the bracket.
|
||||
if m.next_loss:
|
||||
m.next_loss.teams[m.next_loss_slot] = loser
|
||||
|
||||
Reference in New Issue
Block a user