Exemplo n.º 1
0
def minimax(tabuleiro, depth, alpha, beta, maximizingPlayer, current_move, player):
    best_move = current_move
    score = tabuleiro.calculate_board_score(player)

    if depth == 0 or score == inf:
        return score, current_move

    possible_moves = utils.get_possible_moves(tabuleiro.get_board())

    if maximizingPlayer:
        maxEval = -inf
        for move in possible_moves:
            evalue, pos = minimax(utils.make_move(copy.deepcopy(tabuleiro), move, 1), depth-1, alpha, beta, False, move, player)
            if maxEval < evalue:
                maxEval = evalue
                best_move = move
            alpha = max(alpha, evalue)
            if alpha >= beta:
                break

        return maxEval, best_move
    else:
        minEval = inf
        for move in possible_moves:
            evalue, pos = minimax(utils.make_move(copy.deepcopy(tabuleiro), move, 2), depth - 1, alpha, beta, True, move, player)
            if minEval > evalue:
                minEval = evalue
                best_move = move
            beta = min(beta, evalue)
            if alpha >= beta:
                break

        return minEval, best_move
Exemplo n.º 2
0
def minimax_ai(board, player):
    valid_moves = utils.get_valid_moves(board)
    best_move = None
    best_score = None
    for move in valid_moves:
        _board = copy.deepcopy(board)
        utils.make_move(_board, move, player)
        opponent = 'O' if player == 'X' else 'X'
        score = minimax_score(_board, opponent, player)
        if best_score is None or score > best_score:
            best_move = move
            best_score = score
    return best_move
Exemplo n.º 3
0
def minimax_score(board, player_to_move, player_to_optimize, cache={}):
    board_cache_key = str(board)
    if board_cache_key in cache:
        return cache[board_cache_key]

    winner = utils.get_winning_player(board)
    if winner is not None:
        if winner == player_to_optimize:
            return 10
        elif winner == player_to_move:
            return -10
    elif utils.check_for_tie(board):
        return 0

    valid_moves = utils.get_valid_moves(board)
    scores = []
    for move in valid_moves:
        _board = copy.deepcopy(board)
        _board = utils.make_move(_board, move, player_to_move)
        opponent = 'O' if player_to_move == 'X' else 'X'
        score = minimax_score(_board, opponent, player_to_optimize, cache)
        scores.append(score)

    if player_to_move == player_to_optimize:
        cache[board_cache_key] = max(scores) if len(scores) > 0 else -10
    else:
        cache[board_cache_key] = min(scores) if len(scores) > 0 else 10

    return cache[board_cache_key]
Exemplo n.º 4
0
def finds_winning_and_losing_moves_ai(board, player):
    # Checking if we can win
    supposed_winning_move = finds_winning_moves_ai(board, player)
    temp_board = utils.make_move(board, supposed_winning_move, player)
    if utils.get_winner(temp_board) is player:
        return supposed_winning_move
    # Checking if we can loose
    opposite_player = utils.get_opposite_player(player)
    supposed_opposite_winning_move = finds_winning_moves_ai(
        board, opposite_player)
    temp_board = utils.make_move(board, supposed_opposite_winning_move,
                                 opposite_player)
    if utils.get_winner(temp_board) is opposite_player:
        return supposed_opposite_winning_move  # block this move so opponent cannot play this.

    return random_ai(board, player)
Exemplo n.º 5
0
def finds_winning_moves_ai(board, player):
    winning_move = None
    for i in range(0, 3):
        for j in range(0, 3):
            move = (i, j)
            if (utils.is_a_valid_move(board, move)):
                temp_board = utils.make_move(board, move, player)
                if utils.get_winner(temp_board) is player:
                    # This is a winning move.
                    winning_move = move
                    break
    return winning_move if winning_move is not None else random_ai(
        board, player)
Exemplo n.º 6
0
def play_game(playerX, playerO):
    board = utils.new_board()
    moves = 0
    while True:
        utils.render(board)
        player = 'X' if moves % 2 == 0 else 'O'
        move = bots.get_ai(playerX if player == 'X' else playerO)(board, player)
        board = utils.make_move(board, move, player)
        #time.sleep(0.2)
        os.system('clear')
        if utils.get_winner(board, player):
            print('Player', player, 'wins!')
            utils.render(board)
            return 1 if player == 'X' else 2
        elif utils.check_for_tie(board):
            print('It\'s a tie!')
            utils.render(board)
            return 0
        moves += 1
Exemplo n.º 7
0
def Game(player_types):
    print_game_info()
    # Starting Game
    print("Initializing Board")
    board = new_board()
    players = ['O', 'X']
    chance = 0
    while True:
        player = players[chance % 2]
        player_type = player_types[chance % 2]
        render(board)
        move_coords = get_player_move(player_type, player, board)
        board = make_move(board, move_coords, player)
        winner = get_winner(board)
        if winner is not None:
            render(board)
            print("\nWohoo {} has Won!!!\nRun Again\n".format(winner))
            break
        if is_board_full(board):
            render(board)
            print("\nOhho! This is a draw. Begin Again\n")
            break
        chance += 1
Exemplo n.º 8
0
 elif msg[0] == 2:
     # Pega os movimentos possiveis
     resp = urllib.request.urlopen("%s/movimentos" % host)
     movimentos = eval(resp.read())
     # Escolhe um movimento aleatoriamente
     movimento = random.choice(movimentos)
     # Executa o movimento
     resp = urllib.request.urlopen(
         "%s/move?player=%d&coluna=%d&linha=%d" %
         (host, player, movimento[0], movimento[1]))
     msg = eval(resp.read())
 elif msg[0] < 0:
     if msg[0] == -5:
         print("movimento invalido")
         tab2 = copy.deepcopy(tabuleiro)
         tab2 = utils.make_move(tab2, move, -1)
         # Escolhe um movimento
         ab = [-inf, inf]
         score, move = minimax.minimax(tab2, 4, ab, True, inicial_move,
                                       1)
         # Executa o movimento
         print("Movimento Escolhido: " + str(move[0] + 1) + "," +
               str(move[1] + 1))
         end = datetime.datetime.now()
         diff = end - start
         print("Time H:M:S\t" + str(diff))
         resp = urllib.request.urlopen(
             "%s/move?player=%d&coluna=%d&linha=%d" %
             (host, player, move[0] + 1, move[1] + 1))
     else:
         raise Exception(msg[1])
Exemplo n.º 9
0
def begin_new_game(player1, player2):
    """
        This is the function that calls and makes all the necessary updates when the user enters a move
    """

    matrix = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]

    Global_variables.random_player_begin = Global_variables.next_player

    if Global_variables.random_player_begin == 0:

        Global_variables.random_player_begin = randint(1, 2)

    if Global_variables.random_player_begin == 1:

        Global_variables.next_player = 2

        current_player = player1

        print(current_player, end=" ")
        character = input("what character do you want to be? O or X: ")
        if character.upper() == "O":

            player1_character = "O"
            player2_character = "X"

        else:

            player1_character = "X"
            player2_character = "O"

    else:

        Global_variables.next_player = 1

        current_player = player2

        print(current_player, end=" ")
        character = input("what character do you want to be? O or X: ")
        if character.upper() == "O":

            player2_character = "O"
            player1_character = "X"

        else:

            player2_character = "X"
            player1_character = "O"

    while True:

        print_matrix(matrix)

        if current_player == player1:

            character = player1_character

        else:

            character = player2_character

        valid = True

        while valid:

            print(current_player,
                  "enter the position where you want to place",
                  character,
                  "?",
                  end=" ")
            move = int(input(""))

            if validate_move(move, matrix) == True:

                valid = False

            else:

                print(
                    "That move is not valid! You should consider entering a different position!"
                )

        make_move(move, matrix, character)

        if check_if_player_is_winner(character, matrix) == True:

            print("The winner of this match is ", current_player)

            if current_player == player1:

                Global_variables.player_one_score = Global_variables.player_one_score + 1

            else:

                Global_variables.player_two_score = Global_variables.player_two_score + 1

            return

        if current_player == player1:

            current_player = player2

        else:

            current_player = player1

        if can_continue(matrix) == True:

            print("It is a draw!")

            return