足球预测平台通常同时覆盖联赛与杯赛两类赛事。杯赛(淘汰赛)与联赛不同,采用单场淘汰、逐轮晋级的结构,对阵关系随轮次动态变化,因此后端需要一套专门的逻辑框架来处理对阵的生成、推进与查询。
在没有统一框架的情况下,常见的实现问题包括:
本文描述一个面向预测平台的杯赛对阵后端逻辑框架:以种子分排序为基础生成首轮对阵,按括号结构推进后续轮次,并通过统一的数据模型与接口向预测功能提供对阵数据。
框架分为四层:
执行方式:
python cup_bracket.py预期结果:打印杯赛总轮数,以及首轮全部对阵(含轮空标注),对阵条目数满足「实际对阵数 + 轮空数 = slots/2」。
以下代码示例未在本环境实际运行,统一标注为「待验证」,给出的输出为预期结果而非实测记录。
# cup_bracket.py —— 待验证
import math
from dataclasses import dataclass
@dataclass
class Team:
team_id: str
name: str
seed: int # 种子分,越小越强
@dataclass
class Match:
round_no: int
home_id: str
away_id: str
slot: int
is_bye: bool = False
@property
def dedup_key(self) -> str:
# 同一杯赛内,轮次 + 括号位置唯一标识一场对阵
return f"r{self.round_no}-slot{self.slot}"
def next_power_of_two(n: int) -> int:
return 1 << math.ceil(math.log2(max(n, 1)))
def build_first_round(teams: list[Team]) -> list[Match]:
"""按种子生成首轮对阵:最强 byes 支轮空,其余队伍相邻配对。"""
ordered = sorted(teams, key=lambda t: t.seed)
n = len(ordered)
slots = next_power_of_two(n)
byes = slots - n
bye_teams = ordered[:byes]
play_teams = ordered[byes:]
matches: list[Match] = []
slot = 0
for i in range(0, len(play_teams) - 1, 2):
matches.append(Match(1, play_teams[i].team_id, play_teams[i + 1].team_id, slot))
slot += 1
# 单数参赛队时的防御处理:最后一支并入轮空
if len(play_teams) % 2 == 1 and play_teams:
matches.append(Match(1, play_teams[-1].team_id, "", slot, is_bye=True))
slot += 1
for t in bye_teams:
matches.append(Match(1, t.team_id, "", slot, is_bye=True))
slot += 1
return matches
def total_rounds(team_count: int) -> int:
return math.ceil(math.log2(next_power_of_two(team_count)))
def main() -> None:
teams = [
Team("t1", "A队", 1),
Team("t2", "B队", 2),
Team("t3", "C队", 3),
Team("t4", "D队", 4),
Team("t5", "E队", 5),
Team("t6", "F队", 6),
]
first_round = build_first_round(teams)
print("总轮数:", total_rounds(len(teams)))
for m in first_round:
tag = "轮空" if m.is_bye else "对阵"
print(f"第{m.round_no}轮 slot{m.slot} {tag}: {m.home_id} vs {m.away_id or '(轮空)'}")
if __name__ == "__main__":
main()预期输出(6 支队伍,slots = 8,轮空 2 支):
总轮数: 3
第1轮 slot0 对阵: t3 vs t4
第1轮 slot1 对阵: t5 vs t6
第1轮 slot2 轮空: t1 vs (轮空)
第1轮 slot3 轮空: t2 vs (轮空)第二轮参赛队伍数为 2 个胜者 + 2 个轮空 = 4,恰好等于 slots/2,符合单败淘汰括号结构。
示例代码使用命名配置变量承接外部地址,不硬编码任何示例域名;地址由部署环境注入。
# config.py —— 待验证
import os
# 命名配置变量承接外部地址;未设置时为空字符串,由部署环境注入
PREDICT_API_BASE_URL = os.environ.get("PREDICT_API_BASE_URL", "")
BRACKET_SERVICE_ADDRESS = os.environ.get("BRACKET_SERVICE_ADDRESS", "")
MATCH_DATA_SOURCE_URL = os.environ.get("MATCH_DATA_SOURCE_URL", "")
SERVICE_PORT = int(os.environ.get("CUP_SERVICE_PORT", "8000"))依赖 fastapi、uvicorn,执行方式:
pip install fastapi uvicorn
uvicorn service:app --port 8000# service.py —— 待验证(依赖 fastapi、uvicorn)
from fastapi import FastAPI
from config import BRACKET_SERVICE_ADDRESS
from cup_bracket import Team, build_first_round
app = FastAPI(title="cup-bracket-service")
DEMO_TEAMS = [
Team("t1", "A队", 1),
Team("t2", "B队", 2),
Team("t3", "C队", 3),
Team("t4", "D队", 4),
]
@app.get("/cup/{cup_id}/round/1")
def first_round(cup_id: str) -> dict:
"""演示:按种子生成首轮对阵并通过接口返回。"""
matches = build_first_round(DEMO_TEAMS)
return {
"cup_id": cup_id,
"service_address": BRACKET_SERVICE_ADDRESS or "local",
"matches": [
{"home_id": m.home_id, "away_id": m.away_id, "slot": m.slot, "is_bye": m.is_bye}
for m in matches
],
}预期结果:GET /cup/demo/round/1 返回 JSON,matches 包含 2 个对阵(t1 vs t2、t3 vs t4),且 service_address 为配置变量 BRACKET_SERVICE_ADDRESS 的注入值或 "local"。
以下验证方法与预期结果均未在本环境实际执行,不得视为实测通过。
# test_cup_bracket.py —— 待验证
import unittest
from cup_bracket import Team, build_first_round, total_rounds
def make_teams(n: int) -> list[Team]:
return [Team(f"t{i}", f"{i}队", i) for i in range(1, n + 1)]
class BracketTest(unittest.TestCase):
def test_power_of_two(self):
matches = build_first_round(make_teams(8))
self.assertEqual(len(matches), 4)
self.assertTrue(all(not m.is_bye for m in matches))
def test_six_teams_byes(self):
matches = build_first_round(make_teams(6))
self.assertEqual(len([m for m in matches if m.is_bye]), 2)
self.assertEqual(len([m for m in matches if not m.is_bye]), 2)
self.assertEqual(total_rounds(6), 3)
def test_no_duplicate_slots(self):
matches = build_first_round(make_teams(7))
keys = [m.dedup_key for m in matches]
self.assertEqual(len(keys), len(set(keys)))
if __name__ == "__main__":
unittest.main()执行方式:
python -m unittest test_cup_bracket.py预期结果:三个用例全部通过,分别覆盖 2 的幂队伍数、非 2 的幂队伍数(轮空分配)以及对阵去重。
uvicorn service:app --port 8000;以下网址按用户输入逐字原样记录。本文未访问、未抓取、未读取、未解析、未核验这些网址的任何内容,也不以其作为任何技术结论的证明。