Forever Listening for Keystrokes

The construct to the right can be used to enable a sprite to say “Hello!” anytime the space bar is pressed.

However, the Scratch code contains a statement/block not found in Processing—the forever block. You may recall that placing the code that checks for a key press in a loop is necessary so that the program will continually check for key presses rather than doing it once and moving on. So, what is the equivalent for this in Processing?

Processing has the same types of control statements as Scratch that allow for looping. In particular, we will examine the while loop. However, Processing also has an implicit looping structure. You may recall that the draw() function is executed every time the screen is redrawn—defaulting to 60 times per second. This means that any code in the draw() function—including key press checks—will be executed continually as long as the program is running! For this reason, it is a good idea to reserve a section in draw() precisely for this purpose.

As usual, you should read and reference the Processing Documentation in order to understand the use of these constructs.

The while Loop

The while loop is a very useful construct for repetition and is composed of 4 major elements:

  1. Initialization
  2. Condition
  3. Action
  4. Update

To see a while loop in context, let’s imagine we are drawing the buttons on a snowman’s torso. Each of the buttons is essentially the same, so this is a perfect task for a loop.

The red arrows in the above image show the relative positions for each of the four parts of the while loop:

Initialization: Here, we are keeping track of the number of buttons we have drawn. As we have not drawn any before the loop begins, this variable is set to zero.

Condition: We are going to draw five buttons. So, as long as we have not (i.e., while) drawn five buttons, we will keep executing the loop.

Action: This is where we draw a button. Notice that we do not draw five completely identical buttons, because that would mean that we draw them on top of one another. Instead, we vary the y-position, so that the first button begins at y-coordinate 210, and each remaining button is drawn 20 pixels below the previous.

Update: Lastly, it is important that we indicate that we have drawn a new button each time by updating the value of numberOfButtonsDrawn. What would happen if we did not?


Modify your sketchbook from Keyboard Input as follows:

  1. Add a while loop that adds various repeated components to your figure.
  2. The loop should execute a minimum of three times.

You may use the snowman code above as an example.

Reference Starting Points

Variables Control Structures
keyPressed if
key else
keyCode while