1
votes

Im making a small game including enemies and the player. At some point the player can shoot the enemies and the enemies can respond with their own shots. Some levels include more than one enemy. Therefore in some instances one enemy can "accidently" shoot another enemy if the player was in between them and managed to get out of the way. During the case where both guards will shoot and the player gets out of the way, i want to annihilate both of the bullets from both of the enemies. Is there a way of doing this.

Currently i have this method in my weapon class.

def selfannihilation(self, guardbulletsprites):
    guardbulletsprites.remove(self)
    selfannihilation = pygame.sprite.spritecollide(self, guardbulletsprites, True)
    f not selfannihilation:
        guardbulletsprites.add(self)

And i call this method within a seperate function, checking bullet conditions. collision with walls, enemies, player, player bullets

```py
for bullet in guardbulletsprites:
    bullet.selfannihilation(guardbulletsprites)

During execution, the algorithm doesn't work as i expect it to. Only one of the bullets is removed, probably because of the "True" within the spritecollide line. I want both bullets to be removed from the guardbulletsprites group.

Thanks in advance

1

1 Answers

0
votes

The code below is a method within the class weapons

def selfannihilation(self, guardbulletsprites):

changed = False
temp = pygame.sprite.Group.copy(guardbulletsprites)
temp.remove(self)
selfannihilation = pygame.sprite.spritecollide(self, temp, True)
if not selfannihilation:
    guardbulletsprites.add(self)
else:
    changed = True

return changed, guardbulletsprites

And in the function that calls this i wrote.

def bulletannihilation(guardbulletsprites):

for bullet in guardbulletsprites:
    change, guardbulletsprites = bullet.selfannihilation(guardbulletsprites)
    if change:
        bulletannihilation(guardbulletsprites)

The if change: part, makes use of recursion to then call the function again because otherwise it will loop through guardbulletsprites the wrong number of times, only if the contents of guardbulletsprites have been changed.

I used a temp variable holding pretty much the same contents as guardbulletsprites because i felt like the contents of the actual guardbulletsprites were being removed accidentally.

Honestly i don't know how this works.