1 回答

TA贡献1780条经验 获得超5个赞
迭代主线移动
的文档chess.pgn.read_game()
有一个迭代移动的例子。要将移动转换回标准代数符号,上下文需要位置,因此我们另外将所有移动放在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)
访客
上面的例子将整个游戏解析成一个数据结构(game: chess.pgn.Game)。访问者允许跳过该中间表示,这对于使用自定义数据结构或作为优化很有用。但这在这里似乎有些矫枉过正。
尽管如此,为了完整性:
import chess.pgn
class PrintMovesVisitor(chess.pgn.BaseVisitor):
def visit_move(self, board, move):
print(board.san(move))
def result(self):
return None
pgn = open("test.pgn")
result = chess.pgn.read_game(pgn, Visitor=PrintMovesVisitor)
请注意,这也会遍历PGN 顺序的边变化。
添加回答
举报