How to call functions from sprites in groups?

2019-07-21 08:46发布

问题:

I have a Sprite class that I have but in a group. Every time the mouse button is clicked I want to call a function from the class. The function should be called for every item in the group.

I only know how to call the update function from every item in the group but the code would be very slow if instead of calling the function on every mouse click I would call it on every frame.

To make it more clear I'll give an example:

class sprite_object(pygame.sprite.Sprite):
    def __init__(self):
        super(sprite_object, self).__init__()

    def on_mouse_click(self):
        #when the mouse is clicked to some stuff
        pass

    def update(self):
        #do some stuff every frame
        pass

sprite_object_1 = sprite_object()
sprite_object_2 = sprite_object()

group_of_sprites = pygame.sprite.Group()

group_of_sprites.add(sprite_object_1, sprite_object_2)

Now, I could call the on_mouse_click function in the update function but that would make the code inefficient.

How do I call the on_mouse_click function from every object in the group?

回答1:

The sprites() method of a sprite group object returns a list of sprites this sprite group object contains.

You could iterate through this list (i.e. all sprites your sprite group groupe_of_sprites holds) to call the on_mouse_click() method of each individual sprite_object:

for sprite_object in groupe_of_sprites.sprites():
    sprite_object.on_mouse_click()