Thursday, June 3, 2010

What is a conditional statement?

What is a conditional statement?
It's when you tell your robot to do something only if a certain condition is true. If the condition is not true, the robot won't do it.
We use conditional statements all the time in real life, like when we say, for example, "If they are serving fish for lunch, I'm going to the salad bar." 

In Logo, this would look something like this:

to eat.lunch
if fish
[eat saladbar]
end
(Note: I don't have anything against fish.)
Your robot can't eat, though, so let's see what it could do as a result of a conditional statement.

If you want your robot to start driving if you press a switch, this will do it:

to drive
if switcha
[ab, onfor 20]
end
Notice where the brackets go! They enclose the 'if true' command like bread on a sandwich.
If you want your robot to stop driving if you press a switch, this will do it:

to stop.driving
ab, on
if switcha
[ab, off]
end
Well, actually, I kind of lied. The two examples above won't really work because they check if the switch is pressed only once. We need it to check continuously so it will carry out the commands whenever we press the switch. So we have to "loop" the procedure, like this:

to drive

loop [
if switcha
[ab, onfor 20]
]
end

This example will keep checking whether the switch is pressed because loop makes the part inside the brackets repeat indefinitely.

Here's how you can use a switch to control your robot:
Use a switch to start your robot driving on its road course. First plug a switch into sensor port 'a'. 

You can keep your program the way it is and just wrap a conditional statement around it.
to start
loop [
if switcha
[drive]
]
end

to drive
ab, thisway
ab, on
wait 20
etc, etc,
end

Now be sure to put the name 'start' in the 'run this' window so when you press the run button on the robot, it will start the loop instead of just skipping the loop and going straight to the 'drive' procedure.

No comments: