def resume_tournament(self): """ request the name of the tournament :return:name of tournmaent (string) """ cls() icon() self.list_tournament_not_over = list() for self.tournament_name in search_all_tournament(): self.tournament = Tournament() self.tournament.read_in_db(self.tournament_name) if not self.tournament.tournament_over: self.list_tournament_not_over.append(self.tournament) print('Vous souhaitez reprendre un Tournoi, si la liste est vide, ' 'taper Entrée pour revenir au menu principal\n') print(("=" * 113).center(width_calculated())) print(f'| {"Nom du Tournoi".center(35)} |' f'{"Ville".center(35)} |' f'{"Date".center(35)} |'.center(width_calculated()) ) for self.tournament in self.list_tournament_not_over: print(("-" * 113).center(width_calculated())) print(f'| {self.tournament.name.center(35)} |' f'{self.tournament.location.center(35)} |' f'{self.tournament.date.center(35)} |'.center(width_calculated()) ) print(("-" * 113).center(width_calculated())) self.name_tournament = " " while not (self.name_tournament in search_all_tournament() or self.name_tournament == ""): self.name_tournament = input('Tapez le nom du Tournoi : ').capitalize() return self.name_tournament
def run(self): tournament_data = [] validator = TournamentDataValidator() prompt = (('Nom (max. 50 caractères): ', validator.is_name_ok), ('Description (max. 50 caractères): ', validator.is_description_ok), ('Lieu (max. 50 caractères): ', validator.is_place_ok), ('Date de début (jj/mm/aaaa): ', validator.is_start_date_ok), ('Date de fin (jj/mm/aaaa): ', validator.is_end_date_ok), ('Nombre de rounds: (entier positif, par défaut: 4): ', validator.is_number_of_rounds_ok), ('Contrôle du temps (blitz / bullet / coup rapide): ', validator.is_time_control_ok)) for message, check_function in prompt: user_input = ViewPrompt(message).show() while not check_function(user_input): ViewText("Erreur de saisie, veuillez recommencer.").show() user_input = ViewPrompt(message).show() tournament_data.append(user_input) tournament = Tournament(*tournament_data) if tournament not in self.tournament_database: tournament.players = ControllerChoosePlayer( self.player_database).run() self.tournament_database.append(tournament) ViewText("Création du tournoi terminée avec succès.").show() ControllerSaveTournament(tournament).run() else: ViewText( "Erreur: le tournoi existe déjà (même nom, dates, contrôle du temps." ).show()
def edit_player(self): self._model = Tournament({}) all_players = self._model.get_players() self._view.show_items(all_players) ids = [item['id'] for item in all_players] player = self._view.get_user_choice(config.SELECT_PLAYER, ids) player_data = self._model.get_player(player) new_player_data = {} for item in config.NEW_PLAYER: if item == 'ranking': new_data = int( self._view.get_user_input( f'{config.NEW_PLAYER[item]} (current data: {player_data[item]}, press enter to keep as is)' )) else: new_data = self._view.get_user_input( f'{config.NEW_PLAYER[item]} (current data: {player_data[item]}, ' f'press enter to keep as is)') if new_data: new_player_data[item] = new_data else: new_player_data[item] = player_data[item] new_player_data['id'] = player_data['id'] self._model.edit_player(new_player_data) self._view.confirm('player') self.player_menu()
def load(self): """Load a tournament""" report = Reports(players_db, tournaments_db) self.screen.clear() self.screen.info_users(report.tournaments_list()) self.screen.on_screen() tournament_id = input_menu_verification( max_id(tournaments_db), "Saisissez le numéro du tournoi à charger") valid_tournament = search_db(tournament_id, tournaments_db) if valid_tournament is False: self.screen.warning( "Le tournoi {} n'existe pas.".format(tournament_id)) sleep(1) self.load() else: tournament_on_load = Tournament(valid_tournament) tournament_on_load.deserialized() self.tournament = tournament_on_load self.players_on_load = [] for player in self.tournament.players_list: self.players_on_load.append(player.player_id) while len(self.tournament.players_list) < TOURNAMENT_PLAYERS_NB: self.add_player_on_tournament() self.play()
def load_tournaments(self): """Load tournament from database - Get tournaments info from database - Create tournaments instances. """ tournaments: list[dict] = self.database.get_all_tournaments() for tournament in tournaments: # We only create a new instance if we don't already have it if tournament['id'] not in ( tournament.id for tournament in Tournament.TOURNAMENT_LIST): # create tournament object with attributs tournament_obj = Tournament() tournament_dict = { 'id': tournament['id'], 'tournament_name': tournament['tournament_name'], 'location': tournament['location'], 'start_date': tournament['start_date'], 'end_date': tournament['end_date'], 'tour_number': tournament['tour_number'], 'time_controller': tournament['time_controller'], 'number_of_players': tournament['number_of_players'], 'description': tournament['description'] } tournament_obj.add_tournament(tournament_dict) # load round for this tournament self.load_rounds(tournament_obj) # bind player with this tournament tournament_player = [] for player_id in tournament['players_list']: tournament_player.append( Player.get_player_by_id(player_id)) tournament_obj.bind_multiple_players(tournament_player) else: pass
def tournament_rounds_reports(self): """Show rounds for a single tournament""" tournament_id = self.select_tournament() self._model = Tournament({'id': tournament_id}) self._view.report(self._model.get_rounds()) self.tournament_menu()
def load_tournament(self, tournament_json): tournament = Tournament( tournament_json['name'], tournament_json['description'], tournament_json['place'], tournament_json['start_date'], tournament_json['end_date'], tournament_json['number_of_rounds'], tournament_json['time_control']) for player_data in tournament_json['players']: tournament.players.append(Player(**player_data)) for round_ in tournament_json['rounds']: new_round = Round(tournament) new_round.start_time = datetime( round_['start']['y'], round_['start']['mo'], round_['start']['d'], round_['start']['h'], round_['start']['mi'], ) new_round.end_time = datetime( round_['end']['y'], round_['end']['mo'], round_['end']['d'], round_['end']['h'], round_['end']['mi'], ) new_round.end_confirmation = round_['end_confirmation'] for game_data in round_['games']: new_game = Game(Player(**game_data['player1']), Player(**game_data['player2'])) new_game.update_result(game_data['result']) new_round.games.append(new_game) tournament.rounds.append(new_round) return tournament
def add_tournament(self): data = {} for item in config.NEW_TOURNAMENT: data[item] = self._view.get_user_input(config.NEW_TOURNAMENT[item]) if not data['date']: data['date'] = date.today().strftime('%d/%m/%Y') data['players'] = [] self._model = Tournament({}) for i in range(0, self._model.nb_players): self._view.show_items(self._model.get_players()) data['players'].append( int(self._view.get_user_input(config.SELECT_PLAYER))) self._model = Tournament(self._model.create_tournament(data)) self._view.confirm('tournament') self._view.show_items(self._model.show_latest_pairs()) self._view.confirm('pairs') self.tournament_menu()
def tournament_report(self, needs_selection=False): """Show all tournaments in DB""" if not self._model: self._model = Tournament({}) self._view.report(self._model.get_tournaments()) if needs_selection: return self._model.get_tournaments() else: self.tournament_menu()
class TournamentTestCase(unittest.TestCase): tournament = Tournament() def test_create_match(self): match_number = 1 self.assertEqual(self.tournament.match_count, 0) self.tournament.create_match(match_number, "Player A", "Player B") self.assertEqual(self.tournament.match_count, 1) self.assertTrue(self.tournament.get_match(match_number))
def create_tournament(self): """Create tournament instance with user informations.""" tournament_infos = self.tournois_view.get_tournament_info() tournament_infos['id'] = str(uuid1()) tournois_obj = Tournament() tournois_obj.add_tournament(tournament_infos) self.add_multiple_players(int(tournois_obj.number_of_players), tournois_obj) self.generate_first_round(tournois_obj)
def create_game(): game_id_name = request.form['game_number'] winner_name = request.form['winner'] loser_name = request.form['loser'] game_id = game_repository.select(game_id_name) winner = player_repository.select(winner_name) loser = player_repository.select(loser_name) tournament = Tournament(game_id, winner, loser) tournament_repository.save(tournament) return redirect('/tournaments')
def add_player(self): player = {} for item in config.NEW_PLAYER: player[item] = self._view.get_user_input(config.NEW_PLAYER[item]) if not player['ranking']: player['ranking'] = 9999 self._model = Tournament({}) self._model.create_player(player) self._view.confirm('player') self.player_menu()
def get_tournaments_html(column): tournaments = [] for link in column.find_all('li', recursive=False): item = link.find('a') if item: tournament_id = link.find('a').attrs.get('href').replace( '/sport/tournament.aspx?id=', '') name = link.find('h4').a.span.text tournaments.append(Tournament(tournament_id, name)) return tournaments
def resume(tournament): tournament_instance = Tournament() tournament_instance.id = tournament["id"], tournament_instance.name = tournament["name"], tournament_instance.players = tournament_instance.deserialized_player(tournament["players"]) tournament_instance.date = tournament["date"], tournament_instance.number_of_turns = tournament["number_of_turns"], tournament_instance.turns = tournament_instance.deserialize_turns(tournament["turns"]), tournament_instance.turns = tournament_instance.turns[0] tournament_instance.time_control = tournament["time_control"], tournament_instance.description = tournament["description"], return tournament_instance
def select_all(): tournaments = [] sql = "SELECT * FROM tournaments" results = run_sql(sql) for row in results: game = game_repository.select(row['game_id']) winner = player_repository.select(row['winner']) loser = player_repository.select(row['loser']) tournament = Tournament(game, winner, loser, row['id']) tournaments.append(tournament) return tournaments
def __init__(self): """ Create the main tournament menu """ cls() icon() self.list_all_tournament_name = search_all_tournament() self.list_tournaments = [] for self.tournament_name in self.list_all_tournament_name: self.tournament = Tournament() self.tournament.read_in_db(self.tournament_name) self.list_tournaments.append(self.tournament) print("Menu des stats Tournoi \n\n" "1. Voir la liste de tous les Tournois\n" "2. Voir les tours d'un Tournoi avec son nom\n" "3. Voir les matchs d'un Tournoi avec son nom\n" "4. Voir les Joueurs d'un Tournoi avec son nom\n" "5. Retour") self.choice_menu = 0 while not 5 >= int(self.choice_menu) >= 1: self.choice_menu = input( "Faites votre choix en tapant le numéro de menu (ex. 1, 2, 3, 4, ne tapez qu'un seul choix) : " ) if not self.choice_menu.isdigit(): self.choice_menu = 0 if int(self.choice_menu) == 1: self.show_list_all_tournament() input() elif int(self.choice_menu) == 2: if self.show_one_tournament(): self.show_tour() input() else: print("Ce tournoi n'existe pas") input() elif int(self.choice_menu) == 3: if self.show_one_tournament(): self.show_match() input() else: print("Ce tournoi n'existe pas") input() elif int(self.choice_menu) == 4: if self.show_one_tournament(): self.show_player() input() else: print("Ce tournoi n'existe pas") input() elif int(self.choice_menu) == 5: pass
def create_tournament(self): """ Method for initiating a new tournament """ Player.initialise_players_data() super().__init__( Tournament(identity=None, name=Tournament.NAME, location=Tournament.LOCATION, description=Tournament.DESCRIPTION, timer=Tournament.TIMER, max_rounds_number=Tournament.NB_ROUND)) self.tournament.add_round() self.round = self.tournament.rounds[-1] self.launch_menu_round()
def select_tournament(self) -> object: """Allow the user to choose the turnament. Returns: instance of Tournament """ # Selectionner un tournoi -> afficher les tournois self.tournament_view.display_tournament_list( Tournament().TOURNAMENT_LIST) # choisir l'ordre d'affichage number_item = self.menu_view.select_item('tournois') if number_item.isdigit(): try: selected_tournament = Tournament().TOURNAMENT_LIST[int( number_item)] return selected_tournament except IndexError: self.utilities_view.display_error_with_message( 'Pas de tournoi à cet index !') else: self.utilities_view.display_error_with_message( "L'index que vous avez saisi n'est pas un") return None
def get_all_tournaments_objs(self) -> list: """Summary of get_all_tournaments_objs. Returns: list: Description of return value """ items = self.get_all_tournaments() objs = [] for item in items: objs.append( Tournament(item['name'], item['place'], item['date'], item['players'], item['time_control'], item['description'], item['rounds'], item['round_count'])) return objs
def new(self): c = main.MainController() name = c.input_with_options('Tournament name : ') place = c.input_with_options('Tournament place : ') date_regex = re.compile(r'^(0[1-9]|[1-2][0-9]|3[0-1])/' r'(0[1-9]|1[0-2])/[0-9]{4}$') date_start = c.input_with_options('Tournament start date : ', date_regex, 'Date format should be: dd/mm/yyyy', loop=True) date_end_regex = re.compile(r'^(0[1-9]|[1-2][0-9]|3[0-1])/' r'(0[1-9]|1[0-2])/[0-9]{4}$|^$') date_end = c.input_with_options( 'End date ? (Empty if it\'s a 1-day tournament) : ', date_end_regex, 'Date format should be: dd/mm/yyyy', loop=True) date = date_start if date_end != "": date += ' to ' + date_end round_number = c.input_with_options('Number of rounds : ', re.compile('^[0-9]+$'), 'Please enter a positive number', loop=True) description = c.input_with_options('description : ') time_control_list = ['Bullet', 'Blitz', 'Rapid'] text = 'Time control [{}] : \n' for i in range(len(time_control_list)): text += ' ' + str(i + 1) + ') ' + time_control_list[i] + '\n' time_control = c.input_with_options(text, re.compile(r'^[1-3]+$|^$'), 'Please enter 1, 2 or 3', loop=True) if time_control in ['1', '2', '3']: time_control = time_control_list[int(time_control) - 1] tournament = Tournament(name, place, date, time_control, description, round_number) Tournament.add_tournament(tournament) return tournament
def update_tournament(self, name, place, date, players, time_control, description, rounds, round_count=4): """Summary of update_tournament. Args: name place date rounds players time_control description round_count Default to 4 """ assert isinstance(place, str), 'place should be a string' assert is_date(date), 'date cannot be converted to a french date' assert round_count > 0, 'round_count must be greater than 0' assert rounds, 'rounds must not be empty' assert players, 'players must not be empty' assert TimeControl.has_value(time_control), ('time_control must have' ' value: ' '\'Bullet\',' '\'Blitz\' or \'Rapid\'') assert isinstance(description, str), 'description must be a string' item_type = self.tournaments.item_type tournament = Tournament(name, place, date, players, time_control, description, rounds, round_count) try: older = self.tournaments.read_item(name) self.tournaments.update_item(tournament) self.logger.log_tournament_updated( name, older['place'], older['date'], older['round_count'], older['rounds'], older['players'], older['time_control'], older['description'], place, date, round_count, rounds, players, time_control, description) except mvc_exc.ItemNotStored as exc: self.logger.log_item_not_yet_stored_error(name, item_type, exc)
def create_tournament(): tournament = Tournament() tournament.name = input("Enter tournament's name: ") tournament.place = input("Enter tournament's place: ") tournament.date = input("Enter tournament's date: ") tournament.time_control = input("Enter tournament's time_control: ") tournament.description = input("Enter tournament's description: ") players_list = [] for index in range(8): player_id = int(input("Enter the id of the player " + str(index + 1) + " for this tournament : ")) tournament.get_player_for_tournament(player_id, players_table, tournament) players_list = tournament.sort_players_by_rank(tournament) tournament.create(tournament, tournaments_table, players_list, players_table) create_turn(tournament) return tournament
def DEMO_import_auto_tournament(self): """Create random info for a tournament """ tournament_infos = {'tournament_name': f"tournament_name {random.randint(0, 1000)}", 'location': "Strasbourg", 'tour_number': '4', 'start_date': ( f'''{random.randint(10, 20)}/{random.randint(10, 12)}/''' f'''{random.randint(1990, 2000)}''' ), 'time_controller': random.randint(1, 3), 'number_of_players': '8', 'description': 'Description du tournois', 'id': str(uuid1())} tournament_infos['end_date'] = tournament_infos['start_date'] tournament_obj = Tournament() tournament_obj.add_tournament(tournament_infos) self.add_multiple_players(int(tournament_obj.number_of_players), tournament_obj) self.generate_first_round(tournament_obj)
def get_obj(self, its_name, its_type) -> Union[Player, Tournament]: """Summary of get_obj. Args: its_name its_type Returns: Union[Player, Tournament]: Description of return value """ item = self.get_item(its_name, its_type) if its_type == self.players.item_type: return Player(item['last_name'], item['first_name'], item['birth_date'], Gender(item['gender']), int(item['rank']), int(item['match_score']), int(item['current_score']), item['opponents']) tournament_rounds_objs = [] for rnd in item['rounds']: if isinstance(rnd, str): rnd = json.loads(rnd) tournament_round_matches_objs = [] for mat in rnd['matches']: tournament_round_matches_objs.append( Match(mat['pone_name'], mat['pone_score'], mat['ptwo_name'], mat['ptwo_score'])) tournament_rounds_objs.append( Round(rnd['name'], rnd['start_date_time'], rnd['end_date_time'], tournament_round_matches_objs)) tournament_player_objs = [] for play in item['players']: if isinstance(play, str): play = json.loads(play) tournament_player_objs.append( Player(play['last_name'], play['first_name'], play['birth_date'], play['gender'], play['rank'], play['match_score'], play['current_score'], play['opponents'])) return Tournament(item['name'], item['place'], item['date'], tournament_player_objs, item['time_control'], item['description'], tournament_rounds_objs, item['round_count'])
def set_match_results(self): # Get user to select tournament and match is_entering_score = True tournament_id = self.select_tournament() self._model = Tournament({'id': tournament_id}) while is_entering_score: matches = self._model.get_matches(last_round=True) self._view.show_items(matches) match = self._view.get_user_choice(config.SELECT_MATCH, [*range(1, len(matches) + 1)]) - 1 final_scores = [] count = 1 # Get user to enter new scores for item in config.SET_SCORES: player = f'Player {count}' final_scores.append( float( self._view.get_user_input( f"{config.SET_SCORES[item]} ({matches[match][player]})" ))) count += 1 # Manage new scores entry self._model.set_match_results(match, final_scores) # Check if round matches scores are full if self._model.is_round_over(): self._model.set_round_end() if len(self._model.rounds) < len(self._model.players) / 2: self._model.create_new_round() self._model.show_latest_pairs() else: self._view.rounds_done() is_entering_score = False else: # Ask for new entry new_entry = int( self._view.get_user_choice(config.ADD_ANOTHER, [0, 1])) if not new_entry: is_entering_score = False self.tournament_menu()
def insert_tournament(self, name, place, date, players, time_control, description, rounds=None, round_count=4): """Summary of insert_tournament. Args: name place date players time_control description round_count Default to 4 """ assert isinstance(place, str), 'place should be a string' assert is_date(date), 'date cannot be converted to a french date' assert round_count > 0, 'round_count must be greater than 0' assert any(players), 'players must not be empty' assert TimeControl.has_value(time_control), ('time_control must have' ' value: ' '\'Bullet\',' '\'Blitz\' or \'Rapid\'') assert isinstance(description, str), 'description must be a string' item_type = self.tournaments.item_type int_round_count = int(round_count) if not rounds: rounds = [] time_control_obj = TimeControl(time_control) tournament = Tournament(name, place, date, players, time_control_obj, description, rounds, int_round_count) try: self.tournaments.create_item(tournament) self.logger.log_item_stored(name, item_type) except mvc_exc.ItemAlreadyStored as exc: self.logger.log_item_already_stored_error(name, item_type, exc)
def load_tournament_list(self): my_list = Tournament.load_all() for tournament in my_list: player_list = [ Participant(participant['id'], participant['score'], set(participant['old_matchs'])) for participant in tournament['players'] ] round_list = self.round_controller.load_round(tournament['round_list']) tournoi = Tournament( tournament.doc_id, tournament['name'], tournament['start_date'], tournament['end_date'], tournament['location'], player_list, tournament['time_control'], tournament['max_turn'] ) tournoi.round_list = round_list tournoi.actual_turn = tournament['actual_turn'] self.tournament_list.append(tournoi)
def create(self): """Create a new tournmanent""" self.screen.info_users( [" CREATION DE TOURNOI \n\n\n"]) self.screen.clear() self.screen.on_screen() tournament_infos = {} tournament_infos['id'] = max_id(tournaments_db) + 1 tournament_infos['name'] = input("Nom du Tournoi : ") tournament_infos['location'] = input("Lieu du tournoi : ") tournament_infos['date_start'] = strftime("%A %d %B %Y %H:%M:%S") tournament_infos['date_end'] = "on_course" tournament_infos['total_round'] = ROUNDS_NB self.screen.info_users([ "Choix du controleur de temps :\n", " [1] Blitz \n", " [2] Bullet \n", " [3] Coup Rapide \n" ]) self.screen.on_screen() controler_saisie = input_menu_verification( 3, "Veuillez saisir le numéro correspondant à votre choix") if controler_saisie == 1: tournament_infos['time_controler'] = "Blitz" elif controler_saisie == 2: tournament_infos['time_controler'] = "Bullet" elif controler_saisie == 3: tournament_infos['time_controler'] = "Coup rapide" tournament_infos['description'] = input("Description : ") tournament_infos['players_list'] = [] tournament_infos['rounds_list'] = [] self.tournament = Tournament(tournament_infos) self.tournament.save(tournaments_db) self.players_on_load = [] while len(self.tournament.players_list) < TOURNAMENT_PLAYERS_NB: self.add_player_on_tournament() self.tournament.save(tournaments_db) self.play()
def get_command(self): """Create a new tournament.""" name = Input.for_string("Please enter tournament's name : ") location = Input.for_string("Please enter tournament's location : ") date = datetime.date.today().strftime("%d/%m/%Y") mode = Input.for_string("How would you like to play ? bullet / blitz / fast : ") nb_rounds = 4 rounds = [] serialized_rounds = [] description = input("Please enter tournament's description : ") # CHOOSE BETWEEN AUTO or MANUAL list of players : players = self.create_auto_players() # players = self.create_list_players() tournament = Tournament( name, location, date, mode, nb_rounds, rounds, description, players ) tournament.save() print(tournament) first_round = self.progress_first_round( tournament, players, serialized_rounds, ) if first_round == "main menu": return "main menu" nb_rounds = tournament.nb_rounds next_round = self.progress_next_rounds( tournament, players, serialized_rounds, nb_rounds, ) if next_round == "main menu": return "main menu" return "main menu"