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

使用python-chess检测白方通路兵:是否有内置方法及实现方案

用python-chess检测局面中的通路兵

python-chess库没有内置的通路兵检测函数,不过可以自行实现判定逻辑来完成需求。

通路兵的判定逻辑

一方的兵被视为通路兵,需满足两个核心条件:

  • 该兵所在的**文件(列)**以及左右相邻的两个文件中,没有对方的兵存在
  • 该兵已经推进到越过对方初始兵线的位置:
    • 白方兵需在第5行及以上(国际象棋行号从1到8)
    • 黑方兵需在第4行及以下

实现代码

以下是符合要求的函数实现:

import chess

def checkForPassedPawn(position: chess.Board, side_to_move: chess.Color):
    # 获取目标方与对方的所有兵的位置
    target_pawns = position.pieces(chess.PAWN, side_to_move)
    opponent_color = chess.BLACK if side_to_move == chess.WHITE else chess.WHITE
    opponent_pawns = position.pieces(chess.PAWN, opponent_color)

    # 遍历每个目标方的兵,逐一检查是否为通路兵
    for pawn_square in target_pawns:
        pawn_file = chess.square_file(pawn_square)
        # 检查当前兵所在列及左右相邻列是否存在对方兵
        has_opponent_pawn = False
        for file in [pawn_file - 1, pawn_file, pawn_file + 1]:
            if 0 <= file < 8:  # 文件范围限制在0-7(对应棋盘a-h列)
                for opp_pawn_square in opponent_pawns:
                    if chess.square_file(opp_pawn_square) == file:
                        has_opponent_pawn = True
                        break
                if has_opponent_pawn:
                    break
        
        # 若对应列无对方兵,再检查是否越过对方初始兵线
        if not has_opponent_pawn:
            if side_to_move == chess.WHITE:
                if chess.square_rank(pawn_square) >= 4:  # 第5行对应索引4(行号从0开始计数)
                    return True
            else:
                if chess.square_rank(pawn_square) <= 3:  # 第4行对应索引3
                    return True
    # 未找到符合条件的通路兵
    return False

代码说明

  1. 先通过pieces方法获取目标方和对方所有兵的位置集合
  2. 对每个目标兵,遍历其所在列及左右相邻列,确认无对方兵存在
  3. 若列条件满足,再判断兵是否到达越过对方初始兵线的位置
  4. 只要找到一个符合条件的通路兵,立即返回True;遍历完所有兵都不符合则返回False

测试示例

# 创建测试局面:白方e5位有一个通路兵
test_board = chess.Board()
test_board.set_fen("8/8/8/4P3/8/8/8/8 w - - 0 1")
print(checkForPassedPawn(test_board, chess.WHITE))  # 输出:True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:40:59