0
votes

I am creating a sidescroller shooter game in which the enemies(drones)spawn contantly on the right side of the screen. The recently created enemies are appended to a list drones Each enemy goes towards the left of the screen. Once they are out of the screen, they get removed from the list.

I also want to remove the drones when they collide with the player. The following code works properly as long as there are multiple objects in the drones list, but when the list has only one item (so one drone is on the screen) that drone does not get deleted upon collision.

I have no idea why the first list item cannot be destroyed.

drones = []
class Drone
    #other call methods

    def hit(self):
        del drones[drones.index(self)]

def generate_enemy():
    global drones
    if len(drones) < 20:    
        if (random.randint(1,100) == 1):
            drones.append(Drone(screenWidth, random.randint(300,500)) 

def main():
    global drones
    while True:
       #main loop stuff happening
       if condition == True:
           generate_enemy():
       #main loop stuff happening
       if player and (len(drones) > 0):
           for i in range(len(drones)-1):
               if drones[i].hitbox.colliderect(player.hitbox):
                   drones[i].hit()
main()
1

1 Answers

0
votes

The "correct" way to do this in pygame is to let your classes inherit from Sprite, then use a Group instead of a simple list to store your enemies, and using pygame.sprite.spritecollide for collision detection with the dokill argument set to True.