This.attack(enemy); error


#1

I’m in Sarven Brawl, but I’m not sure that matters. When I set up the code “this.attack(enemy);” I get the following error.

I’ve defined the variable, and I’m equipped to use the attack() function. I’ve also used this string of code countless times in other levels. Why am I getting this error now?


#2

Sometimes you can’t see an enemy.
Then this might happen:

var enemy = this.findNearestEnemy()   //No enemy in sight, returns null
this.attack(enemy)                    //== attack(null)

The computer has no idea who you are speaking about, because there is nothing (from his perspective).
You should always check if there is an enemy in sight:

var enemy = this.findNearestEnemy() //No enemy in sight, returns null
if(enemy){                          // Only do something if there is an enemy
    this.attack(enemy)              // can not be attack(null) due to the if
}

#3

Thank you for the response. Here is my code. You’ll see I’ve written it as you suggested. Do you see any other reason why it might not be working?

loop {
var enemy = this.findNearestEnemy();
if (enemy != "sand-yak") {
    this.attack(enemy);
}
else if (enemy == "sand-yak") {
    var x = this.pos.x + 10;
    var y = this.pos.y;
    this.moveXY(x, y);
}

}


#4

That’s not what I said.
I said you should check for the existence, but you try to compare it to something else.

Also you can’t compare an enemy (which is an enemy-object) to a string (which is a string-object). They will never be the same. To get the type of an enemy (which you would need here), you can write this:

if (enemy.type == 'sand-yak'){
    // enemy is a sand-yak, do something
}
else if (enemy.type != 'sand-yak'){
    // enemy is not a sand-yak, do something else (or the same)
}

You can of course replace sand-yak with every other type available.


#5

or in other words what J_F_B_M said is:

if (enemy) {
    if (enemy.type != "sand-yak") {

because by itself:

if (enemy.type != "sand-yak")

should either be error like no .type for null or it will be happy as null isn’t a sand-yak
if you combine them then you have to repeat the “if enemy” part

if (enemy && enemy.type != "sand-yak") { ...; }
else if (enemy && enemy.type == "sand-yak") {

(the ‘enemy.type == “sand-yak”’ on the “else if” is actually redundant (but sometimes helpful to keep your brain straight))


#6

Ok, so my problem was I wasn’t having it identify the enemy before evaluating the enemy type. That makes perfect sense, and it got my code right back on track. Thank you both so much for your help!