HELP PLEASE Timber guard Javascript Computer Science 4

When i tested it, my soldiers spawned, but they didnt attack the ogres.
Here is my code


{
    var item = hero.findNearestItem();
    if (item) {
        while (true) {
            var item = hero.findNearestItem();
            var gold = hero.gold;
            hero.moveXY(item.pos.x, item.pos.y);
            if (gold >= 15) {
                hero.summon("soldier");
            }
        }
    }
    var friends = hero.findFriends();
    for (var friendIndex = 0; friendIndex < friends.length; friendIndex++) {
        var friend = friends[friendIndex];
        if (friend.type == "soldier") {
            var enemy = friend.findNearestEnemy();
            if (enemy) {
                hero.command(friend, "attack", enemy);
            } 
            else {
    hero.command(friend, "move", {x: 43, y: 43});
            }
        }
    }
}

Hi @27narellano , thank you for formatting your code correctly.

You end this first while-true loop before you get to the for-loop, which prevents anything after it from running.
Perhaps move it to the top of the code? (remember to remove the end curly brace)

Here, the soldiers are only moving to the centre of the map. When enemies spawn, the peasants are closer, which means that they attack the peasants instead of the soldiers. Change the x coordinate to a number nearer the right side of the map so that the ogres attack your soldiers first.

Hopefully this helps, feel free to ping me @MarmiteOnToast if you need any other help.

2 Likes

it worked thanks! the soldiers moved finally!

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.