Search code examples
pythonchesspython-chess

How to get a chess board from a final position from read_game?


Here we successfully parse a PGN game:

import chess, chess.svg, chess.pgn, io
game = chess.pgn.read_game(io.StringIO("1. e4 e5 2. Nf3 *"))
print(game)

Unfortunately, board() is still the initial position. How to get the final position instead?

print(game.board())
# 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

Solution

  • The python-chess documentation gives the following example:

    >>> import chess.pgn
    >>>
    >>> pgn = open("data/pgn/kasparov-deep-blue-1997.pgn")
    >>>
    >>> first_game = chess.pgn.read_game(pgn)
    >>> second_game = chess.pgn.read_game(pgn)
    >>>
    >>> first_game.headers["Event"] 
    'IBM Man-Machine, New York USA'
    >>>
    >>> # Iterate through all moves and play them on a board.
    >>> board = first_game.board()
    >>> for move in first_game.mainline_moves(): 
    ...     board.push(move) 
    ...
    >>> board 
    Board('4r3/6P1/2p2P1k/1p6/pP2p1R1/P1B5/2P2K2/3r4 b - - 0 45') 
    

    So you you need to read the (main line) moves via mainline_moves and push them to a board (get it from game.board()), and print that board.

    Alternatively, you can move the game to the end of the main line using the game.end() method. Then you can print the game object:

    game.end().board()