Game Loop

A game loop (or video game loop or main loop) loops the main code of your game while the game is still running. Without such a game loop, all the code in your game would run only once and then the game would be over because the computer had no more code to execute.

The game loop is the primary code loop in a game and one of the most essential parts of game structure. Outside of game programming, it is generally known as the "main loop".

Design of a Basic Video Game Loop

The basic game loop looks like this :

do
    get player input
    do calculations
    produce output
loop while not game over

Get Player Input

First, the game loop gets the player's input (or lack thereof). This can be anything from keyboard input, joystick input, mouse input, or even line input using the INPUT command1.

Do Calculations

Then the game does whatever calculations it needs to do. This could be adjusting variables in a simulation game, or drawing to a screen buffer in a 2D game. If this confuses you, just think of this part of the game loop the part where the game does its thinking and makes its moves.

Produce Output

In this part, the output of the game is presented to the player. It could be some text updates of the player's kingdom in a simulation game, or a new frame is drawn to the screen in an action game.

Loop While not Game Over

Finally the game checks for whatever conditions that cause the game to be over and exits when this condition is met, e.g. player is dead.

Timing and the Game Loop

The game loop is often delayed at the end to correspond with the framerate of the game. The precision of the timing is dependent on the Platform that the game is running on, from the CPU, the operating system, the programming or game programming language the game was created with, and the method of delay used.

In general, most game programming languages and game programming libraries have a function to regulate the frame rate easily and automatically. You will not have to deal with how precise the timing of a game loop is unless you are programming a game that requires such precision — most games simply don't.

Game Loop Timing Functions

  • Basic4GL: Sleep()
  • Brutus2D: Graphics.SetFPS
  • GML: room_speed2
  • FreeBASIC: Sleep
  • PlayBasic: SetFPS()

Related Pages

Links

Categories: Game Programming : Loops : Timing
page_revision: 31, last_edited: 1244646540|%e %b %Y, %H:%M %Z (%O ago)