PyGame 创建某些对象的第二个实例后出现属性错误

PyGame attribute error after creating second instance of certain objects

我可以创建这个 class 的一个实例,它运行良好。但是,无论何时尝试创建第二个实例,即使第一个对象已被删除,它也会 returns 一个错误。这也很奇怪,因为有一个与此相同的 class,它可以根据需要创建尽可能多的实例而不会出现错误。

两次都以完全相同的方式制作对象。

class GOAL(pygame.sprite.Sprite):
    def __init__(self,spawnx,spawny):
        super().__init__()
        self.image = goal
        self.surf = pygame.Surface(self.image.get_rect().size)
        self.rect = self.image.get_rect(topleft = (spawnx,spawny))

Class 启动代码。

goal = GOAL((lineCount*100),(characterCount*100))
all_sprites.add(goal)

Class 创建代码。

Traceback (most recent call last):
  File "C:\Users\User\Documents\python\pygame\simian shenanigans\simian shenanigans.py", line 975, in <module>
    mainmenu()
  File "C:\Users\User\Documents\python\pygame\simian shenanigans\simian shenanigans.py", line 689, in mainmenu
    entity.clicked()
  File "C:\Users\User\Documents\python\pygame\simian shenanigans\simian shenanigans.py", line 540, in clicked
    self.sendfunction()
  File "C:\Users\User\Documents\python\pygame\simian shenanigans\simian shenanigans.py", line 732, in playmenu
    entity.clicked()
  File "C:\Users\User\Documents\python\pygame\simian shenanigans\simian shenanigans.py", line 540, in clicked
    self.sendfunction()
  File "C:\Users\User\Documents\python\pygame\simian shenanigans\simian shenanigans.py", line 768, in level1
    levelgeneration(levelToGenerate,all_sprites,enemies,walls,playerGroup)
  File "C:\Users\User\Documents\python\pygame\simian shenanigans\simian shenanigans.py", line 903, in levelgeneration
    goal = GOAL((lineCount*100),(characterCount*100))
  File "C:\Users\User\Documents\python\pygame\simian shenanigans\simian shenanigans.py", line 638, in __init__
    self.surf = pygame.Surface(self.image.get_rect().size)
AttributeError: 'GOAL' object has no attribute 'get_rect'

错误代码。

请询问是否需要显示任何其他代码。整篇文章有 1000 行,并不是所有内容都相关,所以我尝试包含必要的代码。

您似乎将 self.image 设置为 goal,这是 GOAL 的一个实例,假设这与 class 启动中的目标相同代码。但是,即使 GOALpygame.sprite.sprite,class 也没有 get_rect 功能!

我想你想参考 pygame.Surface instead, according to the example here:

class Block(pygame.sprite.Sprite):

    def __init__(self, color, width, height):
       # Call the parent class (Sprite) constructor
       pygame.sprite.Sprite.__init__(self)

       # Create an image of the block, and fill it with a color.
       # This could also be an image loaded from the disk.
 This--->self.image = pygame.Surface([width, height])
       self.image.fill(color)

       self.rect = self.image.get_rect()