如何从2D列表指定坐标获取对角线,实现国际象棋Bishop的合法走法
国际象棋象(Bishop)类实现方案
前置修正:现有代码的已知问题
首先需要修正原有代码的几个基础bug:
- Piece类中属性名拼写错误:
self.naame应改为self.name - 原代码中
legal_moves、capture_moves是函数内局部变量,没有绑定到实例,需改为实例属性才能被外部调用 - Bishop类中父类初始化调用错误:
super().init应改为super().__init__
核心需求实现
1. @property装饰器的适用场景说明
你提到的@property非常适配这个场景:
- 它可以把类方法伪装成普通属性,调用时不需要加括号
- 象的合法走法依赖当前所在坐标
self.coord,属于动态计算的属性,用@property可以保证每次取到的都是基于当前位置的最新值,不会出现属性值过期的问题
2. Bishop合法走法实现
象的走法逻辑为:沿左上、右上、左下、右下四个斜向移动,步数不限,不能越出棋盘,不能越过己方棋子(以下先提供边界校验的基础实现,可自行扩展挡子校验)。
合法走法用列表推导式实现的逻辑:四个斜向的步长组合为[(-1, -1), (-1, 1), (1, -1), (1, 1)],每个方向走17步,过滤掉超出07棋盘范围的坐标即可。
完整实现代码
class Piece: def __init__(self, team, coord, name): self.name = name self.value = 0 self.team = team self.coord = coord # coord格式为(x, y),均为0~7的整数 # 父类预留合法走法属性,子类各自实现 @property def legal_moves(self): return [] @property def capture_moves(self): # 象的吃子走法和普通走法一致,可直接复用legal_moves return self.legal_moves class Pawn(Piece): def __init__(self, team, coord): super().__init__(team, coord, name='Pawn') self.value = 1 @property def legal_moves(self): # 这里简化实现,仅对应原示例的固定走法,可自行扩展首步进2等逻辑 x, y = self.coord # 黑方pawn走法要翻转向下,这里示例只给白方逻辑,可自行扩展 return [[dx, dy] for dx, dy in [(0,1)] if 0<=x+dx<8 and 0<=y+dy<8] @property def capture_moves(self): x, y = self.coord return [[dx, dy] for dx, dy in [(-1,1), (1,1)] if 0<=x+dx<8 and 0<=y+dy<8] class Bishop(Piece): def __init__(self, team, coord): super().__init__(team, coord, name='Bishop') self.value = 3 @property def legal_moves(self): x, y = self.coord directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)] # 列表推导式实现:遍历四个方向,每个方向走1-7步,过滤出合法坐标 return [ [dx*step, dy*step] for dx, dy in directions for step in range(1, 8) if 0 <= x + dx*step < 8 and 0 <= y + dy*step < 8 ] class Board(): def __init__(self): self.grid = [['x' for _ in range(8)] for _ in range(8)] def get_coord(self, x, y): return self.grid[x][y]
调用示例
# 初始化一个在坐标(2,3)的白方象 white_bishop = Bishop(team='white', coord=(2,3)) # 直接访问legal_moves属性即可得到所有合法走法偏移 print(white_bishop.legal_moves)
如果需要添加挡子校验,只需要在legal_moves的列表推导式中添加对应Board实例的格子判断逻辑即可。
内容的提问来源于stack exchange,提问作者Zii Donato
相关产品推荐
相关产品推荐

