地牢生成脚本报错:RectangularRoom对象无center属性求解决
解决RectangularRoom无center属性的错误
问题原因
错误提示AttributeError: 'RectangularRoom' object has no attribute 'center',是因为你在generate_dungeon函数中调用了room_2.center和room_1.center,但你的RectangularRoom类并未定义center这个属性。
修复方案
在RectangularRoom类中添加center属性,通过房间的边界坐标计算中心位置,使用@property装饰器让它可以像普通属性一样被访问:
修改后的RectangularRoom类代码:
class RectangularRoom: def __init__(self, x: int, y: int, width: int, height: int): self.x1 = x self.y1 = y self.x2 = x + width self.y2 = y + height @property def inner(self) -> Tuple[slice, slice]: """Return the inner area of this room as a 2D array index.""" return slice(self.x1 + 1, self.x2), slice(self.y1 + 1, self.y2) @property def center(self) -> Tuple[int, int]: """返回房间的中心坐标""" center_x = (self.x1 + self.x2) // 2 center_y = (self.y1 + self.y2) // 2 return (center_x, center_y)
说明
- 用整数除法
//计算中心坐标,保证结果是符合网格地图要求的整数 @property装饰器允许你直接通过room.center获取坐标,不需要写成方法调用room.center()
修改后重新运行代码,tunnel_between函数就能正确获取两个房间的中心坐标,生成连接隧道。
内容的提问来源于stack exchange,提问作者GeoNeo
相关产品推荐
相关产品推荐

