Sand Snakes [JAVASCRIPT]

while(true) {
    var coins = hero.findItems();
    var coinIndex = 0;
    var nearest = null;
    var nearestDistance = 9999;

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

What’s wrong with my code? I keep running into the mines.

coinIndex ++ should be after the if loop

It’s a problem with the name of the variables.

Check the result of your algorithm:

while(coinIndex < coins.length) {
        var coin = coins[coinIndex];
        coinIndex++;
        var distance = hero.distanceTo(coin);
        if (distance < nearestDistance) {
           var nearest = coin;
           var nearestDistance = distance;

and then check where the hero is moving.

ask yourself, how can I rename my variables clearly to not make that error again.

Another way of putting this: you are defining a variable, but you are not using it. (for people who like code investigation)

I passed it. Thank you very much for your help. I appreciate it. :smile: