0

I have implemented my minimax() algorithm. My ai is smart enough to find a solution that leads to a victory.

However, it completely disregards the optimal move the enemy could do. This way, it is completely unresponsive.

It is only going for optimal solution if there was no enemy

def min_value(board):
    if terminal(board):
        return utility(board)

    best_score = float("inf")
    best_action = None

    for action in actions(board):

        score = max_value(result(board, action))

        if score <= best_score:
            best_score = score

        return best_score


def max_value(board):

    if terminal(board):
        return utility(board)

    best_score = float("-inf")

    for action in actions(board):

        score = min_value(result(board, action))

        if score > best_score:
            best_score = score

        return best_score


def minimax(board):
    """
    Returns the optimal action for the current player on the board.
    """
    if terminal(board):
        return None

    best_move = None

    if player(board) == "X":

        best_score = float("-inf")

        for action in actions(board):

            score = max_value(result(board, action))
            if score > best_score:
                best_score = score
                best_move = action
    else:
        best_score = float("inf")

        for action in actions(board):

            score = min_value(result(board, action))
            if score < best_score:
                best_score = score
                best_move = action

    return best_move

You must log in to answer this question.

Browse other questions tagged .