Which Way at the Corner?
On each of these maps, the path goes straight, turns once and goes on straight to the goal. But on some maps, it turns left, and on others, right. A program with Turn left ↺ at the corner would work on only some of them. At the corner, the dog has to look around and decide which way to go.
Two new senses help it: path to the left and path to the right. They look at the tile beside the dog, on its left or on its right, and answer true or false, just like path ahead. Left and right are from the dog's point of view, just as with turning. On the third map, the dog faces down the screen, toward you, so its left is on your right.
At the corner, the path goes on either to the left or to the right. That's a choice between two options, so it's a job for If … else:
Ifpath to the leftTurn left ↺
elseTurn right ↻
One question is enough: if the path doesn't go on to the left, it must go on to the right. You could just as well ask about path to the right and swap the turns.
This If isn't inside a loop. The dog needs to decide only once, at the corner, so the If goes between the two straight parts of the walk:
- Walk to the corner:
Repeat whilepath aheadwithMove forward, as in the While There's a Path Ahead exercise. - Decide which way to turn.
- Walk on to the goal.
The program carries out its blocks from top to bottom, and an If is no exception. When the program gets to it, the dog decides, carries out one of the two parts and goes on with the blocks under the If.
Instructions
- 1
Get the dog to the goal on all three maps: walk to the corner, turn the right way and walk on to the goal.