Creating Enemy Threat System

Godot Version

Godot 4.6.3

Question

I am trying to make an enemy threat system, where an enemy can keep multiple threat values for multiple NPCs, then target the NPC with the highest “threat” value. So far, I have tried to enemies have an “threat array”, and when they are hit by an NPC, it will add the NPC object reference to a 2D array at [0][0], and a 0 at [0][1]. The next time that NPC hits the enemy, it will instead increase the value of the 0 at [0][1].

I have tried to do this a variety of ways, the issue is however that there isn’t a 2D version of the .append() function. There is append_array(), but that will simply add the contents of an array onto the end of a 1D array. I’m wondering what the correct way to have this specific 2D array appended onto an array.

Thanks.

May I propose a different solution? To me it seems a dictionary might be more useful than a 2D array here. Each enemy could have a dictionary where each key is a reference to an NPC, and each value is the number of times hit by said enemy.

If an enemy gets hit, it first checks if the dictionary’s keys already contain the NPC that attacked. If not, it creates a new key. If it does, the value linked to the key gets incremented by 1.

I have tried doing that, but I was trying to figure out how to order it but the value, but I can only order it by the key. I also am not sure how to iterate through a dictionary with a for loop to find the highest value.

You can iterate with something like:

var most = 0
var ref  = 0

for entry in dict:
    if dict[entry] > most:
        most = dict[entry]
        ref  = entry

After that, if most is nonzero, ref is your answer.