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

Python Chess库board.attackers函数使用方法及参数适配问题

Python Chess库board.attackers函数参数转换问题

我在用Python Chess库编写娱乐用的象棋代码时,调用board.attackers函数遇到参数格式问题。文档示例使用chess.F3这类常量作为参数,但我从move中提取的字符串格式参数不被函数接受,相关代码如下:

def staticAnalysis(board, move, my_color):
  score = random.random()
  board.push(move)
 
  for (piece, value) in [(chess.PAWN, 1), 
                       (chess.BISHOP, 4), 
                       (chess.KING, 0), 
                       (chess.QUEEN, 10), 
                       (chess.KNIGHT, 5),
                       (chess.ROOK, 3)]:
    score += len(board.pieces(piece, my_color)) * value
    score -= len(board.pieces(piece, not my_color)) * value
     
  score += 100 if board.is_checkmate() else 0
  score += 10 if board.is_capture(move)  else 0

  # 获取移动的目标位置,移除棋子标识,例如Ph1变为h1
  square =  str(move)[-2:]  

  # 但该参数不被接受?如何实现此功能?
  myAttackers = board.attackers(not my_color,  square)
  score +=len(attackers)*-2

return score

问题原因

board.attackers的第二个参数要求传入棋格的整数索引或chess.Square类型的常量(比如chess.H1),而你传入的是字符串格式的棋格标识,不符合参数要求。另外代码里还存在变量名错误:定义了myAttackers却使用未定义的attackers。

解决方法

方法1:直接通过move对象获取目标棋格(推荐)

不用手动截取字符串,直接调用move.to_square就能拿到目标棋格的整数索引:

def staticAnalysis(board, move, my_color):
  score = random.random()
  board.push(move)
 
  for (piece, value) in [(chess.PAWN, 1), 
                       (chess.BISHOP, 4), 
                       (chess.KING, 0), 
                       (chess.QUEEN, 10), 
                       (chess.KNIGHT, 5),
                       (chess.ROOK, 3)]:
    score += len(board.pieces(piece, my_color)) * value
    score -= len(board.pieces(piece, not my_color)) * value
     
  score += 100 if board.is_checkmate() else 0
  score += 10 if board.is_capture(move)  else 0

  # 直接获取目标棋格的整数索引
  square = move.to_square
  myAttackers = board.attackers(not my_color, square)
  # 修正变量名错误
  score += len(myAttackers) * -2

  return score

方法2:字符串转棋格索引

如果一定要从字符串转换,使用chess.parse_square()函数将字符串格式的棋格(如"h1")转为整数:

# 替换原代码中的对应部分
square_str = str(move)[-2:]
square = chess.parse_square(square_str)
myAttackers = board.attackers(not my_color, square)
score += len(myAttackers) * -2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:15:49