Search code examples
pythonloopspygamecollision-detection

For Loop blocking other For Loop


I'm checking missileGroup to see if any instances of missile collided with any instances enemy in enemyGroup. When run, it prints "Hit" for the first loop, but it ignores the second for loop. Why is that?

 #### Imagine this is in a game loop ####
    for missile in missileGroup:
        if pygame.sprite.spritecollide(missile, enemyGroup, False) :
            print("Hit")

    
    for enemy in enemyGroup:
        if pygame.sprite.spritecollide(enemy, missileGroup, False):
            print("HI")

Update: @Rabbid76 stated that spritecollide wouldn't work because the spriteGroup enemyGroup is a list of sprites within a group(enemyGroup <- enemyList <- Enemy(sprite)) instead of a group of sprites(enemyGroup <- Enemy(sprite)). How would I access that?

Update 2 @paxdiablo stated that the first loop maybe emptying the group after iterating. I switched the places of the loops and 2nd loop ran, while the 1st did not.

Update 3 In the full code, .reset() method runs .kill() which removes the sprite from the group. Since the first loop removes the missile sprite before the second loop couldn't detect any collisions:

for missile in missileGroup:
    if pygame.sprite.spritecollide(missile, enemyGroup, False) :
        missile.reset()

for eachEnemy in enemyGroup: 
        if pygame.sprite.spritecollide(eachEnemy, missileGroup, False):
            eachEnemy.reset()

Solution

  • See pygame.sprite.spritecollide():

    Return a list containing all Sprites in a Group that intersect with another Sprite.

    Therefore the arguments to spritecollide() must be a pygame.sprite.Sprite object and a pygame.sprite.Group object.
    A list of pygame.sprite.Sprite objects instead of the Group does not work.

    missileGroup = pygame.sprite.Group()
    enemyGroup = pygame.sprite.Group()
    
    for missile in missileGroup:
        if pygame.sprite.spritecollide(missile, enemyGroup, False):
            print("Hit")
    
    for enemy in enemyGroup:
        if pygame.sprite.spritecollide(enemy, missileGroup, False):
            print("HI")
    

    Furthermore read about kill()

    The Sprite is removed from all the Groups that contain it.

    Hence if you call kill() in the 1st loop, the 2nd loop won't work, because the sprite is removed from all Groups.

    You call kill() in the reset methods. missile.reset() respectively eachEnemy.reset() causes the 2nd loop to fail.