BASIC PROGRAM STRUCTURE



This tutorial is written in C++, but the logic can carry over to just about any language. This will teach you how to set up the basic game loop and create various modes for your game. Before you go through with this tutorial, you should know at least the basics of programming, things like while and switch statements. If you understand those, then please continue reading.

The first thing we need is to plan what modes your game needs. Since this is just an example, I'll throw out a few generic ones. These modes will be listed in an enumeration. Each mode will be given a function to go with it.

enum gm{
	gmStart,
	gmPlay,
	gmGameOver,
	gmEnd
};

void gameStart(){
	...
};

void gamePlay(){
	...
};

void gameGameOver(){
	...
};

void gameEnd(){
	...
};

In the main function (or class, depending on the language you're using), you will use a loop and a switch to make the game run. Take a look at the code below.

#include "main.h"

int main(int argc, char** args){
	//Main variables
	gm gameMode = gmStart;
	bool bQuit = 0;
	
	//Load game assets
	
	//Begin game loop
	while(!bQuit){
		switch(gameMode){
			case gmStart: gameStart(); break;
			case gmPlay: gamePlay(); break;
			case gmGameOver: gameGameOver(); break;
			case gmEnd: gameEnd(); break;
		};
	};
	
	//Cleanup code
	return 0;
};

Let's break this code down. First we have the variable gameMode which keeps track of what mode the game is in. After that, there is a bool named bQuit that tells the game when to stop. I like to put an abbreviated data type at the beginning of each variable's name to remember what it's meant to store, especially in languages with dynamic typing, but this is not required.

If you're familiar with the not (!) operator, then the while statement is pretty self-explanatory. The game will end whenever bQuit is set to 1 or true. As for the switch statement, it simply runs the next function to be run based on whatever mode the game is in.

Fairly simple, yes? I chose to show this method because using a function pointer leads to the possibility of the game mode being set to a function that is not supposed to take its place. This method ensures that only the functions intended to carry out main game code can be used.

The last part is the cleanup code, which is simply where one would put any functions that deal with deleting loaded assets, disconnecting from the internet, etc. Cleanup code is required because anything added to the heap (usually with a new command) will not be automatically deleted, unless the language supports built-in garbage collection. Since I'm assuming this is not the case, the next tutorial will instruct you on how to make cleanup much easier.

Lastly, the return command is given 0 to show that there are no errors. That's it for the barest of bare-bones game engines!