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

[ANSWERED] Slalom, Cloudrip Mountain - Question about While Loops

Hello!
This is the given code for the level Slalom in Cloudrip Mountain. I was wondering why we need to write so many while loops - can’t we just write just three lines:

var gems = hero.findItems();
hero.move({'x':20, 'y':35});
hero.move(gems[0].pos);

Thank you in advance!

// Use object literals to walk the safe path and collect the gems.
// You cannot use moveXY() on this level! Use move() to get around.
var gems = hero.findItems();

while (hero.pos.x < 20) {
	// move() takes objects with x and y properties, not just numbers.
	hero.move({'x': 20, 'y': 35});
}

while (hero.pos.x < 25) {
	// A gem''s position is an object with x and y properties.
	var gem0 = gems[0];
	hero.move(gem0.pos);
}

A question for your question…have you tried your idea? What happens?

The intent of the level lesson (by my reckoning) is to further build on the concepts of the while method. To do this, they are requiring you to use the ‘move’ method, rather than ‘moveXY’. Think of moveXY as a “fire and forget” method…once executed, the code will stop (no further lines will be ran), until the hero reaches the x,y coord’s. Move on the other hand is a “step by step” method. Once executed, the hero will take a step in the direction of the ultimate x,y, but if there is any code following it, this code will also be ran in order. Hence, ‘move’ needs to be placed within a loop, so that with each iteration, a step is taken, until the final x,y is reached.

2 Likes

OhhHHhhhh!
I just tried it - I run right into the trap on the right, since I guess I took a single step towards each direction, and my target settled on the very last gem.
That makes much more sense now! Thank you :smile: