Demilade Sonuga's blog

All posts

Thinking Through Event Handling

2023-03-09

In this post, we're just going to think through exactly what we need to get event handling to work.

Aims

Due to the nature of what we're working on, our event-handling scheme doesn't have to be very sophisticated. It just needs to be adequate for our purposes.

Firstly, functions that can manipulate their environments should be supported.

For example:

func do_something()
     let ball_pos = (0, 0)
     EventHandler::on_timer_tick(
          func change_ball_pos()
               ball_pos.row += 1
               ball_pos.column += 1
          )
     loop

The above pseudocode demonstrates the idea of an event handler accepting a function that modifies its environment. The function increases the position of a ball diagonally with every time step. Remember it was mentioned in a previous post that the timer interrupt is generated every 100ms, so the effect of this code, is to create animation (assuming the ball_pos's value reflects on a ball image on the screen).

An event handler that doesn't accept functions that can manipulate their environment will be very limited in use. The reason is that the function will then only be able to access static variables. Such a limitation will force us to use only static variables in our actual game code. The result will be an unnecessarily unsafe heap of code.

Secondly, the event handler, when invoking functions, should pass relevant information to the functions. For example, consider the following:

func do_something()
     let ball_pos = (0, 0)
     EventHandler::on_keypress(
          func change_ball_pos(key_info)
               if key_info.keycode == escape key
                    pause game
          )
     loop

The intent of the above pseudocode seems clear enough. When the escape key is pressed, pause the game. But we need to understand that without the info passed to the function, there is no way we could determine that it was the escape key that was pressed and, therefore, we can't know if we are to pause the game or move the ball or do something else.

Thirdly, whenever a relevant hardware interrupt occurs, all the functions registered for that event must be called. If a user presses the escape key and the function which is meant to pause the game when such an event occurs isn't called, the result is a buggy game.

As far as we're concerned, these are the only real requirements of our event handling scheme.

Come up with a scheme yourself.

In The Next Post

We'll start implementing an event-handling scheme.