Search code examples
pythonfor-loopwhile-looppygamecollision

How to reduce only a single life in a while loop in pygame?


So basically I am making a game in which, if the player touches the enemy, the player loses a life. I tried to do it by:

if player.rect.colliderect(enemy.rect):
    life -= 1

This code is present in while loop, so it keeps decreasing the life. I just want it to decrease the life by only one.

Any help would be appreciated.

Thanks


Solution

  • Add an attribute collide to the your "Enemy" class:

    class Enemy(pygame.sprite.Sprite):
        def __init__(self, ...):
            # [...]
    
            self.collide = False
    

    Implement the following logic:

    • If an enemy collides with the player and self.collide is set, do nothing.

    • If an enemy collides with the player and self.collide is not set, set self.collide = True and decrement life.

    • If an enemy does not collide with the player, set self.collide = False.

    while run:
        # [...]
    
        for enemy in enemies:
    
            if player.rect.colliderect(enemy.rect):
                
                # If an enemy collides with the player and `self.collide` is set, do nothing.
                if not self.collide:
                    # If an enemy collides with the player and `self.collide` is not set, 
                    # set `self.collide = True` and decrement `life`.
                    self.collide = True
                    life -= 1
                    
            else:
                # If an enemy does not collide with the player, set `self.collide = False`.
                self.collide = False
    

    This logic means that live is only decremented when the enemy hits the player for the first time. The enemy must leave the player's area for a collision to be counted again.