from math import floor from csv import reader from pathlib import Path from random import sample from dataclasses import dataclass @dataclass class Player: name: str skill: int status: bool @dataclass class Team: player1: Player player2: Player @dataclass class Game: team1: Team team2: Team class PlayerList: def __init__(self, location: Path = "players.csv"): with open(location, newline="") as file: data_reader = reader(file) next(data_reader, None) self.players = [ ( Player( name=row[0], skill=row[1], status=(row[2] == "True"), ) ) for row in data_reader ] def get_player(self, player_request: str): return [player for player in self.players if player.name == player_request] def get_active_players(self): return [player for player in self.players if player.status] def toggle_player(self, player_request: Player): self.players = [ ( Player( name=player.name, skill=player.skill, status=not player.status, ) if player.name == player_request else player ) for player in self.players ] def __str__(self): display_string = "" for player in self.players: display_string += player.__str__() + "\n" return display_string TOTAL_PLAYERS_PER_COURT = 4 DUMMY_PLAYER = Player(name="-", skill=0, status=True) DUMMY_TEAM = Team(player1=DUMMY_PLAYER, player2=DUMMY_PLAYER) DUMMY_GAME = Game(DUMMY_TEAM, DUMMY_TEAM) @dataclass class GameList: courts: int = 8 def __post_init__(self): self.games = [DUMMY_GAME for _ in range(self.courts)] def create_games(self, players: list[Player]): possible_games = floor(len(players) / TOTAL_PLAYERS_PER_COURT) chosen_players = sample(players, possible_games * TOTAL_PLAYERS_PER_COURT) clumped_players = [ chosen_players[i : i + TOTAL_PLAYERS_PER_COURT] for i in range(0, len(chosen_players), TOTAL_PLAYERS_PER_COURT) ] games = [] for clump in clumped_players: team1 = Team(player1=clump[0], player2=clump[1]) team2 = Team(player1=clump[2], player2=clump[3]) game = Game(team1, team2) games.append(game) empty_courts = ( self.courts - possible_games if self.courts > possible_games else 0 ) self.games = games + [DUMMY_GAME for _ in range(empty_courts)]