Basic Game Loop

Category: SDL Adventure Game

There are different ways to implement a game loop. For this project, I decided to use the game speed dependent on variable FPS approach, which I found implemented in github.com/gustavopezzi/sdl-gameloop. This implementation works well and doesn’t utilize 100% of the CPU.

The basic structure of an SDL2 game loop looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main(int argc, char** argv) {
  // Initialization
  // ...
  bool game_is_running = true;

  // Game loop
  while (game_is_running) {
    // Poll events
    process_events();
    // Update game state
    update();
    // Render frame
    render();
  }

  // Deinitialization
  // ...

  return 0;
}

Another valuable resource on implementing a game loop using SDL2 is www.studyplan.dev/sdl2-minesweeper/sdl2-application-loop.

Suggested readings about game loops:

CannonBall is a real-world example of a game implemented using SDL2: github.com/djyt/cannonball. Its game loop is implemented in main.cpp.

SDL3

In SDL3, there is a more efficient way to handle game loops. You need to define SDL_MAIN_USE_CALLBACKS, import SDL_main.h, and implement four callbacks:

For more information on using main callbacks in SDL3, visit: wiki.libsdl.org/SDL3/README/main-functions.

SDL_main.h

In general, it’s useful to import SDL_main.h, even with SDL2, to allow SDL to abstract away platform-specific entry point details.

Next: Loading Images Using SDL_image