niklasf / python-chess

A chess library for Python, with move generation and validation, PGN parsing and writing, Polyglot opening book reading, Gaviota tablebase probing, Syzygy tablebase probing, and UCI/XBoard engine communication
https://python-chess.readthedocs.io/en/latest/
GNU General Public License v3.0
2.42k stars 529 forks source link

Cant Convert PGN to string (could be user error...) #32

Closed jordanbray closed 9 years ago

jordanbray commented 9 years ago

Hey,

I've been trying to create a PGN from a game played (engine vs engine) through python-chess.

However, whenever I convert the pgn to a string, I get a stack trace back.

game.pgn = str(pgn)
File "/home/jordan/Projects/virtual_environments/moregames/lib/python3.4/site-packages/chess/pgn.py", line 283, in __str__
self.export(exporter)
File "/home/jordan/Projects/virtual_environments/moregames/lib/python3.4/site-packages/chess/pgn.py", line 366, in export
super(Game, self).export(exporter, comments=comments, variations=variations)
File "/home/jordan/Projects/virtual_environments/moregames/lib/python3.4/site-packages/chess/pgn.py", line 230, in export
exporter.put_move(_board, main_variation.move)
File "/home/jordan/Projects/virtual_environments/moregames/lib/python3.4/site-packages/chess/pgn.py", line 450, in put_move
self.write_token(board.san(move) + " ")
File "/home/jordan/Projects/virtual_environments/moregames/lib/python3.4/site-packages/chess/__init__.py", line 2275, in san
others &= ~BB_SQUARES[move.from_square]
UnboundLocalError: local variable 'others' referenced before assignment

This occurs here in my code:

update the PGN

pgn.add_main_variation(move)
# write the new PGN to the database, now
exporter = chess.pgn.StringExporter()
# pgn.export(exporter, headers=True, variations=True, comments=True)
game.pgn = str(pgn)

I can add moves, just not get the PGN string back.

As you can see above, I also tried the PGN exporter, but that failed with the same exception.

niklasf commented 9 years ago

Hi, thanks for reporting this! I am assuming you're using version 0.8.1.

On the first glance this looks like the moving piece is neither pawn, knight, bishop, rook, queen or king, which is not possible. Has to be some deeper problem ...

Can you please provide the entire list of moves to help reproduce it?

jordanbray commented 9 years ago

This is a user error. I just found the bug in my code. When I was adding moves to the PGN, I was repetedly calling add_main_variation. This was basically telling the PGN software that each move was the first move in the game, many of which were illegal.

I'll find my way through the documentation to figure out the correct way to add a move. Thanks for the other bug fix.

niklasf commented 9 years ago

Alright! I'll add an assertion there, to make the error message a bit clearer. UnboundLocalError really looks like a problem with the library.