Skip to content Skip to sidebar Skip to footer

Why Do Group Lists In Pygame Have To Have "update" Functions, And Not Any Other?

I made a small particles application, but I was testing it and the function at the bottom has to be called 'update'. I thought the function name, just like variables, was just a na

Solution 1:

It will only recognize "update". If I change the function to "move", it will throw an error.

Yes of course. Read the documentation of pygame.sprite.Group.

pygame.sprite.Group.update() and pygame.sprite.Group.draw() are methods which are provided by pygame.sprite.Group. The former delegates the to the update method of the contained pygame.sprite.Sprites - you have to implement the method.

pygame.sprite.Group.update()

Calls the update() method on all Sprites in the Group.

The later uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects - you have to ensure that the pygame.sprite.Sprites have the required attributes

pygame.sprite.Group.draw()

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position.


If you want a similar mechanism with your own method, then you have to implement your own class derived from pygame.sprite.Group. For instance:

classMyGroup(pygame.sprite.Group):

    def__init__(self, *args):
        super().__init__(*args) 

    defmove(self):
        for sprite in self:
            sprite.move()
classparticle_class(pygame.sprite.Sprite):
    # [...]defmove(self):
        self.rect.y+=self.speed
particles = MyGroup()

for i inrange(10):
    particle=particle_class()
    particle.speed=random.randrange(5,11)
    particle.rect.y=0
    particle.rect.x=random.randrange(0,win_width+1)
    particles.add(particle)
particles.move()

Post a Comment for "Why Do Group Lists In Pygame Have To Have "update" Functions, And Not Any Other?"