python - 使用 alphabeta TicTacToe 找到最佳着法

标签 python python-3.x tic-tac-toe alpha-beta-pruning

试图找到最佳着法和分数。我已经让我的程序正确返回游戏分数,但我希望它也返回移动。我如何更改我的代码以使其执行此操作? 类似于 thisthis .查看我的失败代码 here ,如果游戏结束返回的 None 应该是移动。

def alphabeta(game_state, alpha, beta, our_turn=True):
    if game_state.is_gameover():
         return game_state.score()
    if our_turn:
        score = -9999
        for move in game_state.get_possible_moves():
            child = game_state.get_next_state(move, True)
            temp_max = alphabeta(child, alpha, beta, False) 
            if temp_max > score:
                score = temp_max
            alpha = max(alpha, score)
            if beta <= alpha:
                break
        return score
    else:
        score = 9999
        for move in game_state.get_possible_moves():
            child = game_state.get_next_state(move, False)
            temp_min = alphabeta(child, alpha, beta, True)
            if temp_min < score:
                score = temp_min
            beta = min(beta, score)
            if beta <= alpha:
                break
        return score

最佳答案

您可以跟踪到目前为止的最佳着法,例如:

    if game_state.is_gameover():
         return game_state.score(), None
    if our_turn:
        score = -9999
        for move in game_state.get_possible_moves():
            child = game_state.get_next_state(move, True)
            temp_max, _ = alphabeta(child, alpha, beta, False) # _ to disregard the returned move
            if temp_max > score:
                score = temp_max
                best_move = move
            alpha = max(alpha, score)
            if beta <= alpha:
                break
        return score, best_move

其他情况类似

关于python - 使用 alphabeta TicTacToe 找到最佳着法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41111204/

相关文章:

c# - 如何使用随机选择二维数组中的位置?

tic-tac-toe - 将计算函数的值用于agda中的证明

python - 如何识别 Python3 中的视频格式?

python - PyYAML 转储无效的 YAML,除非参数包含数组

python - 内置模块位于何处?

python - 在浏览器中渲染时如何更改绘图图形周围的主体背景?

c - 与井字游戏斗争

python - StopIteration 异常是否会自动通过我的迭代器向上传播?

python - dunder 包属性不返回包名称

python - 列表列表列表中的唯一性