Steve104 Steve104 - 1 year ago 130
Python Question

Pygame remove a single sprite from a group

I am making a game and when the sprite goes under 100 on the x axis it is supposed to be deleted. The sprites are all located in a class. When the first sprite reaches the end, it deletes the final sprite of the group instead of the first.

Enemy Class

class Enemy(pygame.sprite.Sprite):
def __init__(self,x,y):
self.image = pygame.image.load('Enemy.gif').convert()
self.rect = self.image.get_rect(x=x, y=y)

def update(self):
self.rect.x -= 4

def die(self):
for enemy in EnemyList:
if enemy.rect.x<100:

def draw(self, DISPLAY):
DISPLAY.blit(self.image, self.rect)

Main Loop (Part for enemy)

time = 0
while not Gameover: #Loop of the gameplay
if time in (0,50,100,150,200):
enemy = Enemy(DIS_HEIGHT,random.randrange(0,DIS_HEIGHT)
time +=1

I have a background and everything else works fine, I just cannot delete the correct sprite from the enemy group.

Answer Source

You cannot remove items from a list while iterating over it:

def die(self):
    for enemy in EnemyList:
        if enemy.rect.x<100:

You could instead write something like this:

def die(self):
     global EnemyList
     EnemyList = [enemy for enemy in EnemyList if enemy.rect.x>=100]

The global statement is needed so that the function can modify the EnemyList, which is outside its scope in this case.

Or store the enemies that you want to delete to another list, and then delete them afterwards.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download