Search code examples
pythonchesspython-chess

"AssertionError: push() expects move to be legal", showing a board that is not the one passed in


I'm trying to code a simple chess engine that looks for the move that yields the most material advantage. However, I'm running into an odd error that shows a board that is not the one I had passed into it. I am using this library: https://python-chess.readthedocs.io/en/latest/

My code:

def best_move(board):
    print(board)
    
    moves = board.legal_moves
    
    result = choice(list(moves))
    for i in moves:
        newboard = board
        newboard.push(i)
        
        oldboard = board
        oldboard.push(result)
        
        if material_count(newboard) > material_count(oldboard):
            result = i

    return result

However, when running this function, I receive this error:

AssertionError: push() expects move to be pseudo-legal, but got g8h6 in rnbqkb1r/ppppnppp/8/8/3PP3/8/PPP2PPP/RNBQKBNR

The board in the error message looks like this:

r n b q k b . r
p p p p n p p p
. . . . . . . .
. . . . . . . .
. . . P P . . .
. . . . . . . .
P P P . . P P P
R N B Q K B N R

As you can see, my e-file pawn has disappeared entirely, and my knight has taken its fallen comrade's place. However, this is not the board that I passed into my method, as shown below:

r n b q k b n r
p p p p . p p p
. . . . . . . .
. . . . p . . .
. . . P P . . .
. . . . . . . .
P P P . . P P P
R N B Q K B N R

Any ideas? I can't see why the board is being altered in this way.


Solution

  • newboard = board doesn't create a copy of board. Any changes you make to newboard will affect both board and oldboard. The solution is to create a deep copy of board instead.

    According to the asker this is done via:

    newboard = chess.Board(board.fen())