【问题标题】:add variations/nodes to games in python-chess在 python-chess 中为游戏添加变体/节点
【发布时间】:2021-05-28 10:13:04
【问题描述】:

我正在尝试使用"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,该怎么做?

【问题讨论】:

    标签: python nodes variations python-chess


    【解决方案1】:

    我认为解决问题的方法是方法

    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 *
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2016-05-25
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      相关资源
      最近更新 更多