October 26, 2024
Chicago 12, Melborne City, USA
python

What does pygame.sprite.Group() do


I’m trying to create a hierarchy of Pygame Sprite Groups. During the time that the program runs, more sprites will be added to the sub-groups. I am wondering if I have to also add these new sprites to the parent groups manually, or if they will be automatically added to the parent groups simply because they are in the child groups. In short, when you add a sprite group to another sprite group, will the contents of the parent group be updated when you add sprites to the child group?

I’m trying to create several sprite groups, and use pygame to nest the groups:

import pygame

CREATE_NEW_DOG_SPRITE = pygame.USEREVENT + 1

class Dog(pygame.sprite.Sprite):
    pass

class Cat(pygame.sprite.Sprite):
    pass

class Goldfish(pygame.sprite.Sprite):
    pass

animals = pygame.sprite.Group()
mammals = pygame.sprite.Group()
fish = pygame.sprite.Group()
dogs = pygame.sprite.Group()
cats = pygame.sprite.Group()
goldfish = pygame.sprite.Group()

mammals.add([dogs, cats])
fish.add(goldfish)
animals.add([mammals, fish])

pygame.time.set_timer(CREATE_NEW_DOG_SPRITE, 5000)

while True:
    for event in pygame.event.get():
        if event.type == CREATE_NEW_DOG_SPRITE:
            new_dog = Dog()
            dogs.add(new_dog)

When new_dogis added to dogs, will it automatically be added to mammals and then to animals?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video