A mainloop for games
by Peter Stuifzand
Every game contains a mainloop. The mainloop is the center of all the action in a game. But how is a mainloop structured?
Introduction
In the most general sense a game is structured around three parts: startup, the mainloop and shutdown. In this article we will look at the structure of the mainloop in games.
Structure of the mainloop
A mainloop is a simple loop that goes on until some condition is met.
// .. startup code
for (;;) {
handle_input();
update_game_state();
draw_gfx();
}
// .. shutdown code
In most games the mainloop looks like this. It's about as simple as you can get.
Input handling
The best way to handle input is to set a variable for each possible key press. In a sidescrolling game it's easiest to set a speed for left and right movement when the appropriate key is pressed.
The x and y coordinate of the unit can be updated in the
update_game_state function.
Update the game state
Based on input of the previous step we are now able to calculate the differences to the game world.