Sand Snakes Javascript, need help

This is my code:

// This field is covered in firetraps.  Thankfully we've sent a scout ahead to find a path.  He left coins along the path so that if we always stick to the nearest coin, we'll avoid the traps.
// This canyon seems to interfere with your findNearest glasses!
// You'll need to find the nearest coins on your own.
while (true) {
    var coins = hero.findItems();
    var coinIndex = 0;
    var nearest = null;
    var nearestDistance = 9999;
    // Loop through all the coins to find the nearest one.
    while (coinIndex < coins.length) {
        var coin = coins[coinIndex];
        coinIndex++;
        var distance = hero.distanceTo(coin);
        // If this coin's distance is less than the nearestDistance
        if (distance < nearestDistance) {
            // Set nearest to coin
            var nearest = coin;
            // Set nearestDistance to distance
            var nearestDistance = distance;
        }
        // If there's a nearest coin, move to its position. You'll need moveXY so you don't cut corners and hit a trap.
        if (coin) {
            hero.moveXY(coin.pos.x, coin.pos.y);
        }
    }
}

It will take the 1st coin and then move to another coin, but then it hits the mines…

That is a glitch. it happened to me 2. Try using flags if it doesn’t work @BrendGroen

1 Like

@Archion when I run the level there’s no glitch or anything. I didn’t use flags.

@SuperSmacker when I run the level it runs into a bomb while my code was correct :frowning:

What I’m saying is that your code isn’t correct

For one, why’s the “if coin” loop within the while loop?

@Archion I ran the level just now. It works. I beat it without using flags.

@maka the default code for sand snakes has a problem.

The “coinIndex++” should be at the end of the nested while loop, not at the beginning of it.

If you move it to the end then follow the instructions, then the level works perfectly.

1 Like

Hi, i have the same problem. Nothing is happening and i don’t see any mistakes in my code.
Anyone an idea of what is wrong.

Hi, welcome to the Discourse!
In your code, coinIndex++ is at the end of the if loop, not the while loop. Move it out of the if loop and your code should work fine.

Thanks for the reply, is it in the right loop?


because it still won’t work. Any other idea what it could be

Yeah, that’s the right loop.
The last if loop in your script is indented too far, but I don’t think that matters in JS…
Could you please post what gear your hero is using? Maybe the glasses don’t have long enough range