yungalig
yungalig

Reputation: 49

Adding a collision in Aliens.py in Pygame

I'm having a problem adding a collision in the Pygame example aliens.py

I want to add a collision detection that makes the alien UFOs blow up when they collide against each other.

Here's the code of the collisions in the program:

# Detect collisions
        for alien in pygame.sprite.spritecollide(player, aliens, 1):
            boom_sound.play()
            Explosion(alien)
            Explosion(player)
            SCORE = SCORE + 1
            player.kill()

        for alien in pygame.sprite.groupcollide(shots, aliens, 1, 1).keys():
            boom_sound.play()
            Explosion(alien)
            SCORE = SCORE + 1

        for bomb in pygame.sprite.spritecollide(player, bombs, 1):
            boom_sound.play()
            Explosion(player)
            Explosion(bomb)
            player.kill()

        #for alien in pygame.sprite.spritecollide(aliens):
            #boom_sound.play()
            #Explosion(alien)

The last for loop is the one I created. I apparently need 3 parameters, but I'm not sure what other parameters are needed. Please Help!

Upvotes: 0

Views: 621

Answers (1)

Raiyan
Raiyan

Reputation: 1697

From the manual page of pygame.sprite (http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide) There are actually 4 parameters, They are :

  1. sprite : you want to check collision for this
  2. group : check collision against these
  3. dokill : indicates the action i.e. to kill or not to kill upon detecting collision
  4. collided (optional) : the callback function used to detect collision

I'm guess you wish to detect collision between two alien UFOs. You would need something like this:

for a in aliens :
    for alien in pygame.sprite.spritecollide(a, aliens, 1):
        boom_sound.play()
        Explosion(alien)

Upvotes: 1

Related Questions