Authentic Society
An encyclopedia of non-absolute truth. Learn more
Sign In | Create Account
Discussion (5)

How to Write Your Own Computer Games in C++ (Part 1)

From Authentic Society, the Free Learning Website.
Category likeness to » . Added to Authentic Society 6 years ago.
Estimated reading timeEstimated reading time17 minutes 51 seconds (based on 3570 words and 200wpm reading speed)
How to Write Your Own Computer Games in C++ (Part 1) - We are a long way from making a game like Space Invaders in this tutorial.<br/>But you have to start somewhere. Let's make a text-based
We are a long way from making a game like Space Invaders in this tutorial.
But you have to start somewhere. Let's make a text-based "Guess" game in C++ first.


This page assumes no previous experience developing games, and is targeted at the absolute beginner, someone who is looking for a place to start. I learned most of the things from a great book called Tricks of the Windows Game Programming Gurus. It's a bit old, but I don't think the content of the book has lost its relevance. It was written by Andre LaMothe, who sort of developed a following with this book. Thanks for the hard work Andre!

Introduction to Making PC Games

Welcome to my guide on how to make computer games on your PC. We will choose an IDE (Integrated Development Environment) and start with setting it up so we can begin writing some code and create our first window. First we will write a simple text-based game "Guess" to demonstrate what code almost every game utilize at its core. We will then use what we learned with our first game to build our next games that gradually become more advanced, and more fun. You are encouraged to follow the links throughout this page to learn about subjects you don't already know, for example how to create your first window on a Windows-based operating system, which is required knowledge for making PC games that contain graphics.
A game that resembles the classic Wolf3d, programmed in C++.

I want to thank you for stopping by! If you are just as excited about building your own computer games as I am, then proceed reading. Just to clarify, the purpose of this page is not to reach a quick-and-dirty solution on how to slap games together and sell them. In fact, this page has nothing to do with selling games, and I hope that you are just as passionate about the art of writing computer games as I am. Unfortunately, many of today's computer games are based on how well they look on the computer screen, or in other words their graphics. But I believe that the quality of graphics alone shouldn't be the defining factor of how good a game is. If you are with me on this, this and my consequent tutorials will hold invaluable information on how to design and build your own computer games. I remember the time when I just started learning about programming computer games in Windows 95. It was the time when DirectX7 was the latest graphics API for the Windows operating system. When we are learning something we have an interest in, even simplest experiments can be exciting and gratifying. One of my first computer programs was a star-field.

Game Development Community

About The Author

Let me tell you a little about myself first. I designed my first computer game when I was 11 years old. I programmed it in the language known as Basic on a ZX-Spectrum 48K computer. That computer wasn't very popular in the United States at the time. I don't remember what I called my game, but the point was to control your character (that was 16 pixels wide and 24 pixels in height) from one screen to another, pick up several objects and use them to unlock doors as well as other things. The plot was very simple and went as follows: the terrorists opened a valve in the sewer to release deadly gas into the air and have the whole city infected with the poisonous substance (I recently read a book by Stephen King - The Regulators, it's about children's imagination, and I think here we see a perfect example of that). Your mission started in the city's airport. You had to find a shovel, dig a hole in the ground, shut off the valve and return back to the airport.

The screen resolution of the ZX-Spectrum computer was 256 by 192 pixels, so drawing graphics for the game wasn't very challenging, as every graphics tile of my tile-based "graphics engine" was only 8 by 8 pixels. Hardly a graphics engine. At 11, I couldn't program computer software to save my life, and I was just using for-loops and if-statements for everything! but already, I was poking my nose into the Assembly Language code, which was very exciting at the time, even though I understood little of it and copied many lines of code from Science Magazines and the only book on the subject that I had. I always liked to create or build things - anything that I could find - rather than play. Don't get me wrong, I have also played hundreds of games for hours on my ZX Spectrum computer, waiting for each game to load for 3 to 5 minutes, but ever since my uncle had shown me that I could draw a line on the screen of the computer with a one line Basic command, I was hooked. I wanted to draw more lines, I wanted to create character animations and I wanted to build entire games! I would actively talk my parents into going to computer fairs and have them buy me ZX-Spectrum tape cassettes (that's what games were stored on back then), not with games on them though, but rather with collections of arbitrary tools that were used to create games. Even to this day, rarely do I buy computer games. The only two games that I ever bought out of curiosity, were Half-Life and Starcraft. In both cases, when I brought the games back home, I didn't install the games first, I installed the game editing software that was provided with the two games. Half-Life had an editor called Worldcraft, and Starcraft had a map editor called StarEdit. Creating game environments and designing game maps or "levels" is a science into itself, but of course it will be discussed here, only later.

Who is This Page For?

As the title of this page suggests, you have no previous knowledge about making games whatsoever. I remember when I developed an interest in writing computer games and how hard it was to learn building your own games from scratch. Game development is a branch of software engineering that is considered one of the most difficult types of computer programming. That might be one reason why the programs aren't available through the top online universities. Ironically, the most fun and enjoyable games also take a tremendous amount of time and effort to develop. As the computer game industry grew and game development became a popular profession, the mere fact has given a birth to several Computer Game Design Schools, that teach everything from Level Design, 3D Modeling and Programming. For some people going to school would work better, and it's an excellent way to meet people who have the same passion for making computer games.

However, I didn't go to school. I happened to be the kind of a person who likes to learn from an open book and not necessarily a teacher. I remember how difficult it was to start. I looked through all tutorials I could find on the Internet, and purchased several books on the subject. Since then I've learned quite a lot about games and I wanted to write this page to make it easier for every new-comer to understand what the best tools for developing games are and how to start in general. Therefore, the information on this page assumes no previous knowledge of making computer games. I do assume the basic knowledge of a computer language such as C++. I am planning to continue writing about making games further and gradually we will get to more advanced game programming topics and tutorials that come with source code. But for now, let's start from the absolute zero and make one game after another with each game being better than the previous one.

What is a Game Engine?

A game engine can be thought of as a library of different game component functions responsible for graphics rendering, sound output, artificial intelligence, physics calculations and others, depending on the game type. In a bomberman-like game, for example, we don't need physics, because the game is so simple, but we do need 2D sprite rendering functions and playing sound effects. The game engine is the core of your game technology. Games that graphically operate in three dimensions are known to be based on 3D graphics engines. A modern graphics engine utilizes OpenGL or DirectX graphics APIs, which means polygon rendering is done in hardware with the help of a powerful graphics card.

Setting Up Your Development Environment

Where does one begin learning about making their own computer games? Writing computer games takes patience and effort. You are required to know a computer language. There are many different computer languages out there and many Operating Systems to program for. One of the most popular languages for programming computers games is C, or C++. Of course you would need to know the basic OOP (Object Oriented Programming) rules if you are going to write your game in C++. We are going to focus specifically on writing games in C/C++ and compile our code with the help of the Microsoft Visual C++ compiler on a Windows-based computer. To start writing games you must use an IDE (Integrated Development Environment) and a compiler. More than often your compiler will already come with the IDE of your choice. One of the best IDEs for programming games (or other software) on Windows is Microsoft Visual C++. Once you download the most recent version, you will be ready to start programming your first window application. You can learn how to do so from a link you saw in the first paragraph of this page. As you hopefully already noticed, I have written a separate tutorial just for that. When you understand how creating windows works, you will be ready to go on to the next step and learn about the three basic steps which are: game initialization, the game loop and the game destruction function.

The Game Paradigm

The Three Main Functions - Game Initialization, Game Loop and Destruction

What is a paradigm anyway? A paradigm in any system is a pattern or model. Because I decided to write about making computer games from absolute scratch, in this section you will learn the very basics of the computer game design pattern. Therefore I propose, let us not focus on fancy graphics but rather create a simple framework for our first game that we may use later to build any kind of games we want.

First we need to define some variables, also known as global variables. Modern object-oriented programming assumes that global variables as a bad programming practice. Whenever you hear rumours such as these, it is almost always talked about in the context of developing large applications, often developed by more than one person. Because this tutorial is all about writing your first game ever, with no previous programming or coding knowledge, this does not apply to us.

// guess.cpp : Defines the entry point for the console application.

// Guess is a simple game where the player has 5 tries to guess a random number the computer chose.

#include  /* Include srand and rand */
#include   /* Include printf() */
#include    /* Include time() */

/* Define constant values */

#define NUMBER_OF_TRIES 5                     // Guess the number 5 times until game over
#define TRIESLEFT       "You have %i tries left: "
#define TOOLOW          "Computer: The number you entered is too low\n"
#define TOOHIGH         "Computer: The number you entererd is too high\n"
#define WINNER          "CONGRATULATIONS, You won, the number %i is correct!\n"
#define LOSER           "SORRY YOU LOST, The number I thought of was %d\n"

/* Define game variables */

int i,
    tries = NUMBER_OF_TRIES;

Please follow comments in this code block that bear crucial description of what the appropriate include command or a variable declaration is for.

Almost any game usually contains the three important parts: Game Initialization, The Game Loop and Game Destruction. More than often, game developers think of programming games as building state-machines where only certain parts of the code are executed at a time, depending on what state the game is in. To give you a practical example, let's say that you are coming closer to your enemy in a game, but they can't see you because you are behind them So, perhaps we could set that enemy object's state to "idle". Had the enemy been facing the player, theoretically having the player in his eyesight, he may have been set to a state we would call "alert", and react in a way that is defined by the artificial intelligence algorithm assigned to him - to run away or attack the player (you). At this point we will not think about states in depth and only discuss them when it's appropriate. But it's certainly something to think about.

Game Initialization

/* InitGame() 
   Let the computer pick a random number */

void InitGame()
  srand(time(NULL));   // Reset
  number = rand()%100; // Generate the random number
  printf( "Computer: I have thought of a number between 0 and 100. Can you guess it?\n", number);

This is the part where you allocate memory for your game objects, initialize the game elements such as the game menu or options screen and put them into their default states. In your first game we will not concern ourselves with complex game initialization, because frankly, there is not much to initialize. The idea is to understand that this is one of the first functions that we are going to call that initializes the game. Later on we will use this function to load graphics, high score tables, and so forth. All of the code here will depend on what type of game you are making.

The Game Loop

/* Play() 
   This is where gameplay takes place */

void Play()
  printf("Play(): ");
  printf("Please enter the number below.\n");

  // Ask the player to guess the number, the number of times defined in 'tries' variable

  while ( tries ) {

    printf( TRIESLEFT, tries );

    result = scanf( "%d", &i );
    answer = GuessNumber(i);
    if (answer == 0) /* Correct answer */
      printf( WINNER, number ); return;
      answer < 0 ? printf( TOOLOW ) : printf( TOOHIGH );



  // Game over,
  // At this point the player has exceeded the number of tries, and still hasn't guessed the number

   printf( LOSER, number );

The game loop is where your main game code goes. This is where your game monsters dance, so to speak. A game loop function such as "Play()" is called once on each frame of animation from the Window's message loop. Depending on the current state of the game we will do state-specific things. If we are currently choosing an option from the main menu, for example, we will be executing the code that has to do with the main menu logic. After we select "Start Game", a game level data will be loaded, characters will be reset to their default positions and their health level will be reset to 100%. Again, we will not concern ourselves with this for now and just refer to this function as Play(). Simply know that this is the raw meat of your game, where everything happens (for a reason, I hope).

Game Destruction

/* Destroy() 
   This is where we would destroy allocated memory, etc.
   Because Guess is a very simple game, we have nothing to do here,
   But this would be an important step in an advanced computer game

void Destroy()

When the game window is closed, we need to deallocate (release back to the Operating System) memory that was allocated in the initialization stage and the game loop. We need to release memory associated with our game objects (player, monsters, levels, and so forth). This can be thought of as the reverse step of Initialization. Software Engineers are known to be making up all kinds of funky phrases, that make sense in the context of computer programming. So if we "initialize" something, the reverse function would be "uninitialize" or "destroy" game objects. It is common to "uninitialize" game objects one by one in the reverse order as they were created in the Game Initialization step.

Putting it all together

We can now take all of the functions described above and put them into a simple program:

/* int main()
   Program entry point */

int main(int argc, char* argv[])
  return 0;

int main(...) is the entry point of our program. This is where the program begins its execution. This is what any program or game written in C++ must have. The weird-looking arguments (argc and argv[], which is an array) are for passing parameters to the program from the command line. We are not concerned with that in this tutorial, but the main function must be declared this way, whether we are planning on passing parameters from command line to our program or not. In this case, we do not. The final statement return 0; exits the game and lets the operating system know the program has quit.

Your First Computer Game - Guess

Based on what we just learned about the three basic game functions, we are going to write a short text game called "Guess". In this game the computer will "think" of a number between 0 and 100 and have you guess it. You have 5 tries. If you think it's easy, compile the game and run it!

Aside from giving you the idea of how the basic game logic components works, "Guess" features a simple Artificial Intelligence (AI) algorithm which allows the computer to tell you whether the number you are guessing is higher or lower than the target number. There is really not much more to it and at this point we are ready to start writing the game. So fire up your Microsoft Visual C++ IDE and create a new console application. The main() function is known as the entry point. This function returns an integer (0), which means a graceful exit (we are exiting the application, but not because we encountered an error).

C++ Game Source Code

Download Guess C++ source code [here] This console application should compile under Microsoft Visual C++.

Game Screenshot

Here is an example of a possible situation in the game "Guess". Unfortunately, the player loses the game. Notice that the functions InitGame() and Destroy() are called at the beginning of the game and at the end respectively.

Playing 'Guess'

Again, a lot of the stuff that you see on this page was learned from the Tricks of Windows Game Programming Gurus book. The content of the book has not lost its relevance, even though it's a bit old, but I wouldn't say outdated. The book's strength is that it has general information on developing games from scratch, and I just think it's an excellent resource for anyone who is just starting to learn about making video games. It was written by Andre LaMothe

Game Development Community

Authentic Society is an encyclopedia of Knowledge, Wisdom and Understanding. It is an independently edited website containing free, original and good quality content, delivered via simple article format.
If you enjoy the quality of content on this page, have edit suggestions, improvements, questions, comments or business collaborations
feel welcome to reach me by email - Thanks :-)

2006-2011 Articles and Tutorials Copyright Authentic Society.

Privacy Policy | Legal Notice

Help us grow our community! Authentic Society is a small, growing online community (social network)
Create a Free Account to meet people who share the same interests.