0

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!

tyl3366
  • 67
  • 1
  • 6
  • 1
    Something is not right with `eval = getBestMove(board, (depth + 1), alpha, beta, False)`. Where is the `maximizingPlayer` parameter? Check the parameter sequence. – ferdy Apr 27 '23 at 01:30
  • @ferdy Wow, thank you, I somehow overlooked that. I updated the parameter sequence so that `maximizingPlayer` is in the correct position. I also changed `board.pop()` to be right after defining `eval` without an if check. Everything is working now. Thank you! – tyl3366 Apr 27 '23 at 14:32

0 Answers0