Home > Back-end >  few enemies blinks after one gets demage
few enemies blinks after one gets demage

Time:03-13

Problem

When bullet collide with the enemy most times few of other enemies turns invsible for 0.05 seconds (blinks). Well I know why it happends, but I have no idea how to fix it.

Code

Here is my enemy damage code:

    for e in range(len(enemy.x)):
        angle = math.atan2(player.y - enemy.y[e], player.x - enemy.x[e])
        enemy.vel[e] = [math.cos(angle) * 2, math.sin(angle) * 2]
        enemy.x[e]  = enemy.vel[e][0]
        enemy.y[e]  = enemy.vel[e][1]
        rect = pygame.draw.rect(win, (255, 0, 0), (enemy.x[e], enemy.y[e], 40, 40))
        if rect.collidelistall(bullet.rect):
            enemy.healt[e] -= 1
            if enemy.healt[e] <= 0:
                del enemy.x[e]
                del enemy.y[e]
                del enemy.t[e]
                del enemy.vel[e]
                del enemy.healt[e]
            del bullet.x[rect.collidelistall(bullet.rect)[0]]
            del bullet.y[rect.collidelistall(bullet.rect)[0]]
            del bullet.vel[rect.collidelistall(bullet.rect)[0]]
            del bullet.dmg[rect.collidelistall(bullet.rect)[0]]
            break

Why enemy blinks

Enemy blinks because when one enemy gets attacked it needs to be breaked out of loop, even when there is a few enemies left to blit.

Why I need break out of loop

Well if didn't do that I will get Index error, when enemy is destoyed. It happens because when an enemy is destroyed the whole list gets smaller.

Thanks for your help!

CodePudding user response:

See How to remove items from a list while iterating?.

In your case the problem is hard to solve because you don't have just one list, you have separate lists for each coordinate and each velocity. It would be easy to handle this with an enemy object that has coordinates and velocity attributes. So you would have one list of enemies instead of multiple lists of coordinates and velocities.

Anyway, a simple trick to solve your problem is to iterate through the lists in reverse order:

for e in range(len(enemy.x)):

for e in range(len(enemy.x)-1, -1, -1):

So you can get rid of that break statement.

  • Related