我希望从我从文本文件中读取的游戏(使用python-chess库)中依次打印这些移动(每次移动一个字符串)。
所以,假设我有一个pgn文件和一个有以下动作的游戏.
1. f3 e5 2. g4 Qh4# .
..。我想遍历这些移动并逐一打印它们(使用for循环或类似的方法),如
f3
e5
g4
Qh4
我在这里找到了python的文档:https://python-chess.readthedocs.io/en/latest/
从文件中我了解到
但是我发现这类文档很难阅读,并且在示例中会有很大帮助。
我所做的就是从一个pgn文件中读取一个游戏,并使用变体方法一次一次(而不是一个一个地)打印出所有的动作。
import chess.pgn
pgn = open('I:\myfile.pgn')
my_game = chess.pgn.read_game(pgn)
print(my_game.variation(0))发布于 2020-08-21 09:19:33
迭代主线移动
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顺序遍历侧变。
https://stackoverflow.com/questions/63517471
复制相似问题