GregarityNow
GregarityNow

Reputation: 738

Pygame delete all objects in class

I'm working on a pygame project at the moment and I'm wondering if there is an easy way to delete all sprites in a class. I have all the sprites in a group called self.spritegroup, so I couldn't just delete all objects in a group. Is there a simple shortcut to delete all objects in a class?

Upvotes: 1

Views: 2491

Answers (3)

Nex_Lite
Nex_Lite

Reputation: 378

Well you could always just re-assign a new group object to your old group.

your_old_group = new_group

I'm not entirely sure but it seems kill is meant to delete specific sprites.

Upvotes: 0

Dolda2000
Dolda2000

Reputation: 25855

That depends, I guess, on whether you consider this "simple":

for sprite in group:
    if isinstance(sprite, your_class):
        sprite.kill()

If you want to, you can, of course, define a subclass of Group that has this operation as a method:

class MyGroup(pygame.sprite.Group):
    def clear_by_class(self, cls):
        for sprite in self:
            if isinstance(sprite, cls):
                sprite.kill()

Upvotes: 3

Malik Brahimi
Malik Brahimi

Reputation: 16711

Just use pygame.sprite.group like so:

class MySprite(pygame.sprite.Sprite):
    group = pygame.sprite.Group()

    def __init__(self):
        self.image = pygame.image.load('relative/path') # load image
        self.rect = self.image.get_rect() # create rect

        self.rect.topleft = pygame.mouse.get_pos() # set the location
        pygame.sprite.Sprite.__init__(MySprite.group) # add to group

Then to remove and delete:

my_sprite = MySprite()
my_sprite.kill() # removes from group
del my_sprite # deletes object from memory (optional)

Upvotes: 0

Related Questions