python - 更新一个类中的多个项目,而不仅仅是一个
问题描述
在此代码的更新部分,只有第一个 bat 会受到 Bat() 类中的 update() 的影响......在主循环之外:
START_BAT_COUNT = 30
BAT_IMAGE_PATH = os.path.join( 'Sprites', 'Bat_enemy', 'Bat-1.png' )
bat_image = pygame.image.load(BAT_IMAGE_PATH).convert_alpha()
bat_image = pygame.transform.scale(bat_image, (80, 70))
class Bat(pygame.sprite.Sprite):
def __init__(self, bat_x, bat_y, bat_image, bat_health):
pygame.sprite.Sprite.__init__(self)
self.bat_health = bat_health
self.image = bat_image
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image)
self.rect.topleft = (bat_x, bat_y)
def update(self):
self.bat_health -= 1
if self.bat_health < 0:
new_bat.kill()
all_bats = pygame.sprite.Group()
for i in range(START_BAT_COUNT):
bat_x = (random.randint(0, 600))
bat_y = (random.randint(0, 600))
bat_health = 5
new_bat = Bat(bat_x, bat_y, bat_image, bat_health)
all_bats.add(new_bat)
主循环内...
all_bats.update()
all_bats.draw(display)
任何帮助都会很棒!谢谢。
解决方案
在方法对象中,您必须使用实例参数 ( self
) 而不是全局命名空间中的对象实例。这意味着您必须调用self.kill()
而不是new_bat.kill()
:
class Bat(pygame.sprite.Sprite):
# [...]
def update(self):
self.bat_health -= 1
if self.bat_health < 0:
self.kill()