5.5. Listener Functions

We have talked about interactivity: you have gotten input from the end user and you have shown the end user output by having turtles make fun animated drawings in a canvas window. Let’s take that interactivity a step further, now that we know about functions, and add a listener function to our turtle scripts.

First, let’s consider this turtle drawing example.

This example contains three different functions. First note how nicely modularized this code is, with each funtion doing one small thing: moving the turtle, giving the turtle a random colour, and drawing a random sized square. We call the three functions at the bottom of the script on lines 30-32. Not also that line 25 creates a random colour by generating 3 random values. Don’t worry about this for now - you will learn more about digital colours in a later section of this chapter.

If we wanted to draw more than one square, we could put a loop around lines 30-32, but that isn’t very interactive - it doesn’t involve the end user in any way. What if we want the user to decide when they have enough squares on the canvas? By adding a listener function, we can draw squares randomly in response to end user key presses. The version below does this, by adding a key_r function, and adding two lines of code at the bottom of the script to register the listener function and to start listening for window events such as keypresses.

Run the code below, click your cursor inside the canvas and then type the ‘r’ key a few times to see it in action. Now the end user is in control!

Let’s add one more listener function to this script that ends the script. The version below adds a listener event for key_q that closes the canvas and ends the script.

Try it out yourself. Add two functions to the code below. Add a function that draws a triangle (just copy, paste and edit the square function to draw three sides, with a turning angle of 120 instead of 90). Then add a listener function that can be called in response to the end user typing ‘t’. Then add a line of code at the bottom of the script to tell the computer what function to call when the user types ‘t’.

There are a number of other events we can listen for and respond to, such as mouse clicks and drags, but we will return to those when we revisit functions with parameters in Chapter 9.

Common Mistake with Listener Functions

Most of the listener functions you write are functions that you should never invoke yourself. Notice that we never explicitly call key_r() in the scripts above. They are invoked automatically by the operating system. So, don’t call your own listener functions. Run your script, be the end user, and press the keys to test your listener methods!

Check your understanding

You have attempted of activities on this page