Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

Eliminating the loop in if (enemy) while(enemy.health > 0) hero.attack(enemy);

In many levels you need to ensure the attacked enemy is defeated and even in some levels the code will fail while not doing it. To test it one can arm the hero with the weakest weapon and you will find too often the default code crashing.
The code to succeed is usually:

while (true){
  var enemy = hero.findNearest(hero.findEnemies());
    if (enemy) while(enemy.health > 0) hero.attack(enemy);
}

The code I use is a little bit different and no internal loop is needed.
console.log lines are for debugging only - I have to explain visually all that to my son
Delete all lines marked for debug //d*

var enemies = hero.findEnemies(),
      enemy = hero.findNearest(enemies);
var n  = 0; // counter d*
while ( true ){
    if ( enemies.length < 1  ||  enemy.health < 0 ){
        enemies = hero.findEnemies();
        enemy = hero.findNearest(enemies);
    }
    else{
        if (enemy.health == enemy.maxHealth)  //d*
          console.log( 'enemy:'+ enemy.id + ' health:' + enemy.health );  //d*
        hero.attack(enemy);
        console.log( 'enemy:'+ enemy.id + ' health:' + enemy.health );  //d*
        if (enemy.health < 0) console.log(++n + ' killed');  //d*
    }
}

or

var enemy = hero.findNearest(hero.findEnemies());
var n  = 0; // counter d*
while ( true ){
    if ( !enemy  ||  enemy.health < 0 )
        enemy = hero.findNearest(hero.findEnemies())
    else{
        if (enemy.health == enemy.maxHealth)  //d*
          console.log( 'enemy:'+ enemy.id + ' health:' + enemy.health );  //d*        
        hero.attack(enemy);
        console.log( 'enemy:'+ enemy.id + ' health:' + enemy.health );  //d*
        if (enemy.health < 0) console.log(++n + ' killed');  //d*
    }
}

the output is similar to:

 enemy:Brak health:14  
 enemy:Brak health:6.800000000000001  
 enemy:Brak health:-0.3999999999999986  
 1 killed  
 enemy:Treg health:14  
 enemy:Treg health:6.800000000000001  
 enemy:Treg health:-0.3999999999999986
 2 killed
2 Likes