Make a Game (Part 1)

Let's make an HTML5 game.

First step is to set up the canvas which will display our game.

<canvas id="game" class="" width="200" height="100"></canvas>

Now draw something on our canvas

var ctx = document.getElementById("game").getContext("2d");
ctx.fillRect(0,0,10,10);	

Now let's make some keyboard controls to move this little black square around the canvas.

keydown(e){...} is triggered when a key is pressed, and it changes the values of x or y when an arrow key is pressed. This also calls drawGame which erases and redraws the canvas based on the values of x and y.

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

var x = 100;
var y = 50;

function drawGame(){
	ctx.clearRect(0,0,200,100);
	ctx.fillRect(x,y,10,10);
	ctx.fillText("x=" + x + "   y=" + y,2,10);
}

window.onkeydown = keydown;

function keydown(e) {
	var c = e.keyCode;
	if(c == 37)		//left arrow
		x--;
	else if(c == 38)	//up arrow
		y--;
	else if(c == 39)	//right arrow
		x++;
	else if(c == 40)	//down arrow
		y++;
	if(c >= 37 && c <=40) //prevent scrolling
		e.preventDefault();
	drawGame();
}

drawGame();

We are actually making a mario-style platform, so we are going to have to give our sqaure some ground to stand on, and make sure that he gets pulled down towards the ground.

This code doesn't just update the game when a key is pressed, but rather updates every 20ms, or 50 times a second. setInterval(gameLoop, 20); defines the code to be called for the loop, as well as how many milliseconds to wait between loops.

ctx = document.getElementById("game").getContext("2d");
var x = 50;
var y = 50;
var ground = 80;

function drawGame(){
	ctx.clearRect(0,0,200,100);
	ctx.fillRect(0,ground,200,100-ground);
	ctx.fillRect(x,y,10,10);
	ctx.fillText("x=" + x + "   y=" + y,2,10);
}

window.onkeydown = keydown;

function keydown(e) {
	var c = e.keyCode;
	if(c == 37)			//left arrow
		x-=6;
	else if(c == 38)	//up arrow
		y-=6;
	else if(c == 39)	//right arrow
		x+=6;
	else if(c == 40)	//down arrow
		y+=6;
	if(c >= 37 && c <=40) //prevent scrolling
		e.preventDefault();
	drawGame();
}

function moveThings(){
	if(y + 10 < ground){ //if higher than the ground
		y++;
	}
	
	//make sure square is above ground
	y = Math.min(ground-10,y);
	//keep x between 0 and 200, moving around-the-world
	if(x > 200)
		x -= 200;
	if(x < 0)
		x += 200;
}

setInterval(function(){
	moveThings();
	drawGame();
}, 20);

A grasp of the concepts employed in these demos is really most of what you need to know to create a game.

Continued in part 2... (not yet written)



`