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 順序的邊變化。
添加回答
舉報