Hi hotpockets!
While indentation isn’t “necessary” in javascript, it usually helps alot when trying to figure out what you might want to change/fix and where!
This time, i’ve quickly “beautified” your code, so it’s a bit easier to read.
Beautified Code - Click to show
while(true) {
var enemy = hero.findNearestEnemy();
// If there is an enemy, then...
if(enemy) {
// Create a distance variable with distanceTo.
var distance = hero.distanceTo(enemy);
// If the distance is less than 5 meters, then attack.
if distance is less than 5
hero.attack(enemy);
}
// Else (the enemy is far away), then shield.
hero.shield();
} // <----------!!! This is the end of the while(true) loop !!!
// Else (there is no enemy)...
hero.moveXY(40, 34);
// ... then move back to the X.
hero.moveXY(40, 34);
So regarding your error message first: the problem is most likely the line 8 with
if distance is less than 5
In javascript you have ( and ) around the condition of an if statement, so we’d first change it this way:
if(distance is less than 5)
But, sadly, that won’t be enough to make it work.
In order to check if something is less than, greater than, or equal to or similar, see the Info below
condition help - click to expand
Less than something
if( a < b)
this checks if “a” is smaller than “b”
Less than, or equal to something
if( a <= b)
this checks if “a” is smaller than “b” or has exactly the same value (the above one won’t make code run if a is 5 and b is 5!)
Greater than something
if( a > b)
this checks if “a” is bigger than “b”
Greater than, or equal to something
if( a >= b)
this checks if “a” is bigger than “b” or has exactly the same value
Equal to something
if(a == b)
this checks if “a” is equal to (the same as) “B”
Additionally, some information regarding if statements aswell, that you might want to consider:
Click to expand information
While it is possible to have an if statement without curly brackets { and },
it is ONLY used, when you run a single line of code afterwards.
To keep it “beginner” friendly, you might want to consider using these brackets to start and end whatever you want to do, in case the condition is true!
Now, that i’ve also “beautified” your code a bit, do you notice how the 2 hero.moveXY commands are outside of the while(true) loop?
They’ll never execute, as you’ll be in the loop forever! So you’d need to implement them into the while(true) loop as well!
I hope this helps out, even though it might contain more information than necessary and sorry for the length of this answer!