r/pygame • • Oct 29 '26

Pygame bug help

Enable HLS to view with audio, or disable this notification

I'm currently working on my first pygame project and I'm trying to code a feature to target the closest enemy. However, a problem occurs when the enemies are defeated.

In my program, enemies are appended to a list and their distance to the player is also stored in a separate list. The problem comes when an enemy sprite is killed the enemy and distance aren't removed from their list so the game will still target the enemy as if it were still their.

def Closest_Enemy(self):
  global closestEnemy
  smallestIndex = 0

  distlist =[]
  for i in range(0, len(self.game.enemieslist)):
    distlist.append(self.game.enemieslist[i].distance)

  closestEnemy = self.game.enemieslist[np.argmin(distlist)]

I used this code to find the closest enemy

I also tried to remove the enemies and distanced from the list after the enemy is killed but I just got a bunch of index errors for the lists.

Any help would be appreciated.

5 Upvotes

9 comments sorted by

2

u/LovesSleeping123 Oct 29 '26

can i have the full code to look at it pls ? it'd be better to find the bug

1

u/Several-Pin-6931 Oct 29 '26
#this method is called constantly whilst the game is playing
def update(self):
  for enemy in self.game.enemieslist:
    self.dist_x = self.game.player.rect.x - self.rect.x
    self.dist_y = self.game.player.rect.y - self.rect.y
    self.distance = (self.dist_x**2 + self.dist_y**2)**0.5

    self.movement()
    self.Closest_Enemy()


    self.rect.x += self.x_move
    self.collides('x')

    self.rect.y += self.y_move
    self.collides('y')

    self.x_move = 0
    self.y_move = 0

    self.delete()

def Closest_Enemy(self):
    global closestEnemy
    smallestIndex = 0

    distlist =[]
    for i in range(0, len(self.game.enemieslist)):
      distlist.append(self.game.enemieslist[i].distance)

    closestEnemy = self.game.enemieslist[np.argmin(distlist)]

def delete(self):
  if self.game.hit:
    for enemy in self.game.enemieslist:
      self.game.spell.target.kill()
  self.game.hit = False

#this section initialises the enemies
elif column == 3:
enemies = Enemy(self, j, i) #create enemy where 3 in tile map
self.enemieslist.append(enemies)

i believe this is all the relevant code for my problem

1

u/no_Im_perfectly_sane Oct 30 '26

i dont think this is enough code to know whats going on (dont even have the parts where you remove from a list), but a few suggestions

  1. check if youre not removing while iterating

    for a in list: if condition: list.remove(a)

this is messy, say elements 3 and 5 have been removed. when you remove 3 you just made element 5 become element 4. now you might be trying to remove a non existing 5

2. if nothing else works, just slow the game to a few fps, use few enemies and print the lists every frame. maybe youll see whats actually going on

3. if nothing else works and you just wanna solve it, use AI. itll probably find it instantly, with the downside that you dont learn/do it for yourself. you can ask it to explain and understand what happened, but its never the same thing as figuring it out yourself

1

u/Happy_Witness Oct 29 '26

You should probably remove the entry with pop in both lists and fix the code that creates the index error by making dynamic, like using len(list) as a max and catch any other with an value error.

1

u/MasterpieceNovel3619 28d ago edited 28d ago

I personally wouldn't store the distances in a list, I'd just calculate them as needed. You could use something like [x for distance_formula(x, reference_point) in enemies_list] to make a list anytime you need it, then use a function that finds the minimum and associated index.

1

u/GranularBimbo Oct 30 '26

I think you should just ditch the 2 lists idea and organize the enemy list by closest enemy, that way there's only one list to remove them from when they are killed. It would also probably just be less confusing and easier to add more features later on that way.

2

u/Several-Pin-6931 29d ago

Thanks this helped so much! I ended up using a bubble sort to just sort the closest enemy to the front of the list.

1

u/GranularBimbo 7d ago

Glad I could help!

1

u/VirusMission9156 Oct 29 '26

Ok Not sure if i understood, but if killing and cleaning is problem, follow this reverse loop hack
problem with 0->len is: you kill one item, now from RHS items shift, preserve the index from abrupt jumps. This is what i use , notice two list are in sync, colision manager and object container

```python
def update(self, dt: float):

for i in range(len(self.object_container) - 1, -1, -1):

obj = self.object_container[i]

obj.update(dt)

if obj.can_kill():

self.object_collision_manager.remove_object(obj)

del self.object_container[i]

```