[英]Printing individual moves with the python-chess library
I want to sequentially print the moves (one string per move at a time) from a game I read (using the python-chess library) from a text file.我想从文本文件中读取(使用 python-chess 库)的游戏中顺序打印移动(一次一个字符串)。
So, say I have a pgn file with a game that has the following moves...所以,假设我有一个 pgn 文件,其中包含具有以下动作的游戏......
1. f3 e5 2. g4 Qh4# 1. f3 e5 2. g4 Qh4#
... I would like to iterate through the moves and print them one by one (using a for loop or similar), showing ...我想遍历这些动作并一个一个地打印它们(使用 for 循环或类似的),显示
f3 f3
e5 e5
g4 g4
Qh4 Qh4
I found the documentation for python-chess here: https://python-chess.readthedocs.io/en/latest/我在这里找到了 python-chess 的文档: https://python-chess.readthedocs.io/en/latest/
From the documentation I understand that从文档中我了解到
But I find this kind of documentation hard to read and would be greatly helped with examples.但是我发现这种文档很难阅读,并且可以通过示例得到很大的帮助。
What I managed to do is read a game from a pgn file and print all the moves in one go (as opposed to one by one) using the variation method.我设法做的是从 pgn 文件中读取游戏并使用变体方法将所有动作打印在一个 go 中(而不是一个一个地打印)。
import chess.pgn
pgn = open('I:\myfile.pgn')
my_game = chess.pgn.read_game(pgn)
print(my_game.variation(0))
Iterating over mainline moves迭代主线移动
The documentation for chess.pgn.read_game()
has an example for iterating over moves. chess.pgn.read_game()
的文档有一个迭代移动的示例。 To convert the moves back to standard algebraic notation, the position is needed for context, so we additionally make all the moves on a board
.要将移动转换回标准代数符号,上下文需要 position,因此我们另外在
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)
Visitors访客
The above example parses the entire game into a data structure ( game: chess.pgn.Game
).上面的例子将整个游戏解析成一个数据结构(
game: chess.pgn.Game
)。 Visitors allow skipping that intermediate representation, which can be useful to use a custom data structure instead, or as an optimization.访问者允许跳过该中间表示,这对于使用自定义数据结构或作为优化很有用。 But that seems overkill here.
但这在这里似乎有些矫枉过正。
N.netheless, for completeness: N.尽管如此,为了完整性:
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)
Note that this also traverses side variations in PGN order.请注意,这也会遍历 PGN 顺序的边变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.