Intro To Programming For Games With JavaScript

I have been running my Game Development workshops in NYC now for a little over 3 months and one of the most common problems I run into are people who have never coded before or have coded and are interested in getting into game development. So last weekend I figured I would take a step back and start with a blank slate to teach people the fundamentals of game programming. The lesson was a great success and I wanted to capture it here on my blog to help ease the fears of others learning how to program their first game.

For this lesson I chose to use JavaScript. It is easy to create something with JavaScript right in the browser, there are lots of resources on how to build JavaScript games and finally JavaScript requires no tools outside of a simple text editor to write. I highly suggest using a resource such as Code Academy’s online JavaScript course to get you started. I designed this to be a cheat sheet of sorts for those still learning JavaScript and want to start making HTML5 games. With that in mind, these examples all revolve around use cases you would find in games and are designed to help you think about how this code is applicable to game development.

Variables

The first thing you will ever hear in programming is that “a variable is a container”. We use variables to store data. In JavaScript we use var to denote a variable. Here is an example:

var playerName = "Jesse Freeman";

There are 3 basic types of “primitive” variables:

  • Strings – this is text and is always put into quotes
  • Numbers – these are numbers and can be positive, negative, whole number or fractions
  • Booleans – this is a true or false statement. Also you can use the value 0 for false or 1 for true as well.

The most common thing you would probably want to store in a game would be things like the player’s name, their score and whether the player is alive or not. Here are some examples:

//String
var playerName = "Jesse Freeman";
//Number
var score = 0;
//Boolean
var isAlive = true;

In addition to these 3 simple examples you can actually store anything inside of a variable. Let’s look at some more complex data structures.

Arrays

Arrays are similar to variables but they can contain more than one value. Think of Arrays as lists. In games we could use Arrays to keep track of items in the player’s inventory. Here is how you set up an empty array:

var inventory = [];

Likewise you can also create an Array with items inside of it like so:

var inventory = ["item0", "item1", "item2"];

In this example we have 3 Strings inside of the inventory array but we could also have Numbers or Booleans as well. In order to get the value of an array we have to access its index. This is a unique ID related to the position of the item in the Array. In JavaScript Arrays are 0 based so the first item is always index 0. Here is an example of how we would get the value of item0:

inventory[0];

As you can see, we simply reference the Array itself and use brackets to supply the index we want to access. Arrays also have special functions (we’ll learn about functions later) that allow you to add and remove items from the Array. Here is a quick example of how we can add something to the array:

inventory.push("item4");

You can also get the total number of items in an Array like this:

inventory.length;

This would return 3 but remember if you wanted to use this to find out the last value of the Array you would need to subtract 1 from it since the starting index is 0. Here is how you get the last item in the Array:

inventory[inventory.length-1];

Arrays are incredibly versatile and are used to holds lots of different kinds of data structures. One of the most common is a table like structure with rows and columns of values. This is the basic structure we would use for tile maps and would use something called a 2d Array to store the data. A 2d Array is an Array containing other Arrays. Here is an example:

var map = [[1,1,1,1,1],  
	   [1,0,0,0,1],  
	   [1,0,1,0,1],
	   [1,0,0,0,1],  
	   [1,1,1,1,1]];

This simple map example uses two tile values: zero for empty and one for solid. If we were to visualize this map it would be a square room with a solid block of wall right in the middle. Accessing the value of these tiles is similar to how we did with our inventory Array. Let’s say that we want to get the center wall in our room, here is how we would access it:

map[2][2];

One way to help you think of this is that the first index is the row and the second index is the column like this:

map[row][column];

Remember that arrays can contain anything so the nested Arrays don’t have to necessarily store numbers, they could be Strings or even Booleans.

Objects

Up to the point we have simply been storing variables in the global scope. This is not the best way to do that. In order to build more complex data structures we rely on something called Objects. Think of an Object as a container that can hold other Variables, Arrays and even block of code called Functions. Here is an example of how to create an Object:

var player = {};

This is similar to how we created an Array but unlike an Array, values we attach to Objects are not ordered. Here is an example of how we would put a name variable on the player:

player.name = "Jesse Freeman";

When we attach a variable to an object it is called a property of that object. To access its value we simply call it by name like so:

player.name;

This would return “Jesse Freeman”. We can also attach Arrays to Objects just like we do variables:

player.inventory = ["item0", "item1", "item2"];

To get the value of something from the player object’s inventory simply access it just like you would a normal array:

player.inventory[1];

This would return “item1” from the inventory array. Objects are incredibly powerful in JavaScript and should be used to store and organize data such as player info, game settings, level details and even game logic. As you continue to build out a game you will eventually need a place to store instructions of code. For this we use something called functions.

Functions

Functions allow us to create containers of reusable instructions. It also allows us to control when a block of code will get executed. Take the following example:

var firstName = "Jesse";
var lastName = "Freeman";
var fullName = firstName + " " + lastName;

Believe it or not this is a common process where you would want to combine two variables together such as a first and last name. If you run this code in JavaScript it would execute immediately. Also, we would have no way to rerun it. Functions allow us to control when and how this action would take place. Here is the basic template for writing a function:

function getFullName(){  
	//code goes here
}

Just like we declare a variable with var we denote a function with the function identifier. Next is the name of the function and then the block of code that will make up the function is contained in the curly brackets. Here is an example of the above function but with some logic inside of it:

function getFullName(){
	return firstName + " " + lastName;
}

Here you will see that we moved the code that combines the first and last name into the function. We are using a new statement called return which will give us back a value when you call the function. In order to execute this you can call the function by name:

getFullName();

Even better, we can assign the value we get back to a variable:

var fullName = getFullName();

But this will only get us so far. Since the function has a scope of its own, meaning it doesn’t have access to anything outside of the curly brackets, it has no way of getting access to the first and last name variables. Luckily you can pass these into the function via parameters. It looks something like this:

function getFullName(firstName, lastName){ 
	return firstName + " " + lastName;
}

Now when we call the function we can pass in our first and last name and the function will return the full name back.

Var fullName = getFullName("Jesse", "Freeman");

Functions can have any number of arguments and you can pass in Strings, Numbers, Booleans, Arrays, Objects and even references to other functions. As you learn more about coding you will make extensive use out of functions and eventually you will learn how to attach them to Objects so you can reuse them throughout your games.

Conditionals

Games are made up of states and we are constantly trying to determine what happens based on that state. Is the game running? Is the player alive? Does the player have a weapon? If the player has a weapon can they can shoot? In order to test these states we will need to use conditionals. There are three main types of conditionals I’ll go over here. The most basic is an if/else statement:

if(player.isAlive == true){ 
	// do something
}

Here we are testing to see if the player is alive. By using the double equal sign with are making sure the player’s isAlive property value is equal to true. If the player is alive we can run some code. But what happens if the player is not alive. For this we can make use of an else statement.

if(player.isAlive == true){
	// do something
}else{
	// do something else
}

Here you can see we are still testing if the player is alive. Now we can execute different code such as end the game if the player is not alive. Likewise you can add as many if statements as you like this:

if(player.isAlive == true){
	// do something
}else if(player.isAlive == false{
	// do something else
}else{
	// do nothing  
}

Another interesting way to take advantage of conditionals is by using something called a switch statement. It’s similar to an if/then statement but allows you to test a variety of values without the need for adding operators such as equals, less than, etc. Here is how you create a simple switch statement:

switch(letter){
    case "g":
    	//do something
    	Break:
    default:
    	// do something
    	Break;
}

As you can see the switch statement is designed to test a single value against a case. If we were to pass in a string “g” it would pass the first case. We always add a break at the end of a case to keep other cases from executing. Finally we can use a default case to run something if no value is matched. Switches are very common in games and a great example would be getting the value of a letter in a game of scrabble:

getLetterValue(letter) {
    switch (letter) {
        case "g": case "d":
            return 2;
            break;
        case "m": case "b": case "c": case "p":
            return 3;
            break;
        case "y": case "f": case "v": case "w": case "h":
            return 4;
            break;
        case "k":
            return 5;
            break;
        case "j": case "x":
            return 8;
            break;
        case "q": case "z":
            return 10;
            break;
        default:
            return 1;
            break;
    }
}

Here you can see that I am assigning values to different letters. The most common value is always going to be 1 so that becomes my default return value. From there I set up cases for each letter going in order of value. You can add additional cases to a single test as you can see from each one of these score tests I wrote.

There is one additional conditional I want to go over quickly called a ternary operator. It’s similar to an if/then statement but all on one line. Here is an example:

var playerState = (player.isAlive == true) ? "Alive" : "Dead";

In this example we simply test to see if the player’s isAlive property is set to true. We do this test on the left hand side of the question mark. If the statement is true than playerState’s value will be set to “Alive” which is on the left hand side of the colon. If the value was false, the statement would return “Dead” which is on the right hand side of the colon. Here is a quick cheat sheet for how to write ternary operators:

condition ? value if true : value if false;

These are very useful when you don’t need to write out full if statements or are trying to clean up values into strings and need to do it inline of a variable.

Math

I am just going to go over some simple math concepts here. I actually plan on doing a more in-depth post on math for games at a later point. Let’s cover some basics since everything in programming revolves around math. You can add two values together with a plus sign:

var total = 1 + 1;

Likeiwse you can subtract them with a minus sign:

var total = 53;

Multiplication uses an asterisk symbol:

var total = 2 * 1;

And division uses a forward slash

var total = 4/2;

All of the same math rules you used in school will apply here. There are also some shorthand ways to add values together or increment them. Let’s take addition and subtraction for example:

var total = 0;
total ++;

This will increase total by 1. You can do the same with subtraction:

var total = 2;
total –-;

Also you can add two variables together quickly like this:

var valueA = 10;
var valueB = 10;
var valueC = valueA + valueB;

If you want to simplify adding a new value to an existing variable you can do something like this:

var valueA = 10;
valueA += 100;

This will take the current value of valueA and add 100 to it. You can also do the same with subtraction, multiplication and division, simply substitute the plus sign for the correct math operator you want to use.

The last thing I wanted to cover is that addition and multiplication are going to be the fastest math operators you can do. Division is “expensive” meaning it will always be slower than multiplication. Because of this it’s best to use multiplication where possible. We can achieve similar results to what we would get out of division by using fractions. Here is an example of getting half of a value:

var half = 4/2;

We can optimize this by doing the following:

var half = 4 * .5;

This is also incredibly useful for things like displaying a life bar. You may have something like this:

player.life = 5;
player.maxLife = 10;

Here we can get a fraction of the player’s life:

var lifePercent = player.life/player.maxLife;

Now if we have a health bar that we know is 100 pixels wide we can simply set its size to the percent of the player’s life:

var lifeBarWidth = 100;
lifeBar.width = lifeBarWidth * lifePercent;

This will cut the width of the lifeBar in half. I use this a lot in any UI that has a meter or changes size on the fly based on a current and max value.

Now that we have a foundation in JavaScript let’s talk about something a little more complex, loops.

Loops

Loops are critical for any game. All game engines consist of single loop called the game loop which runs each frame updating everything in the game then drawing it to the display. Let’s look over the basic concept of a loop and how it works. There are several types of loops, we will just focus on a for loop:

for (var i=0; i < 100; i++){
	// do stuff
}

This may look confusing but here is the basic concept. We are going to do something 100 times. To start we declare that this will be a for loop. In essence what we are telling JavaScript is that it should loop for as long as i, a variable we set to equal zero, is less than 100. We do the test of i in the middle of the for loop statement by checking to see if i is less than 100. The final part of the statement simply says to increment i by 1. You’ll remember back to the math section that you can quickly increase a value by 1 with two plus signs. Now every time this loop runs it will call its contents and then increase i by 1.

This is very useful for getting access to the contents of an array. Let’s look through how to get all of the items the player may have:

for(var i=0; i < player.inventory.length; i++){
	var item = player.inventory[i];
}

Here we are setting up a for loop based on the length of the inventory array. Arrays return the current number of items, in this case it would be 3 and since we are starting our loop at 0 we are able to iterate through all the contents of the array. We can also nest loops which gets a bit more complicated but is useful for displaying the contents of a 2d array:

for(var i=0; i < map.length; i++){
	// get the row’s content
	var row = map[i];
	for (var j=0; j < row[i].length; j++){
		// get the column’s content
		var column = map[i][j];
	}
}

If you think back to our 2d array example you will remember that if we access the first index of the map array we get the row and the second index will return the column. You should also pay attention to the fact that I am using two different variable names for each loop. If you used the same variable name it would corrupt the parent loop variable.

Loops can easily grow out of control, especially when you start learning game programming. One thing I want to point out is that loops are process blocking so nothing else can execute until the loop is completed. That means if you use lots of for loops or nested for loops you will start to experience performance issues. Be mindful of your loops and how much you try to execute within the scope of a single frame in your game.

I’ll continue to build upon this lesson as I continue to teach people more about game programming in my NY Game Makers meetups. Programming can seem overwhelming but like any other skill you learn, it only gets better with practice. Learning how to program by making a game is a great way to motivate yourself to pick up a new language or just get started from scratch. Hopefully some of these examples help point you in the right direction of how these basic programming concepts can be applied to making games.

Subscribe To My Mailing List

Want to learn how to make a game? Not sure where to start? Even if you are a seasoned game maker there is still a lot you can learn from my mailing list. I'll be covering tips and tricks for how to build, release and market games each month.

Simply sign up for my mailing list and also get access to a 50% off discount code for my eBooks and other content. I promise to not spam your inbox!

Join Now