Road Blocks & js13k

I've been looking forward to entering the js13k competition this year, because it's one of my favourite game jams.

TLDR: play Road Blocks (don't forget to like and share :P)

Set over a month-long period, the js13k challenge is to create a compelling game within 13 kilobytes. This doesn't sound like much, but you can do a lot with it if you get creative.

Last year I dreamed fairly small, with a space invaders clone set to polar coordinates. I had fun making it, but it wasn't especially playable and this year I wanted to do something completely different and come up with a mobile friendly touch-based game.

Road Blocks screenshot

The Concept

The concept had been rattling around in my head for a while. I've a very soft spot for city builders, and I love isometric art. While an outright city builder probably wouldn't be feasible, a subset thereof might just work.

My main inspiration was an old DOS/Windows game called Pipe Dream, in which you're given an infinite number of puzzle pieces and need to connect the start pipe to the edge of the map somewhere before the liquid spills out. Mash this concept up with the city building theme and you've got a basic connect-the-infrastructure sim.

When the theme of the jam came out as “reversed” I really struggled to find a way to align the concept with the theme, so I had to mix it up.

Ultimately I landed on the puzzle-style "arrange the pieces to fit" theme, in which you need to strategically destroy or reverse the order of the tiles as they come off the queue. It's a little less "world buildy" and a little more constrained, but I think the gameplay works, and it gives me the opportunity to expand the game with new puzzles in the future.

The Tech

The tech is also an idea that's been bouncing around in my head for a while. I've long been a fan of isometric art (pixel art as well as more recently isometric vector art and voxel art) so I wanted to do something in that style.

I had a play around in CodePen and came up with a crazy simple plan; draw everything in voxels. The algorithm to draw an isometric cube isn't all that difficult. You've got three visible sides, each side consisting of four lines and a fill colour. Turn that into a function and you can start making some cool stuff.

See the Pen HTML5 Canvas isometric cube demo by Ash Kyd (@AshKyd) on CodePen.

You can adjust the sliders on the example above to modify the cube.

Drawing voxel sprites

With the idea down, the next step was to draw a game world. There's a bunch of sites out there that have isometric code examples. I had Clint Bellanger's isometric math tab pinned in my browser for a good week, though in reality there were only two functions I really needed:

  • Convert isometric position to screen/pixel position
  • Convert screen/pixel position to isometric position

These two functions let me both draw isometric boxes to the appropriate location on the screen, and then detect where those boxes were stacked when the user interacted with them.

From there, the trick was to come up with sprites made from boxes. While it was possible to sort of work it out in your head, this was often a trial-and-error process, placing boxes and seeing where they land in the output.

See the Pen HTML5 Canvas isometric cube demo by Ash Kyd (@AshKyd) on CodePen.

In the above example you can see a road tile with three components, rendered from an array:

var sprite = [
  [-0.25,.9, 0, 0.1, 1, 0.25, '#aaaaaa'],
  [-0.25,.1, 0, .8, 1, 0.2, '#444444'],
  [-0.25,0, 0, 0.1, 1, 0.25, '#aaaaaa'],

Each item in the array corresponds to a coordinate. In this case the z, x, y coordinates, x width, y width and height.

In the end, my sprite list resulted in a bunch of arrays and functions that don't make a great deal of sense to the naked eye but render cute little box sprites in the game engine.

Putting it all together

With a bunch of sprites at my disposal, all that was left was to implement the game! Easy, right?

I actually took a week off specifically to work on Road Blocks, and I'm glad I did. Through the week I implemented the engine various features (some of which didn't make the final version) and tuning interactions.

Because I wanted this to be a first-class touch game, I implemented everything mobile first. This was a fantastic way to discover all the limitations of the platform at the get-go rather than having to refit a desktop game to mobile later on.

I also spent a lot of time user testing the game, be it in person or through analytics. Testing is a really important part of any gamedev process, and it was really enlightening to watch people playing my game for the first time. Many a puzzle or interaction was tuned based on feedback and watching people work out a level.

I also released my game via Twitter as a public beta to gather play statistics and weed out any errors that might crop up. I used Loggly to record a bunch of custom game stats and events, and the results were quite valuable in determining difficulty and how people were faring playing the game.

One particularly revealing fact was that most people were getting stuck on a particular level. Armed with feedback from testers and the hard facts of the analytics, I tweaked it to be not quite as difficult and pushed it from the middle of the campaign to the end to make it a sort of "final boss" level instead.

As a side note, one day I got distracted and came up with a data encoding scheme for level data which helped reduce the file size in the final zip.


I'm really pleased with the results this year. The game clocked in at just under 13 kilobytes and made efficient use of the space.

Some notes in hindsight:

  • Levels and sprites should probably use a binary data scheme to reduce file size and allow the use of Web Workers.
  • For some reason HTML5 canvas makes the CPU spin up like crazy. I'd like to get to the bottom of this sometime.
  • User testing is mandatory. When developing something in isolation you can get into a weird headspace and not notice the obvious stuff.
  • I had initially intended to have little cars animating along the roads, but ran out of space and couldn't think of how best to do this. I need to learn more about vectors in gamedev.

Ultimately, this year's js13k was a whole heap of fun and I'm really proud of my result. There's a bunch of awesome entries that you should check out, and you should consider entering next year.

Further reading

You can play Road Blocks on the js13k website. You can also check out:

jsfxr sequencer

I didn't go into this weekend with a project, but I woke up Saturday with an idea I couldn't get out of my head — I want to write a music sequencer with a really low footprint for use next month in the js13k game competition.

I've written about js13k before, and took part last year. This time around I want to be a bit more prepared, and I wanted to make a tool that would make it easier for the community to make cool stuff!

So this weekend I've been working on a bunch of different tools to make this project a reality.

Mini Sequencer

Mini sequencer is exactly that: a mini sequencer implementation that can play sounds at various times to form tunes.

This was my first mini project, as I was interested to see what the performance of web audio would be like; it's surprisingly good. That said, if I get time I'd like to look into replacing it with the Web Audio API, as it's a lot less hacky and should perform better.


jsfxr is a little 8 bit synth which was implemented a few years ago for use in the js13k competition.

Since this is probably what most of my sounds are going to be implemented by, I wanted to be able to create new sounds from my sequencer. While there's a few sites out there (my favourite by Super Flash Bros) that let you adjust sliders and make new sounds, there's not actually an out-of-the-box tool you can use to plug into your own project.

So after a bit of reverse engineering of as3fxr (the original Flash version), now there is.

This actually took up a whole bunch of my time, and if I were a project manager I would have dropped this to focus on other stuff, but hindsight, right?

Fruity Timeline

I got to the end of the weekend and felt like I hadn't really ended up with much to show off.

The timeline was one of the big things I'd been putting off doing because it's slightly weird and I wasn't quite sure how to tackle it, so I went all-out and implemented a standalone component (depends on jQuery but probably doesn't need to).

I'm pretty proud of this one, it's styled reminiscent of the old Fruity Loops sequencer and just looks a bit retro.

The main event

So despite having made a million things this weekend, I haven't actually finished the project I set out to do. Right now I have:

  • Create & manage a library of instruments (with jsfxr editing built in)
  • A super rudimentary timeline (edit some JSON by hand and the music will update)
  • BPM adjustment.

Things I need to do from here:

  • Plug in the actual fruity timeline so you can edit your song visually.
  • Implement a "piano roll" feature so you can have different pitches of the same instrument.
  • Stop/play/seek functionality
  • Export your file
  • Load up proper audio files (mp3/wav/whatever) so you can play with those too.

It looks like there's a lot there left to do, but I think I'll be able to get a minimum viable product done with another weekend. I'm not sure if I want to publish the code yet since it's a massive pigsty, but I'll aim to get something out before next weekend is through.

Edit: Ended up getting something together Sunday night. Try it out.

Polar Defender & js13k

Over the last month I’ve been working on a game for the #js13k game competition.

The concept is fairly simple: make a game in under 13 kilobytes with no external dependencies. The idea is to see what people can come up with on a budget, and it’s awesome to see some of the entries this year.

My game, Polar Defender, is a basic shoot ’em up on a polar coordinate system. It’s heavily inspired by space invaders, except you have to defend various planets from all sides at once. It’s heavily reliant particles and a basic polar trajectory system to provide messy, explodey space fun.

The theme of “elements: earth, air, fire, water” is optional in the contest, but I incorporated it into my level system (an earth-like planet, water planet fire and gas planet). It’s a /little/ contrived, but I think it works well in terms of playability.

I wanted to include a playable level system with a playful narrative since there’s only so much you can do in 13 kb and I felt it would make it a more personal experience. I feel it worked out well, with six levels (including an initial training level) on various planets and varying degrees of difficulty. After early feedback stating it’s too hard to finish in one go, I adjusted the menus to make each level unlockable rather than having to start over, which really improves the gameplay in a casual sense.

Touch input is significantly more difficult than desktop input because I essentially shoehorned the same concept in where it doesn’t really fit. If I had the chance to do it again I would introduce a separate tap-based firing system on mobile.

The tech

Some of the tech I used includes:

  • jsfxr for sound effects, based on Jack Rugile’s blog post.
  • Liberal use of the native Canvas rotate() method.
  • Regular CSS & JS for the menu system.
  • Gulp, Uglify, svgo and a bunch of hand-tweaks to package and minify my codebase.
  • Super rudimentary box-based collision detection.
  • A basic entity/component model through which to extend base sprites.
  • SVG for infinitely customisable graphics. (There’s only four enemy sprites in
    the game, each recoloured and resized as needed.)
  • Procedurally generated starfield & planets.

How to ultra-compress your JS

13 kilobytes is quite a lot in terms of raw code, but also a challenge to meet when including graphics, sound, polyfills and other boilerplate.

Minification of Polar Defender was done by hand and involved a lot of code tweaks.

The ultimate deliverable needed to be compressed into 13 kilobytes of zip file, which is roughly comparable to a gzipped distribution from a web server.

Some of the things I did which aren’t necessarily best practices include:

  • Strip unnecessary properties and pre-compile SVG files into a JSON file to be bundled into the main JS build process. This improves  compression because there’s less junk and the SVG gets compressed in with the JS which presumably improves duplicate string elimination in the zip format.
  • Collapse JSON structures into CSV-like strings that can be reinflated later. JSON objects are super-wasteful in terms of repeated properties, and while compression algorithms are generally pretty good with repeated content, it’s still better to remove the duplicates where possible.
  • Globalise commonly used functions. This isn’t something I’d usually recommend but considering the constraints what the hey. Things like aliasing window to w and Math to m reduces byte-level repetition. Additionally keeping everything in a local scope lets Uglify optimise away long function names.
  • Loose comparison and other sneaky tricks. For instance using 1 for true and 0 for false saves 3 bytes per bool and works in a loose JS equality operation if you’re prepared to ignore JSHint complaining a lot.
  • Reuse everything. I reused a basic set of drawing functions and sprite classes for everything in-game, meaning each new feature was an iteration on an existing one rather than a completely new piece of functionality. See also entity component system on Wikipedia.

Further reading

In addition to my jS13k entry, I’ve got a side-build available in the
Chrome Web Store which you can install and carry around with you. The main benefit is that your scores are stored in the cloud and unlocked content goes wherever you do.

Overall I think it worked quite well and I’m happy with the result. There’s some awesome games submitted so far and I can’t wait to see how everyone goes.

The source code to Polar Defender can be found on GitHub.

Getting moving with HTML5 Canvas

Initialise a canvas

<canvas id="c" width="640" height="480"></canvas>
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');


  • Width and height determine the canvas size.
  • CSS width and height will stretch the canvas.
  • 2d refers to the rendering context (API). Other options include webgl.

Basic drawing with Canvas

There are several ways of drawing on the 2d drawing context.

  • Rects (rectangles)
  • Paths
  • Text
  • Images

Drawing Rectangles

Rectangles can fill, stroke, or clear an area.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

// Black rectangle ctx.fillRect(0,0,200,200);

// Black outline ctx.strokeRect(200,0,200,200);

// White rectangle (cleared area) ctx.clearRect(50,50,100,100);

See the Pen Canvas Rectangles by Ashley Kyd (@AshKyd) on CodePen.

Drawing Paths

A bit like Logo without the turtle graphic.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

// Draw a triangle ctx.beginPath(); ctx.moveTo(0,100); ctx.lineTo(50,0); ctx.lineTo(100,100); ctx.closePath(); ctx.stroke();

// Draw a circle ctx.beginPath(); ctx.arc(200,50,50,0,Math.PI*2); ctx.fill();

See the Pen Canvas Paths by Ashley Kyd (@AshKyd) on CodePen.

Path Methods

You can use these methods to draw and fill lines onscreen.

Drawing Text

  • The most basic use is ctx.fillText(text, x, y, [maxWidth])
  • Use textAlign=center and textBaseline=middle to center on the specified point.
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

// Default text ctx.strokeRect(0,0,100,100); ctx.fillText('#brisjs',50,50);

// Centered Text ctx.strokeRect(100,0,100,100);

ctx.font = '12px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle' ctx.fillText('#brisjs',150,50);

See the Pen Canvas Text by Ashley Kyd (@AshKyd) on CodePen.

Drawing Images

Use drawImage(img, x, y) to splat any image or canvas element down into your current context.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

// load an image and draw it in! var img = document.createElement('img'); img.onload = function(){ // Draw the image ctx.drawImage(img,0,0);

// and some text
ctx.font = &#39;bold 40px Impact&#39;;
ctx.textAlign = &#39;center&#39;;
ctx.strokeStyle = &#39;#fff&#39;;
ctx.lineWidth = 2;
ctx.fillText(&#39;MEMES AT #brisjs&#39;,200,40);
ctx.strokeText(&#39;MEMES AT #brisjs&#39;,200,40);

img.src = ';;

See the Pen Canvas Images by Ashley Kyd (@AshKyd) on CodePen.

Using Transforms

Transforms adjust the coordinate system your drawing tools use.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

// Example translate ctx.strokeStyle = 'darkgreen'; ctx.strokeRect(0,0,100,100);

ctx.strokeStyle = 'limegreen'; ctx.translate(100,100); ctx.strokeRect(0,0,100,100);

ctx.strokeStyle = 'black'; ctx.rotate(Math.PI/4); ctx.strokeRect(0,0,100,100);

// Make some isometric tiles with setTransform // ctx.strokeStyle = 'purple'; ctx.setTransform(1,-.5,1,.5,0,0); ctx.strokeRect(0,200,100,100); ctx.strokeRect(100,200,100,100); ctx.strokeRect(0,300,100,100); ctx.strokeRect(100,300,100,100);

See the Pen Canvas Transforms by Ashley Kyd (@AshKyd) on CodePen.

  • Transforms are useful for when you have a self-contained item and want it to be able to move.
  • For more information, I've previously written on transforms for isometric games.


setInterval is so 1995. Use the requestAnimationFrame method to call back before the next screen repaint.

var gameLoop = function(){
    // Do stuff
  • requestAnimationFrame won't fire if the browser isn't painting, for instance in another tab or minimised.
  • Unit movement should be calculable as a vector, otherwise everything will stop or slow down with the render process.

Let's get moving

This demo shows the basics of animation. The sine wave is calculable based on the current time.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

function sineWave(){ var yPos = Math.sin( / 500 ) 100; ctx.fillRect(0, yPos, 10, 10); }

var gameLoop = function(){ ctx.clearRect(0, 0, canvas.width, canvas.height);; ctx.translate(150, 150);

// Let&#39;s draw some sine waves
for(var i=0; i&lt;10; i++){;

    // pi</em>2 radians == 360°
    ctx.rotate((i/10)<em>Math.<span class="caps">PI</span></em>2);



See the Pen Canvas Animation by Ashley Kyd (@AshKyd) on CodePen.


Particles are one of the most useful things you can have in a 2D game.

See the Pen Canvas Particle Generator by Ashley Kyd (@AshKyd) on CodePen.

  • Particles can be anything you want, but gradients are slow to draw so you'll need to cache them.
  • You can plug in one of many physics engines from NPM, but it's easier to accelerate out from a center point.

Polar Defender (my entry into the 2014 #js13k)

js13k is a month-long game competition to make a game in under 13 kb.

  • Polar coordinates & .rotate() make it east to do a radial game.
  • SVG sprites: scalable, re-colourable assets.
  • "Everything's a particle" approach simplifies collision detection.
  • jsfxr for 8-bit sounds.
  • Using a bunch of Unicode emoji as game assets (gotta save space).
  • Code on GitHub

Play Polar Defender.

Where to go from here

There's a bunch of stuff already out there to make your life easier. Here's some of my favourites:

  • Pick a game engine (or do it by hand)
  • NPM is a treasure trove of amazing things
  • freenode/#bbg – browser based games
  • Learn about Juice in a talk by Martin Jonasson and Petri Purho