Function pygame.sprite.groupcollide() has been killing all the sprites from a group

Question:

I’ve been programming a game from a book called "python crash course". This game is about a ship that fires against aliens. I’ve been trying to implement a function to detect collision between any bullet sprite and any alien sprite in a group. The problem is when a collision is detected it kills the sprite that got hit and all the other aliens vanish afterward

The funcion:

def _check_bullet_alien_collision(self):
    """Check for any bullets that have hit aliens.
    If so, get rid of the bullet and the alien."""
    collisions = pygame.sprite.groupcollide(
        self.bullets, self.aliens, True, True)

I printed the dictionary "collisions" in order to show what happens and this is the result:

<Bullet Sprite(in 0 groups)> [<Alien Sprite(in 0 groups)>]

I’ve also tried to loop through the sprites and pass a single sprite as argument using another function which I forgot the name but no success.

Here is the project: https://github.com/thiagorizzi/Alien-Invasion

Asked By: Thiago

||

Answers:

I have seen this a few times over the years. The line that actually changes the fleet direction in _change_fleet_direction() should not be part of the loop that drops the aliens; see here.

That indentation issue makes this interesting behavior. When there’s an odd number of aliens, the fleet direction is flipped an odd number of times, so the method ends with a change in the fleet’s direction, which you want. When there is an even number of aliens, the fleet’s direction is flipped an even number of times, which results in no net change to the fleet’s direction. When that happens, the fleet just keeps dropping down and off the screen.

It can be a hard bug to track down.

Answered By: japhyr
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.