在python象棋中为游戏添加变体/节点



我正试图通过使用;蟒蛇象棋-包装

我的问题是我想在游戏中添加变体,所以我使用了以下方法:

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 *

最新更新