def deserialized_player(i): """ This function set back the data about players to instance to the class Player """ player = Player(i['first_name'], i['last_name'], i['birthday'], i['gender'], i['rank'], i['score_of_round'], i['final_score_of_tournament']) player.scores = i["scores"] player.final_score = i['final_score'] return player
def test_object_creating(self): """Test creating objects with dummy data""" player = Player(rank=4325, name="John Doe", level="Master", country="UK", rating=1599) player.save() self.assertEqual(player.rank, 4325) self.assertTrue(player.level == "Master", True)
def players_of_the_tournament(self): """This function add instance of a player to the list of tournament""" i = Player(first_name=PlayerForms.first_name, last_name=PlayerForms.last_name, birthday=PlayerForms.birth_date, gender=PlayerForms.gender, rank=PlayerForms.rank, score_of_round=0, final_score_of_tournament=0) self.list_of_players.append(i) i.scores = {self.name: {}} return i
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 add_player(self): """ Display the add_player menu Loop for each information to retrieve Name (name), Firstname (firstname), Date of Birth (dob), Sex (_genre) Then create a new player and save the list. """ title = "Bienvenue dans le gestionnaire de tournois d'échec.\nAjout d'un joueur" subtitle = "Saisir dans l'ordre :\n" menu = { 1: ('', "Nom du joueur"), 2: ('', "Prénom du joueur"), 3: ('', "Date de naissance (Format dd/mm/aaaa)"), 4: ('', "Sexe (H/F)") } self.view_menu.display_menu(title=title, subtitle=subtitle, question=menu) choice = ('name', 'first_name', 'dob', '_genre') response = [] for i in range(4): if 0 <= i <= 1: # pour les question nom et prénom valid = self.ask_and_store_text(menu[i + 1][1] + ' : ') while not valid[0]: valid = self.ask_and_store_text(menu[i + 1][1] + ' : ') response.append(valid[1]) elif i == 2: # pour la date de naissance valid = self.view_menu.input(menu[i + 1][1] + ' : ') while not self._control_user_input("dob", valid): valid = self.view_menu.input(menu[i + 1][1] + ' : ') response.append(valid) elif i == 3: # pour la saisie du genre valid = self.view_menu.input(menu[i + 1][1] + ' : ') while not self._control_user_input("_genre", valid): valid = self.view_menu.input(menu[i + 1][1] + ' : ') response.append(valid) res = dict(zip(choice, response)) Player(**res) Player.save_all_players() self.menu_players()
def players_of_the_tournament(self): """This function add instance of a player to the list of tournament""" i = Player(first_name=input("first_name"), last_name=input("last_name"), birthday=datetime.datetime(year=int( input("year")), month=int( input("month")), day= int( input("year"))), gender=input("gender"), rank=input("rank"), score_of_round=0, final_score_of_tournament=0) self.list_of_players.append(i) i.scores = {self.name: {}} return i
def add_a_player(): # Set back tournament's data to an instance of class Tournament tournament = convert_to_instance() player_form = PlayerForm() if player_form.validate_on_submit(): player = Player(player_form.first_name.data, player_form.last_name.data, player_form.date_of_birth.data, player_form.gender.data, player_form.rank.data, score_of_round=0, final_score_of_tournament=0) add_a_player_to_database(player) tournament.new_tournament_players(player) add_tournament_to_database(tournament) number_of_players_to_add = len(tournament.list_of_players) return render_template( 'tournament_created.html', tournament=tournament, number_of_players_to_add=number_of_players_to_add) return render_template('add_a_player.html', player_form=player_form, tournament=tournament)
def add_round(self): """ Method to add a round in tournament Returns: Object Round """ r = Round(round_number=len(self.rounds) + 1, players=Player.list_player_tournament()) self.rounds.append(r) return r
def load(cls, save_id: int): """ Method of loading a backup tournament """ Player.initialise_players_data() Player.load_players() Player.all_players_inactive() data_load = cls.table_tournoi.get(doc_id=save_id) # data_load = data_load[-1] t = {} # --------- Load Objet Tournament ---------- t['identity'] = data_load['id'] t['name'] = data_load['name'] t['location'] = data_load['location'] t['tournament_date'] = data_load['tournament_date'] t['timer'] = data_load['timer'] t['description'] = data_load['description'] t['max_rounds_number'] = data_load['max_rounds_number'] tournament = Tournament(t['identity'], t['name'], t['location'], t['tournament_date'], t['description'], t['timer'], max_rounds_number=t['max_rounds_number']) # --------- Load Objet Player --------------- t['players'] = data_load['players'] for player in t['players']: # 1 - Search for the player with uuid stored in player[0]. # 2 - Assign the number of points stored in player[1] # 3 - Fill in the existing matches store in player[2] p_found = [p for p in Player.PLAYERS if player[0] == p.uuid] assert p_found # Raises an exception if the player is not found p_found = p_found[0] p_found.status = True # p_found.switch_player_tournament() p_found.point = player[1] for meet in player[2]: p_found.add_meet(meet) # --------- Load Objet Round ---------------- t['rounds'] = data_load['rounds'] for n, round in enumerate(t['rounds']): # 1 - We scan the saved rounds. # 2 - We extract the information from the rounds. # 3 - We extract the matches and the scores. if n % 2 == 0: tournament.rounds.append(Round(round['number'], Player.list_player_tournament(), round['start'], round['end'], t['rounds'][n+1]['matches'], round['id'])) return tournament
def index_players(db_connection, path_to_player_file): cur = db_connection.cursor() with open(path_to_player_file, 'r') as f: reader = csv.DictReader(f) for line in reader: player = Player(line) cur.execute("INSERT INTO players VALUES (%s, %s, %s)", (player.id, player.first_name, player.last_name)) db_connection.commit()
def list_tournament_players_sort_elo(self): """ Function that will print the list of players in the tournament sorted by ELO """ title = "Bienvenue dans le gestionnaire de tournois d'échec." subtitle = "Listing des joueurs du tournoi :" data = Player.list_player_tournament() data.sort(reverse=True, key=lambda x: int(x.elo)) self.view_menu.display_data(title, subtitle, data)
def list_tournament_players_sort_alpha(self): """ Function that will print the list of players in the tournament sorted alphabetically """ title = "Bienvenue dans le gestionnaire de tournois d'échec." subtitle = "Listing des joueurs du tournoi :" data = Player.list_player_tournament() data.sort(key=lambda x: (x.name, x.first_name)) self.view_menu.display_data(title, subtitle, data)
def start(): data = request.json logger.info("Starting new game | Data: %s", data) try: # Create players player1_name = data['player1']['name'].lower() player2_name = data['player2']['name'].lower() player1 = Player(player1_name, WHITE) player2 = Player(player2_name, BLACK) # Caching players PLAYERS[player1_name] = player1 PLAYERS[player2_name] = player2 game = start_game(player1, player2) GAMES[str(game.id)] = game return_data = { "board": game.board.to_dict(), "id": game.id, "players": { "white": player1.get_name(), "black": player2.get_name(), }, "next_move": game.get_next_move(), } logger.info(f"New game started | White: '{player1.get_name()}' | Black: '{player2.get_name()}' | ID: {game.id}") return jsonify(return_data) except Exception as ex: logger.error("Exception: %s", ex) return jsonify("Error %s" % ex) # TODO: Raise HTTP error
def remove_player_tournament(self): """ Method to remove the active status from the tournament 1° Request the name and firstname of the player 2° Search for the player if he is not already inactive in the tournament 3° Request validation of the inactive status for the tournament """ player = self.found_specific_player() if player is not None: if not player.status: self.view_menu.stand_by_msg( "Attention {} {} n'est pas inscrit au " "tournoi".format(player.name, player.first_name)) else: valid = self.ask_and_store_text( "Confirmez vous que {} {} " "ne participe plus au tournoi ? (O/N)".format( player.name, player.first_name)) if valid[0]: player.switch_player_tournament() Player.save_all_players()
def view_result(self): """ Méthode qui affiche le résultat du tournoi. Returns: """ p = Player.list_player_tournament() p.sort(reverse=True, key=lambda x: (int(x.point), int(x.elo))) data = [] for n, player in enumerate(p): data.append( f"{n + 1} - {player.fullname} ({player.age} ans) avec {player.point} points," f" classement ELO : {player.elo}") title = "Bienvenue dans le gestionnaire de tournois d'échec.\n" subtitle = "Classement du tournoi." self.view_menu.display_data(title, subtitle, data)
def post(): """Adds new chess players by validating them.""" payload = request.get_json() new_item = Player(**payload).save() return Response(new_item.to_json(), mimetype="application/json", status=201)
def test_fields_validation(self): """Tests whether fields are actually validated""" player = Player(rank=2, name="Magnus Carlsen", level="Grandmaster", country="Norway", rating=2650) player.save() with self.assertRaises(mongoengine.errors.NotUniqueError): """Rank field must be unique""" player = Player(rank=2, name="Magnus Carlsen", level="Grandmaster", country="Norway", rating=2650) player.save() self.assertEqual(Player.objects.filter(rank=2).count(), 2) with self.assertRaises(mongoengine.errors.ValidationError): """The values that level field can take are limited.""" player = Player(rank=1, name="Garry Kasparov", level="Grand master", country="Russia", rating=2700) player.save() self.assertNotEqual(player.level, "Grandmaster") with self.assertRaises(mongoengine.errors.ValidationError): """Rating field is required""" player = Player(rank=3, name="Alex Martelli", level="Master", country="Brazil") player.save()
def __init__(self): super().__init__() Player.load_players()
def fixture_lineups(fixture_id): lineups = Player.lineups_from_fixture(fixture_id) return jsonify({"fixtures": lineups})
def topscorers(season, league_id): topscorers_lst = Player.top_scorers(season, league_id) # topscorers_lst = top_scorers return jsonify({'scorers': topscorers_lst})