在 Python 中停止递归函数

问题描述

我正在创建一个国际象棋引擎,但在让它停止从其递归负极大(极小极大)框架进行计算时遇到了一些麻烦。我希望它在给定的时间限制结束时返回迄今为止的最佳移动。以下是我的代码结构:

# Initial call
move = ai_make_move()

# AI function with iterative deepending
def ai_make_move():
    best_move_so_far = []

    # Here I init the time
    start_time = time.time()

    # Iterative deepening to go deeper and deeper into tree
    for depth in range(1,max_depth):
        move = negamax(alpha,beta,depth...)
        best_move_so_far.append(move)

# Negamax function
def negamax(alpha,depth....):
    
    # Here I want to make the time check...
    if time.time() - start_time >= time_limit:
        # Return None to ai_make_move() or return best_move_so_far[-1] to initial call
    
    for move in possible moves:
        make_move()
        negamax(-beta,-alpha)
        unmake_move()

    # ...

我遇到的问题是在 negamax 函数中时间到时停止,并将 None 返回到 ai_make_move() 函数,以便能够执行类似 if not move: return best_move_so_far[-1] 的操作。或者立即将其返回到初始调用

是否可以停止这样的递归调用?现在如果我返回一些东西,它只会返回到之前的 negamax 调用等等,这会产生错误

解决方法

您应该在函数中添加一个 timeout,这里有很好的解释:Timeout on a function call

,

你应该可以只返回当前棋盘的分数,就像游戏结束一样。

if time.time() - start_time >= time_limit:
    return evaluation(board)

显然这不会立即停止函数,因为值必须返回树,但它应该非常快。还有为什么你需要一个 max_depth 和一个 time_limit