I'm trying to make it so then when an enemy collides with the player, a single life is lost and the player is positioned at the center of the screen. It works about half of the time, but the other half of the time two or three lives are lost from one collision.
def collide(self):
for enemy in enemies:
if ((robot.hitbox[0] < enemy.x + 16 < robot.hitbox[0] + robot.hitbox[2]) or (robot.hitbox[0] < enemy.x - 16 < robot.hitbox[0] + robot.hitbox[2])) and ((robot.hitbox[1] < enemy.y + 16 < robot.hitbox[1] + robot.hitbox[3]) or (robot.hitbox[1] < enemy.y - 16 < robot.hitbox[1] + robot.hitbox[3])):
robot.alive = False
robot.x = 400
robot.y = 300
for enemy in enemies:
enemies.remove(enemy)
robot.lives -= 1
robot.alive = True
This is a function under the class Enemy which is called inside of the Enemy's draw function, which is called in the while loop.
while running:
## add if robot.alive == True into loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
userInput = pygame.key.get_pressed()
if len(enemies) <= 3:
randSpawnX = random.randint(32, 768)
randSpawnY = random.randint(77, 568)
if (robot.x - 100 <= randSpawnX <= robot.x + 100) or (robot.y - 100 <= randSpawnY <= robot.y + 100):
randSpawnX = random.randint(32, 768)
randSpawnY = random.randint(77, 568)
else:
enemy = Enemy(randSpawnX, randSpawnY)
enemies.append(enemy)
if robot.alive == True:
for enemy in enemies:
enemy.move()
robot.shoot()
robot.movePlayer(userInput)
drawGame()
Could anyone help me figure out why this is occurring? I believe it's because multiple collisions are registering but since I move the robot to the middle of the screen as soon as the first hit is registered and before the lives are lost, why is this happening?