Event-Driven Programming
In the last lesson we learned that functions give us quite a bit of power and flexibility in our programs. Given what we know about functions, event-driven programs can be written without too much trouble.
An event-driven program is a program that responds to events. Usually, these events are generated from user input via the keyboard or mouse in a Graphical User Interface (GUI) environment. A GUI program has one main loop called the event loop that looks for the next mouse or keyboard event and then dispatches that event by calling an event handler. When we write an event-driven program we provide the event handlers. Turtle graphics supports event-driven programming by allowing us to provide a mouse handler and keyboard handlers.
Consider writing an Etch-A-Sketch program. Let's say we want to write it so that when we push the up arrow on the keyboard we want to draw an arrow going up. Here is what that code looks.
The program above creates a Turtle, hides the turtle, and then sets up three event handlers. The mouseHandler makes the turtle go wherever you click the mouse. The upHandler responds to the up arrow being pressed. The colorHandler responds to the letter c being pressed and changes the drawing color to red.
Now You Try It
Using this program as a template, write an Etch-A-Sketch program that allows you to do the following.
- Pick up and put down the pen
- Change the drawing color
- Change the fill color
- Draw a shape and fill it (remember begin_fill and end_fill)
- Clear the screen