Beispiel #1
0
def play(game):
    """
    :param game: game board of the desired game
    :return:
    """

    while True:
        playerMove = get_player_move(game)
        game = game.move(playerMove)
        if game.is_win:
            print("Human wins!")
            break
        elif game.is_draw:
            print("Draw!")
            break
        aiMove = minimax.find_best_move(game, 5)
        print(f"Computer move is {aiMove}")
        game = game.move(aiMove)
        print(game)
        if game.is_win:
            print("Computer wins!")
            break
        elif game.is_draw:
            print("Draw!")
            break
    def mainLoop(self):
        isPlaying = True

        while isPlaying:
            # Make a move
            if self.current_player == self.player:
                position = int(input('Type position: ')) - 1
                move = [(position // 3), (position % 3)]
                while (not self.isValidMove(move)):
                    print('That wasn\'t a valid move. \nTry again: ')
                    position = int(input('Type position: ')) - 1
                    move = [(position // 3), (position % 3)]
                self.playMove(move, self.player)
            else:
                move = minimax.find_best_move(deepcopy(self.board))
                self.playMove(move, self.computer)

            # Change Player
            self.changePlayer()

            # Print Game
            self.printGame()

            # Check for end of Game
            state = self.checkForWin()
            if state == self.player:
                print('Player won')
            elif state == self.computer:
                print('Computer won')
            elif state == 1:
                print("Draw")

            # changes isPlaying state if the game has terminated
            if state != 0:
                isPlaying = False
Beispiel #3
0
 def test_block_position(self):
     # must block C's win
     to_block_position: List[RotaPlayer] = [RotaPlayer.P, RotaPlayer.E, RotaPlayer.C,
                                            RotaPlayer.E, RotaPlayer.C, RotaPlayer.E,
                                            RotaPlayer.E, RotaPlayer.P, RotaPlayer.E]
     test_board2: RotaBoard = RotaBoard(to_block_position, RotaPlayer.P)
     answer2: Move = find_best_move(test_board2)
     self.assertEqual(answer2, (-1, 6))
Beispiel #4
0
 def test_easy_position(self):
     # win in 1 move
     to_win_easy_position: List[RotaPlayer] = [RotaPlayer.P, RotaPlayer.C, RotaPlayer.P,
                                               RotaPlayer.E, RotaPlayer.E, RotaPlayer.C,
                                               RotaPlayer.P, RotaPlayer.E, RotaPlayer.C]
     test_board1: RotaBoard = RotaBoard(to_win_easy_position, RotaPlayer.P)
     answer1: Move = find_best_move(test_board1)
     self.assertEqual(answer1, (0, 4))
 def test_block_position(self):
     # must block O's win
     to_block_position: List[TTTPiece] = [TTTPiece.X, TTTPiece.E, TTTPiece.E,
                                          TTTPiece.E, TTTPiece.E, TTTPiece.O,
                                          TTTPiece.E, TTTPiece.X, TTTPiece.O]
     test_board2: TTTBoard = TTTBoard(to_block_position, TTTPiece.X)
     answer2: Move = find_best_move(test_board2)
     self.assertEqual(answer2, 2)
 def test_hard_position(self):
     # find the best move to win 2 moves
     to_win_hard_position: List[TTTPiece] = [TTTPiece.X, TTTPiece.E, TTTPiece.E,
                                             TTTPiece.E, TTTPiece.E, TTTPiece.O,
                                             TTTPiece.O, TTTPiece.X, TTTPiece.E]
     test_board3: TTTBoard = TTTBoard(to_win_hard_position, TTTPiece.X)
     answer3: Move = find_best_move(test_board3)
     self.assertEqual(answer3, 1)
 def test_easy_position(self):
     # win in 1 move
     to_win_easy_position: List[TTTPiece] = [TTTPiece.X, TTTPiece.O, TTTPiece.X,
                                             TTTPiece.X, TTTPiece.E, TTTPiece.O,
                                             TTTPiece.E, TTTPiece.E, TTTPiece.O]
     test_board1: TTTBoard = TTTBoard(to_win_easy_position, TTTPiece.X)
     answer1: Move = find_best_move(test_board1)
     self.assertEqual(answer1, 6)
 def test_starting_position(self):
     starting_position: List[TTTPiece] = [
         TTTPiece.E, TTTPiece.E, TTTPiece.E, TTTPiece.E, TTTPiece.E,
         TTTPiece.E, TTTPiece.E, TTTPiece.E, TTTPiece.E
     ]
     test_board1: TTTBoard = TTTBoard(starting_position, TTTPiece.X)
     answer1: Move = find_best_move(test_board1)
     print(f"Best 1st move: {answer1}")
     self.assertTrue(True)
    def test_hard_position(self) -> None:
        to_win: List[TTTPiece] = [
            TTTPiece.X, TTTPiece.E, TTTPiece.E, TTTPiece.E, TTTPiece.E,
            TTTPiece.O, TTTPiece.O, TTTPiece.X, TTTPiece.E
        ]

        test_board3: TTTBoard = TTTBoard(to_win, TTTPiece.X)
        answer3: Move = find_best_move(test_board3)
        self.assertEqual(answer3, 1)
    def test_block_position(self) -> None:
        to_block: List[TTTPiece] = [
            TTTPiece.X, TTTPiece.E, TTTPiece.E, TTTPiece.E, TTTPiece.E,
            TTTPiece.O, TTTPiece.E, TTTPiece.X, TTTPiece.O
        ]

        test_board2: TTTBoard = TTTBoard(to_block, TTTPiece.X)
        answer2: Move = find_best_move(test_board2)
        self.assertEqual(answer2, 2)
Beispiel #11
0
 def test_hard_position(self):
     # X走一步之后,下一步无论O怎么走都无法阻止X赢
     to_win_hard_position: List[TTTPiece] = [TTTPiece.X,TTTPiece.E,TTTPiece.E,
                                             TTTPiece.E,TTTPiece.E,TTTPiece.O,
                                             TTTPiece.O,TTTPiece.X,TTTPiece.E]
     test_board3: TTTBoard = TTTBoard(to_win_hard_position,
                                      TTTPiece.X)
     answer3: Move = find_best_move(test_board3)
     self.assertEqual(answer3, 1)
Beispiel #12
0
 def test_block_position(self):
     # Should block O's winning.
     to_block_position = [
         TicTacToePiece.X, TicTacToePiece.E, TicTacToePiece.E,
         TicTacToePiece.E, TicTacToePiece.E, TicTacToePiece.O,
         TicTacToePiece.E, TicTacToePiece.X, TicTacToePiece.O
     ]
     test_board = TicTacToeBoard(to_block_position, TicTacToePiece.X)
     answer = find_best_move(test_board)
     self.assertEqual(answer, 2)
Beispiel #13
0
 def test_easy_position(self):
     # X should win.
     to_win_easy_position = [
         TicTacToePiece.X, TicTacToePiece.O, TicTacToePiece.X,
         TicTacToePiece.X, TicTacToePiece.E, TicTacToePiece.O,
         TicTacToePiece.E, TicTacToePiece.E, TicTacToePiece.O
     ]
     test_board = TicTacToeBoard(to_win_easy_position, TicTacToePiece.X)
     answer = find_best_move(test_board)
     self.assertEqual(answer, 6)
Beispiel #14
0
 def test_hard_position(self):
     # Find the best move considering 2-left turns.
     to_win_hard_position = [
         TicTacToePiece.X, TicTacToePiece.E, TicTacToePiece.E,
         TicTacToePiece.E, TicTacToePiece.E, TicTacToePiece.O,
         TicTacToePiece.O, TicTacToePiece.X, TicTacToePiece.E
     ]
     test_board = TicTacToeBoard(to_win_hard_position, TicTacToePiece.X)
     answer = find_best_move(test_board)
     self.assertEqual(answer, 1)
def computer_play(board: Board, search_depth: int = 5) -> Tuple[bool, Board]:
    end_of_game: bool = False

    computer_move: Move = find_best_move(board, search_depth)
    print(f"Computer move is {computer_move}")
    board = board.move(computer_move)
    print(board)
    if board.is_win:
        print(f"{board.turn.opposite} wins!")
        end_of_game = True
    elif board.is_draw:
        print("Draw!")
        end_of_game = True
    return end_of_game, board
Beispiel #16
0
 def test_block_position(self):
     # must block O's to win
     to_block_position: List[TTTPiece] = [
         TTTPiece.X,
         TTTPiece.E,
         TTTPiece.E,
         TTTPiece.E,
         TTTPiece.E,
         TTTPiece.O,
         TTTPiece.E,
         TTTPiece.X,
         TTTPiece.O,
     ]
     test_board2: TTTBoard = TTTBoard(to_block_position, TTTPiece.X)
     answer2: Move = find_best_move(test_board2)
     # the best move is to block at Sq 2, the top right sq
     self.assertEqual(answer2, 2)
Beispiel #17
0
    def place_symbol(self):
        global board, empty

        # human
        if self.player == "x":
            x_pos, y_pos = pg.mouse.get_pos()[0], pg.mouse.get_pos()[1]
            x, y = self.which_box(x_pos, "x"), self.which_box(y_pos, "y")
            if x == None or y == None:
                return

        # cpu
        if self.player == "o":
            (x, y) = minimax.find_best_move(board)
            (x, y) = (x*2 + 1, y*2 + 1)

        screen.blit(self.image, (x * (WIDTH // 6) - self.size[0] // 2, y * (HEIGHT // 6) - self.size[1] // 2))
        empty.remove((x, y))
        board[(y-1)//2][(x-1)//2] = self.player
    def AI_turn(self):
        # X (1) -> AI
        # Random choice of first AI move, second in general (for computation reasons):
        if self.turns == 0:
            x = random.randint(0, 2)
            y = random.randint(0, 2)

            if self.TILEMAP[x][y] == 0:
                self.TILEMAP[x][y] = 1  # make a move

                self.turns += 1
                print("### TURN: {} ###".format(self.turns))
                print(mm.print_board(self.TILEMAP))
                print("\n")

                self.game.turn = "human"  # change the turn
                self.game.is_human_turn = True
        # Use of mini-max algorithm for the choice of move
        elif self.turns > 0:
            if not self.game.is_filled():
                current_board = self.TILEMAP

                best_move = mm.find_best_move(current_board)
                x, y = best_move[0], best_move[1]
                self.TILEMAP[x][y] = 1  # make a move

                self.turns += 1
                print("### TURN: {} ###".format(self.turns))
                print(mm.print_board(self.TILEMAP))
                print("\n")
                print("BEST MOVE: {}".format(best_move))
                print("\n")

                self.game.turn = "human"  # change the turn
                self.game.is_human_turn = True
            else:
                self.game.draw()

                print("Board filled!")

                self.game.check_for_win(self.id, 1)
                pg.time.wait(2000)

                self.game.playing = False
Beispiel #19
0
 def test_easy_position(self):
     # win in 1 move
     to_win_easy_position: List[TTTPiece] = [
         TTTPiece.X,
         TTTPiece.O,
         TTTPiece.X,
         TTTPiece.X,
         TTTPiece.E,
         TTTPiece.O,
         TTTPiece.E,
         TTTPiece.E,
         TTTPiece.O,
     ]
     # pass in the current positions and turn to the TTTBoard
     test_board1: TTTBoard = TTTBoard(to_win_easy_position, TTTPiece.X)
     # use find_best_move function to find the best move
     answer1: Move = find_best_move(test_board1)
     # the winning move should be Sq 6, the bottom left sq
     self.assertEqual(answer1, 6)
Beispiel #20
0
def computer_move():
    s = ''.join(
        str(item) for innerlist in session["board"] for item in innerlist)
    # Bepaal beste zet voor de computer. find_best_move(board, player)
    print(f"Bord: {s} en zet voor {session['turn']}")
    pos = minimax.find_best_move(s, session['turn'])
    pos_row = pos % 3
    pos_col = pos // 3
    print(f"Beste zet op positie: {pos+1}, dat is: {pos_row}-{pos_col}")
    #redirect(url_for("play", row=pos_row, col=pos_col))
    session["board"][pos_col][pos_row] = session["turn"]
    session["moves"] += 1
    session["turn"] = "X" if session["turn"] == "O" else "O"
    s = ''.join(
        str(item) for innerlist in session["board"] for item in innerlist)
    if minimax.evalueer_bord(s, "X"):
        session["won"] = "X"
    elif minimax.evalueer_bord(s, "O"):
        session["won"] = "O"
    return (redirect(url_for("index")))
Beispiel #21
0
def play(game, max_depth):
    board = board_factory(game)
    while True:
        human_move: Move = get_player_move(board)
        board = board.move(human_move)
        if board.is_win:
            print("Human wins!")
            break
        elif board.is_draw:
            print("Draw!")
            break
        computer_move: Move = find_best_move(board, max_depth)
        print(f"Computer move is {computer_move}")
        board = board.move(computer_move)
        print(board)
        if board.is_win:
            print("Computer wins!")
            break
        elif board.is_draw:
            print("Draw!")
            break
Beispiel #22
0
 def setMove(self, value):
     mx, my = value
     player_move = (my // CELL_HEIGHT * 3) + (mx // CELL_WIDTH)
     if player_move in self._board.legal_moves:
         self._board = self._board.move(Move(player_move))
         self._grid.pic(PLAYER, player_move)
         if self._board.is_win:
             self._game_over = True
             self._msgBox.active = STATUS.WIN
         elif self._board.is_draw:
             self._game_over = True
             self._msgBox.active = STATUS.DRAW
         if not self._game_over:
             computer_move = find_best_move(self._board)
             self._board = self._board.move(Move(computer_move))
             self._grid.pic(COMPUTER, computer_move)
             if self._board.is_win:
                 self._game_over = True
                 self._msgBox.active = STATUS.LOS
             elif self._board.is_draw:
                 self._game_over = True
                 self._msgBox.active = STATUS.DRAW

def get_player_move() -> Move:
    player_move: Move = Move(-1)
    while player_move not in board.legal_moves:
        play: int = int(input("Enter a legal square (0-8):"))
        player_move = Move(play)
    return player_move


if __name__ == "__main__":
    while True:
        human_move: Move = get_player_move()
        board = board.move(human_move)
        if board.is_win:
            print("Human wins!")
            break
        elif board.is_draw:
            print("Draw!")
            break
        computer_move: Move = find_best_move(board)
        print(f"Computer move is {computer_move}")
        board = board.move(computer_move)
        print(board)
        if board.is_win:
            print("Computer wins!")
            break
        elif board.is_draw:
            print("Draw!")
            break
Beispiel #24
0

def get_player_move() -> Move:
    player_move = Move(-1)
    while player_move not in board.legal_moves:
        move = int(input('Move to (0-6): '))
        player_move = Move(move)
    return player_move


if __name__ == "__main__":
    while True:
        human_move = get_player_move()
        board = board.move(human_move)
        if board.is_done:
            print("You win!")
            break
        elif board.is_draw:
            print("Draw!")
            break
        computer_move = find_best_move(board, 3)
        print("Computer moved to %d." % computer_move)
        board = board.move(computer_move)
        print(board)
        if board.is_done:
            print("You lose!")
            break
        elif board.is_draw:
            print("Draw!")
            break