import numpy as np
import random
class DoubleElimination:
"""Double Elimination Tournament"""
def __init__(self, K):
"""
Double Elimination トーナメントを初期化します。
Args:
K (int): 参加者の総数。2以上である必要があります。
"""
self.K = K
if K < 2:
raise ValueError("Number of participants (K) must be at least 2 for a tournament.")
# 各参加者の敗北数を記録 (0敗, 1敗, 2敗で敗退)
self.losses = np.zeros(K, dtype=int)
# トーナメントから排除されたかどうか (2敗でTrueになる)
self.is_eliminated = np.zeros(K, dtype=bool)
# 勝者ブラケット (Winners Bracket, WB) の状態
# 現在のラウンドでまだ試合が組まれていない、または対戦相手を待っているプレイヤー
self.wb_players_for_round = list(np.arange(K))
random.shuffle(self.wb_players_for_round) # 初期対戦順をランダム化
# 現在のWBラウンドで既に勝利し、次のラウンド進出を待っているプレイヤー
self.wb_round_winners = []
# 現在のWBラウンドで敗北し、敗者ブラケットに落ちるプレイヤー
self.wb_round_losers = []
# WBの最終勝者 (グランドファイナルに進む)
self.wb_finalist = None
# 敗者ブラケット (Losers Bracket, LB) の状態
# 現在のLBラウンドでまだ試合が組まれていない、または対戦相手を待っているプレイヤー
self.lb_players_for_round = [] # 最初は空
# 現在のLBラウンドで既に勝利し、次のラウンド進出を待っているプレイヤー
self.lb_round_winners = []
# LBの最終勝者 (グランドファイナルに進む)
self.lb_finalist = None
# トーナメントの最終勝者
self.champion = None
# トーナメントが終了したかどうか
self.is_tournament_over = False
# グランドファイナルが既にプレイされたかどうか
self.grand_final_played = False
# select_pairで最後に選ばれた対戦がどのブラケットのものであったかを記憶
self._last_selected_from = None # 'WB', 'LB', 'GF'
def _process_wb_round_end(self):
"""
WBの現在のラウンドが終了した際に、次のラウンドへの準備を行います。
不戦勝の処理、WB敗者のLBへの移動、WB勝者の次のWBラウンドへの昇格を含みます。
"""
# 現在のラウンドでプレイヤーが1人残っていれば、それは不戦勝 (bye)
if len(self.wb_players_for_round) == 1:
self.wb_round_winners.append(self.wb_players_for_round.pop())
# WBの試合で負けたプレイヤーをLBへ移動
for loser_id in self.wb_round_losers:
if not self.is_eliminated[loser_id]: # 2敗していなければLBへ
self.lb_players_for_round.append(loser_id)
self.wb_round_losers = [] # 処理済みなのでクリア
# 現在のWBラウンドの勝者を次のWBラウンドのプレイヤーとしてセット
self.wb_players_for_round = self.wb_round_winners
self.wb_round_winners = [] # 処理済みなのでクリア
# もしWBの残りプレイヤーが1人になったら、その人がWBファイナリスト
if len(self.wb_players_for_round) == 1:
self.wb_finalist = self.wb_players_for_round.pop()
self.wb_players_for_round = [] # WBは終了
def _process_lb_round_end(self):
"""
LBの現在のラウンドが終了した際に、次のラウンドへの準備を行います。
不戦勝の処理、LB勝者の次のLBラウンドへの昇格を含みます。
"""
# 現在のラウンドでプレイヤーが1人残っていれば、それは不戦勝 (bye)
if len(self.lb_players_for_round) == 1:
self.lb_round_winners.append(self.lb_players_for_round.pop())
# 現在のLBラウンドの勝者を次のLBラウンドのプレイヤーとしてセット
self.lb_players_for_round = self.lb_round_winners
self.lb_round_winners = [] # 処理済みなのでクリア
# もしLBの残りプレイヤーが1人になったら、その人がLBファイナリスト
if len(self.lb_players_for_round) == 1:
self.lb_finalist = self.lb_players_for_round.pop()
self.lb_players_for_round = [] # LBは終了
def select_pair(self):
"""
次の対戦相手のペアを選択します。
トーナメントの進行状況に応じて、WB、LB、グランドファイナルからペアを選択します。
Returns:
tuple: (p1, p2) 形式の対戦相手のIDのタプル。
トーナメントが終了している、または現在対戦を組めない場合は (None, None) を返します。
"""
if self.is_tournament_over:
return None, None
# 1. グランドファイナルが組めるかチェック
# WBファイナリストとLBファイナリストが揃っており、まだグランドファイナルがプレイされていない場合
if self.wb_finalist is not None and self.lb_finalist is not None and not self.grand_final_played:
self._last_selected_from = 'GF'
return self.wb_finalist, self.lb_finalist
# 2. 勝者ブラケット (WB) の試合が組めるかチェック
# WBファイナリストがまだ決まっていない場合
if self.wb_finalist is None:
# 現在のWBラウンドで試合を組めるプレイヤーが2人以上いるか確認
if len(self.wb_players_for_round) >= 2:
p1 = self.wb_players_for_round.pop(random.randrange(len(self.wb_players_for_round)))
p2 = self.wb_players_for_round.pop(random.randrange(len(self.wb_players_for_round)))
self._last_selected_from = 'WB'
return p1, p2
else:
# 現在のWBラウンドの試合が全て組まれたと判断し、ラウンドを進行させる
self._process_wb_round_end()
# ラウンド進行後、再度 select_pair を呼び出し、次の試合を探す
# (次のWBラウンドの試合、またはWBが終了していればLBの試合、GFの試合)
return self.select_pair()
# 3. 敗者ブラケット (LB) の試合が組めるかチェック
# WBファイナリストは決定しているが、LBファイナリストがまだ決まっていない場合
if self.lb_finalist is None:
# 既に2敗して排除されたプレイヤーを除外
active_lb_players_for_round = [p for p in self.lb_players_for_round if not self.is_eliminated[p]]
self.lb_players_for_round = active_lb_players_for_round # 更新
# 現在のLBラウンドで試合を組めるプレイヤーが2人以上いるか確認
if len(self.lb_players_for_round) >= 2:
p1 = self.lb_players_for_round.pop(random.randrange(len(self.lb_players_for_round)))
p2 = self.lb_players_for_round.pop(random.randrange(len(self.lb_players_for_round)))
self._last_selected_from = 'LB'
return p1, p2
else:
# 現在のLBラウンドの試合が全て組まれたと判断し、ラウンドを進行させる
self._process_lb_round_end()
# ラウンド進行後、再度 select_pair を呼び出し、次の試合を探す
# (次のLBラウンドの試合、またはLBが終了していればGFの試合)
return self.select_pair()
# 上記のどのフェーズにも該当しない場合、トーナメントは終了しているか、
# または現在対戦を組むべきではない状態です。
return None, None
def update(self, i, j, result):
"""
対戦の結果を更新します。
Args:
i (int): プレイヤー1のID。
j (int): プレイヤー2のID。
result (int): 1の場合iがjに勝利、0の場合jがiに勝利。
"""
if self.is_tournament_over:
return
winner = i if result == 1 else j
loser = j if result == 1 else i
# グランドファイナルの場合
if self._last_selected_from == 'GF':
self.champion = winner
self.is_tournament_over = True
self.grand_final_played = True
return
# 敗者の敗北数を更新
self.losses[loser] += 1
# 敗者が2敗になったらトーナメントから除外
if self.losses[loser] >= 2:
self.is_eliminated[loser] = True
# どのブラケットの試合だったかに基づいて勝者と敗者を処理
if self._last_selected_from == 'WB':
self.wb_round_winners.append(winner)
# WBで負けたプレイヤーはLBに落ちる候補として記録
self.wb_round_losers.append(loser)
elif self._last_selected_from == 'LB':
self.lb_round_winners.append(winner)
# LBで負けたプレイヤーは `is_eliminated` で既に2敗とマークされているため、
# 特に次のラウンドのリストに追加する必要はない。
else:
raise RuntimeError(f"Unknown _last_selected_from state: {self._last_selected_from}")
def infer_best(self):
"""
トーナメントの最終的な勝者を推論します。
Returns:
int: 最終的な勝者のID。トーナメントがまだ終了していない場合は -1。
"""
if self.is_tournament_over:
return self.champion
else:
return -1 # トーナメントが終了していない