Fair Battle [JS]

My error message says I’m stuck in an infinite loop or my code is too slow? I haven’t gotten to cloudrip mountain yet so using a for loop mentioned in a different thread isn’t an option for me yet.

// Attack when your soldiers total health is greater
// than the ogres total health

// This function return the sum of all the units health.
function sumHealth(units) {
    var totalHealth = 0;
    
    // Complete this function:
     var unitIndex = 0;
     var unitArray = units[unitIndex];
    while(unitIndex < units.length){
        totalHealth =+ unitArray.health; 
        
    } unitIndex+= 1;
    return totalHealth;
}

while (true) {
    var friends = hero.findFriends();
    var enemies = hero.findEnemies();
    // Get the total health of your soldiers and the ogres.
    if (sumHealth(friends) <= sumHealth(enemies)) {
        hero.say("Wait");
    }
    // Say "Attack" when your side has more total health.
    else {
        hero.say("ATTACK!!!");
    }
}

3 Likes

Hi @Kuzco and welcome to the forum! :partying_face:

Is this inside the while loop?

Andrei

1 Like

It’s just outside, because when I insert it inside the while loop, the hero says “ATTACK” too soon, and everyone dies :frowning: I think the issue is that it’s not adding each units health to the total health, I just don’t know…why…

1 Like

Try to move this inside the second while loop and this

At the end of the first while loop.

Andrei

3 Likes

welcome to the forum @Kuzco :partying_face: :tada:

1 Like

Hi @Kuzco, Welcome to the Discourse :partying_face::tada:

@AnSeDra When I do that, it says that units are not defined. Shouldn’t the var unitArray =units[unitsIndex] be in the function, not the second while loop? (Code for reference). Thanks for the welcome everyone :slightly_smiling_face:

// than the ogres total health

// This function return the sum of all the units health.
function sumHealth(units) {
   var totalHealth = 0;
   // Complete this function:
    var unitIndex = 0;
    var unitArray = units[unitIndex];
   while (unitIndex < units.length){
       totalHealth =+ unitArray.health; 
       unitIndex+= 1;
   } 
   return totalHealth;
}

while (true) {
   var friends = hero.findFriends();
   var enemies = hero.findEnemies();
   var unitArray = units[unitIndex];
   // Get the total health of your soldiers and the ogres.
   if (sumHealth(friends) <= sumHealth(enemies)) {
       hero.say("Wait");
   }
   // Say "Attack" when your side has more total health.
   else {
       hero.say("ATTACK!!!");
   }
}```

When I saud that this should be inside the second while true, I meant this one:

Delete it from outside the function.

Andrei