1

我正在使用 python-chess,我想知道在使用 python-chess 以 pgn 格式记录的单场比赛中跟踪黑国王的运动的好方法是什么。从本质上讲,它创建了每个位置的字符串。

4

1 回答 1

0

记录黑色国王方块、移动 epd 等的示例代码。

代码

import chess.pgn 


# Save position of black king in each game.
data = []

pgnfile = "mygame.pgn"
gcnt = 0

with open(pgnfile) as pgn:
    while True:
        game = chess.pgn.read_game(pgn)
        if game is None:
            break

        gcnt += 1
        sqnames = []
        sqvalues = []
        epds = []
        sanmoves = []
        ucimoves = []

        # first entry of moves is null move
        sanmoves.append(str(chess.Move.null()))
        ucimoves.append(str(chess.Move.null()))

        # Save the first location of king.
        b = game.board()
        sqnames.append(chess.square_name(b.king(chess.BLACK)))
        sqvalues.append(b.king(chess.BLACK))
        epds.append(b.epd())

        for node in game.mainline():  # parse nodes in this game
            board = node.board()
            m = node.move            
            tosq = m.to_square            
            p = board.piece_at(tosq)

            if p.piece_type == chess.KING and p.color == chess.BLACK:
                sqnames.append(chess.square_name(tosq))
                sqvalues.append(tosq)
                epds.append(board.epd())
                sanmoves.append(node.parent.board().san(m))
                ucimoves.append(node.parent.board().uci(m))

        data.append({'game': gcnt, 'sqnames': sqnames, 'sqvalues': sqvalues, 'epd': epds, 'sanmoves': sanmoves, 'ucimoves': ucimoves})
        
        if gcnt >= 10:  # sample limit
            break

# Print tracks of king per game.
for d in data:
    print(d)

输出

{'game': 1, 'sqnames': ['e8', 'g8'], 'sqvalues': [60, 62], 'epd': ['rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -', 'r2q1rk1/p2bbppp/2pppn2/6B1/3NP3/2NQ4/PPP2PPP/2KR3R w - -'], 'sanmoves': ['0000', 'O-O'], 'ucimoves': ['0000', 'e8g8']}
{'game': 2, 'sqnames': ['e8', 'd7', 'e8', 'f8'], 'sqvalues': [60, 51, 60, 61], 'epd': ['rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -', 'rn5r/pp1k1p1p/4bp2/1N2p3/1b6/1N3P2/PPP3PP/R2K1B1R w - -', 'rnr1k3/pp2bp1p/4b3/1N2pp2/8/PN1B1P2/1PP2KPP/R6R w - -', 'r1r2k2/pp1nbp1p/4b3/4pp2/8/PNNB1P2/1PP2KPP/R3R3 w - -'], 'sanmoves': ['0000', 'Kd7', 'Ke8', 'Kf8'], 'ucimoves': ['0000', 'e8d7', 'd7e8', 'e8f8']}
于 2021-11-29T13:56:37.517 回答