The Beginning

This first bit is the easy bit. We just need to create a page with a canvas on it. I will be placing all the code in the one file so I shall define the script section and an initialise function.

<html>
<head>
 <title>8 Bit Game Framework</title>
<script>
init = function()
{
 alert("Init");
}
</script>
</head>
<body onload="init();">
 <h1>8 Bit Game Framework</h1>
 <canvas>Sorry... your browser does not support he canvas element.</canvas>
</body>
</html>

Run this in your browser and if all is well you should get a page appear with the header and an alert box displaying Init.

Initialisation

Next is the initialisation. This section will no doubt grow and change over time but for now lets write what we know we will need.

Lets create a Constants Section in the code. I put this at the top of the code. The contants are coded as variables which we initialise to whatever they should be. I like to use constants for things that I know will get used in lots of places. Declaring them here will make changing them a whole lot easier and also within the code they tend to make things more readable. So the canvas pixel widht and height are ideal candidates for declaring here as once we start moving things around the screen we will probably need to know where the boundries are. I also like to define the actual widht and height of the canvas on the page declared here. Although we will only really ever need to reference them once in the code by defining them as constants here means I can quickly change it to see how the game looks at different scales anytime without having to wade through the code. So that gives us 4 constants. Notice how I define these using underscores and all in capital letter. Its easier to quickly see what is a variable and what is a constant in the code.

// Constants
var SCREEN_WIDTH=640;
var SCREEN_HEIGHT=480;
var CANVAS_WIDTH=320;
var CANVAS_HEIGHT=240;

Now we may as well create another section underneath to store all our global variables. These are any value we wish to store / remember which will get used througout the code. Now if we are using OO we could do away with these but I still like to have them. personal preference. Currently all we need here is the context for the canvas. This is a handle we will need in order to gain access to the contents of the canvas.

// Global Variable
var ctx;

So now lets revisit the initialise function. Here we will need to find the canvas on the page. We can then define the visible size of the canvas and the actual size in terms of numbers of pixels. First of all we will make a slight change to the definition of the canvas in the page body. We need to give it a unique id so that we can find it on the page in our code.

  <canvas id="myCanvas">Sorry... your browser does not support he canvas element.</canvas>

Good. Now we can go ahead and write the code.

init = function()
{
 var canvas = document.getElementById('myCanvas');
 if (canvas.getContext)
 {
  ctx = canvas.getContext('2d');

  canvas.style.width = SCREEN_WIDTH;
  canvas.style.height = SCREEN_HEIGHT;
  canvas.width = CANVAS_WIDTH;
  canvas.height = CANVAS_HEIGHT;
 } 
}

Hopefully this is all fairly easy to follow. First we use the document.getElementById function to find the canvas. Not all browsers currently support the Html5 canvas so we wrap the rest of our code inside the if statement. If a browser supports the canvas then the getContext function will exist. So the if statement simply does just that. So now we get hold of the 2d context of the canvas and we store that in the global ctx variable. The rest of the code uses the constants to resize the canvas on the screen and define the pixel size of the canvas. If you run this you will see nothing much. Lets rectify that slightly. In the header we will add some styling to the page so we can at least see where the canvas is.

 <style>
 #myCanvas
 {
  border: 1px solid black;
 }
 </style>

This will apply a black border to the element on the page with an id of myCanvas. Now when you view the page you will see a black rectagle around the canvas. Mess around with the SCREEN_WIDTH and SCREEN_HEIGHT constants and you will see the canvas size change.

Main Game Function

Our game needs to be moving stuff around on the canvas. You cant just write code in an infinate loop to move objects around as you will find the page will just hang and the canvas never updates. The page will only refresh itself once all the javascript has finished running. Even if you could do that you then have the problem of how fast your game will run. It may look fine on your machine but on a much older machine it will run too slow. Try it on the lastest hardware it could be too fast. Even running it with a different browser could change the speed.

The answer is that we create a timer. The timer will call a function at regular intervals. I will aim for 25 times per second.  The function it will call is our Main Game function. This is the beating heart of our game. Everytime it is called it will move the sprites, check for any input and act upon then and update the canvas.

In the constants section we need a new constant to define the speed of the timer

var FPS = 25;

Now we insert the following at the end of  the init function which will create the timer and tell it the name of the function we want it to run.

 setInterval ( main, 1000/FPS);

and finally create the main function.

main = function()
{
}

If you run this now it still looks exactly the same as before. Not exciting. So lets write some code in the main function which will actually tell us the number of times it is being called per second ( the Frames Per Second  or FPS ).

Add the following variables in the global section.

var dwFrames=0;
var dwCurrentTime=0;
var dwLastUpdateTime=0;
var dwElapsedTime=0;
var fpsText;

We are going to need to have somewhere on the page to display the FPS so lets add a element on the html after the canvas which will show the fpsText. So lets add a paragraph element after the canvas.

	<p id="counter" />

Lastly we can add the following code into the main function.

	// Calculate the number of frames per one second:
	dwFrames++;
	dwCurrentTime = (new Date).getTime();	
	dwElapsedTime = dwCurrentTime - dwLastUpdateTime;
	if(dwElapsedTime >= 1000)
	{        
		fpsText = "FPS " + dwFrames;
		dwLastUpdateTime = dwCurrentTime;
		dwFrames = 0;
	}
	var l = document.getElementById('counter');
	l.innerText = fpsText;

So what is this code doing ?. Well first it just increments the frames counter. We want to keep counting the frames until a whole second has passed. Next we get the value of the current time. The number returned here contains the time in milliseconds. We now calculate the number of milliseconds since the last time a second had elapsed.
If the elapsed time is >= 1000 ( remember the time is in milliseconds ) then we create a text string consisting of “FPS:” and an integer number of the number of frames multiplied by 1000 and divided by the actual elapsed time. Now we can store our current time into the last update time and reset the fps.
You may notice that the first time into this code the Last Update Time has not been set yet. This doesn’t matter. It is initialised with a value of zero and there the elapsed time will end up being a HUGE value. So what… this just means that the FPS value in the first frame is zero.

So ends our first step. Below is a link to a zip containing the final file.

8BitGameTutorial1

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required