// Summon some soldiers, then direct them to your base.
// Each soldier costs 20 gold.
while (hero.gold > hero.costOf("soldier")) {
hero.summon("soldier");
}
var soldiers = hero.findFriends();
var soldierIndex = 0;
// Add a while loop to command all the soldiers.
while(true) {
var soldier = soldiers[soldierIndex];
hero.command(soldier, "defend", {x: 50, y: 40});
// Go join your comrades!
hero.moveXY(51, 41);
}
You’re almost there, you just need to command them to “move” not “defend”. There’s also another problem in the while loop, but I’ll let you try and figure it out first.
-Danny
this is my new code but only 1 soldier goes to the cross
// Summon some soldiers, then direct them to your base.
// Each soldier costs 20 gold.
while (hero.gold > hero.costOf("soldier")) {
hero.summon("soldier");
}
var soldiers = hero.findFriends();
var soldierIndex = 0;
// Add a while loop to command all the soldiers.
while (true){
var soldier = soldiers[soldierIndex];
hero.command(soldier, "move", {x: 50, y: 40});
// Go join your comrades!
hero.moveXY(50, 40);
}
Deadpool: you just need to command them to “move” not “defend”.
I substituted ‘move’ with “defend” in my code and the code ran for the same time.
defend = move + attack ( if there is an enemy) @CODEBOY2 : You have
var soldierIndex = 0;
and you must use this variable in the while loop. And do you really need while(true) loop?
May be while( somthing_else) loop?
A while loop is a loop which continues until a certain condition is true.
A while true loop continues for ever. (Unless you break)
Here’s and example of a while loop:
var enemies = hero.findEnemies();
while(enemies.length > 0) { // this is looping until there are 0 enemies (enemies.length === 0)
var enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy); // once you've killed all the enemies it will stop looping
}
var enemies = hero.findEnemies(); // updating enemies so when it loops round it registers that you've killed an enemy.
}
The while loop you need for this level needs an index, which you can increase by one each time you command a soldier to move. This means you can compare the index with the friends.length to check when you should stop.
Do you understand it a bit more now?
You must have added that, in the original level it just has this:
// Summon some soldiers, then direct them to your base.
// Each soldier costs 20 gold.
while (hero.gold > hero.costOf("soldier")) {
hero.summon("soldier");
}
var soldiers = hero.findFriends();
var soldierIndex = 0;
// Add a while loop to command all the soldiers.
var soldier = soldiers[soldierIndex];
hero.command(soldier, "move", {x: 50, y: 40});
// Go join your comrades!
//the correct usage is:
soldierIndex += 1;
//with the + before the =.