提问者:小点点

Python中Ticrectoe的极小极大算法


我最近报名参加了CS50人工智能Python课程,其中一个要做的项目是为一个小游戏实现一个极小值算法。我寻求帮助并搜索了stackoverflow,但我没有找到一个可以帮助我的答案。它的图形部分已经实现了,你所需要做的就是对模板的给定函数进行编程,我相信我是对的,除了算法部分,函数如下:

import math
import copy

X = "X"
O = "O"
EMPTY = None


def initial_state():
    """
    Returns starting state of the board.
    """
    return [[EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY]]


def player(board):
    """
    Returns player who has the next turn on a board.
    """
    if board == initial_state():
        return X

    xcounter = 0
    ocounter = 0
    for row in board:
        xcounter += row.count(X)
        ocounter += row.count(O)

    if xcounter == ocounter:
        return X
    else:
        return O


def actions(board):
    """
    Returns set of all possible actions (i, j) available on the board.
    """
    possible_moves = []
    for i in range(3):
        for j in range(3):
            if board[i][j] == EMPTY:
                possible_moves.append([i, j])
    return possible_moves


def result(board, action):
    """
    Returns the board that results from making move (i, j) on the board.
    """
    boardcopy = copy.deepcopy(board)
    try:
        if boardcopy[action[0]][action[1]] != EMPTY:
            raise IndexError
        else:
            boardcopy[action[0]][action[1]] = player(boardcopy)
            return boardcopy
    except IndexError:
        print('Spot already occupied')


def winner(board):
    """
    Returns the winner of the game, if there is one.
    """
    columns = []
    # Checks rows
    for row in board:
        xcounter = row.count(X)
        ocounter = row.count(O)
        if xcounter == 3:
            return X
        if ocounter == 3:
            return O

    # Checks columns
    for j in range(len(board)):
        column = [row[j] for row in board]
        columns.append(column)

    for j in columns:
        xcounter = j.count(X)
        ocounter = j.count(O)
        if xcounter == 3:
            return X
        if ocounter == 3:
            return O

    # Checks diagonals
    if board[0][0] == O and board[1][1] == O and board[2][2] == O:
        return O
    if board[0][0] == X and board[1][1] == X and board[2][2] == X:
        return X
    if board[0][2] == O and board[1][1] == O and board[2][0] == O:
        return O
    if board[0][2] == X and board[1][1] == X and board[2][0] == X:
        return X

    # No winner/tie
    return None


def terminal(board):
    """
    Returns True if game is over, False otherwise.
    """
    # Checks if board is full or if there is a winner
    empty_counter = 0
    for row in board:
        empty_counter += row.count(EMPTY)
    if empty_counter == 0:
        return True
    elif winner(board) is not None:
        return True
    else:
        return False


def utility(board):
    """
    Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
    """
    if winner(board) == X:
        return 1
    elif winner(board) == O:
        return -1
    else:
        return 0


def minimax(board):
    current_player = player(board)

    if current_player == X:
        v = -math.inf
        for action in actions(board):
            k = min_value(result(board, action))    #FIXED
            if k > v:
                v = k
                best_move = action
    else:
        v = math.inf
        for action in actions(board):
            k = max_value(result(board, action))    #FIXED
            if k < v:
                v = k
                best_move = action
    return best_move

def max_value(board):
    if terminal(board):
        return utility(board)
    v = -math.inf
    for action in actions(board):
        v = max(v, min_value(result(board, action)))
    return v    #FIXED

def min_value(board):
    if terminal(board):
        return utility(board)
    v = math.inf
    for action in actions(board):
        v = min(v, max_value(result(board, action)))
    return v    #FIXED

最后一部分是minimax(棋盘)函数所在的位置,它应该获取棋盘的当前状态,并根据AI是玩家“X”还是“O”(可以是两者中的任意一个)计算出可能的最佳移动,“X”玩家试图最大化分数,“O”应该利用效用(棋盘)函数最小化分数,该函数返回1表示X赢、-1表示“O”赢或0表示平局。到目前为止,人工智能的移动不是最优的,我可以轻松地在我不应该的时候战胜它,因为在最好的情况下,我应该得到的是一个平局,因为人工智能应该在这一点上计算每一个可能的移动。但我不知道怎么了。。。


共3个答案

匿名用户

首先谈谈调试:如果要打印递归调用中完成的计算,可以跟踪问题的执行情况并快速找到答案。

但是,你的问题似乎是最重要的。在你的极小值调用中,如果当前玩家是X,你就调用该状态的每个子级的max_value,然后取结果的最大值。然而,这在树的顶部应用了两次max函数。游戏中的下一个玩家是O,所以您应该为下一个玩家调用min_value函数。

因此,在minimax调用中,如果当前_播放器为X,则应调用minu value;如果当前_播放器为O,则应调用max_value。

匿名用户

@cs50项目页面上说,harsh kothari

重要的是,原始板应该保持不变:因为极小值最终需要在计算过程中考虑许多不同的板状态。这意味着简单地更新单元格本身并不是结果函数的正确实现。在进行任何更改之前,您可能希望首先对董事会进行深度复制。

为了避免子列表被修改,我们使用深度复制而不是复制

在此处阅读有关copy()和deepcopy()的更多信息

匿名用户

将操作(板)代码更改为

possibleActions = set()

for i in range(0, len(board)):
    for j in range(0, len(board[0])):
        if board[i][j] == EMPTY:
            possibleActions.add((i, j))

return possibleActions