I am creating a chess engine and have some trouble getting it to stop calculating from its recursive negamax (minimax) framework. I want it to return best move so far when a given time limit is up. Here is how my code is structured:
# 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, beta, 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()
# ...
The problem I have is to stop when time is up in the negamax function and return None to ai_make_move() function to be able to do something like if not move: return best_move_so_far[-1]
. Or to return that immediately to the initial call.
Is it possible to stop a recursive call like this? Right now if I return something it will just return to the previous call of negamax and so on, which will give an error.