Have the car world open in front of you as you work through this page. Make sure world is selected in the top left pane. Part of the window should be showing this:
Before we look at how you were able to control the car, let's see how that original (non-interactive) video you watched was created. It made use of the method test drive. Bring the code up for that method in the editor pane, like this:
This is typical of the code we have written so far - the behavior of the car is entirely specified in the code before it runs, and every time we call test drive we will get the same result.
Now take a look in the Events area - this is in the top right of the screen. You should see four tiles in blue, as follows:
Each one of these tiles is known as an event handler. To understand what that means, let's look at each one in turn:
"the world starts" is an event. It is something that happens as a result of the user's action. The world starts when the user hits the Play button. This event handler is checking for this event - "When the world starts,". The second part of the event handler indicates what to do when this event happens. So, a way of reading this particular event handler is: When the user clicks on the Play button to get the program/world running, go ahead and execute the world's my first method method.
This event handler is always included in a new world - if you look back at any of your earlier Alice programs you will see it there. Now let's look at the next event handler in the list:
[Q6.2.1]: Write down what you think this one means.
Go ahead and take a look at the code for the turn car left method (make sure world is selected in the top left pane). You can see that it's a Do together with a turn instruction and a call to the method car go forward. Look at the code for car go forward as well, so that you can see exactly what this method is doing.
(Note, by the way, that this is an example of one of the methods we have written (turn car left) calling another method we have written (car go forward). We've not seen this before - but I hope you can see that it is a perfectly natural thing to do. It is just the same as my first method calling any of the methods we have written.)
Now run the program again, and watch the car very closely as you hit the left arrow.
[Q6.2.2]: Why does the turn car left method contain calls to instructions to make it both turn left and go forward? Why not just have a turn left instruction?
If you're not sure, try removing the world.car go forward instruction in the method turn car left, run the world to see... compare hitting both the left and the right arrow keys.
Answer on the next page...