Event Driven Programming
In an event-driven application, there is generally a main loop that listens for events, and then triggers a handler or callback function when one of those events is detected. ]
event: Something that happens “outside” the normal control flow of our program, usually from some user action. Typical events are mouse operations, keypresses, or timer events.
handler: A function that is called in response to an event.
binding: We bind a function (or associate it) with an event, meaning that when the event occurs, the function is called to handle it.
callback function: A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (or execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback, or it might happen at later time as in an asynchronous callback.
Handling Key-press Events
import turtle turtle.setup(400,500) # Determine the window size wn = turtle.Screen() # Get a reference to the window wn.title("Handling keypresses!") # Change the window title wn.bgcolor("lightgreen") # Set the background color tess = turtle.Turtle() # Create our favorite turtle # The next four functions are our "event handlers". def h1(): tess.forward(30) def h2(): tess.left(45) def h3(): tess.right(45) def h4(): wn.bye() # Close down the turtle window # These lines bind keypresses to the handlers we've defined. wn.onkey(h1, "Up") wn.onkey(h2, "Left") wn.onkey(h3, "Right") wn.onkey(h4, "q") # Now we need to tell the window to start listening for events, # If any of the keys that we're monitoring is pressed, its # handler will be called. wn.listen() turtle.mainloop()
Handling Mouse-click Events
import turtle turtle.setup(400,500) wn = turtle.Screen() wn.title("How to handle mouse clicks on the window!") wn.bgcolor("lightgreen") tess = turtle.Turtle() tess.color("purple") tess.pensize(3) tess.shape("circle") def h1(x, y): tess.goto(x, y) wn.onclick(h1) # Wire up a click on the window. turtle.mainloop()
Handling Timer Events
import turtle turtle.setup(400,500) wn = turtle.Screen() wn.title("Using a timer to get events!")wn.bgcolor("lightgreen") tess = turtle.Turtle() tess.color("purple") def h1(): tess.forward(100) tess.left(56) wn.ontimer(h1, 600) h1() turtle.mainloop()
Traffic Light: Advance-State Machine
import turtle turtle.setup(400,500) wn = turtle.Screen() wn.title("Tess becomes a traffic light!") wn.bgcolor("lightgreen") tess = turtle.Turtle() def draw_housing(): """ Draw a nice housing to hold the traffic lights """ tess.pensize(3) tess.color("black", "darkgrey") tess.begin_fill() tess.forward(80) tess.left(90) tess.forward(200) tess.circle(40, 180) tess.forward(200) tess.left(90) tess.end_fill() draw_housing() tess.penup() # Position tess onto the place where the green light should be tess.forward(40) tess.left(90) tess.forward(50) # Turn tess into a big green circle tess.shape("circle") tess.shapesize(3) tess.fillcolor("green") # A traffic light is a kind of state machine with three states, # Green, Orange, Red. We number these states 0, 1, 2 # When the machine changes state, we change tess' position and # her fillcolor. # This variable holds the current state of the machine state_num = 0 def advance_state_machine(): global state_num # global prevents creation of local variable if state_num == 0: # Transition from state 0 to state 1 tess.forward(70) tess.fillcolor("orange") state_num = 1 elif state_num == 1: # Transition from state 1 to state 2 tess.forward(70) tess.fillcolor("red") state_num = 2 else: # Transition from state 2 to state 0 tess.back(140) tess.fillcolor("green") state_num = 0 # Bind the event handler to the space key. wn.onkey(advance_state_machine, "space") wn.listen() # Listen for events turtle.mainloop()
Lab #10 Exercises:
Task 1. Add new key bindings to the first sample program:
Pressing keys R, G or B should change tess’ color to Red, Green or Blue. Pressing keys + or – should increase or decrease the width of tess’ pen. Ensure that the pen size stays between 1 and 20 (inclusive).
Task 2. Change the traffic light program so that changes occur automatically, driven by a timer.
Task 3. Your traffic light controller program has been patented, and you’re about to become seriously rich. But your new client needs a change. They want four states in their state machine: Green, then Green and Orange together, then Orange only, and then Red. Additionally, they want different times spent in each state. The machine should spend 3 seconds in the Green state, followed by one second in the Green+Orange state, then one second in the Orange state, and then 2 seconds in the Red state. Change the logic in the state machine program.
Task 4 (Extra Credit): Try to create a two-player game combining several events with two turtles and a traffic light to create a game such as red-light, green-light, 1, 2, 3.
Documentation for turtle methods can be found at the link:
No comments yet.