Basic Game Programming Part 1


A lot of people think the best way to get young people into programming is through making games. I agree. Unfortunately, it is kind of hard to find the basics, so I want to do a series on it (Pygame is your best bet for a tutorial, but I’ve personally had bad experiences with it). This is definitely not meant to be some comprehensive tutorial. It is only meant to introduce some basic ideas.

There’s a lot of tools out there to make this easy (RPG Maker comes to mind). These tools allow you to make a fairly complicated and polished game without having any idea about how it is coded. Drag and drop images on a screen, and voila, a game is born. This defeats the whole point!

Other tools like game engines (Pygame, Unreal Engine, Unity, Monogame, Cocos, etc) are important to not have to deal with complicated graphics rendering or other hassles. These should be used in real life. For the purpose of this series, we will look at rudimentary simplifications of some of the things going on underneath these engines.

I will not assume you are comfortable with programming, but I also won’t explain the code much. I’ll assume you can look at the code and are able to figure out with some prompting what it does. The most important part of learning to program is learning the ability to look things up.

I’m going to use C++ even though I know most people learn Python or Java these days as their first language. But if you want to write cross-platform games, you’ll want to use C++ (Cocos) or C# (Unity and Monogame) or whatever Unreal uses. If you want a refresher, this game will only use cin, cout, variables, if/else. This should take less than 2 hours to learn from a reasonable tutorial.

If you have a little programming experience, there is a fundamental concept you’ll have to get used to called the game loop. It essentially looks like this:

while(true) {
    //Insert entire game here.
}

The game will infinitely loop through the instructions. For most simple games, this is overkill and uses a ton of unnecessary processing power. Also, without a professional game engine underneath, you don’t have a way to limit the speed at which it loops (30 times per second or 60 times per second). Don’t worry about any of this. Just know that you will eventually want this constant loop, so it is good to get used to it.

Let’s add a touch more detail now. The game loop roughly consists of three parts: Getting input from the player, Updating the game state based on that input, and Drawing to the screen whatever has changed from the update step. This is called the engine, because it keeps churning and puts the game in motion. If you use Unity or some pre-built engine, each of these parts will exist already (and will loop independently in parallel, but that is for another time).

Our game now looks like this:

while(true) {
   GetInput();
   Update();
   Draw();
}

Again, this is needlessly complicated for the game we will make, but it is worth getting used to this flow with something basic so you aren’t learning a whole new framework with something more complicated.

Now let’s describe the game. The game will display your health and the enemy’s health. The player will have 2 choices: Attack or Run. If you attack, you hit the enemy, in which case the enemy’s health decreases by some amount (we’ll make it random between 0 and 3). If you run, you leave the game (effectively a “quit” choice). The enemy always hits you.

If the enemy’s health reaches 0, the player wins. If the player’s health reaches 0, the player loses.

A part of the engine I didn’t describe is the initialization that come before entering the game loop. In this case, we might want to describe the setup and get the initial variables set up and call the Draw() function to get something on the screen.

There will be 2 variables: PlayerHealth and EnemyHealth. Let’s set them both to 10 to start. At this point I think we can write the first form of the Draw() function, which right now will just print out and label these variables and give the two options for action. Eventually, we’ll probably want to say who got hit, too.

void Draw(int playerhealth, int enemyhealth) {
  cout << "Your Health: " << playerhealth << "\n";
  cout << "Enemy Health: " << enemyhealth << "\n";
  cout << "a. Attack \n";
  cout << "b. Run \n";
}

This might look a bit confusing, but “cout” just means “print to the screen.” So each line of that is printing “Your Health: 10” (and the \n means “new line”).

Now let’s get the input. We’ll do something a little bad, but we’re just trying to get the flow down here. We’ll worry about “good coding practices” some other time. Let’s make the function Input() return the string the user inputs, so we can store it rather than modifying some global variable.

string Input() {
  string tmp;
  cin >> tmp;
  return tmp;
}

Again, “cin” just asks for the player input. The input is stored in the variable “tmp” and then gets returned.

The most complicated part of this is going to be the Update() function, but it isn’t so bad. Update() needs to say: if the player typed “a” we subtract the attack amount from EnemyHealth. If the player typed “b” we exit the loop. If anything else was typed, we don’t do anything and notify them it is not an option.

if (PlayerInput == "a") {
      int r1 = rand() % 4;
      EnemyHealth -= r1;
    }
    else if (PlayerInput == "b") {
      break;
    }
    else {
      cout << "This is not a valid option.\n";
    }

I used here a random number between 0 and 3 (inclusive) for how much damage the attack does. (Look up rand() for how it works. It is part of the standard library.) There isn’t much left, so I’ll give the whole thing now with some comments:

#include <iostream>
#include <stdlib.h>

using namespace std;

void Draw(int playerhealth, int enemyhealth) {
  cout << "Your Health: " << playerhealth << "\n";
  cout << "Enemy Health: " << enemyhealth << "\n";
  cout << "a. Attack \n";
  cout << "b. Run \n";
}

string Input() {
  string tmp;
  cin >> tmp;
  return tmp;
}

int main() {
  //Initialize the variables
  int PlayerHealth = 10;
  int EnemyHealth = 10;
  string PlayerInput;

  //Initial Information Drawn
  cout << "An enemy approaches... \n";
  Draw(PlayerHealth, EnemyHealth);

  //Game Loop
  while(true) {
    PlayerInput = Input();

    //Update Information based on input.
    if (PlayerInput == "a") {
      int r1 = rand() % 4;
      EnemyHealth -= r1;
    }
    else if (PlayerInput == "b") {
      break;
    }
    else {
      cout << "This is not a valid option.\n";
    }

    //Enemy attacks.
    int r2 = rand() % 4;
    PlayerHealth -= r2;

    //Break out of the game looop if won or lost.
    if (EnemyHealth <= 0) {
      cout << "You Win.\n";
      break;
    }
    else if (PlayerHealth <= 0) {
      cout << "You Lose.\n";
      break;
    }

    //Print out the Updated Info
    Draw(PlayerHealth, EnemyHealth);
  }

  cout << "Game Over.\n";

  return 0;
}

Here’s some features to add as homework. Now that the core is there, if you think of one thing and add it each day (15 minutes tops?), in 2 weeks you’ll have a pretty interesting and complicated text-based game. They don’t have to be these or even in this order. These are what popped into my head.

Excercise 0: Try cleaning up the current code so that Update() is its own function like Input() and Draw(). Don’t try too hard, because it is more complicated than it’s worth. You will encounter your first struggle with how to scope variables that all your functions want to know about. Also, breaking out of the while loop will become tricky.

Feature 1: Look up how to do random numbers. Make it so that you only hit the enemy 50% (or whatever you want) of the time. Make it so the enemy only hits you sometimes. This might be a 2 day feature if you are totally new to programming in C++.

Feature 2: Tell the Player that they hit the enemy and how much damage they did.

Feature 3: Make a “Title Screen” that tells you the game you are about to play.

Feature 4: Add some backstory to the introductory text.

Feature 5: Add more options for player input (different types of attacks that do different damage amounts).

Feature 6: Figure out where to clear the screen to not be so cluttered.

Feature 7: Ask if the player wants to play again rather than automatically closing the program when it is over.

That’s a whole week’s worth of exercises, and you’ll have a basic working game at the end. Next week, I’ll go through implementing these changes and maybe make a quick video to show that end result can look like a real-life, old-school text game.

Advertisements

One thought on “Basic Game Programming Part 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s