Code to attack a particular enemy that is not the nearest?

If I do if enemy.type == whatevs, it finds the enemy but then when I define enemy it identifies whatever is nearest.

Or, if you find your particular enemy and then use hero.move to get to it, how do you also attack enemies that come towards your path along the way?

when you define enemy, you are asking it to find the nearest one: hero.findNearestEnemy() but once you check for the type, it filters out the nearest of that type

as for this, you will have to move a few steps, check for enemies, and then move another few steps and so on, which will take an enormous amount of code
i dont think there is another way around

while (true) {
    let enemy = hero.findNearestEnemy();
    if (enemy && hero.distanceTo(enemy) <= 10) hero.attack(enemy);
1 Like


while True:
    enemy = hero.findNearestEnemy()
    if hero.distanceTo(enemy) >= 20:
        while enemy and > 0 and hero.distanceTo(enemy) <= 10:

that will never run and will give you an error, 1. you’re not checking if the enemy exists, 2. you’re checking if the distance is bigger or equal to 20, and then checking if it’s smaller or equal to 10… and why the else?

Thanks for your help (you, and everyone!). I forgot to say I’m doing python, sorry.

So I’m still confused and not sure I stated my question correctly. Here is a sample of code where none of the code executes for “shaman” type. Only the “else” is executing. Maybe it’s a bug with the distance condition stuff but even with simpler code, I always seem to struggle to get it to run when’ it’s about types.

while True:
    enemies = hero.findEnemies()
    for enemy in enemies:
        if enemy.type == "shaman":
            distance = hero.distanceTo(enemy)
            if distance >30:
                hero.move(enemy.pos.x, enemy.pos.y)
                if distance <15:
                    if >0:
            enemy = hero.findNearestEnemy()

Ok I got it to work by (fixing stupid stuff and) pulling it out as a function and then loop:

if enemy:

The problem was hero was in a loop of finding nearest enemy and attacking. Is that the theme I’ve been missing, that you have to make it a function to stop the loop for attacking the nearest or is there a more elegant approach to this? Thanks!