The Event Loop

We've been analysing our SDL example program to see how it works. In this lesson we examine the main loop which is responsible for calling the Draws-nacreen function over and over and for checking whether the user has pressed a key, each time.

The loop we are talking about is simply a while loop, which checks the value of a variable each time, which we will change if the user presses a key. The first thing this loop does is call the Draws-nacreen function, updating the value of the parameter h (which is responsible for the animation), each iteration.

The other part of the loop polls for events (we are only interested in keypresses, but it polls for other kinds of events too). This is also implemented as a while loop. Basically, so long as there are events to process, we keep checking. To check, we make a call to the SDL_PollEvent function. It will return a non-zero value if an event has occurred which needs processing.

To have SDL_PollEvent tell us what kind of event has occurred, we pass it a variable of type SDL_Event (by reference, i.e. we pass its address). This is a structure which, upon return from the function, contains the type of event that has occurred, encoded in its type field.

We use a simple switch statement to distinguish the different types of events, and in both cases of interest to us, we simply change the keypress variable so that our outermost while loop terminates. The program then calls SDL_Quit to shut down the SDL system and to clean up, and we terminate our program.

The lines of code that implement the event loop are as follows-na:

while(!keypress) {
   Draws-nacreen(screen,h++);
   while(SDL_PollEvent(&event)) {
      switch( event.type ) 
	{
	case SDL_QUIT:
	  keypress = 1;
	  break;
	case SDL_KEYDOWN:
	  keypress = 1;
	  break;
	}
   }
}