Ejemplo n.º 1
0
 def __init__(self, playerXType, playerOType):
     self.game = ConnectFour()
     self.state = gameState.X
     self.playerXType = playerXType
     self.playerOType = playerOType
     self.result = None
     if self.playerXType == playerType.Human and self.playerOType == playerType.Human:
         self.runHumanGame()
Ejemplo n.º 2
0
def connect4():
    global game, bot, moving
    # reset moving
    moving = False
    game = ConnectFour()
    # randomize the first player
    game.active_player = random.choice([0, 1])
    # set the bot to be the best generalizeable bot we have (with a solid speed)
    bot = AdvisedMonteCarloPlayer(7, 2, 4)
    return render_template("connect4.html", player=game.active_player)
Ejemplo n.º 3
0
def play_sample_game_with_model(model) -> None:
    sample_state = ConnectFour()

    while not sample_state.is_game_over():
        if sample_state.turn == sample_state.BLACK:
            sample_state.make_random_move()
        else:
            state_representation = generate_state_representation(sample_state)
            state_representation = torch.from_numpy(
                state_representation).float().cuda()
            state_representation = state_representation.view(1, 3, 6, 7)

            with torch.no_grad():
                predicted_policy, predicted_value = model(state_representation)

            predicted_policy = predicted_policy[0].cpu()
            predicted_value = predicted_value[0].cpu()

            print("NN Policy:", predicted_policy)
            print("NN Value:", predicted_value)

            best_move = np.argmax(predicted_policy)
            while best_move not in sample_state.legal_moves:
                predicted_policy[best_move] = -999
                best_move = np.argmax(predicted_policy)

            sample_state.make_move(best_move)

        sample_state.print_board()
Ejemplo n.º 4
0
    def newGame(self, p1type='random', p2type='random'):
        # Ask for players' names
        self.p1 = 'Blue'
        self.p2 = 'Red'

        self.game = ConnectFour(p1type=p1type, p2type=p2type)
        self.canvas.delete(ALL)
        self.canvas.config(width=(self.elementSize) * self.game.size['c'],
                           height=(self.elementSize) * self.game.size['r'])
        self.drawGrid()
        self.drawGameState()
        self.master.update()  # Rerender window
Ejemplo n.º 5
0
def main():
    """ Play a game!
    """
    connect_four = ConnectFour()
    menu_choice = 1
    while menu_choice == 1:
        # start the game
        connect_four.start_new()
        # menu
        print("Menu")
        print("1 - Play again")
        print("2 - Quit")
        menu_choice = int(raw_input("choice : "))
Ejemplo n.º 6
0
def main():
    """ Play a game!
    """
    import numpy as np
    import os
    if os.path.isfile('playing_sequence.npy'):
        arr=np.load('playing_sequence.npy')
    else:
        connect_four = ConnectFour()
        connect_four.start_new() 
        arr=np.load('playing_sequence.npy')  
    
    menu_choice = 1
    
    batch_size=2
Ejemplo n.º 7
0
def main():
    connect_four = ConnectFour(settings.HUMAN_PLAYER, settings.AI_PLAYER)
    is_playing = True

    while is_playing:
        connect_four.play()
        connect_four.display_game_results()
        connect_four.display_overall_results()
        
        play_again = replay()

        if play_again == "no":
            is_playing = False
        else:
            connect_four.restart()
        
    print("Thank you for playing!")
Ejemplo n.º 8
0
class Game:
    def __init__(self, playerXType, playerOType):
        self.game = ConnectFour()
        self.state = gameState.X
        self.playerXType = playerXType
        self.playerOType = playerOType
        self.result = None
        if self.playerXType == playerType.Human and self.playerOType == playerType.Human:
            self.runHumanGame()

    def get_result(self):
        return self.result

    def runHumanGame(self):
        #human vs human game
        if (self.playerXType == playerType.Human
                and self.playerOType == playerType.Human):
            while self.state is not gameState.Gameover:
                print(self.game.board_to_string())
                placement_state = PlacementState.fail
                (row, col) = (-1, -1)
                if self.state == gameState.X:
                    while placement_state is not PlacementState.success:
                        colInput = int(
                            input(
                                "It is X's turn. Please type which column you would like your piece to go in:"
                            ))
                        (placement_state,
                         (row,
                          col)) = self.game.place_piece(colInput, Piece.X)
                    if self.game.check_for_winner(row, col):
                        self.state = gameState.Gameover
                        self.result = gameResult.X
                        print(self.state.value + "wins!")
                    elif self.game.is_tie():
                        self.state = gameState.Gameover
                        self.result = gameResult.Tie
                        print("the game has ended in a tie!")
                    self.state = gameState.O

                elif self.state == gameState.O:
                    while placement_state is not PlacementState.success:
                        colInput = int(
                            input(
                                "It is O's turn. Please type which column you would like your piece to go in:"
                            ))
                        (placement_state,
                         (row,
                          col)) = self.game.place_piece(colInput, Piece.O)
                    if self.game.check_for_winner(row, col):
                        self.state = gameState.Gameover
                        self.result = gameResult.O
                        print(self.state.value + "wins!")
                    elif self.game.is_tie():
                        self.state = gameState.Gameover
                        self.result = gameResult.Tie
                        print("the game has ended in a tie!")
                    self.state = gameState.X
Ejemplo n.º 9
0
def test_board_size():
    game = ConnectFour()
    player = 1
    game.player = player
    with pytest.raises(IndexError):
        game.insert_disc(8)

    with pytest.raises(IndexError):
        for _ in range(8):
            game.insert_disc(0)
Ejemplo n.º 10
0
def test_insert_disc():
    game = ConnectFour()
    col = 1
    player = 1
    game.player = player
    game.insert_disc(col)
    msg = "insert disc into (0,0)"
    assert game.get_board_cell(0, col) == player, msg
Ejemplo n.º 11
0
def test_insert_disc_on_top():
    game = ConnectFour()
    player = 1
    game.player = player
    col = 2
    for _ in range(3):
        game.insert_disc(col)
    msg = "insert disc of player 1 into (2,2)"
    assert game.get_board_cell(2, col) == player, msg
Ejemplo n.º 12
0
        winner = original_game.who_won()
        if winner is None:
            # list of MonteCarloEvaluation objects for each game
            lower_level = [
                monte_carlo_eval(game, player_number, main_player, rewards,
                                 simulation_amount, depth - 1, opponent)
                for game in original_game.get_next_level()
            ]
            # average the values across the same level
            return MonteCarloEvaluation(
                sum([e.value for e in lower_level]) / len(lower_level),
                sum([e.simulations for e in lower_level]))
        else:
            # game is finished, so use winner_eval
            return MonteCarloEvaluation(
                winner_eval(winner, player_number, rewards).value,
                simulation_amount)


if __name__ == "__main__":
    from tic_tac_toe import TicTacToe
    from connect_four import ConnectFour
    from players import RandomPlayer
    import random

    g = TicTacToe()
    g = ConnectFour()
    player = RandomPlayer()
    for i in range(100):
        print(monte_carlo_eval(g, 0, player, [1, -1, 0], 5, 3))
        print(monte_carlo_eval(g, 0, player, [0, 0, 1], 5, 3))
Ejemplo n.º 13
0
class GUI:
    elementSize = 80
    gridBorder = 3
    gridColor = "#AAA"
    p1Color = "#4096EE"
    p2Color = "#FF1A00"
    backgroundColor = "#FFFFFF"

    def __init__(self, master):
        self.master = master

        master.title('Connect Four')

        label = Label(master, text="Connect Four")
        label.grid(row=0)

        button = Button(master,
                        text="New Game, you can play by yourself!",
                        command=self._newGameButton)
        button.grid(row=1)

        button1 = Button(master,
                         text="New Game (random vs random)!",
                         command=self._newGameButtonRandom)
        button1.grid(row=2)

        button1 = Button(master,
                         text="New Game - random vs heuristic!",
                         command=self._newGameButtonOptimized)
        button1.grid(row=3)

        self.canvas = Canvas(master,
                             background=self.backgroundColor,
                             highlightthickness=0)
        self.canvas.grid(row=4)

        self.currentPlayerVar = StringVar(self.master, value="")
        self.currentPlayerLabel = Label(self.master,
                                        textvariable=self.currentPlayerVar,
                                        anchor=W)
        self.currentPlayerLabel.grid(row=5)

        self.canvas.bind('<Button-1>', self._canvasClick)
        self.newGame()

    def drawGameState(self):
        #sleep(0.3)
        max_row = self.game.size['r'] - 1
        for c in range(self.game.size['c']):
            for r in range(self.game.size['r']):

                x0 = c * self.elementSize
                y0 = (max_row - r) * self.elementSize
                x1 = (c + 1) * self.elementSize
                y1 = ((max_row - r) + 1) * self.elementSize
                if self.game.gameState[r][c] == 1:
                    fill = self.p1Color
                    self.canvas.create_oval(
                        x0 + 2,
                        self.canvas.winfo_height() - (y0 + 2),
                        x1 - 2,
                        self.canvas.winfo_height() - (y1 - 2),
                        fill=fill,
                        outline=self.gridColor)

                elif self.game.gameState[r][c] == (-1):
                    fill = self.p2Color
                    self.canvas.create_oval(
                        x0 + 2,
                        self.canvas.winfo_height() - (y0 + 2),
                        x1 - 2,
                        self.canvas.winfo_height() - (y1 - 2),
                        fill=fill,
                        outline=self.gridColor)

    def drawGrid(self):
        x0, x1 = 0, self.canvas.winfo_width()
        for r in range(1, self.game.size['r']):
            y = r * self.elementSize
            self.canvas.create_line(x0, y, x1, y, fill=self.gridColor)

        y0, y1 = 0, self.canvas.winfo_height()
        for c in range(1, self.game.size['c']):
            x = c * self.elementSize
            self.canvas.create_line(x, y0, x, y1, fill=self.gridColor)

    def newGame(self, p1type='random', p2type='random'):
        # Ask for players' names
        self.p1 = 'Blue'
        self.p2 = 'Red'

        self.game = ConnectFour(p1type=p1type, p2type=p2type)
        self.canvas.delete(ALL)
        self.canvas.config(width=(self.elementSize) * self.game.size['c'],
                           height=(self.elementSize) * self.game.size['r'])
        self.drawGrid()
        self.drawGameState()
        self.master.update()  # Rerender window

    def _updateCurrentPlayer(self):
        self.game.update_player()
        if (self.game.player == 1):
            p = self.p1
        else:
            p = self.p2
        self.currentPlayerVar.set('Current player: ' + p)

    def drawAndCheckForWinning(self):
        self.drawGameState()
        # evaluate game state
        if Helper.move_was_winning_move(self.game.gameState, self.game.player):
            self.game.noWinnerYet = False
            x = self.canvas.winfo_width() // 2
            y = self.canvas.winfo_height() // 2
            if self.game.player == 1:
                winner = self.p1
            else:
                winner = self.p2
            t = winner + ' won!'
            self.canvas.create_text(x,
                                    y,
                                    text=t,
                                    font=("Helvetica", 32),
                                    fill="#333")
        elif (self.game.move_still_possible(self.game.gameState) == 0):
            self.game.noWinnerYet = False
            x = self.canvas.winfo_width() // 2
            y = self.canvas.winfo_height() // 2
            self.canvas.create_text(x,
                                    y,
                                    text='there is a draw',
                                    font=("Helvetica", 32),
                                    fill="#333")

    def _canvasClick(self, event):
        if not self.game.noWinnerYet: return
        if Helper.move_was_winning_move(self.game.gameState, self.game.player):
            return

        c = event.x // self.elementSize
        if (0 <= c < self.game.size['c']):
            if (self.game.drop(c)):
                self.drawAndCheckForWinning()
                self._updateCurrentPlayer()

    def sleepInGame(self):
        sleep(0.2)
        self.master.update()  # Rerender window

    def game_loop(self):
        while (self.game.noWinnerYet):
            self.game.drop()
            self.drawAndCheckForWinning()
            self._updateCurrentPlayer()
            self.sleepInGame()

    def _newGameButton(self):
        self.newGame(p1type='manual', p2type='manual')
        while (self.game.noWinnerYet and 0 not in self.game.gameState[0]):
            if (self.game.drop()):
                self.drawAndCheckForWinning()
                self._updateCurrentPlayer()
                self.sleepInGame()

    def _newGameButtonRandom(self):
        self.newGame(p1type='random', p2type='random')
        self.game_loop()

    def _newGameButtonOptimized(self):
        self.newGame(p1type='random', p2type='minmax')
        self.game_loop()
Ejemplo n.º 14
0
    r = jsonify({
        'winner': winning_player_id,
        'squares': squares,
        'board': board.values.tolist(),
    })

    return r


@app.route('/return_board')
def return_board():
    data = connect_four.return_board()
    r = Response(data)

    return r


@app.route('/clear_board')
def clear_board():
    connect_four.clear_board()

    data = connect_four.return_board()
    r = Response(data)

    return r


if __name__ == '__main__':
    connect_four = ConnectFour()
    app.run(debug=True)
Ejemplo n.º 15
0
def test_class():
    assert ConnectFour() != None, "has class"