Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

Sand Snakes Pathing [JavaScript]

Hey all, I’m back with the same problem, how do I get out of Sand Snakes? Okar keeps grabbing the first coin right, but then suddenly decides to go way north.

// This field is covered in firetraps.  Thankfully weve sent a scout ahead to find a path.  He left coins along the path so that if we always stick to the nearest coin, well avoid the traps.

// This canyon seems to interfere with your findNearest glasses!
// Youll 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];
        var distance = hero.distanceTo(coin);
        // If this coins distance is less than the nearestDistance
        if (distance < nearestDistance) {
            // Set nearest to coin
            var nearest = coin;
            // Set nearestDistance to distance
            var nearestDistance = distance;
    // If theres a nearest coin, move to its position. Youll need moveXY so you dont cut corners and hit a trap.
        hero.moveXY(nearest.pos.x, nearest.pos.y);

Hi @Captain_Critz, your code is very nearly right. The problem lies in the positioning of this line:

I don’t normally do javascript so this took me a long time to work out. I’m not surprised you’re finding it hard, this level’s a bit of a pain, but very satisfying once it’s done.
I hope this helps,

Extra hint (only if you're stuck)

Remember your Semicolon placement {} and indentation! (For the line mentioned above)

Sorry for the late reply, but thank you so much this level caused me quite some time. I usually don’t find most coding things hard, but debugging without a console is my worst enemy.

Never realized just how much of a savior MC’s console is.

At least in Chrome, you can access the web Console with Ctrl+Shift+J. The link below shows you how you can add console.log to your code to see the output. Better than using hero.say and slowing your code.