I am using the module python-chess (https://python-chess.readthedocs.io/en/latest/index.html) to extract analyze 4 million chess games (http://caissabase.co.uk/).
How do I load all moves for a game as strings into a list? The idea is for me to be able to extract information about moves. For example, how many times did a Queen capture an opponent's piece? I would thus search for "Qx" in each move string. I have tried this:
test = [] # list I wish to append moves to (as strings)
game = chess.pgn.read_game(pgn)
board = game.board()
for move in game.mainline_moves():
board.push(move)
test.append(board.san(move)) # this does not work and seems to cause the below error
The above code generates the following error:
AssertionError: san() and lan() expect move to be legal or null, but got g1f3 in rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b KQkq - 1 1
However the rest of the code without test.append(board.san(move))
prints all game moves as strings just fine.
Any help is greatly appreciated.
board.san(move)
gives you the notation of the move based on the current position (see documentation). However, you have already changed the position before by making the move on the board. Therefore it doesn't recognise the first knight move g1f3
as legal: the knight is already on f3!
I suspect that if you exchange the two lines in the loop it should work. That is, you first need to write down the move, and then make it (somewhat different to what you would do playing actual chess ;))