[Solved] Stuck at Library Tactician


#1

Hey! I don’t know where my mistake is. When I run the code, I get an error message from a part of the code that was already written:

var nearest = archer.findNearestEnemy();

It tells me that I should try hero.findNearestEnemy but that’s not what I want here. Even with this error I tried executing, but I can’t complete the quest since one soldier always dies. I don’t know what to do…

function commandSoldier(soldier, soldierIndex, numSoldiers) {
    var angle = Math.PI * 2 * soldierIndex / numSoldiers;
    var defendPos = {x: 41, y: 40};
    defendPos.x += 10 * Math.cos(angle);
    defendPos.y += 10 * Math.sin(angle);
    hero.command(soldier, "defend", defendPos);
}

function findStrongestTarget() {
    var mostHealth = 0;
    var bestTarget = null;
    var enemies = hero.findEnemies();
    for(var i=0; i<enemies.length; i++){
     if(enemies[i].health > mostHealth){
      mostHealth = enemies[i].health;
      bestTarget = enemies[i];
     }
    }
    

    if (bestTarget && bestTarget.health > 15) {
        return bestTarget;
    } else {
        return null;
    }
}


function commandArcher(archer) {
    var nearest = archer.findNearestEnemy();
    if(archerTarget) {
        hero.command(archer, "attack", archerTarget);
    } else if(nearest) {
        hero.command(archer, "attack", nearest);
    }
}

var archerTarget = null;
while(true) {
    if(!archerTarget || archerTarget.health <= 0) {
        archerTarget = findStrongestTarget();
    }
    var friends = hero.findFriends();
    var soldiers = hero.findByType("soldier");
    var archers = hero.findByType("archer");
    for(var i=0; i < soldiers.length; i++) {
        var soldier = soldiers[i];
        commandSoldier(soldier, i, soldiers.length);
    }
    for(var j=0; j<archers.length; j++){
     var archer = archers[i];
     commandArcher(archer);
    }
}

#2

Ugh… sorry, I found my mistake…
In my archer loop

for(var j=0; j<archers.length; j++){
var archer = archers[i];
commandArcher(archer);
}

I used archers[i] instead of archers[j], which explains why I couldn’t use the findNearestEnemy with archer, since it was null