Event Polling!
Goals:
- Learn about polling, a powerful idiom for working with events
- Explore algorithms that move sprites fluidly in response to end-user input
Coding Snippets:
- Pencil Code gives direct access to the most-recently-generated mouse event objects with variables
lastclick
,lastmouseup
,lastmousedown
, andlastmousemove
. - The
pressed
function can be used to check whether a specific key has been pressed (as shown in the example) or to list all currently-pressed keys by callingpressed()
.
Math and Computer Concepts:
- Pencil Code maintains records of the most recent event object for several mouse-related events, as well as a list of all currently pressed keys. It does this, behind the scenes, using event listeners.
- Referencing these records of events in a frequent, repeated manner—i.e., within the body of a callback to a timing event—is called polling.
- Polling allows us to write code that responds more fluidly to events, owing to the fact that the timer dictates the timing interval of the execution of our callback, rather than the timing of the mouse or keyboard event.
Activities:
Save each of the following in a folder called EventPolling.
- MouseMover: Code a script that directs a sprite to move around the screen using the arrow keys and the
turnto
andmoveto
methods. Make the movements smooth and fluid by using event polling rather than explicit use of mouse event bindings. - KeyboardMover: Program a script that lets you maneuver a sprite around a fixed area of the screen using the arrow keys (or, if you prefer, a,w,s,d). Experiment with different turn angles and forward distances to come up with an algorithm that makes smooth movements and (as an extra challenge) also prevents the sprite from crossing the boundary. Access event objects using event polling, not keybinding functions!
- CopsAndRobbers: Make a chase game, in which the player controls a police-car sprite in hot pursuit of a randomly-moving getaway-car sprite. Add features, such as hazards or roads, that make the game more challenging and/or interesting. As an extension, add a button to let the player choose which role to play—or perhaps turn it into a two-player, head-to-head game?
- Explore the performance advantage of polling over direct use of events by conducting a new variant of TurtleRace: set up a keydown event listener which instructs one racer to move forward each time the event fires (either from repeated pressing of the key or from refirings when the key is held down). Set up a timer that uses polling to instruct the other racer to move forward whenever that same key is pressed. Under what situations can the "event" racer win?