问题描述
我正在尝试使用 "python-chess"-package
构建国际象棋引擎我的问题是我想为游戏添加变体,所以我使用了以下方法:
add_variation(move: chess.Move,*,comment: str = '',starting_comment: str = '',nags: Iterable[int] = []) → chess.pgn.ChildNode
如果我有一款有动作的游戏。
1. e4 e5 2. Nf3 Nf6
然后我可以为第一步做到这一点:
pgn = io.StringIO("1. e4 e5 2. Nf3 Nf6 *")
game = chess.pgn.read_game(pgn)
board = game.board()
for move in game.mainline_moves():
board.push(move)
node0 = game.add_variation(chess.Move.from_uci("d2d4"))
node = node0.add_variation(chess.Move.from_uci("d7d5"))
node = node.add_variation(chess.Move.from_uci("g1f3"))
node2 = game.add_variation(chess.Move.from_uci("a2a4"))
print(game)
它会显示
1. e4 ( 1. d4 d5 2. Nf3 ) ( 1. a4 ) 1... e5 2. Nf3 Nf6 *
然后我有两个节点用于第一步。 (一个以移动“d4”开头,一个以移动“a4”开头)
我的问题是我找不到其他任何动作的方法。所以例如如果我想将节点添加到移动 2. Nf3
,有什么方法可以做到?
解决方法
我认为解决问题的方法是方法
chess.pgn.GameNode.next()
它返回下一步的下一个节点。但是,它似乎不是获取特定移动节点的直接方法,因此您必须递归应用该方法以逐步向前移动以到达特定节点/移动。
我对解决方案做了一个简短的演示。它有点笨重,我怀疑有更优雅的方法可以通过使用包来做到这一点。但我不是一个有经验的程序员,而且这个包的文档有点缺乏。
import chess
import chess.pgn
import io
def UCIString2Moves(str_moves):
return [chess.Move.from_uci(move) for move in str_moves.split()]
# mainline
game = chess.pgn.read_game(
io.StringIO("1.f4 d5 2.Nf3 g6 3.e3 Bg7 4.Be2 Nf6 5.0-0 0-0 6.d3 c5 *"))
board = game.board()
for move in game.mainline_moves():
board.push(move)
# 1:st line,1:st move in mainline
str_line1 = "a2a4 d7d5 g1f3 g7g6"
game.add_line(UCIString2Moves(str_line1))
# 2:nd line,1:st move in mainline
str_line2 = "h2h5 d7d6 g1f3 g8f6"
game.add_line(UCIString2Moves(str_line2))
# 3:rd line,2:nd move in mainline
move2_main = game.next() # get the node for 2:nd move
str_line3 = "a7a6 g1f3 g8f6"
move2_main.add_line(UCIString2Moves(str_line3))
# 1:st variation,3:rd move in mainline
move3_main = move2_main.next() # get the node for 3:rd move
move3_main.add_variation(chess.Move.from_uci("c1c3"))
chess.pgn.GameNode.next()
print(game)
移动和变化/线条的符号(没有特定的开头,只是随机移动):
1. f4 ( 1. a4 d5 2. Nf3 g6 ) ( 1. h5 d6 2. Nf3 Nf6 )
1... d5 ( 1... a6 2. Nf3 Nf6 )
2. Nf3 ( 2. Bc3 ) 2... g6 3. e3 Bg7 4. Be2 Nf6 5. O-O O-O 6. d3 c5 *