Sarven shepherd: now in JS


#1

Hello guys! After been playing for a while in python and almost finish the 4th world I wanted to start with JS (cause I need it for class).

I went through the forum and I could not find something similar.

This is my code:

loop {
    this.say("start");
    var enemies = this.findEnemies();
    var enemyIndex = 0;
    while (enemies.length>=enemyIndex) {
        var enemy=enemies[enemyIndex];
        if (enemy.type != "sand-yak"){
            while (enemy.health>0) {
                this.attack(enemy);
                this.attack(enemy);
            }
        }
        enemyIndex +=1;
    }
    this.moveXY(40, 32);
}

I also checked my code with my character in python and it is basically the same. And I am pretty sure That this is how it should work.

But what I get is: kill the two first enemies, and get stacked :S It does not define new array of enemies again. It gives null error in enemy.type, not exceeded execution limit. So I am very lost right now.


#2

The while condition is incorrect: enemies.length >= enemyIndex should be enemies.length > enemyIndex, or, written in a more conventional way, enemyIndex < enemies.length.

Array indexes start at zero, so an array with length x only has indexes 0...x-1. E.g. an array with a length of 5 contains indexes from 0 to 4.

Side-note: you don’t need to attack twice inside the while (enemy.health > 0) loop. You may put a single attack statement inside the loop and your hero will keep attacking until the enemy health falls to zero or below. With two attack statements inside the loop, it is possible that the enemy health falls to zero in the first attack and the second attack is wasted.


#3

hey! You are right, usally i do the enemyIndex<len in the conventional way, and it was giving the same error, I tried that and i forgot to change it.

And also with only one attack inside the while, and always the same error, so it must be something else


#4

The attack statements were a side note. Are you sure that changing the condition from enemies.length >= enemyIndex to enemies.length > enemyIndex (or enemyIndex < enemies.length) does not fix the issue? It is the only real problem I can see in your code.


#5

This is true. I have fixed the while-loop in your code and run it, and the code is valid. Maybe you should double-check that you have the syntax correct. If you think you do, post your code again.


#6

Now i see the error, i was writing enemyIndex<=enemies.length instead of enemyIndex<enemies.length

I do not understand why this becomes an error, but it won’t happen again, thanks!


#7

You know that array indices start at zero, right? So the last element of an array has one less than the length of the array. Therefore, when enemyIndex is equal to enemies.length, then it is trying to find an element at an index that is nonexistent. This is what caused the error.


#8

I’ve explained this in my first reply. :wink: