Da Fish in Sea

These are the voyages of Captain Observant

Setting Up BDD With Jasmine and ExtJS 4

| Comments

Jasmine is described on its site as a ‘behaviour driven development framework for testing your JavaScript code.’ I thought I would give it a try, using it while developing a new game with my Canvasteroids framework.

First off, though, I should address the different terminology here: what is ‘behaviour driven development’ anyways? Why isn’t it called a Unit Testing framework? To understand why, you should read this article The idea that the names matter really rings true for me and it always seemed weird to me to try and test something which does not yet exist. Thinking of ‘specifications’ rather than ‘tests’ makes a lot more sense to me. Also, thinking about testing ‘units’ of code is more likely to make your tests closely coupled to your implementation, leading to maintenance headaches and unnecessary, verbose tests.

Installing Jasmine is ridiculously easy: I just downloaded the standalone project, and extracted it as the ‘specs’ folder in the Canvasteroids project. Inside it is a SpecRunner.html file.. opening up this in a browser will run the dummy tests which are there by way of example. Then I removed them so that I could run my own specs. I also installed some Jasmine Snippets for Vim to make writing specs even easier.

I created a new spec file called BreakoutSpec.js in the specs/ folder and added the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
describe("Breakout Game Specs", function () {

    var game;

    beforeEach(function () {
        game = new breakout.Breakout();
    });

    it("should exist", function () {
        expect(game).toBeDefined();
    });

});

The describe() function defines a Suite of Specs. The function given to it as its second argument contains the specs themselves. Each spec is defined by an it() function call, which similarly takes a function as its second argument. The first argument to both describe() and it() is a descriptive string which will be shown in reports. Within the it() function there are calls to expect() which will check specific things to determine whether the Spec has been fulfilled. See the list of them here. In this case we are simply checking that the Breakout game instance was created successfully. Obviously, beforeEach() is run before each spec. We need to include the spec in the SpecRunner.html file, which now looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
    <head>
        <title>Jasmine Test Runner</title>
        <link rel="stylesheet" type="text/css" href="lib/jasmine-1.0.2/jasmine.css">
        <script type="text/javascript" src="lib/jasmine-1.0.2/jasmine.js"></script>
        <script type="text/javascript" src="lib/jasmine-1.0.2/jasmine-html.js"></script>

        <!-- include spec files here... -->
        <script type="text/javascript" src="spec/BreakoutSpec.js"></script>

    </head>
<body>

<script type="text/javascript">
        jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
        jasmine.getEnv().execute();
</script>

</body>
</html>

Refreshing the SpecRunner.html file, we see that this Spec fails. There are two failures, one which is the result of a run-time error while executing the spec (because the namespace ‘breakout’ in ‘breakout.Breakout’ is undefined, and because the expectation was not met (because ‘game’ was not defined).

So, I made a new folder called ‘breakout’ in the games folder, and copied the index.html file from Asteroids into it, renaming the reference to the Asteroids game class to be Breakout. I also created the new game class in a file alongside the index.html file, called Breakout.js, with the following Ext 4 class definition in it:

1
2
3
4
Ext.define('breakout.Breakout', {
    constructor: function () {
    }
});

So we have a Breakout class now, but how do we load it in our test runner? Why not use the Ext JS 4 Class loader, just as we do in the game itself? This is what the updated SpecRunner looks like (we also need to load the ext-foundation.js file).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<head>
    <title>Jasmine Test Runner</title>
    <link rel="stylesheet" type="text/css" href="lib/jasmine-1.0.2/jasmine.css">
    <script type="text/javascript" src="lib/jasmine-1.0.2/jasmine.js"></script>
    <script type="text/javascript" src="lib/jasmine-1.0.2/jasmine-html.js"></script>

    <!-- include Ext JS 4 Class framework -->
    <script src="../lib/extjs/ext-foundation.js" type="text/javascript" charset="utf-8"></script>

    <!-- include spec files here... -->
    <script type="text/javascript" src="spec/BreakoutSpec.js"></script>

</head>
<body>

<script type="text/javascript">
    Ext.Loader.setConfig({
        paths: {
            'breakout': '../games/breakout'
            },
            enabled: true
        });
        Ext.require('breakout.Breakout');
        Ext.onReady(function () {
            jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
            jasmine.getEnv().execute();
        });
</script>

</body>
</html>

Note that we made the call to Ext.Loader.setConfig(), defining the required namespace ‘breakout’ to be the relative path of the directory containing the class file. And we wrapped the Jasmine code in a call to Ext.onReady(), which will only execute when the classes required have been loaded. This is handy, because we will not have to worry about adding them to the SpecRunner, which can be a chore with other Javascript Testing frameworks I’ve used. We will however need to update the paths of the namespaces used by any classes in the application, so that any namespaces are correctly resolved. And when we run the SpecRunner again … we get the green light! The spec succeeded.

So I admit this is a trivial spec… but it should be enough to get you started with Jasmine and Ext JS4.

Building on a Solid Foundation With Ext JS 4

| Comments

I’ve been working with Ext JS a lot at work over the last year, and have grown to like it. Last year I went to the Sencha Conference in San Francisco, and was very impressed by the features of the upcoming release of Ext JS 4. One of the big changes is the new Class system, which makes defining classes easy and also loads required classes dynamically when required. The build tools which Sencha (The company which makes Ext JS) provides make it easy to produce a single compressed .js file of your app for deployment. All in all it is a great framework.

Ext JS 4 is well modularized, and you can use as little or as much of it as you like. For the Canvasteroids game framework that I’m working on, I decided to use the ‘ext-foundation.js’ file which is the essential core of the library, which defines the Class management system, as well as a useful collection of utility methods for the core Javascript types. However no changes are made to the native object prototypes, so there will not be complications when combining Ext 4 with other frameworks.

The Ext JS 4 class system lets you define a class as follows:

1
2
3
4
5
6
7
8
9
Ext.define('some.Thing', {
    extend: 'some.ThingElse',
    constructor: function () {
        this.name = "Thing1";
    },
    greet: function () {
        alert("o hai");
    }
});

Obviously, the ‘constructor’ function is what becomes the class constructor. The ‘extend’ property will cause this class to inherit the given class. Note also the use of namespaces, eg ‘foo.Bar’ in the names of classes. In Ext JS 3 you had to explicitly declare all your namespaces, but in v4 this is handled automagically.

Mix it up with Mixins

Additionally, you can have ‘mixins’ which add in methods (or properties) of the given class. This is very helpful as it enables another way of re-using code besides inheritance. This is how you declare mixins (an example from Canvasteroids):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Ext.define('drawable.DrawableLine', {
    extend: 'geometry.Line',
    mixins: ['drawable.Drawable'],
    constructor: function (props) {
        this.callParent([props]);
        //this is a base drawable class -- set context (required property)
        this.initDrawable(this.context);
    },
    draw: function (ctx) {
        this.beforeDraw(ctx);
        this.ctx.beginPath();
        this.ctx.moveTo(this.start.x, this.start.y);
        this.ctx.lineTo(this.end.x, this.end.y);
        this.ctx.stroke();
        this.afterDraw(ctx);
    }
});

The initDrawable(), beforeDraw(), draw(), and afterDraw() methods all come from the Drawable mixin class (which is defined in the same was a regular class except it does not have a constructor). Drawing is a behaviour, and this is a good use case for using a Mixin. As with inheritance, you can override methods or properties from a Mixin class. In this case I overrode the ‘draw’ method with a custom implementation. In this way Mixins can act like Abstract Classes, but you are free to use more than one at a time.

callParent() is super!

Also note the call to callParent() : this is equivalent to super() in ActionScript.. it calls the same method from which it is called on the parent class. So in a constructor it will call the super-class’s constructor. Note that the arguments must be passed as an array.

Getting Loaded with Ext.Loader

If you’ve worked on a large scale Javascript application, you know it can become a pain to maintain a large number of script tags, and resolve dependencies. Every time you add a new class to the system, you have to add it to the list of scripts includes in your HTML page, and you have to figure out where in the list of includes it has to go in order to have all of its dependencies satisfied and to satisfy its dependents. This is usually done by trial and error and can be quite annoying. Ext.Loader to the rescue! Once properly configured, you will never need to add another script tag again! Here’s how to set up dynamic loading in your main HTML file:

1
2
<script src="../../lib/extjs/ext-foundation-debug.js" type="text/javascript"><!--mce:0--></script>
<script type="text/javascript"><!--mce:1--></script>

The ‘enabled:true’ attribute of the object passed to Ext.Loader.setConfig() is what turns on the dynamic loading of classes. When this is turned on, Ext JS will dynamically add a ‘script’ tag when it notices that it needs to load a class. By default, it will look for a file with the same name as the class (replacing ‘.’ with ‘/’) relative to the HTML file. If you wish to use a different path you will need to add a mapping to the ‘paths’ hash object. By default, the ‘Ext’ namespace is mapped to the ‘src’ directory of the library so it will load other classes from the framework if you are using them.

Then you load your main app using a call to Ext.require(). In this case I required the main Asteroids game class, which was in the same directory as the HTML file this code is in. The ‘Asteroids’ class itself has multiple dependent classes, and the Loader will recursively parse them until they are all satisfied.For example the ‘canvasutils.Context2D’ class will be resolved to ‘../../lib/canvasutils/Context2D.js’. NB: make sure you name your class correctly, or errors will occur in the loading process. In addition to any classes referenced in an ‘extends’ or ‘mixins’ definition, there is a ‘requires’ property which can be used to explicitly declare a class’s dependencies. For example in the Asteroids class, I have defined the requires as follows:

1
2
3
4
5
6
7
Ext.define('Asteroids', {
    extend: 'oop.InitProps',
    requires: ['eventbus.EventBus', 'controller.TouchPad', 'drawable.DrawableLine',
     'soundeffects.SoundEffects', 'sprites.Rock', 'sprites.Ship', 'sprites.ShipFragment',
     'sprites.Bullet', 'drawable.Layer', 'controller.Keyboard', 'ui.Button', 'ui.Text',
     'interactive.DraggableLayer'],
    //...

When the Loader is enabled, Ext JS will wait until all the dependent classes have been loaded before executing Ext.onReady(). At this point you can simply instantiate the class normally with ‘new’ as I have done. Alternatively, you can use Ext.create() with the class name as a string. This has the advantage that if for some reason the class was not loaded, the Loader will load the class synchronously. However, this is non-optimal for performance, and you will be warned in the console about this. Since I want to avoid this, and for ease of debugging, I tend to use the old fashioned form of instantiation with ‘new Xxx()’, and remember to add the class to the list of ‘requires’.

Note that the order of the classes in the ‘requires’ array does not matter.

Building a Deployment version

While loading .js files dynamically is nice for debugging, it is not optimal for deployment, due to all the additional HTTP requests. It is recommended to combine all the required Javascript files into one, and compress it by removing comments, whitespace, etc. If you have used the Ext.Loader as I describe above, this will be very easy. First you will need to install the free Sencha tools from here (see the links for the different platforms tools near the bottom of the page). Then use a terminal to go to the same directory as you HTML file and type the following command:

1
sencha create jsb -a index.html -p app.jsb3

This will create a .jsb3 (JSBuilder, Sencha’s JavaScript compression tool) configuration file for the application. If that worked then do this:

1
sencha build -p app.jsb3 -d .

And you should have a app-all.js file which will be the combined and compressed version of your app. You should create another HTML file for deployment which references this file, rather than the Ext.Loader config we used for develpoment. That’s it! Your Ext JS 4 app is ready to go.

This is a brief overview of the Class system, for more info see the excellent docs:

Class System docs

Ext JS 4 Getting Started

Updates to Asteroids

| Comments

I was pleasantly shocked the other day to see a pull request in my GitHub account for the Canvasteroids game framework I recently created. There were the following features added to the Asteroids game:

  • score
  • lives
  • game over after 3 lives lost
  • an animation when the rocket is being thrusted
  • enhancements to the firing of bullets
  • a new Text class for the framework (used to display the lives and score)

Some kind folks from the Chico State Open Source Team had picked my project to flex their programming skills. I was quite impressed with the quality of their contributions, and that they were able to dive into the project which I admit is not really documented at all.

This has inspired me to continue my efforts on Canvasteroids, as well as documenting it better, to enable further collaboration. I’ve since posted on my blog about one of the patterns I use in the framework: ‘State and Transition Oriented Programming’. I’ve also started on a second game, which I will hopefully be launching soon.

STOP Programming in Javascript

| Comments

You may be wondering about the title of this post… well, it isn’t the advice my grandfather gave me but I never heeded :) STOP is a reference to the concept of State and Transition Oriented Programming. I found out about this concept from Troy Gardner at the 360Flex conference a couple of years ago. The video of this presentation is well worth watching.

To summarize, in case you’re not done watching it yet.. States are a very important aspect of programming interactive systems, but they are often neglected and as a result can lead to nasty bugs. By dealing with states carefully and consciously it becomes a lot easier to develop more complex systems. Troy developed a framework in ActionScript to provide readymade support for state management and transitions.

It would be possible to port the framework to JavaScript, but the basic idea is so simple that it does not require a framework to implement and benefit from using it. This post is my attempt to describe how to do that.

Usually, from what I’ve seen, states are defined as constants, or enums or something like that, and assigned to some global variable…

1
2
3
4
if (isHoliday)
    STATE = "happy";
else
    STATE = "sad";

Then later on, there will be forks in the code to do different things depending on the state:

1
2
3
4
if (STATE === "happy")
    smile();
else if (STATE === "sad")
    frown();

While this works fine most of the time, you can quickly end up with a mess of duplciated conditional logic all over the place, as every time you need to do something, you have to check which State is active to decide if and how you’re going to do it.

It’s worth considering the difference between lowercase ‘state’ and uppercase State. The former is simply the values of variables that your application contains. This is vague and generalized and not what I’m referring to here. The uppercase State refers to a global condition which usually corresponds to a phase of activity of the application. For example a video player component might be ‘loading’ or ‘playing’ or ‘paused’. The State of the application fundamentally changes its behaviour, and how it will respond to events. Having said this, I’m not going to consistently capitalize ‘State’, but I’m always referring to the this more specific meaning of the word.

Events are things that happen in your application, whether it is user input or a result of processing or time passing. A collision between two objects is an example of a typical event in a game for example. Depending on which State the application is in, events will be handled differently. When events occur, we can send ‘messages’ or ‘signals’ to the currently active State, which can decide how to respond.

The idea that I’ve borrowed/stolen from Troy Gardner is to implement States as functions. Since they are essentially global constants, they are capitalized. This also indicates their special significance, and differentiates them from reqular functions. Here is how the two states of a light switch might be implemented (if we visualize the switch as having two buttons, ‘off’ and ‘on’):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var state = OFF;

offBtn.onClick = function () {
    state("turn_off");
}

onBtn.onClick = function () {
    state("turn_on");
}

function OFF(msg) {
    if(msg === "turn_on") {
        turnLightOn();
        state = ON;
    }
}

function ON(msg) {
    if(msg === "turn_off") {
        turnLightOff();
        state = OFF;
    }
}

Notice how the event handlers did not have to know about the different States of the application, but simply sent a message to the currently active State function, which is dynamically assigned when the state is set. Assigning the State function to the ‘state’ variable effectively sets the State, and alters the behaviour of the system… Note how the OFF State does not respond to the ‘turn_off’ message, and the ON State does not respond to the ‘turn_on’ message. There is no switching on the state value - rather the State function will handle the messages it is sent, ignoring any it is not interested in.

Transitions

It is often necessary to perform actions when changing from one State to another. But it can be easily done by using ‘enter’ and ‘exit’ messages which are passed to every State when they are made active or deactivated. The way to make this happen is to use a ‘changeState()’ function to change from one state to another:

1
2
3
4
5
function changeState(newState) {
    this.state('exit');
    this.state = newState;
    this.state('enter');
}

Then you can manage your transitions by listening for these messages in your State functions:

1
2
3
4
5
6
7
8
9
10
function DAY(msg) {
    if (msg === "enter") {
        wakeUp();
    } else if(msg = "exit") {
        turnLightsOn();
    }
}

changeState(DAY);
changeState(NIGHT);//lights get turned on

Hierarchical States

If you want to nest States, eg. LUNCH within DAY, this can be done by passing on any unknown messages to the super-state:

1
2
3
4
5
6
7
function LUNCH (msg) {
    if(msg === "eat") {
        eatLunch();
    } else {
        DAY(msg);//eg "check_email" msg would be handled by DAY
    }
}

If you have events which need to be handled at any time, they can be put in a BASE state, and other states can pass on messages to it. For example, if the user resizes the browser window, there could be a ‘resize’ message which would be handled by the BASE State:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function BASE (msg) {
    if (msg === "resize") {
        resizeGame();
    }
}

function PLAYING (msg) {

    if (msg === "scored") {
        increaseScore();
    }

    //always pass on messages to BASE
    BASE(msg);//resize will be handled

}

As you can see by comparing these two examples, you have the option of passing all messages to the super-state, or only passing on unknown messages.

This method of handling events by sending messages to State functions is very flexible and dynamic, and makes adding new States easy. It adds some abstraction between events and the response to them, which reduces coupling within your application. It also reduces duplication and conditional branching, and I think it also makes the code easier to read, as behaviours are grouped by State and message, which should be self-descriptive.

Finally, STOP programming is not opposed in any way to OOP, but is orthogonal to it. I have found it to be particularly useful in developing games, which tend to have many different states with different behaviours.

For a more complex example of this pattern in action, see the Asteroids game.

A Is for Asteroids

| Comments

A while back I decided to have a go at making a Javascript + Canvas version of Asteroids. I was able to get a basic version of the game working in a weekend, but I wasn’t happy about the code being in one huge file, so I set about refactoring it using ExtJS 4 for OO support (but not the whole library). This turned out to be quite addictive and after a while I had a small library of code on my hands. The initial title of the game was ‘CanvAsteroids’, but as I shifted to working on the supporting library I started to think of it as ‘CanvaSteroids’ : Canvas on Steroids. And so I have named the library this awkward name and renamed the game itself to just be Asteroids. The plan is to work my way through the alphabet, making a game for each letter. Next is Breakout. It’s good to have goals ;)

I want to write some more posts about some of the techniques I used to get the game working, especially the collision detection. I found a way to do this using the Canvas ‘isPointInPath’ method, which seems to perform quite well. The game uses keyboard for controls (left-right arrows for turning, spacebar to fire) and I also added some mouse/touch control inspired by Seb Deslisle’s JSTouchController. I don’t think the game is really well suited to touch, but at least I learned how to handle the touch events. If anyone has an iPad I’d be interested to know how it works.. unfortunately I heard the performance of Canvas is not great on iOS. However I’m really not into targeting one platform, and I’d like the games to be playable on any desktop or mobile device which has a decent browser (ie supports Canvas). For the IE < 9 users, I added Chrome Frame. For sound I used SoundManager2. The actual sounds were recorded off my Atari 2600 during gameplay, and edited in Audacity.

Anyways, enough nerdy banter.. here’s the game (warning LOUD sound effects!).

Play Asteroids

I used GitHub’s nifty new pages feature (plus a domain) to host a site here:

canvasteroids.com

And for all your source-y needs, the Github repo