实现alpha-beta修剪算法时函数中的奇怪行为

时间:2012-09-24 16:46:12

标签: python artificial-intelligence chess

我已经实现了具有alpha-beta修剪的minimax算法。为了获得最佳移动,我使用rootAlphaBeta函数调用alpha-beta算法。但是,在rootAlphaBeta函数中,我发现了一些非常奇怪的行为。当我用rootAlphaBeta 4调用ply函数时,它会进行大约20 000次调用,但是当我直接调用alphaBeta函数时,它只会进行大约2000次调用。我似乎无法找到问题所在,因为呼叫的数量应该是相同的。

两种算法最终找到的举动应该是一样的,对吗?我是这么认为的,至少移动的得分是一样的,我无法知道alphaBeta在没有rootAlphaBeta的情况下直接调用它时所选择的移动。

def alphaBeta(self, board, rules, alpha, beta, ply, player):
    """Implements a minimax algorithm with alpha-beta pruning."""
    if ply == 0:
        return self.positionEvaluation(board, rules, player)

    move_list = board.generateMoves(rules, player)
    for move in move_list:
        board.makeMove(move, player)
        current_eval = -self.alphaBeta(board, rules, -beta, -alpha, ply - 1,
                                       board.getOtherPlayer(player))
        board.unmakeMove(move, player)

        if current_eval >= beta:
            return beta

        if current_eval > alpha:
            alpha = current_eval

    return alpha


def rootAlphaBeta(self, board, rules, ply, player):
    """Makes a call to the alphaBeta function. Returns the optimal move for a 
    player at given ply."""
    best_move = None
    max_eval = float('-infinity')

    move_list = board.generateMoves(rules, player)
    for move in move_list:
        board.makeMove(move, player)
        current_eval = -self.alphaBeta(board, rules, float('-infinity'),
                                       float('infinity'), ply - 1,
                                       board.getOtherPlayer(player))
        board.unmakeMove(move, player)

        if current_eval > max_eval:
            max_eval = current_eval
            best_move = move

    return best_move

1 个答案:

答案 0 :(得分:4)

您的rootAlphaBeta未更新alpha值。当它可以缩小除第一个子节点之外的所有子节点的范围时,它会调用其所有子节点的全部范围(-inf,inf)。这将防止修剪一些对最终得分没有影响的分支,并增加节点数。