Creating Simple JavaScript Games


How Easy Is it to Make a JavaScript Game?

Well if you are creating a basic game then you can create one in as little as 20 minutes, as we will see later in this article.

If you are looking to get into game programming or indie development then creating simple JavaScript games may be the way to go as JavaScript is a good entry-level programming language to learn.

Browser games are great for cross-platform compatibility and can enable you to reach a wider audience in a short amount of time.

Can I Make Games with JavaScript?

JavaScript works in tandem with HTML and CSS, together forming a trifactor that is more commonly used for creating webpages. Because of this association, some people consider this a limitation and don’t think it is possible to create a full game using this framework.

An advantage of using JavaScript to code your games is that they can be converted into hybrid apps that can be played on Android and Apple devices.

Software like Xamarin can be used to bridge this gap. Xamarin is part of the .net framework it allows you to code in different languages and then convert it into native code to be played on a device of your choice.

How do I make a game in JavaScript?

You can start by using a simple HTML document like below to house your game. The below markup simply creates a canvas element. With this, we can access the context of the canvas, which will in turn expose its API.

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Our Game</title>
	<link rel="stylesheet" href="ourGame.css" />
	<script src="ourGame.js"></script>
</head>
<body>
	<canvas id="gCanvas" width="600" height="400"></canvas>
</body>
</html>

With this, we can link two other files to our HTML document. The first one will be the CSS ( cascading style sheets ) and the second will be the JavaScript file.

What is the Simplest Game to Make With JavaScript?

Well, one of the simple games is probably pong the classic 1970s game involving block-to-block
warfare. Snake is another classic simple game that has you gobbling up food as it is randomly generated
on the screen.

How to Create HTML5 Games with JavaScript?

We are going to quickly build a simple game using the HTML5 Canvas. The game will involve controlling our play and moving them about the screen eating up the food before they disappear.

First, we take out the example boilerplate script from earlier and amend it slightly:

This is what the Mark up for our game will look like:

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Simple Game</title>
	<link rel="stylesheet" href="simple game.css" />
	<script src="simple game.js"></script>
</head>
<body>
	<canvas id="gCanvas" width="600" height="400"></canvas>
</body>
</html>

This file will provide the structure for our game environment and includes the Canvas element we are going to draw on. This file also provides links to the other two external files we need, this being the CSS file and the JavaScript.

This is what our external CSS file looks like:

body {
	
	background: #000;
}
canvas {
	background: #fff;
}

This file will control the document’s background color and the background of our canvas. This simple CSS setup is all we need for this example.

For browser games the CSS file can be used in lots of useful ways, one key use case would be using it to create all the UI elements of your game. This is quite simple to do and can save processing by turning off and on simple tag elements when needed.

A simple example of this would be displaying options on a menu screen or the game over and restart buttons when the player dies.

Now we have covered the HTML and CSS side, we now come to the more complex of the three files. The JavaScript file will hold all our game logic, including player movement and other behaviors.

All of the game logic will be contained within the window.onload() function

window.onload = function(){}

The next two statements will give us access to the canvas and its context

var canvas = document.getElementById("gCanvas");
var ctx = canvas.getContext("2d");

You can change the name of these variables to whatever you want, but it makes sense to create them with a name that makes sense.

I like to create my reference variable for the context as ctx, this saves time writing out context each time you need to use its methods.

Now we have access to the canvas API we can invoke the ctx.fillRect() method, Let’s test this by creating a simple rectangle and drawing it to the canvas.

ctx.fillRect(100,100,64,64);

This should create the following result:

This is great! But we want to create a constructor that we can use to create all our game objects. This is essentially a function that will create an object with parameters you feed into it at run time.

This is what the constructor will look like

var Asset = function(x,y,w,h,vx,vy){
	this.x=x;
	this.y=y;
	this.w=w;
	this.h=h;
	this.vx=vx;
	this.vy=vy;
	this.alpha = 1;
}
Asset.prototype.draw =function(){
	ctx.save();
	ctx.globalAlpha = this.alpha;
	ctx.fillRect(this.x,this.y,this.w,this.h);
	ctx.restore();
}
Asset.prototype.move = function(){
	this.x += this.vx;
	this.y += this.vy;
}

This looks quite complex but I will break it down:

We first start by creating the function names and their parameters. This argument will tell the function how to populate the properties and fields that lie within.

In this case, this includes the object’s X and Y positions, Width, Height Velocity and Alpha.

We then create the draw method that will draw the images to the screen, this will use the object’s custom values to set its Alpha, X and Y position and Size.

The last prototype function will change the position of our object when we need to move it around the screen.

We also create a simple variable called screenCenter, this will help set our game objects’ positions later on. We initialize it with the value 250;

var screenCenter = 250;

We then use our constructor to create our first two objects

var player = new Asset(screenCenter+10,150,64,64,0,0);
var container = new Asset(50,50,500,300,0,0);

Then we will now create our startGame function and our game loop

function startGame(){
	gameLoop();
}
function gameLoop(){
	window.requestAnimationFrame(gameLoop)
	ctx.clearRect(0,0,canvas.width,canvas.height);
	player.draw(ctx);
        player.move();
	container.draw();
	container.alpha =0;
}
	startGame();
}

The startGame() function will hold the things we want to initiate at the start of the game, in this case, it will simply start our game loop

The gameLoop function will do the heavy work with the window.requestAnimationFrame() looping through all our game objects.

We then use the clearRect() method to clear the canvas on each frame, this ensures the animation moves smoothly. If you leave this line out the image will smudge across the screen.

We then use the assets draw() method to draw the player and the container to the screen. We also set the container’s alpha to 0 as we don’t want to see it we just want to use it to set the bounds for the pickup we will create later.

The pickup will be an item the player has to collect.


We have created our player object but without any kind of interaction, it isn’t really a game. We now want to create an event listener to handle the player input.

window.addEventListener('keydown', function(e){
	var whatKey = e.keyCode
		if(whatKey == 65){//left
			player.vx =-2;
		}
		if(whatKey == 68){//right
			player.vx =2;
		}
		if(whatKey == 87){//up
			player.vy =-2;
		}
		if(whatKey == 83){//down
			player.vy =2;
		}
})

window.addEventListener('keyup', function(e){
	
	var whatKey = e.keyCode
		if(whatKey == 65){//left
			player.vx =0;
		}
		if(whatKey == 68){//right
			player.vx =0;
		}
		if(whatKey == 87){//up
			player.vy =0;
		}
		if(whatKey == 83){//down
			player.vy =0;
		}
})

These are the key-up and key-down functions, they will listen for a key event and set the player’s velocity accordingly.

We now add the player.move() method to the game loop so that we have a way to move our player object.

Refresh the screen and you should now have a block that you can move around the screen using the AWSD keys.

Next, we want to create a random number generator function. We will use this to create a random position for our pickup object.

function Random(){
	var random ={x:0,y:0}
	random.x = 40+Math.random()*container.w;
	random.y = 40+Math.random()*container.h;
	return random;
}

Within the random function we create a variable that holds an object with two properties X and Y. We then use the random.x and random.y properties to hold a random position within our container object. This will return the random number when the function is invoked.

Next, we will use the constructor again to create our pickup object, this will be what our playable character will collect.

var ran = new Random();
var pickUp = new Asset(ran.x,ran.y,32,32,0,0);

We also create a new Random object ran which we use to initialise our pickup object X and Y position. We then draw our pickup object to the screen by adding the draw method to the loop

pickUp.draw(ctx);

Now we have a character that moves around and a pickup that we can collect. The only trouble is nothing happens when we collide with our objects, we can change this by creating our collision function.

function collision(){
	if(!(player.x+player.w < pickUp.x) &&
	   !(pickUp.x+pickUp.w < player.x) &&
	   !(player.y+player.h < pickUp.y)&&
	   !(pickUp.y+pickUp.h < player.y)){
		   nRan = new Random()
		   pickUp.x = nRan.x
		   pickUp.y = nRan.y
	   }
}

So for this collision function, we will be using an inverse conditional statement which evaluates if the contents of the parenthesis are false.

This will evaluate whether the player’s position and the pickup position are overlapping, if all the conditions are false then the two objects are overlapping. This means the two objects have hit each other.

In this case, we want to reuse the pickup object and respawn it again at another location.

To do this we create a new random number and update the object’s positions, simple. We now just have to add the collision function to the main game loop.

If you run this now in your browser you should have a functional game, granted a very simple one. The aim is to collect the objects on the screen as they respawn in different locations.

Although this is a very simple game we have covered quite a lot. We made a constructor to instantiate the objects in our scene, this being the Player and Pickup objects. We dealt with grabbing user input via the keyboard to control our player object. We created a random number generator and then created some basic rectangle collision detection.


Recent Posts