An If Inside an If
Now the path turns both left and right, at different places on each map. In the Which Way at the Corner? exercise, there was only one corner, so the dog decided just once. Here, it has to decide on every tile, in two steps:
- Is there a path ahead? If there is, it moves forward.
- If not: is there a path to the left? If there is, it turns left, and otherwise right.
The second decision is made only when the first one came out "no". That's why it belongs in the else part of the first block. An If put inside another If is called a nested condition:
Ifpath aheadMove forward
elseIfpath to the leftTurn left ↺
elseTurn right ↻
What if you put the second If … else under the first one instead of into its else part? Then the dog would also ask about the left after every step on a straight part, where there's no path to the left. So it would turn right, to face the grass, and on the next pass, turn back. It would still get to the goal, but it would take almost twice as long. The else makes sure that the dog turns only when it can't go on.
Instructions
- 1
Get the dog to the goal on all three maps.