Пример #1
0
class MatchResultController:
    """
    This controller allows to write results and save in the database.
    """
    def __init__(self):
        self.round_view = RoundView()
        self.match_view = MatchView()

    def __call__(self):
        if len(Database().all_tournaments_in_progress()) == 0:
            self.round_view.error_no_active_tournament()
            return HomeMenuController()
        else:
            self.tournament = Database().all_tournaments_in_progress()[0]

        self.match_view.display_active_tournament(self.tournament)
        self.players = self.tournament.get_players_from_tournament()

        if len(self.tournament.rounds) != 0:
            pairs = flatten_list(list(self.tournament.rounds[-1].values()))
        else:
            pairs = []

        left_matches = len(self.tournament.matches_not_played(pairs))
        self.round_view.display_if_round_over(left_matches)
        if left_matches > 0:
            if left_matches == 1:
                self.check_if_tournament_is_over(left_matches)
            pairs = self.tournament.matches_not_played(pairs)
        else:
            pairs = self.tournament.sorted_pairs(self.players)
            self.tournament.create_round()

            self.tournament.save_pairs_in_db(pairs)

        pairs = self.tournament.matches_not_played(pairs)
        self.match_view.display_matches(
            self.tournament.get_name_from_ids(pairs))

        pair_played_choice = int(self.match_view.get_match_played())
        pair = pairs[pair_played_choice]
        self.tournament.add_matches_in_tournament(pair)

        self.set_point(pair)

        return HomeMenuController()

    def check_if_tournament_is_over(self, left_matches):
        """
        Check if the tournament has left rounds if there is no left round, the tournament switches off to False for
        "is_active" and it means the tournament is over.
        """
        if left_matches == 1:
            self.tournament.update_end_round()
            if self.tournament.left_round == 0:
                self.tournament.is_active = False
                self.tournament.save_in_db()

    def set_point(self, pair):
        """
        Attribute points to each foe if it is a draw, the result of the match is a "D"
        """
        draw = self.match_view.ask_if_draw()

        if draw == 'N':
            winner = int(self.match_view.get_the_winner())
            self.tournament.winner_match(winner)
            self.tournament.create_match(pair, winner)
        else:
            self.tournament.draw_match(pair)
            self.tournament.create_match(pair, "D")