Skip to content Skip to sidebar Skip to footer

Printing Individual Moves With The Python-chess Library

I want to sequentially print the moves (one string per move at a time) from a game I read (using the python-chess library) from a text file. So, say I have a pgn file with a game t

Solution 1:

Iterating over mainline moves

The documentation for chess.pgn.read_game() has an example for iterating over moves. To convert the moves back to standard algebraic notation, the position is needed for context, so we additionally make all the moves on a board.

import chess.pgn

pgn = open("test.pgn")
game = chess.pgn.read_game(pgn)

board = game.board()

for move in game.mainline_moves():
    print(board.san(move))
    board.push(move)

Visitors

The above example parses the entire game into a data structure (game: chess.pgn.Game). Visitors allow skipping that intermediate representation, which can be useful to use a custom data structure instead, or as an optimization. But that seems overkill here.

Nonetheless, for completeness:

import chess.pgn

classPrintMovesVisitor(chess.pgn.BaseVisitor):
    defvisit_move(self, board, move):
        print(board.san(move))

    defresult(self):
        returnNone

pgn = open("test.pgn")
result = chess.pgn.read_game(pgn, Visitor=PrintMovesVisitor)

Note that this also traverses side variations in PGN order.

Post a Comment for "Printing Individual Moves With The Python-chess Library"