An If Inside an If

Now the path turns both left and right. When the dog can't move forward, it also has to decide which way to turn. Two new senses help it: path to the left and path to the right. Left and right are from the dog's point of view, just as with turning.

So the dog decides in two steps:

  1. Is there a path ahead? If there is, it moves forward.
  2. 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. A condition put inside another condition is called a nested condition:

  • If path ahead
    • Move forward
  • else
    • If path to the left
      • Turn left ↺
    • else
      • Turn right ↻

Why aren't two separate If blocks one under another enough, one for turning left and one for turning right? Try it in your head: the dog is at a left turn, and the first block turns it left. The second block then asks whether there's a path to the right, and there is, because that's where the dog came from. So it turns the dog back. One decision has to rule out the other, and that's exactly what else does.

Instructions

Get the dog to the goal on all three maps.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/4