[Solved]Need help on Clash of Clones(javascript)

Please teach me where shoud I fix.

■What I want to do
①First, hero will defeat captain.
②② After that, the hero will defeat the strongest enemy in order from the remaining enemies.

■What I can’t understand.
・Do one task(①) and if it finished move next task(②).
・ After defeating the strongest enemy, how to continue searching for the strongest enemy from the remaining enemies.

while(true) {
    var enemies = hero.findEnemies();
    var enemyIndex = 0;
    while (enemyIndex < enemies.length) {
        var enemy = enemies[enemyIndex];
        if (enemy.type == "captain") {
            while (enemy.health > 0) {
                  hero.attack(enemy);
             }
            break;   
        }
          enemyIndex ++; 
      }
      
     while (enemyIndex < enemies.length) {
         var strongest = null;
         var strongHealth = 0;
         var enemy = enemies[enemyIndex];
         enemyIndex ++;        
         
         if (enemy.health > strongHealth) {
             strongHealth = enemy.health;
             strongest = enemy;
         }
     
         if (strongest) {
             while(strongestHealth > 0) {
              hero.attack(strongest);   
             }
         }
     }
}

The problem is you aren’t defeating the enemy “captain” before you die. Since you have the same gear, you will attack each other at the same rate and damage if you don’t use special abilities (rings, emperor’s glove, cleave, bash, shield). This level isn’t as much about simply coding, but developing a strategy that you have to code. If you don’t have a lot of special gear, you can control your hero with flags to control the fight better.

The few suggestions I would make about your current code:

You can combine both the while (enemyIndex < enemies.length) into one and just have an if - else if chain to find the different enemies. Tip: add a line of code to prevent your hero from attacking “sand-yak”

if (enemy.type == "captain") {} //may not want to directly attack unless using special abilities
else if (enemy.health > strongHealth) {}

Make sure you keep your starting variables outside of the loop otherwise you reset them every time and it will skew the results.

Lastly, make sure your if (strongest) is outside of the while (enemyIndex < enemies.length) loop so you only get the results of the strongest. Oh and typo on the while (strongest.health >0). You want to evaluate the health of the enemy you are fighting not a value that you collected at first.

The post below will give you some other insight for strategy using basic level gear and abilities. While the code is in Python, the concepts carry over.

I have read your commentary and recommended posts.
As a result, I cleared this level.
I can move on to the next study.
Thank you.

1 Like