It said it didn't work but it did


#1

when I use this code

{
    // Find the archer.
    var friend = this.findNearest(this.findFriends());
    var enemy = this.findNearest(this.findEnemies());
    if(enemy){
        pos = {x: enemy.pos.x - 10,y: enemy.pos.y - 10};
    }
    // Tell the archer to attack the enemy!
    if(friend && enemy) {
        distance = friend.distanceTo(enemy);
        if(distance > 10){
            this.command(friend, "attack", enemy);
        }
        else {
            this.command(friend, "move", pos);
        }
    }
    
    // Wait, no, that doesn't work that well. Maybe try something else?
    // The munchkin is awfully slow...
    
    
}

The error comes up and says that I cannot read the pos property of null
but the code still works can anyone explain this?


#2

I think its probably your (friend && enemy) at some point there might not be a friend. When it says"pos property of null" I’d think it was talking about “this.command(friend, “move”, pos)” . Change it to friend or enemy and it might go away. I know its the same error that comes up if a skip putting in a Boolean variable or write a incorrect one.


#3

OOPS my bad I did not notice the top had been cut off here is the entire code

loop {
    // Find the archer.
    var friend = this.findNearest(this.findFriends());
    var enemy = this.findNearest(this.findEnemies());
    if(enemy){
        pos = {x: enemy.pos.x - 10,y: enemy.pos.y - 10};
    }
    // Tell the archer to attack the enemy!
    if(friend && enemy) {
        distance = friend.distanceTo(enemy);
        if(distance > 10){
            this.command(friend, "attack", enemy);
        }
        else {
            this.command(friend, "move", pos);
        }
    }
    

Edit: I ran the code again and now its not giving me an error hmmmmmmmmmmmmmmmmmmm

anyways that for your help