Hunters and prey- cannot solve pls help - JS

I am having a problem commanding the archers’

// Ogres are trying to take out your reindeer!
// Keep your archers back while summoning soldiers to attack.

function pickUpCoin() {
    // Collect coins.
        var items = hero.findItems();
        var nearest = hero.findNearest(items);
        if (nearest) {
            hero.move(nearest.pos);
        }
        // hero.moveXY(item.pos.x,item.pos.y);    
}

function summonTroops() {
    // Summon soldiers if you have the gold.
    if (hero.costOf("soldier") < (hero.gold)) {
        hero.summon("soldier");
    }
}

// This function has an argument named soldier.
// Arguments are like variables.
// The value of an argument is determined when the function is called.
function commandSoldier(soldier) {
    // Soldiers should attack enemies.
    if (enemy) {
        var friends = hero.findFriends();
        var enemy = hero.findNearestEnemy();
        hero.command(friends, "attack", enemy);
    }
}

// Write a commandArcher function to tell your archers what to do!
// It should take one argument that will represent the archer passed to the function when it's called.
// Archers should only attack enemies who are closer than 25 meters, otherwise, stay still.
function commandArcher(archer) {
    var enemy = hero.findNearestEnemy();
    if (enemy) {
        var distance = hero.distanceTo(enemy);    
    }
    if (enemy && distance <25) {
        hero.command(archer, "attack", "enemy");
        }
    
}
while(true) {
    pickUpCoin();
    summonTroops();
    var friends = hero.findFriends();
    for(var i=0; i < friends.length; i++) {
        var friend = friends[i];
        if(friend.type == "soldier") {
            // This friend will be assigned to the variable soldier in commandSoldier
            commandSoldier(friend);
        } else if(friend.type == "archer") {
            // Be sure to command your archers.
            commandArcher();
        }
    }
}

did you define archers?
and if so write:

if (archer){
//whatever to do here
}

before you command

1 Like

Do you want to attack “enemy” or an actual enemy? The variable enemy is being defined as the closest enemy to the hero, so you would want to attack that enemy, not the string “enemy”.

1 Like

You also set distance = hero.distanceTo, and I think you probably want distance = archer.distanceTo.

I’m curious, do your soldiers attack? I’ve never tried to command them as a group:
hero.command(friends, …), only individually through a loop. If it works, please tell us - that would be handy. Otherwise, you may be calling a method that isn’t permitted.