Problem in Sarven Shepherd (Javascript)


#1

I had a problem in this level
And I have seen other articles which talk about it,But still not works.
Here is my code:

loop{
var enemies = this.findEnemies();
var enemyIndex = 0;

while (enemyIndex<3) {
    var enemy = enemies[enemyIndex];
    if(enemy.type != "sand-yak") {
      while (enemy.health > 0) {
         this.attack(enemy);
      }
     enemyIndex++;
    }
   
}
}

I have no idea why my character still attack sand-yak under my code =
if(enemy.type != “Sand-Yak”)
???
Appreciate for your help!


#2
if (enemy.type != "sand-yak") {
        this.attack(enemy);}

Works fine for me…


#3

The thing is you used lowercase sand-yak where @Arthur_Wu used uppercase Sand-Yak. I believe this makes a difference.


#4

Thank you but I had change my code to lowercase:

loop{
var enemies = this.findEnemies();
var enemyIndex = 0;

while (enemyIndex<3) {
    var enemy = enemies[enemyIndex];
    if(enemy.type != "sand-yak") {
      while (enemy.health > 0) {
         this.attack(enemy);
      }
     enemyIndex++;
    }
   
}
}

And it shows : Hard execution limit of 3000000 exceeded.
Maybe I should send an email to the Operators…


#5

Thank you, maybe I should send an email to the Operators…


#6

First of all, please paste your code between 3 backticks (`) according to the FAQ so we can see it clearly. Indenting also helps (I :heart: python). You can edit edit your post with the little pencil icon.


What I can see (after cleaning up the formatting) is that you only increase the enemyIndex if the enemy is not a sand yak, because it’s included in the if block. Thus, as soon as you see a sand yak, the while loop becomes an infinite loop, because you don’t increase the index… It’s best to increase the index right after you used it. See the comments below:

loop {
    var enemies = this.findEnemies();
    var enemyIndex = 0;
    
    while (enemyIndex < 3) {
        var enemy = enemies[enemyIndex];
        // increase your index here:
        enemyIndex++;

        if (enemy.type != "sand-yak") {
            while (enemy.health > 0) {
                this.attack(enemy);
            } // end while

            // this is still within the 'if' block:
            // enemyIndex++;

        } //end if

    } // end while

} // end loop

Also, you’re checking only the first 3 enemies:

while (enemyIndex < 3) {

I guess you should check all enemies:

while (enemyIndex < enemies.length) {

Cheers


#7

I know why I failed in both format and coding after watching your detailed instruction !

Thank you very much !


#8
 Thank you sooooooooooooooooooooooooooooo much your detailed help helped a lot!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Again thanks soooooooooooooooooooooooo much!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! :joy: