Ejemplo n.º 1
0
    def play_against(self,
                     opponent: Player,
                     game: Connect4Game = Connect4Game()):
        """
        Make the agent play against another player on the given game or a new game.
        If both player have the same game turn id, self will change its game turn id
        Returns the winner
        :param opponent: another player
        :param game: The current game, if nothing specified then a new game
        :return: the winner (0 for draw, 1 for player 1, 2 for player 2
        """
        if self.player_turn_id == opponent.player_turn_id:
            self.player_turn_id = 3 - self.player_turn_id
        yellow_goes_first = game.get_turn() == 1
        winner = game.get_win()
        while winner is None:
            if game.get_turn() == self.player_turn_id:
                game.place(self.choose_action(game))
            else:
                game.place(opponent.choose_action(game))
            winner = game.get_win()

        if winner != 0 and not yellow_goes_first:
            winner = 3 - winner
        return winner
 def choose_action(self, game: Connect4Game) -> int:
     best_substring = ""
     letter = None
     for gh_i in range(len(game.history)):
         for chromo in self.chromosomes:
             if chromo[-1] != str(game.get_turn()):
                 continue
             substring = game.history[gh_i:-2]
             index = chromo.rfind(substring)  # Search from the end
             # If we found the substring and is longer than the previous best
             # and that it is not the game outcome
             if index != -1 and len(substring) > len(best_substring):
                 best_substring = substring
                 letter = chromo[index + len(best_substring)].lower()
     # If nothing was found
     if letter is None or game.history.count(
             letter.lower()) + game.history.count(letter.upper()) >= 6:
         action = random.randint(0, 6)
     else:
         action = ord(letter) - ord("a")
     return action