Restless Dead - Javascript - stuck in while loop

Hero never leaves the while loop, even after he’s reach the redX.

let redX = {x: 19,y: 40};
hero.moveXY(57, 27);
while (hero.pos != redX) {
    let enemy = hero.findNearestEnemy();
    if (enemy) {
        hero.attack(enemy);
    }
    let coins = hero.findItems();
    if (coins) {
        for (let coin of coins) {
            hero.move(coin.pos);
        }
    }
    hero.move(redX);
}
hero.summon("soldier");

If none of the checks work, it’ll do that forever, and won’t get off since while true is there.

The while condition should check the hero’s position and leave the loop when his position is on the redX. Why is it not working?

I see your problem. you use !=, but you need to use !==. Javascript is weird like that. Only using one equal sign means that it won’t properly check the variable. Plus, instead of doing that, personally I would suggest doing this:

while (true){
    //do stuff
    if (hero.pos.x == redX.x && hero.pos.y == redX.y){
        break;
    }
}

Thank you fuery. I tried it this code using !==, but it still seems stuck in the while loop. I will try your other suggestion and let you know how it goes.

let redX = { x: 19,y: 40};
while (hero.pos !== redX) {
    var coins = hero.findItems();
    var enemy = hero.findNearestEnemy();
    if (enemy) {
            hero.attack(enemy);
    }
    if (coins) {
        for (var coin of coins) {
            hero.move(coin.pos);
        }
    }
    hero.move(redX);
}
hero.say("I have arrived.");

while (hero.pos !== redX)

This tries to compare one whole object with another (which apparently doesn’t work).

while (hero.pos.x !== redX.x)```
This just compares a number to another number - and works!  Thank you

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.