简体   繁体   English

如何跟踪单个棋子的移动?

[英]How to track movement of a single chess piece?

I'm using python-chess and I would like to know what is a good way to track movement of let say a black King throughout a single match recorded in pgn format using python-chess.我正在使用 python-chess,我想知道在使用 python-chess 以 pgn 格式记录的单场比赛中跟踪黑国王的运动的好方法是什么。 Essentially creating a string of every position it achieved.本质上是创建一个它实现的每个 position 的字符串。

Sample code to record black king squares, moves epd etc.记录黑色国王方块、移动 epd 等的示例代码。

Code代码

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)

Output Output

{'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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM