Game Loop
Before I provide you with a definition of a Game Loop I would like to look at some corner concepts.
What is a Computer Program?
What a strange question? Everyone knows the answer! I can agree with that statement, but do you really know what computer program is in essence? After ten years in software development and thousands lines of code I’m re-thinking this question.
A computer program is a collection of instructions that perform a specific task when executed by a computer.
— Wikipedia.
To understand this definition I propose you to return to the past and look at Punhed Cards that were used as a source code for “Big Iron Machines”. The punched card was a pasteboard card with holes aligned by the columns, quantity of which could vary based on a card type. Originally, each individual hole on the card could contain the answer to a separate yes/no question, but further organization by the columns allowed to indicate digits and characters of text. For example, one hole in the column could represent 1, two holes could represent 2 and so on. I don’t think that we need to dive deeper in the details, just imagine that one card represented an instruction that the machine had to do, for example, to add one number to another. In such a way, a set of cards that are sequentaly loaded to “Big Iron Machines” represented a computer program. The main point here is the program started when the first card was loaded and ended as soon as the last one was processed.
You can be surprised, but there is no change nowadays! The computer program still works in the same way! Powerfull laptops replaces “Big Iron Machines”, numerous file types are used instead of cards. But the program ends as soon as instructions end. You don’t believe me? Just write a simple console application that displays “Hello World!”.
// C#
class Program
{
static void Main(string[] args)
{
Console.Write("Hello World!");
}
}
Have you seen the text when you run the application? I haven’t. The program had ended and had closed earlier than I could understand what happened.
How to See the Message?
You can say that we need to add something like Console.ReadKey()
. But, do you really think that this approach can be applied to a game? I don’t. This command completely blocks our programm until the user presses any button. Gennerally, the game is a world that lives independently of a user actions. The wind is blowing, the water is flowing, the monsters are getting closer and closer…
How can we allow our program to handle all these things? The answer is simpler than you can imagine. It is almost endless loop, each iteration of which represents a moment in a game live, in other words, a picture on the screen that users see. Let’s rewrite a little our program.
// C#
class Program
{
static void Main(string[] args)
{
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
{
Console.Clear();
Console.Write("Hello World!");
}
}
}
If you run the program you will see nothing. It happens because our output Console.Write("Hello Word!");
is not synchronized with the video output (for more details please see Computer Graphics article).
Can we call the loop above a game loop? No, we can’t! To call the loop a “Game loop” it should be able to do a couple more things. The first is to change the world.
How to Change the World?
Generally, change the world statement means that you need to change the program state. In our case, the simplest way to change the program state is to change the state of the letters from which our message consists of. For example… let’s change their case.
//C#
class Program
{
private static string world = "hello world!";
private static int index = 0;
static void Main(string[] args)
{
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
{
Console.Clear();
ChangeWorld();
DrawFrame();
Thread.Sleep(1000);
}
}
private static void ChangeWorld()
{
world = world.ToLower();
if (index == world.Length)
{
index = 0;
}
Char[] chars = world.ToCharArray();
chars[index] = Char.ToUpper(chars[index]);
world = new String(chars);
index++;
}
private static void DrawFrame()
{
Console.Write(world);
}
}
Now we have a world reprepresented by letters that changes their case in time. What is the last thing left to make for our program to transform it to a game? Right! We need to allow the user to interact with the world.
How Can the User Interact with World?
I think that in our programm the user can change the direction in which the letters’ case is changed. For this we need to do the following:
- To add two fields: one to hold the key pressed by the user and one to store a state of letters’ change direction (0 - right, 1 - left)
//C#
private static int direction = 0;
private static ConsoleKey? key = null;
- To modify loop to allow us to have access to the pressed key and process the user input
//C#
while (!(key == ConsoleKey.Escape))
{
if (Console.KeyAvailable)
{
key = Console.ReadKey(true).Key;
}
Console.Clear();
ProcessUserInput();
ChangeWorld();
DrawFrame();
Thread.Sleep(1000);
}
- To implement
ProcessUserInput();
method
//C#
private static void ProcessUserInput()
{
if (key == ConsoleKey.LeftArrow)
{
direction = 1;
}
if (key == ConsoleKey.RightArrow)
{
direction = 0;
}
}
- To apply direction to
ChangeWorld()
method
//C#
//instead of index++
if (direction == 0)
{
if (index == world.Length - 1)
{
index = -1;
}
index++;
}
else
{
if (index == 0)
{
index = world.Length;
}
index--;
}
Congratulations, you have just created a game!
What is a Game Loop?
Game loop is a loop used by us in the main method of our program. It runs continuously during the program execution. Each turn of the loop processes user input without program blocking, updates the program’s state, and redraws word that user sees. Also, it tracks execution time of the turn to be synchronized with screen redrawing.