Pygame实现精灵移动到最近精灵时'int'对象无x属性错误排查
报错原因
- 你定义的
Scot类没有声明x、y实例属性,精灵的坐标全部存储在rect属性下,impact方法中直接访问self.x、self.y属于非法调用,是触发属性错误的直接原因。 update方法中调用impact的逻辑完全错误:impact是实例方法,需要通过实例对象调用,你用类名Scot.impact(enemy)调用既没有传入实例参数,还传入了未定义的enemy变量,同时没有接收impact的返回值,会导致后续逻辑找不到enemy变量。- 逻辑漏洞:你在遍历
all_sprites找最近精灵时没有排除自身,当场景内只有1个精灵时会返回自己,移动逻辑无意义;且impact返回的是精灵对象,后续代码错误地将其当做元组用enemy[0]、enemy[1]取值,会触发二次报错。
修复方案
直接替换Scot类的impact和update方法即可,修改后代码如下:
class Scot(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = scot_scaled.convert() self.rect = self.image.get_rect() self.image.set_colorkey(BLACK) def impact(self): # 查找最近精灵时排除自身 other_sprites = [e for e in all_sprites if e is not self] if not other_sprites: # 场景内只有自身时不移动 return None # 坐标取rect下的x、y enemy = min(other_sprites, key=lambda e: pow(e.rect.x-self.rect.x, 2) + pow(e.rect.y-self.rect.y, 2)) return enemy def update(self): enemy = self.impact() if not enemy: # 没有其他精灵时直接跳过移动逻辑 return a = 1 for sprite in all_sprites: if sprite is self: continue if self.rect.colliderect(sprite.rect): a = 0 break # 目标坐标取精灵的rect属性 destination_x = enemy.rect.x destination_y = enemy.rect.y if self.rect.x == destination_x: pass else: if self.rect.x < destination_x: self.rect.x += 1 * a else: self.rect.x -= 1 * a if self.rect.y == destination_y: pass else: if self.rect.y < destination_y: self.rect.y += 1 * a else: self.rect.y -= 1 * a
修复后即可正常运行,点击鼠标生成的精灵会自动朝向最近的其他精灵移动,接触后停止。
内容的提问来源于stack exchange,提问作者jojo osass
相关产品推荐
相关产品推荐

