Search code examples
pythonpygamepygame-surface

Pygame's Group.remove() function slows down game


In the space invaders project in Python Crash Course, we need to remove the bullets from the group once they are out of the bounds of the screen. This is achieved by

for bullet in self.bullets.copy():
    if bullet.rect.bottom <= 0:
        self.bullets.remove(bullet)

After saving and running the program as it is, the game seemed to have slowed down considerably to the point where it was unplayable. I changed the speed of the bullet, but the game became stuttery and laggy. The structure of the game where the remove function is present is somewhat like this:

while True: # main game loop
    --snip--
    self.game_updates() # other game functions
    self._update_bullets() # updating the bullets
    --snip--

def _update_bullets():
    self.bullets.update() # updates the rect.y of the bullets. self.bullets is the Group.
    for bullet in self.bullets.copy():
        if bullet.rect.bottom <= 0:
            self.bullets.remove(bullet)

I am sure it is not the if statement or the loop structure which is slowing it down, rather it is the remove() function. I tried replacing the remove with a print statement, and it works without any lag.

How can this be fixed?

(If you wish to view the entire project, here is the link.)


Solution

  • self.bullets is a pygame.sprite.Group() object. If you want to remove pygame.sprites.Sprite objects you have to call kill:

    remove the Sprite from all Groups

    for bullet in self.bullets:
        if bullet.rect.bottom <= 0:
            bullet.kill()
    

    With this solution you do not need to copy the pygame.sprite.Group.