Handling Events

CodeWorld uses a single function to handle all events. An Event can represent mouse actions, key actions, and even time passing.

In general you use activityOf, which is like Racket’s big-bang. You provide:

  1. a starting value (“the initial model”);
  2. an event handling function; and
  3. a “draw handler” that creates the picture that you see.

Important Note: your handler function needs a default case that does not change the model when an unanticipated event happens.

Example Code

  • A number on the screen shows how much time has elapsed. (Code.)
  • A circle increases in radius as time passes. This example shows how to handle all of the common different types of events.
    • Click to set the radius so the mouse is on the circle.
    • Hitting the “R” key sets the radius to 1.0.
    • Hitting the “T” key sets the radius to 9.0.
    • Hitting any other key resets to the initial radius (5.0).
    • The radius of the circle grows at a rate of one unit per second.

Exercises

  1. Modify the number on the screen animation (above) so that a radius 2 solid red circle moves on the line from (-10,-4) to (10,7) as time passes. Use the x coordinate as the game state.

  2. Create ten 2x2 outlined rectangles spread out along the x-axis. Start out with the leftmost one highlighted. Move the highlighting left and right using the keys “A” and “D”. The game state should be a number telling you which rectangle is highlighted. YouTube: Square on a Line.

  3. See the futher exercises for more complex projects.

Last modified August 18, 2023: 2022-2023 End State (7352e87)