如何从 read_game 的最终位置得到棋盘?

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

这里我们成功解析了一款PGN游戏:

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

很遗憾,board()还是初始位置。如何获得最终位置?

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

python-chess documentation给出了下面的例子:

>>> 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') 

所以你需要通过 mainline_moves and push them to a board (get it from game.board()) 阅读(主线)移动,然后打印该板。

或者,您可以使用game.end()方法将游戏移动到主线的末尾。然后你可以打印游戏对象:

game.end().board()