【问题标题】:How to get a chess board from a final position from read_game?如何从 read_game 的最终位置获得棋盘?
【发布时间】:2021-01-17 10:07:10
【问题描述】:

这里我们成功解析了一个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 python-chess


    【解决方案1】:

    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 读取(主线)移动并将它们推送到棋盘(从game.board() 获取),然后打印该棋盘。

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

    game.end().board()
    

    【讨论】:

    • 谢谢game.end().board()解决了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多