首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何跟踪单个棋子的移动?

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

Stack Overflow用户
提问于 2020-12-28 03:51:24
回答 1查看 69关注 0票数 1

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

EN

回答 1

Stack Overflow用户

发布于 2021-11-29 13:56:38

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

代码

代码语言:javascript
复制
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)

输出

代码语言:javascript
复制
{'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']}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65469818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档