【问题标题】:Why does it say I don't have a rect为什么说我没有直肠
【发布时间】:2018-08-14 08:28:53
【问题描述】:

我已输入代码self.rect = pygame.Rect(x, y, 100, 100)。有一个AttributeError: type object 'MobRow1' has no attribute 'rect'。为什么我把rect放进去后,这个错误一直弹出来。

我试过self.rect = pygame.Rect(self.x, self.y, 100, 100) 还是不行。

        class MobRow1(pygame.sprite.Sprite):
            def __init__(self, x, y):
                pygame.sprite.Sprite.__init__(self)
                self.image = pygame.image.load(badguy_file).convert_alpha()
                self.image = pygame.transform.scale(self.image, (50, 50))
                self.x = x
                self.y = y
                self.rect = pygame.Rect(x, y, 100, 100)
                self.mask = pygame.mask.from_surface(self.image)

            def update(self):
                self.rect.y += self.speedy
                self.rect.x += self.speedx

【问题讨论】:

  • 请创建一个MCVE 并将完整的错误回溯添加到您的问题中。
  • 这里肯定少了一段代码。您的函数 update 是否在脚本中的任何位置调用?
  • @ValBerthe 它没有在任何地方调用。你想让我给你看一下所有的代码吗?
  • @MaxCOSSETTO 请先添加错误回溯
  • @ValBerthe Traceback(最近一次调用最后):文件“C:\Users\maxco\AppData\Local\Programs\Python\Python36\codingandcaring github\Basketball 2.2.3.py”,第 143 行,在 MobRow1.update(screen_rect) 文件“C:\Users\maxco\AppData\Local\Programs\Python\Python36\codingandcaring github\Basketball 2.2.3.py”中,第 140 行,在更新 self.rect 中。 y += self.speedy AttributeError: 'pygame.Rect' 对象没有属性 'rect'

标签: python attributes pygame sprite


【解决方案1】:

您调用MobRow1.update(screen_rect),这将导致self 成为screen_rect。

因此,当调用 self.rect.y += self.speedy 时,它将失败并返回 AttributeError,因为 self,即 screen_rect,即 Rect 实例,没有 rect 属性。


您应该做的是在MobRow1 的实例 上调用update,而不是在MobRow1 类本身上。此外,如果您这样做,您要么必须向其 update 函数添加另一个参数,要么从函数调用中删除 screen_rect 参数。

【讨论】:

  • 你能举个例子吗?我会把代码放在哪里(例如 Main、Sprite 等)
  • 因为建议的代码目前不适合我。
  • @MaxCOSSETTO 我不能给你一个例子,因为我不知道你的其余代码是什么样的,MobRow1 实际代表什么以及它应该如何在你的游戏中工作。是否只有一个MobRow1?它总是在那里吗?然后你可能应该在你的主循环之前创建它,比如mob = MobRow1(x, y) 然后调用mob.update()
猜你喜欢
  • 1970-01-01
  • 2017-05-20
  • 2016-09-27
  • 2010-12-26
  • 1970-01-01
  • 2016-01-15
  • 2021-04-26
  • 1970-01-01
  • 2022-10-17
相关资源
最近更新 更多