Problems with Sarven Shepherd JS

Hi,
can anyone tell me what I doing wrong in this code. I have tried to search trough this forum, but still have problems.

while (true) {
    var enemies = hero.findEnemies();
    var enemyIndex = 0;
    // Wrap this logic in a while loop to attack all enemies.
    // Find the array's length with:  enemies.length
    while (enemyIndex < enemies.length) {
        var enemy = enemies[enemyIndex];
        // "!=" means "not equal to."
        if (enemy.type != "sand-yak") {
            // While the enemy's health is greater than 0, attack it!
            while (enemy.health > 0) {
                hero.attack(enemy);
            }
            enemyIndex += 1;
        }
        hero.moveXY(40, 30);    // Between waves, move back to the center.
    }
} `Preformatted text`

You should put this in the attack loop

Hi
I did what you suggested. My hero is still doing nothing…```

// Use while loops to pick out the ogre
while (true) {
var enemies = hero.findEnemies();
var enemyIndex = 0;
// Wrap this logic in a while loop to attack all enemies.
// Find the array’s length with: enemies.length
while (enemyIndex < enemies.length) {
var enemy = enemies[enemyIndex];
// “!=” means “not equal to.”
if (enemy.type != “sand-yak”) {
// While the enemy’s health is greater than 0, attack it!
while (enemy.health > 0) {
hero.attack(enemy);

            enemyIndex += 1;
        }
        
    }
    hero.moveXY(40, 30);    // Between waves, move back to the center.
}

} `Preformatted text````

// Use while loops to pick out the ogre
while (true) {
    var enemies = hero.findEnemies();
    var enemyIndex = 0;
    // Wrap this logic in a while loop to attack all enemies.
    // Find the array's length with:  enemies.length
    while (enemyIndex < enemies.length) {
        var enemy = enemies[enemyIndex];
        // "!=" means "not equal to."
        if (enemy.type != "sand-yak") {
            // While the enemy's health is greater than 0, attack it!
            while (enemy.health > 0) {
                hero.attack(enemy);
                
                enemyIndex += 1;
            }
            
        }
        hero.moveXY(40, 30);    // Between waves, move back to the center.
    }
}  `Preformatted text`

Hmm, no - sameivar already has ‘var enemy = enemies[enemyIndex]’, which is correct.

I think the problem is that the ‘enemyIndex += 1’ is in the wrong place. At the moment it only runs if the 3 lines above it all run. What happens if enemy is a sand-yak?

Jenny

2 Likes

Hi, The code is ok. I had to change the hero, and suddenly everything worked out. Thank you!
Sameivar

2 Likes