If only Reeborg could decide on his own ...
If, if, if ...
Wait a minute! Reeborg can decide make some decisions on his own. Didn't I tell you?
1. First decisions
Well, to tell the truth, Reeborg does need some help to decide: you have to give him some choices to decide between. For example, when Reeborg is next to a beeper, you can give him some choices as to what to do; for example, you can ask him to pick it up as follows
Let's look at the meaning of the above code:
This explanation may seem complicated when you read it, but it's actually quite simple to use an if statement. Let's look at it in a simple example. Suppose we want Reeborg to take 9 steps, picking up any beepers that are there along the way. (We suppose that there can be at most one beeper at a given spot.) For example, the starting position might be like the following:
- The python keyword if tells Reeborg that some condition, whose value is True or False, is going to follow;
- next_to_a_beeper() is a condition (or test) which is True if Reeborg is next to a beeper (at the same apparent position on the screen) and False otherwise;
- The colon (:) precedes the series of instructions that Reeborg must follow if the condition is True;
- The series of instructions to follow in that case is indented, just like we had in the case of definitions.
and we want the final position to be:
So, we want to ask Reeborg to:
repeating the above steps 9 times. Remember that if we ask Reeborg to pick up a beeper where there is none, he will complain and turn himself off. Here is how we can do this:
- Take a step forward;
- Check to see if there is a beeper;
- Pick up the beeper if there is one; otherwise ignore and keep going;
Harvest time again!
It's harvest time, yet again! However, this time not all seeds have sprouted and some carrots are missing.
Have Reeborg pick up all the carrots (represented by beepers)
in this garden. The world file is harvest3.wld. Look back at the second last harvesting exercise that you did last chapter; chances are, all that you need to do is change the instruction harvest_one_row() so that it looks similar to the above move_and_pick() instruction.
Note that your new program should also work as is with the world file harvest1.wld that we had used before. Try it!
Avoiding repetitions, again!
Listen to me ... or else ....