Making HTML5 games by someone who knows nothing about making games.

Fleet Command - a HTML5 Game

If your thinking about trying your hand at creating a HTML5 game, but have no game creation experince on which to draw, your probably in the same boat as me. Since, despite this limitation, I decided to start making  a HTML5 game anyway, I thought I may as well post about my experiences in the hope they are useful (or at least interesting) to other people.

My true first attempt to create a HTML5 game was a few months back when I decided I’d start hitting the keyboard and hope something worked. Over the following week  I slowly hacked together the outline of a more-a-less functional but totally unsustainable JavaScript based Asteroids style shoot-em up game. Although it never really went any where, I did  learn some pretty important lessons from the experience. The summarise them:

  • Game loops are important and a set interval doesn’t quite cut it.
  • Object collision is hard – especially if you want to do it accurately and don’t wan’t to kill the computer running it.
  • Geometry – This stuff really does have a use.
  • If you plan to do anything clever with the game, you need to keep performance in mind from the get go. Its very easy to bring stuff to a crawl.
  • Sprites look better than triangles.

Based on this, for my latest attempt at making a game (which is substantially more ambitious) I decided to actually have a proper think at how I planned to develop it. I even went so far as to think up a basic plot and doodle roughly how i wanted it all to look. Aside from this though, one of my first major actions was to have a look at some of the HTML5 Game Development frameworks out there, so as to save myself having to reinvent the wheel for the second time (Granted that for the purpose’s of this analogy my last “wheel” was more oval than circle).

It turns out there are actually  quite a lot of HTML5 Game Development frameworks out there, after trying a few though i ended up selecting Batiste’s Spirte.js to be my starting point. The reasons for this are fairly simple, sprite.js is very lightweight,  it support’s webGL (I’m not actually making use of this, i just think its cool), it includes some great extras such as functions for path finding class & collision detection (which you can include as needed) and even though the documentation is a little sparse, the code is easy to read and there are a load of useful examples included.

After finally deciding to go ahead with the game using sprite.js, I spend a good few hours playing around with it, reading its documentation and taking a look though the examples on offer. One of the first things I noticed was that features such as pausing a game, were actually added by sprite.js out of the box. Additionally there were also handy methods to access user input, load assets in to memory prior to the game starting and a host other other little bits & bobs which help to make starting a new game much less painless.

After getting roughly to grips with the codebase, I decided I may as well start actually building my game. My initial aim was to try and replicate the functionality iIhad managed on my first foray in to HTML5 Game building territory. To do this I started off by creating a new HTML file, set up a basic HTML5 structure  (html,head,body kinda stuff, no real content) and added a JavaScript include to grab sprite.js itself, plus this code in the head:

<script type="text/javascript">
	var bootstrap = function(){
		//Create new Sprite.js Scene (effectively the Canvas that sprite js draws on to)
		var scene = sjs.Scene({'w':window.innerWidth, 'h':window.innerHeight});
		var layer = scene.Layer("game_layer");
		//Load images needed to display (ensure these images exist or it won't load)
		 function() {
	 		//Create instance of Engine (class i'm using to run the game)
	 		engine = new Engine(scene, layer);
	 		//Setup game loop via Sprite.js's ticker (calls engine's run method)
	 		ticker = scene.Ticker(function() {; });
	 		//Pass ticker to engine
	 		//Start the ticker;
	//Bootstap Game (when page is loaded)
	window.addEventListener("load", bootstrap, false);

The job of the above code is pretty much to set sprite.js up and then pass along all the important values to my “engine” class. Once the document has loaded and sprite.js has loaded its required assets, the engine class is instantiated, the ticker is created and finally everything gets set in motion with the call to  The most basic engine class that won’t crash should look something along the lines of:

function Engine(scene, layer){
		//store scene and layer for later
		this.scene = scene;
		this.layer = layer;
		this.ticker = null;
		//Create our sprite
		this.myship = this.scene.Sprite("ship.png",{
			"layer": this.layer, //Layer ship will be displayed in.
			"x": 100, 	//X position of sprite
			"y": 100, 	//Y position of sprite
			"w": 37, 	//width of sprite.
			"h": 75 	//height of sprite.

		//Add set ticker method to Engine
		this.setTicker = function(ticker){
			this.ticker = ticker;

		//Create run method which will be called each time the
		//game loop runs. = function(){
			//Apply sprites changes (in this case make
			//it so we can see it)

And running the above code should give you something that looks like this.

If all has gone to plan (it hasn’t died horribly) the next step is to make the game actually do something in its run loop. We can use the built in Inputs() Class to get our inputs from the user. To add this, just add the below code under the “this.layer = layer;’ line in the engine class.

this.inputs = scene.Input();

The addition of the above code now means which can check for “this.inputs.keyboard.up” which will return true whenever the user hits the up arrow (or w) key. The same is true for when the down key is pressed, or the left and right arrow keys. Using this we can start making things happen when these keys are pressed, the simplest form of this I could think of was to simply hook each action up so that it alters ships current position by adding or subtracting from its x and y values. The result being that a user will then be able to move the ship around the game are using their arrow keys.

Once this was done, my updated run method looked much like this: = function(){
		//Get ships current x and y.
		nx = this.myship.x;
		ny = this.myship.y;
		//Update it depending on which keys are pressed.
			nx -= 2;
			nx += 2;
			ny -= 2;
			ny += 2;
		//Tell the ship
		//Apply the changes

Assuming everything went well running you game should now give you somthing along the lines of this.

So, now we have movement, but it isn’t really very space ship like movement. To make the movement a little more “space ship” like, my first action was to change the behaviour of the left and right arrow keys, so that the rotate the ship in a given direction, rather than just move it left or right. To do this,  grab the ships current angle and just add or subtract 2 degree’s depending on which way we want to turn the ship. The code may look like:

	ang = this.myship.angle;
	//Update it depending on which keys are pressed.
		ang = (-2*(Math.PI/180))+ang;
		ang = (2*(Math.PI/180))+ang;

One thing you probably noticed is the adding 2 degrees is a little more maths heavy than you would have guessed. The reason for this is that sprite.js uses radians rather than degrees to calculate the rotation of the ship. To convert from degrees to radians we need to multiply are degree value by PI/180 and then everything will work as expected. Once we have are 2 degrees in radian form, we simply add it to the current angle value to produce a new value for our ships rotation.

On its own though this won’t do a lot as we still need to tell the sprite we want it to rotate to the angle value we just worked out. To do this simply add the call to the setAngle method, passing it our value, before the sprites update method .update() is run.


With the addition of the above code and a little luck your ship should now rotate. The next step is going to be making the ship travel in the right direction when we hit the up button, something that’s going to take a little math to solve. Fortunately the required math has already been calculated, meaning all we need to do is to shove our own values in to the formula below.

new_x += (movement * Math.sin(angle));
new_y += (movment * Math.cos(angle));

So for the purposes of our code, our go forward method should look like: (Keep in mind the Y position is the distance from the top of the canvas, so we need to invert this value for it to make sense in the context of our game)

	nx += (5 * Math.sin(ang));
	ny += (5 * Math.cos(ang))*-1;

We now move in the right direction, but it still seems a little lacking. Whats needed is a way to keep track of momentum and for simplicity sake the easiest way to do this is just add a var called speed outside of the run loop and set it to 0. The next step is then to move the “forward” code out for the forward action and to the main body of the run method, so that it will be called every time the game loop runs. Inside the now empty forward if statments action, add the following code

if(speed < 5) speed = speed+0.5;

This will essentially cause the speed value to be increased when you hit the forward button.(limiting it to a max speed of 5 pixels per game loop.) Additionally you now need to swap the 5 in the moment code to use your speed value instead (or you will constantly be moving at that speed).

Now you have momentum, its also probably also worth adding a way of slowing back down again. The simplest way to do this is to add a little code in to the down arrows action, that does pretty much the exact opposite of the forward keys action. For example

if(speed > 0) speed -= 0.5;

Altogether your run loop should now look something like:

	var speed =0;
	//Create run method which will be called each time the
	//game loop runs. = function(){

		//Get ships current x and y.
		nx = this.myship.x;
		ny = this.myship.y;
		ang = this.myship.angle;

		//Update it depending on which keys are pressed.
			ang = (-2*(Math.PI/180))+ang;
			ang = (2*(Math.PI/180))+ang;
			if(speed < 5) speed = speed+0.5;
			if(speed > 0) speed -= 0.5;
		nx += (speed * Math.sin(ang));
		ny += (speed * Math.cos(ang))*-1;

		//Tell the ship
		//Apply the changes

You can see the full code (so far) in action here.

I’m planning to create a series of posts on HTML5/JavaScript game making when I get the time, so with luck this is just the first of many such articles. Since I covered a lot of the basic set-up in this post, hopefully in my next one I’ll be able to make a little more headway in to the actual meat of the stuff.

You can now view the next tutorial in this series here

Also, if your wondering how the game that inspired this tutorial is going, check out what I’ve got so far here.

PHP Secret Santa

Secret Santa ScreenShot

PHP Secret Santa

After a few years of neglect I decided it was about time I gave my ageing PHP Secret Santa App a bit of an update.

The original, having been the result of a spur of the moment, hacked together reaction to the idea of running a CS Secret Santa between my friends (way back when in my second year of UNI), was as you may have guessed a pretty crappy implementation. The code was awful and the word awful just doesn’t capture just how bad the UI really was. Despite this, I’ve still somehow ended up running the script almost every time Christmas rolls come around.

My newer version of the script functions, effectively, the same as my original. Rather than taking the more common approach of putting the names in to two arrays, shuffling one, then joining em back together until no one ends up with themselves, I decided to stick with my original “names in a hat” style algorithm. Mostly just for nostalgia value. The implementation effectively mirrors its real world equivalent, with each user taking their turn to grab a value from the “hat” (array of users who need gifts buying from them)  and putting it back and taking another if they happen to get themselves. This continues until every user has someone to buy for. The one flaw with this plan is that when the final person comes to pick, if it so happens that the only person left in the “hat” is themselves, there a little stuck. My solution to this problem was essentially just to make them swap with another user. Which so far has worked pretty well 🙂

Once everyone has been assigned someone to buy for, the next step is just email everyone telling them who they have. It may not be the shortest, simplest or most straight forward solution, but I quite like it either way.

The next step of the Rebuild was to try and create a “slightly” nicer looking UI, although due to my terrible design skills I’m not sure how successful this was, but on the bright side, I found an excuse to make a JavaScript Add User button.

As normal the code can be found on my github or you can use the live version here:

Please feel free to ask questions, point out bugs/flaws or even just use the script for your own Secret Santa’s.

Read and write to SharePoint lists using PHP

Its been a while since I last blogged so I thought I may as well post an update. The main thing I plan to present is my, hopefully useful, PHP SharePoint API Class.

The aim of the class is essentially to make interacting with the SharePoint Lists API a whole lot more straight forward and allow PHP developers to talk with the Lists API without having to get there hands dirty with SOAP.

As with most stuff I create, its free under MIT licence and is being maintained on my Github account. At current the tool is fairly basic, although if I end up working on a SharePoint based project again I may take the opportunity to expand it further. If anyone spots any bugs or wants to add some features feel free to send em my way or just fork the github repo. Currently the SharePointAPI code is only capable of interacting with an existing SharePoint list and does not support creating new ones programmatically at this time.

You can grab the full source from:

Setting up the PHP SharePointAPI Object

Using the SharePointAPI to read a SharePoint list is pretty straight forward. The first step is to create a new instance of the SharePointAPI object which requires a username and password (which it will authenticate with in order to interact with the lists) as well as the path to a local copy of the SharePoint Lists WSDL file.

You can normally grab the WSDL from: sharepoint.url/subsite/_vti_bin/Lists.asmx?WSDL

$sp = new SharePointAPI('<username>','<password>','<path_to_WSDL>');

Reading from a Sharepoint List

Once the SharePointAPI Object has been created, you can read from a list simply by calling:


More advanced filtering is also possible, for example if you wanted to filter on surname = Smith and only return 5 results you would call:

$sp->read('<list_name>', 5, array('surname'=>'Smith'));

You can filter on multiple parameters simply by adding extra values to the filter array. (currently only AND ing is possible)

All results are returned as associative arrays, calling print_r on the results of a $sp->read(‘<list>’); is probably the best way to understand exactly what data is being returned.

Writing to a SharePoint List

Writing to a SharePoint list (or inserting a new list item) is equally straight forward. The data to be inserted is simply provided as an associative array to the function. For example to add someone called bob to a list you may use:

$sp->write('<list_name>', array('forename'=>'Bob','surname'=>'Brown','pet' =>'cat'));

Editing a SharePoint List Item

To edit an existing SharePoint item the syntax is fairly similar to the above examples. The primary difference being that the ID of the record you wish to edit is also required. Assuming the ID for Bob’s record was 20, you could change his pet to dog with the following code:

$sp->update('<list_name>','20', array('pet'=>'dog'));

Deleting a SharePoint List Item

Deleting a SharePoint list item also requires the ID of the record you wish to remove.



Thanks for reading 🙂

P.S.  I’m now only one week away from starting my new job on the Kent Web Development team. Woo 😀

JSnip 0.5, a Portfolio Section and a little blog optimisation.

A Photo I took in Sloveina!


As a result of a holiday in Slovenia (obligatory photo to the right), being a little busier than normal at work and a hint of having nothing interesting to post it appears it’s actually been quite a while since I last updated my blog.

My solution as you may have noticed is this somewhat rambling posting purportedly providing interesting information and such.

Probably the most interesting update to the estimated two people that actually read this blog is the release of my latest version of JSnip. The new version includes with it an array of bug fixes and a brand new LightBox Snippet, along with a rather snazzy little zoom animation to go with it. As always you can get the full code on Github and check out the new features on the sample page.

Probably less interesting would be the fact I finally got a more or less functioning version of my portfolio page on-line (minus quite a few projects I lack pictures for). The best part of this being my site is now finally free from those pesky “coming soon” pages, and that I’ve also found somewhere to dump a little feed from my github.

Least interesting of all, but probably still quite a nice change for anyone who actually views these pages is that the blog should now be loading signifcantly faster thanks to the addition of WP Super Cache. (Previously page loads were taking a good ice age and a half which was kinda ridiculous)

P.S. Click the Holiday Image to the right to see the new JSnip Lightbox in action.

JavaScript URL Parser

For science reasons I decided to write a simple JavaScript URL Parser this morning. The basic idea behind the function is to make it easier to extract the bits of a URL your interested in, be it the Port,  Host,  Protocol or even the value of a parameter in the query string.

 * URL Parse
 * A quick URL parsing function for JavaScript
 * @version 0.4
 * @author Carl Saggs
function urlParse(url){
	var self = {};
	//Store full url
	self.url = url;
	//array to store params
	self.QueryParams = new Array();
	//Use DOM to get URL basics
	self.a = document.createElement('a');
	self.a.href = url;
	//Parse Query String
	q_seg ='&');
	for(i=0; i<q_seg.length;i++){
		s = q_seg[i].split('=');
		self.QueryParams[s[0]] = s[1];
	//Extract the Port
	self.port = url.split('/')[2].split(':')[1];

	//Return Protocol in use
	self.getProtocol = function(){
		return self.a.protocol;
	//Return Host
	self.getHost = function(){
		return':')[0];//Remove the port from the end
	//Return Port
	self.getPort = function(){
		//Assume default port if none is set
		return  (self.port == null)
				? ((self.getProtocol=='https:')?443:80) 
				: self.port; 
	//Return Path
	self.getPath = function(){
		return self.a.pathname;
	//Get full Query String
	self.getQueryString = function(){
	//Get Query String as Array
	self.getQueryArray = function(){
		return self.QueryParams;
	//Get value of parameter in query string
	self.getQueryParam = function(x){
		return self.QueryParams[x];
	//Return original URL
	self.getURL = function(){
		return self.url;
	//Get Fragment
	self.getFragment = function(){
		return self.a.hash.substring(1);//Remove # from start

	//Return self
	return self;

The function is designed to be pretty straight forward to use, calling the function will return the object containing all of the URLs attributes which can then be accessed by the provided get Methods. An additional advantage to having the function return an object is that you can chain the functions when it seems appropriate (as in the final example below).

//Usage Demo
var test = urlParse("");
alert(test.getQueryParam('queryArg2')); // "goodbye"
alert(test.getPort()); // "1337"
alert(test.getHost()); // ""
alert(test.getPath()); // "/test/sample.php"
//Alterntive usage
alert(urlParse("").getQueryParam('a')); // "Cake"

Anyways, hopefully someone will find it helpful 🙂

Feel free to request additional features / notify me of any bugs in the comments. You can now also find it on my GitHub.

[Edit: 2011/10/07] The source code has been updated to fix the scoping bug mentioned by Rikky.