Updating multiple items in a class, not just one

Viewed 53

In the update section of this code, only the first bat that gets made is affected by update() in class Bat()... Outside of main loop:

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)

Inside main loop...

all_bats.update()
all_bats.draw(display)

Any help would be great! Thanks.

1 Answers

In Method Objects you must use the instance parameter (self) instead of an object instance in the global namespace. This means you have to call self.kill() instead of new_bat.kill():

class Bat(pygame.sprite.Sprite):
    # [...]

    def update(self):
        self.bat_health -= 1 
        if self.bat_health < 0:
            self.kill()
Related