# c++ – Tower Defense: Sorting Algorithm with multiple weights (enemy AI)

I’m writing a sorting algorithm for a tower defense mobile game. As a quick synopsis, I have a “tower” that can shoot at incoming threats that are within X distance from the base of the tower.

Each incoming enemy, will have an associated {distance_from_tower} and {enemy_weight}. The {distance_from_tower} will be a value between 0 and X (X being the max range of the tower). The {enemy_weight} is a valued weight of “how important” it is to target that enemy mob. For example:

Three enemies:

Archer: {distance_from_tower} = 3 , {enemy_weight} = 1

Knight: {distance_from_tower} = 7 , {enemy_weight} = 5

Zombie: {distance_from_tower} = 10 , {enemy_weight} = 3

Currently, I have a simple sorting algorithm that only sorts enemies by their distance from the tower. (So, in the above example, the tower would target: Archer –> Knight –> Zombie)

Which is a “fine” first logical step, but I want my towers targeting to be more robust. I want the sorting to take into account both the {distance_from_tower} AND the {enemy_weight}. (For reference as well, these two values are updated at every Z seconds during the game, so they are constantly being recalculated).

I would like for the tower to be “smarter” and have a more robust sorting mechanism, that takes into account both weights, as said above. That could potentially lead to the tower targeting an enemy mob that is further away because the {enemy_weight} value of that respective enemy mob is of “high priority”. (So, in the above example, the inclusion of using both weights could lead to the tower targeting in this order: Knight –> Archer –> Zombie).

I’ve been digging around for a few possible solutions, such as using a Travelling Salesman approach, Dijkstra’s algorithm, or Floyd’s algorithm, and I can’t figure out the best way to go about sorting using both weights in a manner that makes sense to me. Any intuition or help is greatly appreciated! Thanks!