Ejemplo n.º 1
0
    def generate_next_round(self, previous_round, tournois_obj):
        """Create the next round.

        Keyword arguments:
        previous_round : Round -- round instance that has just ended
        tournois_obj : Tournament -- Instance of Tournament
        """
        # Check tour number
        if len(tournois_obj.round_list) < DEFAULT_TOUR_NUMBER:

            match_list = Suisse().generate_next_round(previous_round, tournois_obj)

            self.round = Round().create_round(f'Round {len(tournois_obj.round_list)+1}')
            RoundView().start_new_round(self.round)
            for match in match_list:
                formated_match = Match().create_match(match[0][0], match[0][1], match[1][0], match[1][1])
                self.round.add_match_to_round(formated_match)
            tournois_obj.add_round(self.round)
            self.view_controller.display_match_of_round(self.round)

        # end of tournament => display final score
        else:
            # récupérer la liste triée:
            players = Suisse().get_players_list_with_score(tournois_obj.round_list[-1])
            sorted_list = Suisse().sort_list_by_score(players)
            self.score.display_final_score(sorted_list)
            tournois_obj.set_final_score(sorted_list)
            print("Fin du tournois")
Ejemplo n.º 2
0
    def start(self, date_time):
        """Summary of start.

        Args:
            date_time

        Returns:
            list: Description of return value
        """
        rank_p = sorted(self.players, key=lambda x: x.rank)
        length = len(rank_p)
        middle_index = length//2
        first_half = rank_p[:middle_index]
        second_half = rank_p[middle_index:]
        matches = []
        for i in range(middle_index):
            matches.append(Match(first_half[i].first_name +
                                 ' ' +
                                 first_half[i].last_name,
                                 0,
                                 second_half[i].first_name +
                                 ' ' +
                                 second_half[i].last_name,
                                 0))
            first_half_play = next((x for x in self.players if x.first_name +
                                    ' ' +
                                    x.last_name == first_half[i].first_name +
                                    ' ' +
                                    first_half[i].last_name), None)

            second_half_play = next((x for x in self.players if x.first_name +
                                     ' ' +
                                     x.last_name == second_half[i].first_name +
                                     ' ' +
                                     second_half[i].last_name), None)
            first_half_play.opponents.append(second_half_play.first_name +
                                             ' ' +
                                             second_half_play.last_name)
            second_half_play.opponents.append(first_half_play.first_name +
                                              ' ' +
                                              first_half_play.last_name)
        if length > middle_index*2:
            matches.append(Match("Pas d'adversaire", 0,
                                 second_half[middle_index].first_name +
                                 ' ' +
                                 second_half[middle_index].last_name, 0))
            second_half_play = next((x for x in self.players if x.first_name +
                                     ' ' +
                                     x.last_name == second_half[middle_index].first_name +
                                     ' ' +
                                     second_half[middle_index].last_name), None)
            second_half_play.opponents.append("Pas d'adversaire")
        for i in range(self.round_count):
            if i == 0:
                self.rounds.append(Round("Round {}".format(i + 1),
                                         date_time, "", matches))
            else:
                matches = []
                self.rounds.append(Round("Round {}".format(i + 1),
                                         "", "", matches))
Ejemplo n.º 3
0
 def get_next_round(self, tournament, rounds, players):
     """Create Round 2, 3 , 4."""
     print(f"\n*******************ROUND {len(rounds)+1}******************\n")
     round = Round(
         f"Round {len(rounds) + 1}",
         datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"),
         matchs=[],
     )
     players = sorted(
         sorted(
             players,
             key=lambda player: player.rank,
         ),
         key=lambda player: player.points,
         reverse=True,
     )
     print(players)
     round.get_opponents(players)
     for player in players:
         add_point = Input.for_score(
             f"\n Please enter {player.first_name}'s score : "
         )
         player.add_points(add_point)
     round.end = str(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
     rounds.append(round)
     print(f"\n{round}")
     return round
 def get_first_round(self, rounds, players):
     """Create the first round of a tournament."""
     print(
         f"\n*******************ROUND {len(rounds)+1}******************\n")
     round = Round(
         f"Round {len(rounds)+ 1}",
         datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"),
         matchs=[],
     )
     players = sorted(players, key=lambda player: player.rank)
     nb_matchs = 4
     for index in range(nb_matchs):
         print(
             f"{players[index].first_name} vs {players[index+4].first_name}"
         )
     self.get_first_opponents(players)
     for player in players:
         add_point = Input.for_score(
             f"Please enter {player.first_name}'s score : ")
         player.add_points(add_point)
     Round.display_first_matchs(round, players)
     round.end = str(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
     rounds.append(round)
     print(f"\n{round}")
     return round
Ejemplo n.º 5
0
 def progress_next_rounds(
     self,
     tournament,
     players,
     serialized_rounds,
     nb_rounds,
 ):
     """Run the following rounds."""
     while nb_rounds > 0:
         rounds = tournament.rounds
         round = self.get_next_round(tournament, rounds, players)
         serialized_round = Round.serialized(round)
         serialized_rounds.append(serialized_round)
         tournament.update_round(serialized_rounds)
         tournament.update_players(players)
         if nb_rounds > 1:
             command = self.update(players, tournament)
             if command == "main menu":
                 return "main menu"
             players = sorted(
                 sorted(
                     players,
                     key=lambda player: player.rank,
                 ),
                 key=lambda player: player.points,
                 reverse=True,
             )
         nb_rounds = 4 - len(rounds)
     for player in players:
         score = player.add_final_score(player.points, player.score)
         Player.update_score(player, score)
     View.display_final_score(tournament, players)
Ejemplo n.º 6
0
def submit_stats(game_id, player, round_id):

    # get round instance - do we need game_id????
    round = Round.get_by_id(round_id)

    stats_array = [
        int(request.form.get('attack-input')),
        int(request.form.get('hitpoints-input')),
        int(request.form.get('luck-input'))
    ]

    # get round number from round index form or hidden inputs in round show
    round_num = request.form.get('round_num')

    if player == '1':
        round.player_1_stats = stats_array
        round.player_1_initiative = -1
        round.save()
    else:
        round.player_2_stats = stats_array
        round.player_2_initiative = -1
        round.save()

    return redirect(
        url_for('rounds.show',
                game_id=game_id,
                round_id=round_id,
                round_num=round_num))
Ejemplo n.º 7
0
def join_existing_game(game: Game, player: Union[User, int]) -> Game:
    print(f"Player {player} of type {type(player)} is joining game {game}")

    if isinstance(player, int):
        print(f"Player {player} is an AI player")
        player_config = dict(
            human_player=None,
            ai_player=player,
        )
    else:
        print(f"Player {player} is a human player")
        if game.has_human_player(player):
            return game

        game.human_players.add(player)
        player_config = dict(
            human_player=player,
            ai_player=None,
        )
        if game.is_ready():
            Round(
                game=game,
                round_number=1,
            )

    rack = Rack(
        game=game,
        tiles=game.tile_bag.fill_rack(),
        **player_config,
    )
    commit()
    print(f"Created rack {rack} for human player {rack.human_player} and ai player {rack.ai_player}")
    num_racks = len(Rack.select()[:])
    print(f"Total number of racks: {num_racks}")
    return game
Ejemplo n.º 8
0
    def generate_first_round(self, tournois_obj):
        """Create first round.

        Keyword arguments:
        tournois_obj : Tournament -- Instance de class Tournament
        """
        # generate_first_round renvoi une liste de tuple
        # => pair de joueur [(player1, player2), (player1, player2), ...]
        first_round_list = Suisse().generate_first_round(tournois_obj.players_list)
        self.round = Round().create_round('Round 1')
        for players in first_round_list:
            # Create match instance - init score
            match = Match().create_match(players[0], 0, players[1], 0)
            self.round.add_match_to_round(match)
        #  Création du match suivant, et affichage des prochains matchs
        tournois_obj.add_round(self.round)
        RoundView().start_new_round(self.round)
        self.view_controller.display_match_of_round(self.round)
Ejemplo n.º 9
0
 def load_round(self, data):
     round_list = [
         Round(round['name'], [
             Match(self.player_controller.get_by_id(
                 match["p1"]["id"]), match["p1"]["score"],
                   self.player_controller.get_by_id(match["p2"]["id"]),
                   match["p2"]["score"]) for match in round["match_list"]
         ], round["start_time"], round["end_time"]) for round in data
     ]
     return round_list
Ejemplo n.º 10
0
def async_create_round(game_id):

    # get time delta to sunday midnight ( monday 00:00:00 ) in seconds
    present_time = datetime.utcnow()
    sec_per_day = 24 * 60 * 60
    delta = (
        7 - present_time.weekday()
    ) * sec_per_day - present_time.hour * 60 * 60 - present_time.minute * 60 - present_time.second

    # automatically end currently active round if it exists
    # can we code logic for loghabit using queries in loghabit functions?

    # add round to db for game
    round = Round(game_id=game_id)
    round.save()

    # start recursive background task to execute on Monday 00:00:00 - which recalls async_round_create
    # for development purposes set timedelta = 30s
    async_create_round.apply_async((game_id, ), countdown=delta)
Ejemplo n.º 11
0
 def progress_first_round(
     self,
     tournament,
     players,
     serialized_rounds,
 ):
     """Run the first round."""
     rounds = tournament.rounds
     round = self.get_first_round(rounds, players)
     serialized_round = Round.serialized(round)
     serialized_rounds.append(serialized_round)
     tournament.update_round(serialized_rounds)
     tournament.update_players(players)
     return self.update(players, tournament)
 def read_in_db(self, name: str) -> bool:
     """
     Allows to load all the data of the DB of the searched tournament with its name
     :rtype: True if loading OK | False if loading NOK
     :param name: str tournament name
     :return: bool
     """
     try:
         self.data = self.tournament_table.search(Query().name == name)[0]
         self.name = self.data['name']
         self.location = self.data['location']
         self.date = self.data['date']
         self.time_control = self.data['time_control']
         self.tournament_over = self.data['tournament_over']
         self.list_players = list()
         for player_id in self.data['list_players']:
             self.player = Player()
             self.player.load_player(player_id)
             self.list_players.append(self.player)
         self.list_rounds_played = list()
         if self.data['list_round'] != [""]:
             for self.unique_round_dict in self.data['list_round']:
                 self.round = Round(self.list_players)
                 self.round.read_in_db([
                     int(self.key) for self.key, self.value in
                     self.unique_round_dict.items()
                 ][0])
                 self.round_played = {
                     self.round: self.unique_round_dict[self.key]
                 }
                 self.list_rounds_played.append(self.round_played)
         self.list_match_possible_not_played = self.data[
             'list_match_possible']
         self.comment_director = self.data['director_comment']
         return True
     except IndexError:
         return False
Ejemplo n.º 13
0
    def deserialize(cls, serialized_tournament):
        name = serialized_tournament['name']
        place = serialized_tournament['place']
        date = serialized_tournament['date']
        time_control = serialized_tournament['time_control']
        description = serialized_tournament['description']
        rounds_total = serialized_tournament['rounds_total']
        tournament = Tournament(name, place, date, time_control, description,
                                rounds_total)
        tournament.rounds = [
            Round.deserialize(serialized_round)
            for serialized_round in serialized_tournament['rounds']
        ]
        tournament.players = serialized_tournament['players']

        return tournament
Ejemplo n.º 14
0
def create():

    #Getting habit_id from the hidden form
    habit_id = request.form.get('habit-id')
    current_habit = Habit.get_or_none(Habit.id == habit_id)

    game_id = current_habit.game_id
    game = Game.get_or_none(Game.id == game_id)

    user = User.get_or_none(User.id == current_habit.user_id)
    username = user.username

    sender_id = current_habit.user_id
    if sender_id == game.player_1_id:
        receiver_id = game.player_2_id
    else:
        receiver_id = game.player_1_id


    # if current_user == user:



    image_file = request.files[f'image-for-{habit_id}']

    output = upload_file_to_s3(image_file, Config.S3_BUCKET)



                
    latest_round = Round.select(pw.fn.MAX(Round.id)).where(Round.game_id == game_id).scalar()


    new_habit_logged = LogHabit(habit_id = habit_id,
                                sender_id = current_habit.user_id,
                                receiver_id = receiver_id,
                                approved = False,
                                image_path = str(output),
                                game_round_id = latest_round)
    
    new_habit_logged.save()

    flash('Habit submitted. Waiting for your opponent\'s approval. Keep up the good work!', 'success')

    return redirect(url_for('games.show', game_id = game_id, username = username ))
Ejemplo n.º 15
0
    def load_matchs(self, round: dict):
        """Load matchs for a round from database

        Args:
            round (dict): round infos
        """
        matchs: list[dict] = self.database.get_all_matchs_of_round(round['id'])
        for match in matchs:
            match_dict = {
                "id": match["id"],
                "player1": Player.get_player_by_id(match['player1']),
                "score_player1": match['score_player1'],
                "player2": Player.get_player_by_id(match['player2']),
                "score_player2": match['score_player1']
            }
            match: object = Match().load_match(match_dict)
            round_obj: object = Round.find_round_by_id(round['id'])
            round_obj.load_match_to_round(match)
Ejemplo n.º 16
0
    def load_rounds(self, tournament):
        """Load rounds for a tournament from database

        Args:
            tournament (tournament instance): specify a tournament to get his rounds
        """
        rounds: list[dict] = self.database.get_all_rounds_of_tournament(
            tournament.id)
        for round in rounds:
            round_dict = {
                "id": round['id'],
                "round_name": round['round_name'],
                "start_round_datetime": round['start_round_datetime'],
                "end_round_datetime": round['end_round_datetime']
            }
            round_obj = Round().load_round(round_dict)
            # import pdb; pdb.set_trace()
            tournament.add_round(round_obj)
            self.load_matchs(round)
Ejemplo n.º 17
0
def pass_round(game: Game, player: Union[User, int]):
    current_round = game.current_round_as_round_type()
    RoundAction(
        human_player=player if isinstance(player, User) else None,
        ai_player=player if isinstance(player, int) else None,
        round=current_round,
        # word="",
        score_gained=0,
        clicked_pass=True,
    )

    # If this is the last word placed for this round, create another round
    if len(current_round.round_actions) == game.total_player_count():
        Round(
            round_number=current_round.round_number + 1,
            game=game,
        )

    commit()
Ejemplo n.º 18
0
    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'])
Ejemplo n.º 19
0
def build_game(first_player: User, human_player_count: int, ai_player_count: int) -> Game:
    tile_bag = TileBag.build_bag()
    new_game = Game(
        human_players={},
        human_player_count=human_player_count,
        ai_player_count=ai_player_count,
        board=BoardState().serialize(),
        tile_bag=tile_bag,
        has_finished=False,
    )
    tile_bag.game = new_game
    commit()
    join_existing_game(new_game, first_player)
    for ai_player_index in range(1, ai_player_count + 1):
        join_existing_game(new_game, ai_player_index)
    if new_game.is_ready():
        Round(
            game=new_game,
            round_number=1,
        )
        commit()
    return new_game
Ejemplo n.º 20
0
def roll_dice(game_id, player, round_id):
    roll_value = int(request.form.get('roll_value'))
    roll_index = int(request.form.get('roll_index'))

    # get round instance - do we need game_id????
    round = Round.get_by_id(round_id)

    # get round number from round index form or hidden inputs in round show
    round_num = request.form.get('round_num')

    if player == '1':
        round.player_1_rolls[roll_index] = roll_value
        round.save()
    else:
        round.player_2_rolls[roll_index] = roll_value
        round.save()

    return redirect(
        url_for('rounds.show',
                game_id=game_id,
                round_id=round_id,
                round_num=round_num))
Ejemplo n.º 21
0
 def get_command(self):
     "Choose a uncompleted tournament in the database."
     tournament = None
     while not tournament:
         name = Input.for_string("Name of an UNcompleted tournament ? ")
         tournament = Tournament.get(name)
         if not tournament:
             print("The value entered doesn't match any tournament !\n")
     rounds = tournament.rounds
     serialized_rounds = []
     for round in rounds:
         serialized_round = Round.serialized(round)
         serialized_rounds.append(serialized_round)
     players = tournament.players
     nb_rounds = 4 - len(rounds)
     super().progress_next_rounds(
         tournament,
         players,
         serialized_rounds,
         nb_rounds,
     )
     return "main menu"
Ejemplo n.º 22
0
    def test5GameValidateStartGame(self):

        lastJoinedGame = {'gameID': 1}
        self.game_namespace.on("game_started", self.passGetCurrentGame)
        self.game_namespace.emit("start_game", lastJoinedGame)
        self.socketIO.wait(seconds=1)

        print("\n\n")
        print("****************************************************")
        print("*Test If start game button work********************")
        print("(1)*CurrentGame == startGame***********************")
        print("(2)*Create New Round*******************************")
        print("(3)*Create New Turn********************************")
        print("(4)*Assign Roles for Players************************")
        print("****************************************************")
        print("\n")
        # Test joined team player do right join!
        print("Test(1)*********************************************Pass")
        self.assertEqual(self.currentGame, lastJoinedGame)
        print("Test(2)*********************************************Pass")
        session = Session()
        turnID = 1
        roundID = 1
        round = RoundModel.getRoundById(roundID, session)
        turn = TurnModel.getTurnById(turnID, session)
        self.assertEqual(self.currentGame["gameID"], round.gameId)
        print("Test(3)*********************************************Pass")
        self.assertEqual(self.currentGame["gameID"], turn.gameId)
        self.assertEqual(round.id, turn.roundId)
        print("Test(4)********************************************Pass")

        teller_id = turn.turnTellerId
        moderator_id = turn.turnModeratorId
        player_teller = PlayerModel.findPlayerById(session, teller_id)
        player_moderator = PlayerModel.findPlayerById(session, moderator_id)
        # Test if teller from turn table has role of teller
        # Test if moderator from turn table has role of moderator
        self.assertEqual(player_teller.role, 1)
        self.assertEqual(player_moderator.role, 2)
    def get_command(self):
        "Choose a uncompleted tournament in the database."
        tournament = self.tournament
        if not tournament:
            name = Input.for_string("Name of an UNcompleted tournament ? ")
            tournament = Tournament.get(name)
        if not tournament:
            return ""
        rounds = tournament.rounds
        serialized_rounds = []
        for round in rounds:
            serialized_round = Round.serialized(round)
            serialized_rounds.append(serialized_round)

        players = tournament.players
        nb_rounds = 4 - len(rounds)
        super().progress_next_rounds(
            tournament,
            players,
            serialized_rounds,
            nb_rounds,
        )
        return "main menu"
Ejemplo n.º 24
0
def battle(game_id, player, round_id):

    game = Game.get_by_id(game_id)

    # get round instance - do we need game_id????
    round = Round.get_by_id(round_id)

    # get round number from round index form or hidden inputs in round show
    round_num = request.form.get('round_num')

    player_initiative = int(request.form.get('initiative_input'))

    if player == '1':
        round.player_1_initiative = player_initiative
        round.save()
    else:
        round.player_2_initiative = player_initiative
        round.save()

    # algorithm to calculate winner
    # only execute if both players initiatives have been rolled (therefore both > 0)
    if (round.player_1_initiative > 0) and (round.player_2_initiative > 0):

        player_1_initiative = round.player_1_initiative
        player_2_initiative = round.player_2_initiative

        if player_1_initiative == player_2_initiative:
            if random.random() < 0.5:
                first_attack = 1
            else:
                first_attack = 2
        elif player_1_initiative > player_2_initiative:
            first_attack = 1
        else:
            first_attack = 2

        # based on first attacker, increment initiative by 1
        # for the case where initiatives are equal
        # in order to correctly calculate battlescript on client side
        if first_attack == 1:
            round.player_1_initiative += 1
            round.save()
        elif first_attack == 2:
            round.player_2_initiative += 1
            round.save()

        p1_attack = round.player_1_stats[0]
        p1_hp = round.player_1_stats[1]
        p1_luck = round.player_1_stats[2]

        p2_attack = round.player_2_stats[0]
        p2_hp = round.player_2_stats[1]
        p2_luck = round.player_2_stats[2]

        # determine winner of round
        while (p1_hp > 0 and p2_hp > 0):
            # if player 1 goes first
            if first_attack == 1:
                # check if critical hit
                if random.random() * 100 < p1_luck:
                    p1_damage = p1_attack * 2
                else:
                    p1_damage = p1_attack
                round.player_1_dmg_array.append(p1_damage)
                round.save()

                # check if p2 alive
                p2_hp = p2_hp - p1_damage
                if p2_hp <= 0:
                    round.result = User.get_by_id(game.player_1_id)
                    round.save()
                    game.player_1_score += 1
                    game.save()
                    break

                # repeat for p2
                if random.random() * 100 < p2_luck:
                    p2_damage = p2_attack * 2
                else:
                    p2_damage = p2_attack
                round.player_2_dmg_array.append(p2_damage)
                round.save()

                # check if p1 alive
                p1_hp = p1_hp - p2_damage
                if p1_hp <= 0:
                    round.result = User.get_by_id(game.player_2_id)
                    round.save()
                    game.player_2_score += 1
                    game.save()
                    break
            else:  # if player 2 attacks first
                if random.random() * 100 < p2_luck:
                    p2_damage = p2_attack * 2
                else:
                    p2_damage = p2_attack
                round.player_2_dmg_array.append(p2_damage)
                round.save()

                # check if p1 alive
                p1_hp = p1_hp - p2_damage
                if p1_hp <= 0:
                    round.result = User.get_by_id(game.player_2_id)
                    round.save()
                    game.player_2_score += 1
                    game.save()
                    break

                if random.random() * 100 < p1_luck:
                    p1_damage = p1_attack * 2
                else:
                    p1_damage = p1_attack
                round.player_1_dmg_array.append(p1_damage)
                round.save()

                # check if p2 alive
                p2_hp = p2_hp - p1_damage
                if p2_hp <= 0:
                    round.result = User.get_by_id(game.player_1_id)
                    round.save()
                    game.player_1_score += 1
                    game.save()

    return redirect(
        url_for('rounds.show',
                game_id=game_id,
                round_id=round_id,
                round_num=round_num))
Ejemplo n.º 25
0
def show(game_id, round_id):

    # get game model object
    game_id = game_id
    game = Game.get_by_id(game_id)

    # empty array for number of dice
    dice_array = []
    num_dice = 0

    # get round id and round instance
    round_id = round_id  # hardcode for dev purposes
    round = Round.get_by_id(round_id)

    # get round number from round index form or hidden inputs in round show
    round_num = request.args['round_num']

    # determine if current_user is p1 or p2 and get roll array
    game_player_1_id = game.player_1_id
    if current_user.id == game_player_1_id:
        # if current_player.id == game_player_1_id:
        player_variable = 1
        roll_array = round.player_1_rolls
        player_stats = round.player_1_stats
        opponent_stats = round.player_2_stats
        player_initiative = round.player_1_initiative
        opponent_initiative = round.player_2_initiative
    else:
        player_variable = 2
        roll_array = round.player_2_rolls
        player_stats = round.player_2_stats
        opponent_stats = round.player_1_stats
        player_initiative = round.player_2_initiative
        opponent_initiative = round.player_1_initiative

    round_result = round.result
    winner = User.get_or_none(User.id == round_result)

    # querydb get habits with user_id==current user AND game_id==game_id
    # current_user_habit_array = Habit.select().where((Habit.user_id == current_user.id) & (Habit.game_id == game_id))
    current_user_habit_array = Habit.select().where(
        (Habit.user_id == current_user.id) & (Habit.game_id == game_id))

    # for each habit, query log_habits table and get number of rows for that habit for current_round that r approved
    # compare to frequency number of the habit
    for habit in current_user_habit_array:

        # query loghabit table for rows belonging to habit/user which are approved
        # approved_logs = LogHabit.select().where((LogHabit.sender==current_user.id) & (LogHabit.habit_id == habit.id) & (LogHabit.approved==True) & (LogHabit.game_round_id == round_id))
        approved_logs = LogHabit.select().where(
            (LogHabit.sender == current_user.id)
            & (LogHabit.habit_id == habit.id) & (LogHabit.approved == True)
            & (LogHabit.game_round_id == round_id))

        # get length of list
        # compare length of list to frequency number
        if len(approved_logs) >= habit.frequency:
            # append to dice list
            dice_array += [1]
            num_dice += 1

    return render_template('rounds/show.html',
                           round=round,
                           round_id=round_id,
                           round_num=round_num,
                           num_dice=num_dice,
                           dice_array=dice_array,
                           player_variable=player_variable,
                           game_id=game_id,
                           roll_array=roll_array,
                           player_stats=player_stats,
                           opponent_stats=opponent_stats,
                           player_initiative=player_initiative,
                           opponent_initiative=opponent_initiative,
                           round_result=round_result,
                           winner=winner)
Ejemplo n.º 26
0
 def create_round(self, params):
     self.current_round = Round(**params)
     self.this_round = self.current_round.params
Ejemplo n.º 27
0
class RoundManager:
    """ Class of a round manager

        This class contains methods to create rounds and matches. It contains 4 methods:
        create_match: creates all the matches for a round by sorting the players from lowest rank
                    to highest rank, separating them in two lists and associating the players with
                    their index, making sure a match has not been already created.
        ask_score: asks the score of each player and adds it to the previous score.
        create_round: create a round from the params and puts it in the rounds dict.
        serialize_round: serialize a round.

        """
    def __init__(self):
        self.set_matches = set()
        self.this_round = {}
        self.current_round = None
        self.rounds = []
        self.utils = Utils()

    def create_match(self, players_list, nb_round):
        print("")
        print(f"Round n°{nb_round+1}")
        self.rounds.clear()

        sorted_players = sorted(players_list, key=lambda player: (player[1], player[0]['rank'],
                                                                  player[0]['last_name']))
        first_half = sorted_players[0:4]
        second_half = sorted_players[4:8]

        for i in range(4):
            next_player = 0
            match = (first_half[0], second_half[0])

            current_match = (match[0][0]['identifier'], match[1][0]['identifier'])
            inverted_current_match = current_match[::-1]

            if current_match not in self.set_matches and inverted_current_match not in self.set_matches:
                print(f"{match[0][0]['last_name']} {match[0][0]['first_name']} contre "
                      f"{match[1][0]['first_name']} {match[1][0]['last_name']}")
                first_half.pop(0)
                second_half.pop(0)
            elif len(first_half) == 1 and len(second_half) == 1:
                pass
            else:
                while True:
                    next_player += 1
                    match = (first_half[0], second_half[next_player])

                    current_match = (match[0][0]['identifier'], match[1][0]['identifier'])
                    inverted_current_match = current_match[::-1]

                    if current_match not in self.set_matches and inverted_current_match not in self.set_matches:
                        print(f"{match[0][0]['last_name']} {match[0][0]['first_name']} contre "
                              f"{match[1][0]['first_name']} {match[1][0]['last_name']}")
                        first_half.pop(0)
                        second_half.pop(next_player)
                        break
                    else:
                        continue

            self.set_matches.add(current_match)
            self.rounds.append(match)

    def ask_score(self, players_list):
        new_score = self.utils.ask_float(f"Score de {players_list[0]['last_name']} {players_list[0]['first_name']}: ")
        players_list[1] += float(new_score)

    def create_round(self, params):
        self.current_round = Round(**params)
        self.this_round = self.current_round.params

    def serialize_round(self):
        self.current_round.serialize()
Ejemplo n.º 28
0
def index(game_id, user_id):
    rounds = Round.select().where(Round.game_id == game_id)
    game = Game.get_by_id(game_id)
    return render_template('/rounds/index.html', rounds=rounds, game=game)
Ejemplo n.º 29
0
)
from controllers.controller import Controller
from models.enums import Gender
from models.enums import TimeControl
from models.tournament import Tournament
from models.player import Player
from models.round import Round
from models.carriers import TournamentCarrier
from models.carriers import PlayerCarrier
from views.menu import CYSMenu
from views.logger import Logger

my_matches = [{}]

my_rounds = [
    Round("round1", "21/21/21", "21/21/21", my_matches),
    Round("round2", "21/21/21", "21/21/21", my_matches),
    Round("round3", "21/21/21", "21/21/21", my_matches),
    Round("round4", "21/21/21", "21/21/21", my_matches)
]

my_player = Player("hey", "heythere", "23/12/1992", Gender.FEMALE, 129)

my_updated_player = Player("hey", "heythere", "23/11/1800", Gender.OTHER, 100)

my_players = [
    Player("Carrasco", "Michael", "23/12/1992", Gender.MALE, 299),
    Player("Myers", "Michael", "25/05/1963", Gender.MALE, 23),
    Player("Weaver", "Susan", "08/08/1949", Gender.FEMALE, 53),
    Player("Tobia", "Jacob", "07/06/1991", Gender.OTHER, 156),
    Player("Kasparof", "Garry", "13/04/1963", Gender.MALE, 2),
Ejemplo n.º 30
0
class ModelsController:

    def __init__(self) -> None:
        self.view_controller = ViewsController()
        self.menu_view = MenuView()
        self.player_view = PlayerView()
        self.round_view = RoundView()
        self.score = ScoreView()
        self.utilities_view = UtilitiesView()
        self.tournois_view = TournamentView()

        self.players: List = []

    def end_of_round(self, tournament):
        """End a round :
            - set an end time to round
            - update score
            - generate new round

        Args:
            tournament (tournament instance): tournament instance
        """
        try:
            round = tournament.round_list[-1]
            if round.end_round_datetime == 'Round en cours':
                round.stop_round()
                self.round_view.display_stop_time(round)
                self.update_score_round(round)
                self.generate_next_round(round, tournament)
            else:
                self.utilities_view.display_tournament_is_finished()
        except AttributeError:
            self.view_controller.display_error()

    def update_score_round(self, round):
        """Update player's score at the end of a round.

        Keyword arguments:
        round : Round -- instance of Round
        """

        for match in round.matchs:
            # On demande : qui est le vainqueur
            winner = self.score.update_score(match)
            # passer le score en variable de config
            if winner == 0:
                # match null
                match.score_player1 += SCORE_FOR_NULL
                match.score_player2 += SCORE_FOR_NULL
            elif winner == 1:
                # player 1 gagne
                match.score_player1 += SCORE_FOR_WINNER

            elif winner == 2:
                # player 2 gagne
                match.score_player2 += SCORE_FOR_WINNER

    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 DEMO_import_auto_players(self, players_number: int, tournois_obj: object):
        """DEMO : import players auto for a tournament


        Args:
            players_number (int): players number in the tournament
            tournois_obj (tournament instance): tournament instance
        """
        self.players = []
        for num_player in range(int(players_number)):
            player_infos = {
                "last_name": f'Nom {str(num_player+1)}',
                "first_name": f'Prénom {str(num_player+1)}',
                "date_of_birth": f'{random.randint(10, 28)}/{random.randint(10, 12)}/{random.randint(1950, 2021)}',
                "sex": 'M' if random.randint(0, 1) else 'F',
                "ranking": random.randint(300, 2000),
                "id": str(uuid1())}
            player_obj = Player()
            player_obj.add_player(player_infos)
            self.players.append(player_obj)
        self.bind_multiple_players_to_tournament(tournois_obj, self.players)
        self.players = []

    #  ______________________________________________________________________

    def create_multiple_player(self, player_info: dict):
        """Create player instance, add to players list

        Args:
            player_info (dict): player informations from user

        """
        player_obj = Player()
        player_obj.add_player(player_info)
        self.players.append(player_obj)

    def create_new_player(self, player_info):
        """Create a player instance

        Args:
            player_info (dict): player informations from user

        Returns:
            player instance
        """
        player_obj = Player()
        player_obj.add_player(player_info)
        return player_obj

    def ask_player_info(self, num_player: int) -> dict:
        """Input player informations, ask to user

        Args:
            num_player (int): player number to show
                - it can be number in the turnament
                - or count of all players

        Returns:
            dict: player info
        """
        player_info: dict = self.player_view.get_player_info(num_player + 1)
        id = str(uuid1())
        player_info['id'] = str(id)
        return player_info

    def check_players_list(self, tournament_obj):
        """Get a list of players without player already in the tournament

        Args:
            tournament_obj (tournament instance): tournament instance

        Returns:
            List : List of all players, without players already in the tournament
        """
        check_list = list(Player.LIST_PLAYERS)
        for player in tournament_obj.players_list:
            if player in check_list:
                check_list.remove(player)
        return check_list

    def import_players_manuel(self, players_number, tournament_obj):
        """Import player to a tournament
            - already saved player
            - Input new player

        Args:
            players_number (int): player number for this tournament
            tournament_obj (tournament instance): tournament instance where we wants to imports players
        """
        for num_player in range(int(players_number)):
            # check_list is a list of all players without players already binded with tournament
            check_list = self.check_players_list(tournament_obj)
            # Display menu if
            if len(check_list) != 0:
                while True:
                    selected_menu = self.menu_view.display_menu_add_player()
                    # Player already saved
                    if selected_menu == '1':
                        self.player_view.display_players_list(check_list)
                        player_id = int(self.menu_view.select_item('joueur'))
                        try:
                            player = check_list[player_id]
                        except IndexError:
                            self.utilities_view.display_error_with_message('Index non trouvé !!')
                        if player in tournament_obj.players_list:
                            self.utilities_view.display_error_with_message('Joueur déjà enregistré dans ce tournoi !!')
                        else:
                            self.bind_player_to_tournament(tournament_obj, player)
                            break
                    # input new player
                    elif selected_menu == '2':
                        player_info = self.ask_player_info(num_player)
                        player = self.create_new_player(player_info)
                        self.bind_player_to_tournament(tournament_obj, player)
                        break
                    else:
                        self.utilities_view.display_error()
            # input new player
            else:
                player_info = self.ask_player_info(num_player)
                player = self.create_new_player(player_info)
                self.bind_player_to_tournament(tournament_obj, player)

    def add_multiple_players(self, players_number: int, tournament_obj: object):
        """Add players to a tournament.

        Keyword arguments:
        players_number : int -- number of players to add
        """
        selected_menu = self.menu_view.import_auto_or_manuel_menu()
        self.player_import_type(selected_menu, players_number, tournament_obj)

    def player_import_type(self, selected_menu, players_number, tournois_obj):
        """Select a way to import players :
                - auto
                - manuel

        Args:
            selected_menu (int): selection by user
            players_number (int): number for a player
            tournois_obj (tournament instance): instance du tournoi.
        """
        # import auto
        if selected_menu == '1':
            self.DEMO_import_auto_players(players_number, tournois_obj)
        # import manuel
        elif selected_menu == '2':
            self.import_players_manuel(players_number, tournois_obj)
        else:
            self.view_controller.display_error()

    def bind_player_to_tournament(self, tournament_obj, player_obj):
        """Bind player to a tournament :
            Add player instance to a list in the tournament instance.

        Args:
            tournament_obj (Tournament instance): tournament where we want to link players
            player_obj (Player instance): player we want to link
        """
        tournament_obj.bind_player(player_obj)

    def bind_multiple_players_to_tournament(self, tournament_obj: object, players: List[Player]):
        """Add players lists to tournament.

        Keyword arguments:
        tournois_obj : Tournament -- Instance of Tournament
        players : [Player] -- List of Player's instance
        """
        tournament_obj.bind_multiple_players(players)

    def generate_first_round(self, tournois_obj):
        """Create first round.

        Keyword arguments:
        tournois_obj : Tournament -- Instance de class Tournament
        """
        # generate_first_round renvoi une liste de tuple
        # => pair de joueur [(player1, player2), (player1, player2), ...]
        first_round_list = Suisse().generate_first_round(tournois_obj.players_list)
        self.round = Round().create_round('Round 1')
        for players in first_round_list:
            # Create match instance - init score
            match = Match().create_match(players[0], 0, players[1], 0)
            self.round.add_match_to_round(match)
        #  Création du match suivant, et affichage des prochains matchs
        tournois_obj.add_round(self.round)
        RoundView().start_new_round(self.round)
        self.view_controller.display_match_of_round(self.round)

    def generate_next_round(self, previous_round, tournois_obj):
        """Create the next round.

        Keyword arguments:
        previous_round : Round -- round instance that has just ended
        tournois_obj : Tournament -- Instance of Tournament
        """
        # Check tour number
        if len(tournois_obj.round_list) < DEFAULT_TOUR_NUMBER:

            match_list = Suisse().generate_next_round(previous_round, tournois_obj)

            self.round = Round().create_round(f'Round {len(tournois_obj.round_list)+1}')
            RoundView().start_new_round(self.round)
            for match in match_list:
                formated_match = Match().create_match(match[0][0], match[0][1], match[1][0], match[1][1])
                self.round.add_match_to_round(formated_match)
            tournois_obj.add_round(self.round)
            self.view_controller.display_match_of_round(self.round)

        # end of tournament => display final score
        else:
            # récupérer la liste triée:
            players = Suisse().get_players_list_with_score(tournois_obj.round_list[-1])
            sorted_list = Suisse().sort_list_by_score(players)
            self.score.display_final_score(sorted_list)
            tournois_obj.set_final_score(sorted_list)
            print("Fin du tournois")

    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 get_ended_tournament(seld):
        ended_tournament = []
        for tournament in Tournament.TOURNAMENT_LIST:
            if ((tournament.round_list[-1].end_round_datetime != 'Round en cours') and
                    (len(tournament.round_list) == int(tournament.tour_number))):
                ended_tournament.append(tournament)
        return ended_tournament