Home > OS >  Why should I loop through pygame sprites method instead of looping through the group itself?
Why should I loop through pygame sprites method instead of looping through the group itself?

Time:07-19

I am reading python crash course second edition. I am currently reading the game project. In this code that I copy from the book, it loops through a group using sprites() method.

    def _check_fleet_edges(self):
        """Respond appropriately if any aliens have reached an edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """Drop the entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y  = self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

Now In this book self.aliens is a group containing aliens which themselves inherit from class pygame.Sprite. When I delete the sprites method and replace it with self.aliens, that is the group itself, the result isn't changed. So what exactly sprites() method do? And why instead of looping through the group itself, the code in the book loops through the sprites() method?

CodePudding user response:

Read the documentation of sprites():

Return a list of all the Sprites this group contains. You can also get an iterator from the group, but you cannot iterate over a Group while modifying it.

So as long as you don't try to change the contents of the Group during iteration, there is no difference between for alien in self.aliens and for alien in self.aliens.sprites():.
However, for alien in self.aliens.sprites(): is the safer version because it allows you to change the contents of the Group inside the loop.

  • Related