Skip to main content
 首页 » 编程设计

python之Pygame.sprite.Group.add 错误

2025年05月04日11yyy_WW

好的,这是一段代码

lives_group = pygame.sprite.Group() 
life_pos = [603,566,529,492] 
pos = 0 
for life in range(0,ship.lives): 
    live = game_display.Life([10, life_pos[pos]]) 
    lives_group.add(live) 

.Life ting 是这样的:

class Life(pygame.sprite.Sprite): 
    def __init__(self, location): 
        self.image = pygame.image.load('Spaceship_life.png') 
        self.rect = self.image.get_rect() 
        self.rect.left, self.rect.top = location 

这是我得到的错误:

Traceback (most recent call last): 
  File "C:\Users\------\My programs\old\GUI based games\Spaceblaster\0.1\main.py", line 17, in <module> 
    lives_group.add(live) 
  File "C:\Python33\lib\site-packages\pygame\sprite.py", line 360, in add 
    sprite.add_internal(self) 
  File "C:\Python33\lib\site-packages\pygame\sprite.py", line 163, in add_internal 
    self.__g[group] = 0 
AttributeError: 'Life' object has no attribute '_Sprite__g' 

很抱歉说出了我的名字,但我保留了它的长度以防万一

请您参考如下方法:

不要忘记调用父类的构造函数

class Life(pygame.sprite.Sprite): 
    def __init__(self, location): 
        super(Life, self).__init__() 
        self.image = pygame.image.load('Spaceship_life.png') 
        self.rect = self.image.get_rect() 
        self.rect.left, self.rect.top = location