You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何加速Python国际象棋引擎中走法生成相关的类与对象

国际象棋引擎Python开发优化问题

走法生成模块现状

  • 伪合法走法生成速度:30-40K步/秒
  • 加入自定义慢速走法验证后速度降至:11K步/秒,正在开发更优的验证版本

棋盘与类结构优化尝试

  • 使用一维双字符数组表示棋盘(此前二维数组版本速度更快)
  • 实现GameState和Move类并启用__slots__特性,希望进一步提升类运行效率
  • 尝试过numba库,但因Move类构造函数需传入GameState对象,代码无法编译,寻求其他加速方案

额外信息

  • 用pygame编写GUI运行引擎脚本,由main.py处理

GameState类构造函数代码

class GameState:
    __slots__ = ('board', 'white_to_move', 'moveLog', 'w_l_c', 'b_l_c', 'w_r_c', 'b_r_c', 'white_king_loc', 'black_king_loc', 'check_mate', 'stale_mate', 'white_en_passant_sq', 'black_en_passant_sq')

    def __init__(self):
        self.board = [  # 切换为一维棋盘表示,左右移动±1,上下移动±8
            'bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR',  # 0-7
            'bP', 'bP', 'bP', 'bP', 'bP', 'bP', 'bP', 'bP',  # 8-15
            '--', '--', '--', '--', '--', '--', '--', '--',  # 16-23
            '--', '--', '--', '--', '--', '--', '--', '--',  # 24-31
            '--', '--', '--', '--', '--', '--', '--', '--',  # 32-39
            '--', '--', '--', '--', '--', '--', '--', '--',  # 40-47
            'wP', 'wP', 'wP', 'wP', 'wP', 'wP', 'wP', 'wP',  # 48-55
            'wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR']  # 56-63

        self.white_to_move = True
        self.moveLog = []

        self.w_l_c, self.b_l_c = True, True  # 白方和黑方的王车易位左路权限
        self.w_r_c, self.b_r_c = True, True  # 白方和黑方的王车易位右路权限

        self.white_king_loc = 60  # 修改棋盘时需同步更新该值
        self.black_king_loc = 4
        self.check_mate, self.stale_mate = False, False

        self.white_en_passant_sq, self.black_en_passant_sq = (None, None), (None, None)

Move类构造函数代码

class Move:
    __slots__ = ('start_ind', 'end_ind', 'move_ID', 'piece_moved', 'piece_captured', 'castle_move', 'en_passant')

    def __init__(self, start_sq, end_sq, board, castle_move=False, en_passant=False):
        self.start_ind = start_sq  
        self.end_ind = end_sq  

        self.move_ID = self.start_ind * 100 + self.end_ind
        self.piece_moved = board[self.start_ind]

        self.piece_captured = board[self.end_ind]

        self.castle_move = castle_move
        self.en_passant = en_passant

内容的提问来源于stack exchange,提问作者Federico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:15:42