首页 > 解决方案 > 极小极大的评估函数

问题描述

大家好,我目前正在学习 CS50AI 课程。第一个任务是创建一个带有 minimax 函数的 tictactoe AI。我的问题是:据我了解,必须对游戏的位置进行静态评估。我试图用伪代码写这样的东西:

If next move is a winning move:
    return 10 point
elif opponent is going to win stop him:
    return 8 point

之类的事情。但是当我检查其他 minvalue - max value 函数时,没有这样的事情。

def minimax(board):
    """
    Returns the optimal action for the current player on the board.
    """
    currentactions = actions(board)
    if player(board) == X:
        vT = -math.inf
        move = set()
        for action in currentactions:
            v, count = maxvalue(result(board,action), 0)
            if v > vT:
                vT = v
                move = action
    else:
        vT = math.inf
        move = set()
        for action in currentactions:
            v, count = minvalue(result(board,action), 0)
            if v < vT:
                vT = v
                move = action
    print(count)
    return move

    def maxvalue(board, count):
        """
        Calculates the max value of a given board recursively together with minvalue
        """
    
        if terminal(board): return utility(board), count+1
    
        v = -math.inf
        posactions = actions(board)
    
        for action in posactions:
            vret, count = minvalue(result(board, action), count)
            v = max(v, vret)
        
        return v, count+1
    
    def minvalue(board, count):
        """
        Calculates the min value of a given board recursively together with maxvalue
        """
    
        if terminal(board): return utility(board), count+1
    
        v = math.inf
        posactions = actions(board)
    
        for action in posactions:
            vret, count = maxvalue(result(board, action), count)
            v = min(v, vret)
        
        return v, count+1

这是 sikburn 的 tictactoe 实现的 max - min 函数。我无法理解最大值或最小值函数会产生什么结果。任何人都可以澄清我的逻辑吗?顺便说一句,terminal()函数检查游戏是否结束(有赢家或平局),并且result()函数将棋盘和动作作为输入并返回结果棋盘。感谢所有的帮助。

标签: pythonartificial-intelligencecs50minimax

解决方案


utility函数中(未包含在您的代码中),您可能将 1 分配给 X 胜利,-1 分配给 O 胜利,否则为 0。该minimax函数递归调用所有可能的移动minvaluemaxvalue直到游戏结束,无论是平局还是胜利。然后它调用utility以获取值。两者minvaluemaxvalue保证 X 和 O 将始终选择最佳可能的移动。

不要忘记检查板是否是终端,None如果是终端,则在继续之前,在minimax函数中返回。

交换minvaluemaxvalue函数的调用minimax:对于 X,调用minvalue(因为 X 想知道 O 下一步行动)和对于 O,调用maxvalue(出于相同的原因)。

如果您想在每次迭代中查看评估,您可以在返回这些值之前在and函数的末尾打印类似f"Minvalue: {v}, Iteration: {count+1}"and的内容。我认为这会更容易理解。f"Maxvalue: {v}, Iteration: {count+1}"minvaluemaxvalue

我 hppe 我澄清了你的疑虑。


推荐阅读