krz/nba-scores

A CLI/TUI app for NBA scores.

clone: git clone https://gitbay.org/krz/nba-scores.git

main: nba/standings.py · raw

 1"""
 2Tabulate the current conference standings.
 3"""
 4
 5from tabulate import tabulate
 6
 7# ANSI escape codes for text formatting
 8BOLD = "\033[1m"
 9END = "\033[0m"
10RED = "\033[91m"
11GREEN = "\033[32m"
12
13
14def _build_conference_table(standings, conference: str) -> str:
15    """Build a formatted table string for one conference."""
16    data = []
17    rank = 1
18
19    for result_set in standings["resultSets"]:
20        if result_set["name"] == "Standings":
21            for team in result_set["rowSet"]:
22                if team[5] != conference:
23                    continue
24                wins = team[12]
25                losses = team[13]
26                win_pct = team[14]
27                streak = team[35]
28
29                strk_color = (
30                    f"{RED}{streak}{END}"
31                    if int(streak) < 0
32                    else f"{GREEN}{streak}{END}"
33                )
34
35                data.append(
36                    [
37                        f"{rank}",
38                        team[4],
39                        f"{wins}-{losses}",
40                        f"{win_pct:.3f}",
41                        team[37],
42                        strk_color,
43                        team[19],
44                        team[17],
45                        team[18],
46                    ]
47                )
48                rank += 1
49
50    headers = ["Rank", "Team", "W-L", "PCT", "GB", "STRK", "L10", "HOME", "AWAY"]
51    label = "Eastern" if conference == "East" else "Western"
52    return f"{BOLD}{label} Conference Standings:{END}\n" + tabulate(
53        data, headers=headers, tablefmt="grid"
54    )
55
56
57def get_east_standings_table(standings) -> str:
58    """Returns the Eastern Conference standings as a formatted string."""
59    return _build_conference_table(standings, "East")
60
61
62def get_west_standings_table(standings) -> str:
63    """Returns the Western Conference standings as a formatted string."""
64    return _build_conference_table(standings, "West")
65
66
67def get_standings_tables(standings) -> str:
68    """
69    Builds and returns both conference standings as a formatted string.
70
71    Args:
72            standings (dict): Team standings data.
73
74    Returns:
75            str: Formatted standings string with ANSI color codes for both conferences.
76    """
77    return (
78        get_east_standings_table(standings)
79        + "\n\n"
80        + get_west_standings_table(standings)
81    )
82
83
84def build_standings(standings) -> None:
85    """
86    Prints team standings in two separate tables.
87
88    Args:
89            standings (dict): Team standings data.
90    """
91    print(get_standings_tables(standings))