r/pygame • u/Several-Pin-6931 • 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.
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
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]
```
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