Sorting enemies by distance (Python)


#1

I found a code snippet that was supposed to sort items by distance, so I modified it to try to sort enemies by distance:

def compare_distance(item1, item2):
    return distance(item1) - distance(item2)

enemies = sorted(hero.findEnemies(), cmp=compare_distance)
i=0
while i < len(enemies):
    hero.debug(hero.distanceTo(enemies[i]))
    i+=1

However, the debugging output still says:
|Hel’s Krieger| 28.20994297809327
|Hel’s Krieger| 37.144368939078184
|Hel’s Krieger| 33.42445434966645
|Hel’s Krieger| 29.936677108466633

In other words, the enemies are not in order. What gives?


#2

I am not sure but I don’t think this code work, my knowledge is not perfect though
sorted take an iterable and a key(optional)

the function compare_distance ask for 2 arguments, and there is none when you call it
so I believe the key is null in this code

The sorted() function won’t show error because the second argument is optional

The Array should still get sorted though: by the name of the monsters. (for example if you check the array there is an high chance that enemies[0] start with letter A.

I’ll look into it later.


#3

I’ve tried many things, I think all the arguments in the sorted function does not work
I tried reverse = True

and it did not reverse the order of the array.

enemies = hero.findEnemies()
sort_enemies = sorted(enemies, key=None, reverse=True)
i=0

hero.say(sort_enemies[0])