Saturday, July 4, 2015

architecture - How should I write a main game loop?



How should I write a main game loop? What are some things that you should do in the game loop, and what are some things that you shouldn't do in the game loop?


I've written plenty of them, but I've never really read up on game loops. I'm sure I could improve them considerably, but I am unsure how.



Answer



The main game loop handles three major tasks:




  1. Get user input

  2. Update the game state

  3. Draw the game


A simple game loop just mushes these three tasks into one while loop. This has some undesired results:



  1. Game runs at different speeds on different computers.

  2. CPU (can be needlessly) pegged at 100% usage.

  3. "Game states"/menus are missing or mixed with game code.


  4. Main game loop is very long and hard to maintain.

  5. Code is difficult to extend/port to other platforms.


Advanced gamed loops address the issues listed above. Here are some useful articles:



For an excellent example game loop, take a look at the Allegro skater demo game:



Game loops often do the same type of work for most games, so I have been thinking of a way to make a generalized game framework. It is better to write one implementation of a game loop and share it between games. It saves work when creating a new game, and improvements to the shared game loop can be shared by all games (for example, adding a FPS counter or screen capture feature).


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...