so I have just started programming a simple chess engine in Python. I am currently working on updating my search to include Alpha Beta pruning.
Here is my current search function
def getBestMove(board, depth, maximizingPlayer, alpha=float('-inf'), beta=float('inf')):
if depth == maxDepth or board.legal_moves.count() == 0: # maxDepth = 5
score = evaluate(board) # Returns float value
return score
if maximizingPlayer:
maxEval = float('-inf')
for move in board.legal_moves:
print(board)
board.push(move)
eval = getBestMove(board, (depth + 1), alpha, beta, False)
maxEval = max(maxEval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break
elif depth != maxDepth and eval > alpha:
board.pop()
break
return maxEval
else:
minEval = float('inf')
for move in board.legal_moves:
print(board)
board.push(move)
eval = getBestMove(board, (depth + 1), alpha, beta, True)
minEval = min(minEval, eval)
beta = min(beta, eval)
if beta <= alpha:
break
if depth != maxDepth and eval < alpha:
board.pop()
break
return minEval
So here's the problem, when I run
print(getBestMove(board, 1, True))
I get the following result:
AssertionError: push() expects move to be pseudo-legal, but got g1f3 in rnbqkbr1/pppppppp/7n/6N1/8/8/PPPPPPPP/RNBQKB1R
I get this error after the console prints 5 boards, the last one being the fen in the error, so I believe what's happening is that the loop runs down until depth=5, but when it goes back up to depth=4 the board is not properly going a move backwards. I've tried to incorporate board.pop()
at the correct time to avoid this, but clearly I'm doing something wrong.
How can I push the board a move back at the proper time to run the search function correctly? Or maybe I'm entirely wrong and something is wrong with the actual search. Either way, any help is greatly appreciated!