gameQuery (with Backbone.js)

Since I enjoy game development and am getting into Javascript, I wanted to take a look at the Javascript game engines out there.  gameQuery appealed to me because it supported older browsers; the other popular ones were for HTML5 and therefore for modern browsers.  Yeah, not sure why I care about IE8 at this point.  But you know, you never know.  Anyway.  🙂

In my demo, I’ve paired gameQuery with Backbone.js.  I began with a simple index.html file:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>gameQuery Demo</title>
</head>
<body>
<div id="main">
<div id="playgroundArea"></div>
</div>
<script src="js/libs/jquery-1.7.1.min.js"></script>
<script
src="js/libs/underscore-min.js"></script>
<script src="js/libs/backbone-min.js"></script>
<script src="js/libs/jquery.gamequery-0.7.0.js"></script>
<script src="js/model.js"></script>
<script src="js/view.js"></script>
<script src="js/main.js"></script>
</body>
</html>

Note the div id “playgroundArea.”  This is where we’ll append our divs that contain our game images as their background-images.  Also note the ordering of the scripts for model.js, view.js, and main.js, as view.js makes calls to model.js, and main.js makes calls to view.js.  Here are short descriptions of what the files contain:

1. model.js – Basic game data, such as the background, player, and baddie (rock) sizes, as well as initial x and y positions.  It also has the refresh rate and player move amount in pixels.  In my demo, I basically set default properties in a Backbone model:

var GameModel = Backbone.Model.extend({
defaults: {
bgWidth:640,
bgHeight:640,
refreshRate:60,
...
}
});

2. view.js – Renders the images such as the background, player, and baddie (rock).  For example, setting up and rendering the background image could look like the following:

var GameView = Backbone.View.extend({
el: $('#main'),
initialize: function(){
this.render();
},
render: function(){
var bg = new $.gameQuery.Animation({imageURL: 'img/bg.jpg'}),
playgroundArea = $(this.el).find('#playgroundArea'),
bgWidth = this.model.get('bgWidth'),
bgHeight = this.model.get('bgHeight');
...
// set up sprites
playgroundArea.playground({ width:bgWidth, height:bgHeight, refreshRate:this.model.get('refreshRate') })
.addGroup('background',{animation:bg, width:bgWidth, height:bgHeight, overflow:'visible'}).end()
...
}
});

    • playground() defines the div used to display the game.
    • addGroup() adds a transparent sprite to the currently selected element.

3. main.js – Main game functionality.  A couple of key things happen here, the startGame() and registerCallback() functions.  setupKeys() in the snippet below registers the keydown event and checks if the keys “a” (to move the player left) or “d” (to move the player right) have been pressed.

// start game
$.playground().startGame(function(){
setupKeys();
});


// called at a regular interval
$.playground().registerCallback(function(){
$('#baddies').y( 8, true );

var baddiesTop = Number( $('#baddies').css('top').replace('px','') ),
baddiesLeft = Number( $('#baddies').css('left').replace('px','') ),
playerTop = Number( $('#player').css('top').replace('px','') ),
playerLeft = Number( $('#player').css('left').replace('px','') );

// hit test
if ( ( (baddiesTop > (playerTop)) && (baddiesTop < (playerTop+40)) ) && ( (baddiesLeft > (playerLeft+40)) && (baddiesLeft < (playerLeft+80)) ) ) {
alert('hit');
}

}, gameModel.get('refreshRate'));

  • startGame() preloads the resources and starts the main game loop.
  • registerCallback() registers a function to be called at a regular interval.  In my demo, it’s where I move the baddie (rock).

Screenshot:

My full source code can be found here.

Mobile Frameworks Research

In a quest to find a mobile framework in Javascript for building mobile websites, I experimented with a couple of popular open source ones: Zepto and The M-Project.  Interestingly enough, they were actually quite different.

1. Zepto

Zepto is a minimalist Javascript library.  It is pretty light (~5k to ~10k) and therefore fast!  It is a subset of JQuery, so it provides an easy learning curve…

“If you use JQuery, you already know how to use Zepto.”

…although some of its methods’ signatures and feature sets are different.  It’s leaner than JQuery because it doesn’t support old desktop browsers; just the modern ones, since it’s targeted for mobile devices.

2. The M-Project

The M-Project is more than just a library.  It contains an MVC-based architecture and has a UI based on JQuery Mobile.  Its Views are actually wrapped up JQuery Mobile UI components (buttons, lists, images, etc.).  It even includes a build system called Espresso and has a way to package your project with PhoneGap, which is a framework that allows you to deploy your mobile website into a native-looking mobile app.

3. Comparison

It is almost like comparing apples and oranges then.  A more valid comparison would be something more like:

Zepto + [some MVC framework] + [some UI widgets toolkit]

+ [some build process]

vs.

The M-Project

Screenshots:

Top: Zepto using my custom CSS styling for list. Bottom: M-Project using default styling for list.
Mobile Screenshot 2
Top: Zepto with my custom CSS styling for “Call” button, “Last updated” text, and “Wrong Information” hyperlink. Bottom: M-Project with its default styling for button (“Call”), text (“Last updated”), and hyperlink (“Wrong Information”).

4. My Conclusion

So what is my preference?  If I were to build a mobile website, I often think of a few factors:

  • Performance.  I mean, it is a mobile website, and we can’t expect our mobile devices to have the same processing power as our desktops.  I don’t want users to be sitting for minutes waiting for it to load.
  • UI Customization.  Do I want to be tied down to one look and feel?  Surely, changing the colors are just CSS changes, but what about how the lists or the forms or the buttons look?

Based on these factors, I suppose it is obvious that I would skew towards Zepto.  Not only is it light, but going back to my comparison in #3, I could mix and match it with a UI widgets toolkit of my choice.  I don’t have to be tied down to just JQuery Mobile, but down the road, I could replace it with Twitter Bootstrap.  Having the architecture and the UI loosely coupled would be preferable for me, and with its MVC framework and UI components so intertwined, The M-Project does not provide that option.

5. My Conclusion Continues: Filling in the Blanks

Since I’ve chosen Zepto, what about the MVC framework, the UI widgets toolkit, and the build process?  For now, I’ll just leave it at Backbone.js for the MVC framework, Twitter Bootstrap for the UI widgets toolkit, and Grunt for the build process.  Because with Zepto, you have the option to choose what you like based on your experiences, and what works for you based on your project, and even gives room to experiment or swap stuff out if needed.

For my demos of this mobile research, check out my source code here and here.

Starling

Many claim that “Flash is dead,” but I believe that in the world of gaming, this is not so. One of the reasons is a framework called Starling.

Starling is a free open source Actionscript 3 library which renders its content by using Flash’s Stage 3D technology. What does this mean? Faster performance which makes use of GPU hardware acceleration. The ever-so popular game Angry Birds was built using this framework.

My Starling Game Demo Example
Screenshot from my Starling game demo example

After trying out Starling on my own, I was pretty amazed by a few things:

1. Quick setup.
It is simply a swc file that you include in your library. Then, create a Startup class that will instantiate and start up the Starling instance:

import flash.display.Sprite;
import starling.core.Starling;

[SWF(width="400", height="300", frameRate="60", backgroundColor="#ffffff")]
public class Startup extends Sprite
{
private var _starling:Starling;

public function Startup()
{
_starling = new Starling(Game, stage);
_starling.start();
}
}

The “Game” parameter of the constructor expects a class that is a Starling display object.

2. Ease of use.
You can then go on your merry way writing AS3 as usual, but instead of using the regular Flash display classes, use the ones in Starling. Since I use Flash Builder, the IDE would often automatically import “flash.display” classes; you’d have to replace those with “starling.display.” Also, loading images is a bit of more work than loading an image and adding it to the display list. Starling uses a Texture class that contains an image’s data, and then it uses an Image class to render that data:

...
// load background
loadBackground( _gameModel.bgImagePath );
}

/**
* Load background image.
* @param url URL of background image.
* TODO: Create image loader utility class that all image loading can use, then dispatch event when that particular image is ready.
*/
private function loadBackground( url:String ):void
{
_loader.load( new URLRequest( url ) );
_loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, onLoadBackgroundComplete);
}

/**
* On load background image complete.
* @param event Flash event for event complete.
*/
private function onLoadBackgroundComplete( event:flash.events.Event ):void
{
_loader.removeEventListener(flash.events.Event.COMPLETE, onLoadBackgroundComplete);

// add background to display list
var loadedImage:Bitmap = event.currentTarget.loader.content as Bitmap;
var image:Image = new Image(Texture.fromBitmap(loadedImage));
_bgContainer.addChild(image);

3. Awesome performance.
The smoothness of Starling is impeccable, but I am sure it is even more evident with the more graphic-intensive games out there (like Angry Birds). With Starling’s awesome performance and with Adobe Air (and even Flash CS5.5+)’s ability to deploy to iOS and Android, who says that Flash is dead? 🙂

Check out my source files and you’ll find how quick and easy it is for AS3 developers to jump onto Starling!