Sand Snakes JavaScript Help Needed

I have tried to follow other threads about this level, but I am still stuck. Here is my code below. Can someone please help me out?

while(true) {
    var coins = hero.findItems();
    var coinIndex = 0;
    var nearest = null;
    var nearestDistance = 9999;
    
    while(coinIndex < coins.length) {
        var coin = coins[coinIndex];
        var distance = hero.distanceTo(coin);
        if(distance < nearestDistance){
            nearest = coin;
            nearestDistance = distance;
        }
        coinIndex++;
    }
    if(nearest == coin){
        hero.moveXY(coin.pos.x, coin.pos.y);    
    }
}

The issue is in this line.

if(nearest == coin){

The comments says "// If there's a nearest coin, move to its position. The variable nearest has a coin assigned from the previous while loop. You don’t need to check the nearest variable against coin, just nearest by itself.

2 Likes

I fixed that, but my hero runs into the fire trap on the right when I run it.

I figured it out. Along with changing it to just nearest in the condition, I had to change

to move nearest.pos.x and nearest.pos.y

2 Likes

Good catch! :nerd_face:

why not use flags???