The game loop is an essential part of game programming. Without it, your game code would run once and only once. The game loop is what keeps the game going until it is over.
Game Loop Tutorial I
The game loop is just like any other loop. It keeps going until something happens that ends the game, such as the player has no lives or has managed to defeat the dragon of gardoz. But, there's more to it than just a simple loop, you also have to consider the overall structure of your game code.
Inside a Game
Game code typically has three sections, initialization, the game loop, and termination, in that order.
'Initialization 'Game Loop 'Termination
Initialization comes at the very beginning of the game. This is where you set up the game to be played. For example, if you want the player to start off with 100 gold coins, you give them to him here. Naturally, you do this by diming a variable and giving it a starting value.
' Initialization ' ------------------------ dim goldCoins as integer goldCoins = 100 'Game Loop 'Termination
Later, you'll be using the initialization part of your game to load sprites, sounds and other resources the game will need. In a text game, however, creating a few variables and giving them a starting value is all you need.
You'll also want to set up any variables your game will need to run. We need one variable to tell if the game is over. We'll call it gameOver and set it to , which means that the game isn't over.
'Initialization '------------------------ dim gameOver as integer gameOver = 0 dim goldCoins as integer goldCoins = 100 'Game Loop 'Termination
The Game Loop
The game loop will continue running the main code of your game until something happens that triggers the end of the game. Let's first look at the loop itself.
do 'main game code loop until gameOver
This game loop will keep running forever because the game will never be over. The only way to end the loop (other then using end is to set gameOver to 1. Therefore, whenever the event happens that triggers the game to end, we simply set gameOver to 1. For simplicity, let's say the game is over when the player runs out of gold coins.
do if goldCoins <= 0 then gameOver = 1 loop until gameOver
While programming text games, you really don't have to worry about termination too much. In more advanced tutorials you will learn how to use the termination section to clean up any mess your game may have made. Even though you don't have to worry about it now, just keep it in mind that this is where you clean up.
In a text game you can use it to tell the player his final results. That he is dead, due to the lack of hit points, for example. Another example would be the game ending, where you tell the player of all the great things he has achieved, whether this be the score in a simple dice game, or saving a kingdom from the Slightly Mad Dark Knight of Cheese. Mmm. Cheese.
And there you have it. In almost all of the later tutorials you will be using a game loop.