SDL Event Loop

If your game doesn’t read input from the player, you don’t have much of a game. SDL supports keyboard, mouse, and joystick input as well as changing applications, quitting the application, resizing windows, and updating the contents of windows. You can also create your own events, which you may remember if you read the previous section of this article.

Mac OS X developers should keep in mind that closing a window generates a quit event. The Cmd-Q key combination, which is the standard way to quit Mac OS X applications, does not generate a quit event. If you want your game to support the Cmd-Q key combination on Mac OS X, you must handle Cmd-Q in your keyboard event handler.

What SDL programs do is check for events. When an event occurs, SDL provides you with the event’s data structure. Use the event structure’s type field to determine the type of event that occurred. Normally you write a switch statement with one case for each type of event your game handles.

There are two ways SDL can check for events: polling and waiting. Polling tells the operating system to constantly check for events. Waiting tells the operating system to do nothing until an event occurs. Waiting is more efficient than polling.

Call the function SDL_WaitEvent() to wait for events, and call the function SDL_PollEvent() to poll. The following code is an example of an event loop that waits for events:

bool done;

void GameApp::EventLoop(void)
{
    SDL_Event event;
    
    while((!done) && (SDL_WaitEvent(&event))) {
        switch(event.type) {
            case SDL_USEREVENT:
                HandleUserEvents(&event);
                break;
                
            case SDL_KEYDOWN:
                // Handle any key presses here.
                break;

            case SDL_MOUSEBUTTONDOWN:
                // Handle mouse clicks here.
                break;

            case SDL_QUIT:
                done = true;
                break;
                
            default:
                break;
        }   // End switch
            
    }   // End while
        
}

void GameApp::HandleUserEvents(SDL_Event* event)
{
    switch (event->user.code) {
        case RUN_GAME_LOOP:
            GameLoop();
            break;
            
        default:
            break;
    }
}

If you decide to wait for events, make sure you provide a way to exit the while loop. When you call SDL_WaitEvent(), nothing happens until an event occurs. If you provide no way out of the while loop, you won’t be able to quit the program.

Next (Cleaning Up)

Previous (Timers)