Improving the Snake Game

Exclusive offer: get 50% off this eBook here
Learn HTML5 by Creating Fun Games

Learn HTML5 by Creating Fun Games — Save 50%

Learn one of the most popular markup languages by creating simple yet fun games with this book and ebook

$29.99    $15.00
by Rodrigo Silveira | July 2013 | Games Web Development

In this article by Rodrigo Silveira, the author of the book Learn HTML5 by Creating Fun Games, we will see how to enhance a snake game created in HTML5. This article is the second and final part of the series where we're building a more robust snake game. The first version of the game used five HTML5 concepts, namely 2D canvas rendering, offline application cache, web workers, typed arrays, and requestAnimationFrame.

The first version of the game used five HTML5 concepts, namely 2D canvas rendering, offline application cache, web workers, typed arrays, and requestAnimationFrame. In this version, we'll include two features from the new web storage API, namely local storage and session storage. We'll also look at a third API that is part of web storage, IndexedDB, as well as the web messaging feature, which includes cross-domain messaging.

Local storage and session storage are two mechanisms that allow us to save data on the user's browser using a key-value strategy. This is similar to a cookie, where every value must be a string. The difference between these two storage options and a cookie, first and foremost, is that a cookie is always sent back to the server through HTTP requests. This can be especially undesirable when we have larger amounts of data that we would like to store, since that data would be traveling around consuming extra bandwidth, and there is nothing that we can do about it. With HTML5's web storage, we can save more data locally, and that data never leaves the user's machine, though HTTP components like cookies do.

IndexedDB, also part of web storage, is similar to local and session storage, where data is stored in a key-value manner, but instead of values being limited to strings only, IndexedDB is more of an object store, where we can store entire JavaScript objects. Of course, IndexedDB is much more than a mere hash map that holds objects for us. As the name implies, this new API allows us to index these stored objects with the purpose of being able to search for them through a query system. In summary, IndexedDB is a NoSQL database accessed through an asynchronous programming interface.

Finally, the web messaging API provides an interface through which an HTML document can communicate with other HTML contexts. These documents can be related by iframes, in separate windows, and even in different domains.

(For more resources related to this topic, see here.)

The game

Two new features were added to this second version of the game. First, we now keep track of the highest score achieved by a player, saving it through local storage. Even if the player closes the browser application, or turns off the computer, that value will still be safely stored in the player's hard drive, and will be loaded when the game starts again. Second, we use session storage to save the game state every time the player eats a fruit in the game, and whenever the player kills the snake. This is used as an extra touch of awesomeness, where after the player loses, we display a snapshot of all the individual level ups the player achieved in that game, as well as a snapshot of when the player hit a wall or run the snake into itself, as shown in the following screenshot:

At the end of each game, an image is shown of each moment when the player acquired a level up, as well as a snapshot of when the player eventually died. This images are created through the canvas API (calling the toDataURL function), and the data that composes each image is saved throughout the game, and stored using the web storage API.

With a feature such as this in place, we make the game much more fun, and potentially much more social. Imagine how powerful it would be if the player could post, not only his or her high score to their favorite social network website, but also pictures of their game at key moments. Of course, only the foundation of this feature is implemented in this article (in other words, we only take the snapshots of these critical moments in the game). Adding the actual functionality to send that data to a real social network application is left as an exercise for the reader.

API usage

A general description and demonstration of each of the APIs used in the game are given in the following sections. For an explanation of how each piece of functionality was incorporated into the final game, look at the code section. For the complete source code for this game, check out the book's page from Packt Publishing's website.

Web messaging

Web messaging allows us to communicate with other HTML document instances, even if they're not in the same domain. For example, suppose our snake game, hosted at http://snake.fun-html5-games.com, is embedded into a social website through iframe (let's say this social website is hosted at http://www.awesome-html5-games.net). When the player achieves a new high score, we want to post that data from the snake game directly into the host page (the page with iframe from which the game is loaded). With the web messaging API, this can be done natively, without the need for any server-side scripting whatsoever.

Before web messaging, documents were not allowed to communicate with documents in other domains mostly because of security. Of course, web applications can still be vulnerable to malicious external applications if we just blindly take messages from any application. However, the web messaging API provides some solid security measures to protect the page receiving the message. For example, we can specify the domains that the message is going to, so that other domains cannot intercept the message. On the receiving end, we can also check the origin from whence the message came, thus ignoring messages from any untrusted domains. Finally, the DOM is never directly exposed through this API, providing yet another layer of security.

How to use it

Similar to web workers, the way in which two or more HTML contexts can communicate through the web messaging API is by registering an event handler for the on-message event, and sending messages out by using the postMessage function:

// ---------------------------------
// Host document: web-messaging.html
// ---------------------------------
var doc = document.querySelector("iframe").contentWindow;
// alternatively:
// var doc = window.open("web-messaging-rec.html", "",
"width=800,height=600");
// Post a message to the child document
doc.postMessage({msg: "Hello!"}, "http://localhost");
// --------------------------------------
// Child document: web-messaging-rec.html
// --------------------------------------
window.addEventListener("message", function(event) {
var data = event.data;
// Post a message back to the parent document
event.source.postMessage({msg: "Thanks for saying " + data.msg},
"*");
});

The first step to using the web messaging API is to get a reference to some document with whom we wish to communicate. This can be done by getting the contentWindow property of an iframe reference, or by opening a new window and holding on to that reference. The document that holds this reference is called the parent document, since this is where the communication is initiated. Although a child window can communicate with its parent, this can only happen when and for as long as this relationship holds true. In other words, a window cannot communicate with just any window; it needs a reference to it, either through a parent-child relationship, or through a child-parent relationship.

Once the child window has been referenced, the parent can fire messages to its children through the postMessage function. Of course, if the child window hasn't defined a callback function to capture and process the incoming messages, there is little purpose in sending those messages in the first place. Still, the parent has no way of knowing if a child window has defined a callback to process incoming messages, so the best we can do is assume (and hope) that the child window is ready to receive our messages.

The parameters used in the postMessage function are fairly similar to the version used in web workers. That is, any JavaScript value can be sent (numbers, strings, Boolean values, object literals, and arrays, including typed arrays). If a function is sent as the first parameter of postMessage (either directly, or as part of an object), the browser will raise a DATA_CLONE_ERR: DOM Exception 25 error. The second parameter is a string, and represents the domain that we allow our message to be received by. This can be an absolute domain, a forward slash (representing the same origin domain as the document sending the message), or a wild card character (*), representing any domain. If the message is received by a domain that doesn't match the second parameter in postMessage, the entire message fails.

When receiving the message, the child window first registers a callback on the message event. This function is passed a MessageEvent object, which contains the following attributes:

  • event.data: It returns the data of the message
  • event.origin: It returns the origin of the message, for server-sent events and cross-document messaging
  • event.lastEventId: It returns the last event ID string, for server-sent events
  • event.sourceReturns: It is the WindowProxy of the source window, for cross-document messaging
  • event.portsReturns: It is the MessagePort array sent with the message, for cross-document messaging and channel messaging

    Source: http://www.w3.org/TR/webmessaging/#messageevent

As an example of the sort of things we could use this feature for in the real world, and in terms of game development, imagine being able to play our snake game, but where the snake moves through a couple of windows. How creative is that?! Of course, in terms of being practical, this may not be the best way to play a game, but I find it hard to argue with the fact that this would indeed be a very unique and engaging presentation of an otherwise common game.

With the help of the web messaging API, we can set up a snake, where the snake is not constrained to a single window. Imagine the possibilities when we combine this clever API with another very powerful HTML5 feature, which just happens to lend itself incredibly well to games – web sockets. By combining web messaging with web sockets, we could play a game of snake, not only across multiple windows, but also with multiple players at the same time. Perhaps each player would control the snake when it got inside a given window, and all players could see all windows at the same time, even though they are each using a separate computer. The possibilities are endless, really.

Surprisingly, the code used to set up a multi-window port of snake is incredibly simple. The basic setup is the same, we have a snake that only moves in one direction at a time. We also have one or more windows where the snake can go. If we store each window in an array, we can calculate which screen the snake needs to be rendered in, given its current position. Finding out which screen the snake is supposed to be in, given its world position, is the trickiest part.

For example, imagine that each window is 200 pixels wide. Now, suppose there are three windows opened. Each window's canvas is only 200 pixels wide as well, so when the snake is at position 350, it would be printed too far to the right in all of the canvases. So what we need to do is first determine the total world width (canvas width multiplied by the total number of canvases), calculate which window the snake is at (position/canvas width), then convert the position from world space down to canvas space, given the canvas the snake is in.

First, lets define our structures in the parent document. The code for this is as follows:

// 1. Create an array to hold each frame (aka. window)
var frames = new Array();
// 2. Let's keep track of some settings for these frames
frames.max = 3;
frames.width = 200;
frames.height = 300;
frames.margin = 50;
// 3. Finally, we'll need a snake to move around
var snake = {
max: 3,
pos: {
x: 0,
y: 0
},
w: 25,
h: 25,
speed: 3,
dir: {
x: 1,
y: 0
},
color: "#0a0"
};

When this script loads, we'll need a way to create new windows, where the snake will be able to move about. This can easily be done with a button that spawns a new window when clicked, then adding that window to our array of frames, so that we can iterate through that array, and tell every window where the snake is. The code for this is as follows:

// Define a few global variables in order to keep the code shorter
and simpler
var isPaused = true;
var timer;
var dirChange = 100;
var btn = document.createElement("button");
btn.textContent = "Add Window";
btn.addEventListener("click", function(event){
var left = frames.length * frames.width + frames.margin * frames.
length;
frames[frames.length] = window.open("/packt/snake-v2/snake-panels.
html", "",
"width=" + frames.width + "," +
"height=" + frames.height + "," +
"top=100, left=" + left);
isPaused = false;
clearTimeout(timer);
play();
}, false);
document.body.appendChild(btn);
// We'll close all the windows we have opened to save us the
// trouble of clicking each window when we want them closed
function closeAll() {
for (var i = 0, len = frames.length; i < len; i++) {
frames[i].close();
}
}
window.onunload = closeAll;

Now, the real magic happens in the following method. All that we'll do is update the snake's position, then tell each window where the snake is. This will be done by converting the snake's position from world coordinates to canvas coordinates (since every canvas has the same width, this is easy to do for every canvas), then telling every window where the snake should be rendered within a canvas. Since that position is valid for every window, we also tell each window individually whether or not they should render the information we're sending them. Only the window that we calculate the snake is in, is told to go ahead and render.

function play() {
// This is used to change the snake's position randomly
// from time to time. The reason for this is so we don't
// need to implement any event handling to handle user input,
// since this is just a simple demonstration.
if (dirChange-- < 0) {
dirChange = 100;
var rand = parseInt(Math.random() * 1000) % 4;
// Make the snake move to the right
if (rand == 0) {
snake.dir.x = 1;
snake.dir.y = 0;
// Make the snake move to the left
} else if (rand == 1) {
snake.dir.x = -1;
snake.dir.y = 0;
// Make the snake move down
} else if (rand == 2) {
snake.dir.x = 0;
snake.dir.y = 1;
// Make the snake move up
} else if (rand == 3) {
snake.dir.x = 0;
snake.dir.y = -1;
}
};
// Update the snake's position, making sure to wrap the snake
// around each window. If it goes too far to the right, and
// wanders off one window, it needs to wrap to the left side
// of the next window.
snake.pos.x += snake.dir.x * snake.speed;
snake.pos.x %= frames.width * frames.length;
snake.pos.y += snake.speed * snake.dir.y;
if (snake.pos.y < 0)
snake.pos.y = frames.height - snake.h;
if (snake.pos.y + snake.h > frames.height)
snake.pos.y = 0;
if (snake.pos.x < 0)
snake.pos.x = (frames.width - snake.w) * frames.width * frames.
length;
var shouldDraw;
for (var i = 0, len = frames.length; i < len; i++) {
// Determine which window the snake is in, and tell only that
// window that it needs to render the snake
shouldDraw = snake.pos.x + snake.w <= frames.width * (i + 1) &&
snake.pos.x >= frames.width * i ||
snake.pos.x <= frames.width * (i + 1) &&
snake.pos.x >= frames.width * i;
// Lastly, we pass all this information to each window in canvas
coordinates.
frames[i].postMessage({
x: snake.pos.x % frames.width,
y: snake.pos.y,
w: snake.w,
h: snake.h,
shouldDraw: shouldDraw,
color: snake.color
}, "*");
}
}

That's really all there is to it. The code that makes up all the other windows is the same for all of them. In fact, we only open a bunch of windows pointing to the exact same script. As far as each window is concerned, they are the only window opened. All they do is take a bunch of data through the messaging API, then render that data if the shouldDraw flag is set. Otherwise, they just clear their canvas, and sit tight waiting for further instructions from their parent window.

// 1. Create a canvas
var canvas = document.createElement("canvas");
canvas.width = 400;
canvas.height = 300;
// 2. Attach the canvas to the DOM
document.body.appendChild(canvas);
// 3. Get a reference to the canvas' context
var ctx = canvas.getContext("2d");
// 4. Set up the callback to receive messages from some parent window
function doOnMessage(event) {
// 5. For security, make sure we only process input from a trusted
window
if (event.origin == "http://localhost") {
var data = event.data;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 6. And here's where the magic happens for this window. If told
to
// draw something through the message received, go ahead and do
so.
if (data.shouldDraw) {
ctx.fillStyle = data.color;
ctx.fillRect(data.x, data.y, data.w, data.h);
}
}
}
window.addEventListener("message", doOnMessage, false);

Web storage

Before HTML5 came along, the only way web developers had to store data on the client was through cookies. While limited in scope, cookies did what they were meant to, although they had several limitations. For one thing, whenever a cookie was saved to the client, every HTTP request after that included the data for that cookie. This meant that the data was always explicitly exposed, and each of those HTTP requests were heavily laden with extra data that didn't belong there. This is especially inefficient when considering web applications that may need to store relatively large amounts of data.

With the new web storage API, these issues have been addressed and satisfied. There are now three different options for client storage, all of which solve a different problem. Keep in mind, however, that any and all data stored in the client is still exposed to the client in plain text, and is therefore not meant for a secure storage solution.

These three storage solutions are session storage, local storage, and the IndexedDB NoSQL data store. Session storage allows us to store key-value data pairs that persist until the browser is closed (in other words, until the session finishes). Local storage is similar to session storage in every way, except that the duration that the data persists is longer.

Even when a session is closed, data stored in a local storage still persists. That data in local storage is only cleared when the user specifically tells the browser to do so, or when the application itself deletes data from the storage. Finally, IndexedDB is a robust data store that allows us to store custom objects (not including objects that contains functions), then query the database for those objects. Of course, with much robustness comes great complexity. Although having a dedicated NoSQL database built in right into the browser may sound exciting, but don't be fooled. While using IndexedDB can be a fascinating addition to the world of HTML, it is also by no means a trivial task for beginners. Compared to local storage and session storage, IndexedDB has somewhat of a steep learning curve, since it involves mastering some complex database concepts.

As mentioned earlier, the only real difference between local storage and session storage is the fact that session storage clears itself whenever the browser closes down. Besides that, everything about the two is exactly the same. Thus, learning how to use both will be a simple experience, since learning one also means learning the other. However, knowing when to use one over the other might take a bit more thinking on your part. For best results, try to focus on the unique characteristics and needs of your own application before deciding which one to use. More importantly, realize that it is perfectly legal to use both storage systems in the same application. The key is to focus on a unique feature, and decide what storage API best suits those specific needs.

Both the local storage and session storage objects are instances of the class Storage. The interface defined by the storage class, through which we can interact with these storage objects, is defined as follows (source: Web Storage W3C Candidate Recommendation, December 08, 2011, http://www.w3.org/TR/webstorage/):

  • getItem(key): It returns the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.
  • setItem(key, value): It first checks if a key/value pair with the given key already exists in the list associated with the object. If it does not, then a new key/value pair must be added to the list, with the given key and with its value set to value. If the given key does exist in the list, then it must have its value updated to value. If it couldn't set the new value, the method must throw a QuotaExceededError exception. (Setting could fail if, for example, the user has disabled storage for the site, or if the quota has been exceeded.)
  • removeItem(key): It causes the key/value pair with the given key to be removed from the list associated with the object, if it exists. If no item with that key exists, the method must do nothing.
  • clear(): It automatically causes the list associated with the object to be emptied of all key/value pairs, if there are any. If there are none, then the method must do nothing.
  • key(n): It returns the name of the nth key in the list. The order of keys is user-agent defined, but must be consistent within an object so long as the number of keys doesn't change. (Thus, adding or removing a key may change the order of the keys, but merely changing the value of an existing key must not.) If n is greater than or equal to the number of key/value pairs in the object, then this method must return null. The supported property names on a Storage object are the keys of each key/value pair currently present in the list associated with the object.
  • length: It returns the number of key/value pairs currently present in the list associated with the object.

Local storage

The local storage mechanism is accessed through a property of the global object, which on browsers is the window object. Thus, we can access the storage property explicitly through window.localStorage, or implicitly as simply localStorage.

window.localStorage.clear();
localStorage.length == 0; // True

Since only DOMString values are allowed to be stored in localStorage, any other values other than strings are converted into a string before being stored in localStorage. That is, we can't store arrays, objects, functions, and so on in localStorage. Only plain JavaScript strings are allowed.

var typedArray = new Uint32Array(100);
localStorage.setItem("my-array", typedArray);
var myArray = localStorage.getItem("my-array");
myArray == "[object Uint32Array]"; // True

Now, while this might seem like a limitation to the storage API, this is in fact done by design. If your goal is to store complex data types for later use, localStorage wasn't necessarily designed to solve this problem. In those situations, we have a much more powerful and convenient storage solution, which we'll look at soon (that is, IndexedDB). However, there is a way to store complex data (including arrays, typed arrays, objects, and so on) in localStorage.

The key lies in the wonderful JSON data format. Modern browsers have the very handy JSON object available in the global scope, where we can access two important functions, namely JSON.stringify and JSON.parse. With these two methods, we can serialize complex data, store that in localStorage, then unserialize the data retrieved from the storage, and continue using it in the application.

// 1. Define some class
var Person = function(name) {
this.name = name;
};
// 2. Add functions to the class
Person.prototype.greet = function(){
return "Hello, " + this.name;
};
// 3. Create an array of objects of that class
var people = new Array();
people.push(new Person("Rodrigo"));
people.push(new Person("Silveira"));
// 4. Stringify the complex array, and store it away
var json = JSON.stringify(people);
localStorage.setItem("people", json);
// 5. Retrieve that serialized data, and parse it back into what it
was
people = JSON.parse(localStorage.getItem("people"));
people[0].name == "Rodrigo"; // True
people[0] instanceof Person; // False
people[0].greet(); // TypeError: Object has no method 'greet'

While this is a nice little trick, you will notice what can be a major limitation: JSON stringify does not serialize functions. Also, if you pay close attention to the way that JSON.stringify works, you will realize that>Person, the result will be a simple object literal with no constructor or prototype information. Still, given that localStorage was never intended to fill the role of object persistence (but rather, simple key-value string pairs), this should be seen as nothing more than a limited, yet very neat trick.

Session storage

Since the sessionStorage interface is identical to that of localStorage, there is no reason to repeat all of the information just described. For a more in-depth discussion about sessionStorage, look at the two previous sections, and replace the word "local" with "session". Everything mentioned above that applies to local storage is also true for session storage. Again, the only difference between the two is that any data saved on sessionStorage is erased when the session with the client ends (that is, whenever the browser is shut down).

Some examples of how to use sessionStorage will be shown below. In the example, we will attempt to store a value in the sessionStorage if that value doesn't already exist. Remember, when we set a key-value pair to the storage, if that key already exists in the storage, then whatever value was associated with that key will be overwritten. If the key doesn't exist, it gets created automatically.

var name = sessionStorage.getItem("coolestPerson");
// Only set a new value if the key exists,
// and the value is not what we want
if (name != null && name != "Rodrigo") {
sessionStorage.setItem("coolestPerson", "Rodrigo");
}

Note that we can also query the sessionStorage object for a specific key using the in operator, which returns a Boolean value shown as follows:

if ("coolestPerson" in sessionStorage) {
// …
}

Finally, although we can check the total amount of keys in the storage through sessionStorage.length, that by itself may not be very useful if we don't know what all the different keys are. Thankfully, the sessionStorage.key function allows us to get a specific key, through which we can then get a hold of the value stored with that key.

sessionStorage.clear();
sessionStorage.length == 0; // True
sessionStorage.setItem("name", "Rodrigo");
sessionStorage.setItem("book", "Learn HTML5");
sessionStorage.setItem("publisher", "Packt Pub");
sessionStorage.setItem("isColor", true);
sessionStorage.setItem("rating", 5);
var values = new Array();
for (var i = 0, len = sessionStorage.length; i < len; i++) {
var key = sessionStorage.key(i);
var value = sessionStorage.getItem(key);
values.push({key: key, value: value});
}
values.length == sessionStorage.length; // True
values[0].key == "book"; // True*
values[0].value == "Learn HTML5"; // True*

Thus, we can query sessionStorage for a key at a given position, and receive the string key representing that key. Then, with the key we can get a hold of the value stored with that key. Note, however, that the order in which items are stored within the sessionStorage object is totally arbitrary. While some browsers may keep the list of stored items sorted alphabetically by key value, this is clearly specified in the HTML5 spec as a decision to be left up to browser makers.

IndexedDB

As exciting as the web storage API might seem so far, there are cases when our needs might be such that serializing and unserializing data, as we use local or session storage, might not be quite sufficient. For example, imagine we have a few hundred (or perhaps, several thousand) similar records stored in local storage (say we're storing enemy description cards that are part of an RPG game). Think about how you would do the following using local storage:

  • Retrieve, in alphabetical order, the first five records stored
  • Delete all records stored that contain a particular characteristic (such as an enemy that doesn't survive in water, for example)
  • Retrieve up to three records stored that contain a particular characteristic (for example, the enemy has a Hit Point score of 42,000 or more)

The point is this: any querying that we may want to make against the data stored in local storage or session storage, must be handled by our own code. In other words, we'd be spending a lot of time and effort writing code just to help us get to some data. Let alone the fact that any complex data stored in local or session storage is converted to literal objects, and any and all functions that were once part of those objects are now gone, unless we write even more code to handle some sort of custom unserializing.

In case you have not guessed it by now, IndexedDB solves these and other problems very beautifully. At its heart, IndexedDB is a NoSQL database engine that allows us to store whole objects and index them for fast insertions, deletions, and retrievals. The database system also provides us with a powerful querying engine, so that we can perform very advanced computations on the data that we have persisted.

The following figure shows some of the similarities between IndexedDB and a traditional relational database. In relational databases, data is stored as a group of rows within a specific table structure. In IndexedDB, on the other hand, data is grouped in broadly-defined buckets known as data stores.

The architecture of IndexedDB is somewhat similar to the popular relational database systems used in most web development projects today. One core difference is that, whereas relational databases store data in a database, which is a collection of related tables, an IndexedDB system groups data in databases, which is a collection of data stores. While conceptually similar, in practice these two architectures are actually quite different.

If you come from a relational database background, and the concept of databases, tables, columns, and rows makes sense to you, then you're well on your way to becoming an IndexedDB expert. As you'll see, there are some significant distinctions between both systems and methodologies. While you might be tempted to simply replace the words data store with tables, know that the difference between the two concepts extends beyond a name difference.

One key feature of data stores is that they don't have any specific schema associated with them. In relational databases, a table is defined by its very particular structure. Each column is specified ahead of time, when the table is first created. Then, every record saved in such a table follows the exact same format. In NoSQL databases (which IndexedDB is a type of), a data store can hold any object, with whatever format they may have. Essentially, this concept would be the same as having a relational database table that has a different schema for each record in it.

IDBFactory

To get started with IndexedDB, we first need to create a database. This is done through an implementation of IDBFactory, which in the browser, is the window.indexedDB object. Deleting a database is also done through the indexedDB object, as we'll see soon.

In order to open a database (or create one if it doesn't exist yet), we simply call the indexedDB.open method, passing in a database name, along with a version number. If no version number is supplied, the default version number of one will be used as shown in the following code snippet:

var dbName = "myDatabase";
var dbVersion = 1;
var request = indexedDB.open(dbName, dbVersion);

As you'll soon notice, every method for asynchronous requests in IndexedDB (such as indexedDB.open, for example), will return a request object of type IDBRequest, or an implementation of it. Once we have that request object, we can set up callback functions on its properties, which get executed as the various events related to them are fired, as shown in the following code snippet:

var dbName = "myDatabase";
var dbVersion = 1;
var db = null;
var request = indexedDB.open(dbName, dbVersion);
request.onerror = function(event) {
console.log("Error:", event);
};
request.onsuccess = function(event) {
db = event.target.result;
};

IDBOpenDBRequest

As mentioned in the previous section, once we make an asynchronous request to the IndexedDB API, the immediately returned object will be of type IDBRequest. In the particular case of an open request, the object that is returned to us is of type IDBOpenDBRequest. Two events that we might want to listen to on this object were shown in the preceding code snippet (onerror and onsuccess). There is also a very important event, wherein we can create an object store, which is the foundation of this storage system. This event is the onupgradeneeded (that is, on upgrade needed) event. This will be fired when the database is first created and, as you might expect, whenever the version number used to open the database is higher than the last value used when the database was opened, as shown in the following code:

var dbName = "myDatabase";
var dbVersion = 1;
var db = null;
var store = null;
var request = indexedDB.open(dbName, dbVersion);
request.onupgradeneeded = function(event) {
db = event.target.result;
store = db.createObjectStore("myDataStore", {keyPath: "myKey"});
};

The call to createObjectStore made on the database object takes two parameters. The first is a string representing the name of the object store. This store can be thought of as a table in the world of relational databases. Of course, instead of inserting records into columns from a table, we insert whole objects into the data store. The second parameter is an object defining properties of the data store. One important attribute that this object must define is the keyPath object, which is what makes each object we store unique. The value assigned to this property can be anything we choose.

Now, any objects that we persist in this data store must have an attribute with the same name as the one assigned to keyPath. In this example, our objects will need to have an attribute of myKey. If a new object is persisted, it will be indexed by the value of this property.

Any additional objects stored that have the same value for myKey will replace any old objects with that same key. Thus, we must provide a unique value for this object every time we want a unique object persisted.

Alternatively, we can let the browser provide a unique value for this key for us. Again, comparing this concept to a relational database, we can think of the keyPath object as being the same thing as a unique ID for a particular element. Just as most relational database systems will support some sort of auto increment, so does IndexedDB. To specify that we want auto-incremented values, we simply add the flag to the object store properties object when the data store is first created (or upgraded) as shown in the following code snippet:

request.onupgradeneeded = function(event) {
var settings = {
keyPath: "myKey",
autoIncrement: true
};
db = event.target.result;
store = db.createObjectStore("myDataStore", settings);
};

Now we can persist an object without having to provide a unique value for the property myKey. As a matter of fact, we don't even need to provide this attribute at all as part of any objects we store here. IndexedDB will handle that for us. Take a look at the following diagram:

Using Google Chrome's developer tools, we can see all of the databases and data stores we have created for our domain. Note that the primary object key, which has whatever name we give it during the creation of our data store, has IndexedDB-generated values, which, as we have specified, are incremented over the last value.

With this simple, yet verbose boilerplate code in place, we can now start using our databases and data stores. From this point on, the actions we take on the database will be done on the individual data store objects, which are accessed through the database objects that created them.

IDBTransaction

The last general thing we need to remember when dealing with IndexDB, is that every interaction we have with the data store is done inside transactions. If something goes wrong during a transaction, the entire transaction is rolled back, and nothing takes effect. Similarly, if the transaction is successful, IndexedDB will automatically commit the transaction for us, which is a pretty handy bonus.

To use transaction, we need to get a reference to our database, then request a transaction for a particular data store. Once we have a reference to a data store, we can perform the various functions related to the data store, such as putting data into it, reading data from it, updating data, and finally, deleting data from a data store.

var TodoItem = function(task) {
this.task = task;
this.completed = false;
};
try {
var trans = db.transaction(storeName, "readwrite");
var store = trans.objectStore(storeName);
var task1 = new TodoItem("Buy more pizza");
var task2 = new TodoItem("Finish writing the book");
var task3 = new TodoItem("Shave before going to work");
var request = store.put(task1);
// We can reuse this request object to store multiple objects
request = store.put(task2);
request = store.put(task3);
request.onsuccess = function(e) {
log("Success!" + value.key);
};
request.onerror = function(e) {
log(e.stack);
};
} catch (e) {
log(e.stack);
}

To store an item in our data store we need to follow a couple of steps. Note that if anything goes wrong during this transaction, we simply catch whatever error is thrown by the browser, and execution continues uninterrupted because of the try/catch block.

The first step to persisting objects in IndexedDB is to start a transaction. This is done by requesting a transaction object from the database we have opened earlier. A transaction is always related to a particular data store. Also, when requesting a transaction, we can specify what type of transaction we'd like to start. The possible types of transactions in IndexedDB are as follows:

readwrite

This transaction mode allows for objects to be stored into the data store, retrieved from it, updated, and deleted. In other words, readwrite mode allows for full CRUD functionality.

readonly

This transaction mode is similar to readwrite, but clearly restricts the interactions with the data store to only reading. Anything that would modify the data store is not allowed, so any attempt to create a new record (in other words, persisting a new object into the data store), update an existing object (in other words, trying to save an object that was already in the data store), or delete an object from the data store will result in the transaction failing, and an exception being raised.

versionchange

This transaction mode allows us to create or modify an object store or indexes used in the data store. Within a transaction of this mode, we can perform any action or operation, including modifying the structure of the database.

Getting elements

Simply storing data into a black box is not at all useful if we're not able to retrieve that data at a later point in time. With IndexedDB, this can be done in several different ways. More commonly, the data store where we persist the data is set up with one or more indexes, which keep the objects organized by a particular field. Again, for those accustomed to relational databases, this would be similar to indexing/applying a key to a particular table column. If we want to get to an object, we can query it by its unique ID, or we can search the data store for objects that fit particular characteristics, which we can do through indexed values of that object.

To create an index on a data store, we must specify our intentions during the creation of the data store (inside the onupgradeneeded callback when the store is first created, or inside a transaction mode versionchange). The code for this is as follows:

request.onupgradeneeded = function(event) {
var settings = {
keyPath: "myKey",
autoIncrement: true
};
db = event.target.result;
store = db.createObjectStore("myDataStore", settings);
var indexSettings = {
unique: true
};
store.createIndex("taskIndex", "task", indexSettings);
};

In the preceding example, we create an index for the task attribute of our objects. The name of this index can be anything we want, and commonly is the same name as the object property to which it applies. In our case, we simply named it taskIndex. The possible settings we can configure are as follows:

  • unique – if true, an object being stored with a duplicate value for the same attribute is rejected
  • multiEntry – if true, and the indexed attribute is an array, each element will be indexed

    Note that zero or more indexes can be created for a data store. Just like any other database system, indexing your database/data store can really boost the performance of the storage container. However, just adding indexes for the fun it provides is not a good idea, as the size of your data store will grow accordingly. A good data store design is one where the specific context of the data store with respect to the application is taken into account, and each indexed field is carefully considered. The phrase to keep in mind when designing your data stores is the following: measure it twice, cut it once.

    Although any object can be saved in a data store (as opposed to a relational database, where the data stored must carefully follow the table structure, as defined by the table's schema), in order to optimize the performance of your application, try to build your data stores with the data that it will store in mind. It is true that any data can be smacked into any data store, but a wise developer considers the data being stored very carefully before committing it to a database.

Once the data store is set up, and we have at least one meaningful index, we can start to pull data out of the data store. The easiest way to retrieve objects from a data store is to use an index, and query for a specific object, as shown in the following code:

var TodoItem = function(task) {
this.task = task;
this.completed = false;
};
function getTask(taskName, callback) {
// 1. Open a transaction. Since we don't need to write anything to
// the data store, a simple readonly transaction will sufice.
var trans = db.transaction(storeName, "readonly");
var store = trans.objectStore(storeName);
// 2. specify an index to use, and the data to get from it
var req = store.index("taskIndex").get(taskName);
req.onsuccess = function(e) {
var todoItem = e.target.result;
// todoItem.task => "Buy more pizza"
// todoItem.completed => false
callback(todoItem);
};
req.onerror = function(e) {
// Handle error
};
};
// Search for a TodoItem object with a task property of "Buy more
pizza"
getTask("Buy more pizza", function(taskItem) {
console.log("TaskItem object: " + taskItem.task);
});

The preceding function attempts to retrieve a single saved object from our data store. The search is made for an object with its task property that matches the task name supplied to the function. If one is found, it will be retrieved from the data store, and passed to the store object's request through the event object passed in to the callback function. If an error occurs in the process (for example, if the index supplied doesn't exist), the onerror event is triggered. Finally, if no objects in the data store match the search criteria, the resulting property passed in through the request parameter object will be null.

Now, to search for multiple items, we can take a similar approach, but instead we request an IndexedDBCursor object. A cursor is basically a pointer to a particular result from a result set of zero or more objects. We can use the cursor to iterate through every object in the result set, until the current cursor points at no object (null), indicating that there are no more objects in the result set.

var TodoItem = function(task) {
this.task = task;
this.completed = false;
};
function getTask(taskName, callback) {
// 1. Open a transaction. Since we don't need to write anything to
// the data store, a simple readonly transaction will sufice.
var trans = db.transaction(storeName, "readonly");
var store = trans.objectStore(storeName);
// 2. specify the range in the data store to request data from
var keyRange = IDBKeyRange.lowerBound(0);
var req = store.openCursor(keyRange);
req.onsuccess = function(e) {
// cursor IDBCursorWithValue
// key : int
// primaryKey : int
// source : IDBObjectStore
// value : Object
//
var cursor = e.target.result;
// Before we continue, we need to make sure that we
// haven't hit the end of the result set
if (!cursor) {
callback();
}
// If there are still results, let's process them
// cursor.value === todoItem
// cursor.value.task => "Buy more pizza"
// cursor.value.completed => false
// Since results are plain, typeless object literals, we need to
rebuild
// each object from scratch.
var todoItem = new TodoItem(cursor.value.task);
todoItem.myKey = cursor.value.myKey;
todoItem.completed = cursor.value.completed;
todoItems.push(todoItem);
// Tell the cursor to fetch the next result
cursor.continue();
};
req.onerror = function(e) {
// Handle error
};
};
// Retrieve every TodoItem in the data store
var todoItems = new Array();
getTask("Buy more pizza", function() {
for (var i = 0; i < todoItems.length; i++) {
console.log("TaskItem object: " + todoItems[i].task);
}
})

You will note a few things with the above code snippet. First, any object that goes into our IndexedDB data store is stripped of its DNA, and only a simple hash is stored in its stead. Thus, if the prototype information of each object we retrieve from the data store is important to the application, we will need to manually reconstruct each object from the data that we get back from the data store.

Second, observe that we can filter the subset of the data store that we would like to take out of it. This is done with an IndexedDB Key Range object, which specifies the offset from which to start fetching data. In our case, we specified a lower bound of zero, meaning that the lowest primary key value we want is zero. In other words, this particular query requests all of the records in the data store.

Finally, remember that the result from the request is not a single result or an array of results. Instead, all of the results are returned one at a time in the form of a cursor. We can check for the presence of a cursor altogether, then use the cursor if one is indeed present. Then, the way we request the next cursor is by calling the continue() function on the cursor itself.

Another way to think of cursors is by imagining a spreadsheet application. Pretend that the 10 objects returned from our request each represent a row in this spreadsheet. So IndexedDB will fetch all 10 of those objects to memory, and send a pointer to the first result through the event.target.result property in the onsuccess callback. By calling cursor.continue(), we simply tell IndexedDB to now give us a reference to the next object in the result set (or, in other words, we ask for the next row in the spreadsheet). This goes on until the tenth object, after which no more objects exist in the result set (again, to go along with the spreadsheet metaphor, after we fetch the last row, the next row after that is null – it doesn't exist). As a result, the data store will call the onsuccess callback, and pass in a null object. If we attempt to read properties in this null reference, as though we were working with a real object returned from the cursor, the browser will throw a null pointer exception.

Instead of trying to reconstruct an object from a cursor one property at a time, we could abstract this functionality away in a generic form. Since objects being persisted into the object store can't have any functions, we're not allowed to keep such functionality inside the object itself. However, thanks to JavaScript's ability to build an object from a reference to a constructor function, we can create a very generic object builder function as follows:

var TodoItem = function(task) {
this.task = task;
this.completed = false;
this.toHTML = function() {
var el = document.createElement("li");
el.textContent = this.task;
if (this.completed) {
el.style.textDecoration = "line-through";
}
return el;
};
};
function inflatObject(class, object) {
// 1. Create an instance of whatever class we reference
var obj = new class();
// 2. Copy every property from the object returned by the cursor
// into the newly created object
for (var property in object) {
obj[property] = object[property];
}
// 3. Return the inflated object
return obj;
}
// …
var req = store.openCursor(keyRange);
req.onsuccess = function(e) {
var cursor = e.target.result;
// Before we continue, we need to make sure that we
// haven't hit the end of the result set
if (!cursor) {
callback();
}
var todoItem = inflatObject(TodoItem, cursor.value);
// We could even call methods on the new inflated object
var itemElement = todoItem.toHTML();
document.body.appendChild(itemElement);
todoItem.myKey == cursor.myKey; // True
todoItem.task == cursor.task; // True
todoItem.completed == cursor.completed; // True
todoItems.push(todoItem);
// Tell the cursor to fetch the next result
cursor.continue();
};

Deleting elements

To remove specific elements from a data store, the same principles involved in retrieving data apply. In fact, the entire process looks fairly identical to retrieving data, only we call the delete function on the object store object. Needless to say, the transaction used in this action must be readwrite, since readonly limits the object so that no changes can be done to it (including deletion).

The first way to delete an object is by passing the object's primary key to the delete function. This is shown as follows:

function deleteTask(taskId, callback) {
// 1. Open a transaction. Since we definitely need to change the
object
// in the data store, we need proper access and benefits
var trans = db.transaction(storeName, "readwrite");
var store = trans.objectStore(storeName);
// 2. specify an index to use, and the data to get from it
var req = store.delete(taskId);
req.onsuccess = function(e) {
// Do something, then call callback
};
req.onerror = function(e) {
// Handle error
};
};

The difficulty with this first approach is that we need to know the ID of the object. In some cases, this would involve a prior transaction request where we'd retrieve the object based on some easier to get data. For example, if we want to delete all tasks with the attribute of complete set to true, we'd need to query the data store for those objects first, then use the IDs associated with each result, and use those values in the transaction where the objects are deleted.

A second way to remove data from the data store is to simply call clear() on the object store object. Again, the transaction must be set to readwrite. Doing this will obliterate every last object in the data store, even if they're all of different types as shown in the following code snippet:

var trans = db.transaction(storeName, "readwrite");
var store = trans.objectStore(storeName);
var req = store.clear();
req.onsuccess = function(e) {
// Do something, then call callback
};
req.onerror = function(e) {
// Handle error
};

Finally, we can delete multiple records using a cursor. This is similar to the way we retrieve objects. As we iterate through the result set using the cursor, we can simply delete the object at whatever position the cursor is currently on. Upon deletion, the reference from the cursor object is set to null as shown in the following code snippet:

// 1. Be sure to set the transaction to readwrite. Else, there will
be a nice
// exception raised if we try to delete readonly data.
var trans = db.transaction(storeName, "readwrite");
var store = trans.objectStore(storeName);
// 2. specify the range in the data store to request data from
var keyRange = IDBKeyRange.lowerBound(0);
var req = store.openCursor(keyRange);
req.onsuccess = function(e) {
var cursor = e.target.result;
// Before we continue, we need to make sure that we
// haven't hit the end of the result set
if (!cursor) {
callback();
}
// Here, we could have accessed the object's primary ID through
// the cursor object in cursor.value.myKey. However, accessing
// cursor.primaryKey maps to the specific property name that holds
// the value of the primary key.
store.delete(cursor.primaryKey);
// Tell the cursor to fetch the next result
cursor.continue();
};

This is pretty much the same routine as fetching data. The only detail is that we absolutely need to supply an object's key. The key is the value stored in the object's keyPath attribute, which can be user-provided, or auto-generated. Fortunately for us, the cursor object returns at least two references to this key through the cursor.primaryKey property, as well as through the object's own property that references that value (in our case, we chose the keyPath attribute to be named myKey).

The code

The two upgrades we added to this second version of the game are simple, yet they add a lot of value to the game. We added a persistent high score engine, so users can actually keep track of their latest record, and have a sticky record of past successes. We also added a pretty nifty feature that takes a snapshot of the game board each time the player scores, as well as whenever the player ultimately dies out. Once the player dies, we display all of the snapshots we had collected throughout the game, allowing the player to save those images, and possibly share it with his or her friends.

Saving the high score

The first thing you probably noticed about the previous version of this game was that we had a placeholder for a high score, but that number never changed. Now that we know how to persist data, we can very easily take advantage of this, and persist a player's high score through various games. In a more realistic scenario, we'd probably send the high score data to a backend server, where every time the game is served, we can keep track of the overall high score, and every user playing the game would know about this global score. However, in our situation, the high score is local to a browser only, since none of the persistence APIs (local and session storage, as well as IndexedDB) share data across other browsers, or natively to a remote server.

Since we want the high score to still exist in a player's browser even a month from now, after the computer has been powered off (along with the browser, of course) multiple times, storing this high score data on sessionStorage would be silly. We could store this single number either in IndexedDB or in localStorage. Since we don't care about any other information associated with this score (such as the date when the score was achieved, and so on), all we're storing really is just the one number. For this reason, I think localStorage is a much better choice, because it can all be done in as few as 5 lines of code. Using IndexedDB would work, but would be like using a cannon to kill a mosquito:

function setHighScore(newScore, el) {
var element = document.querySelector(el);
// Multiply by 1 to cast the value from a string to a number
var score = localStorage.getItem("high-score") * 1;
// Check if there is a numerical score saved
if (score && !isNaN(score)) {
// Check if new score is higher than current high score
if (newScore > element.textContent * 1) {
localStorage.setItem("high-score", newScore);
element.textContent = newScore;
} else {
element.textContent = score;
}
} else {
localStorage.setItem("high-score", newScore);
element.textContent = newScore;
}
}

This function is pretty straight forward. The two values we pass it are the actual score to set as the new high score (this value will be both saved to localStorage, as well as displayed to the user), and the HTML element where the value will be shown.

First, we retrieve the existing value saved under the key high-score, and convert it to a number. We could have used the function parseInt(), but multiplying a string by a number does the same thing, but with a slightly faster execution.

Next, we check if that value evaluated to something real. In other words, if there was no high-score value saved in local storage, then the variable score would have been evaluated to undefined multiplied by one, which is not a number. If there is a value saved with the key high-score, but that value is not something that can be converted into a number (such as a string of letters and such), we know that it is not a valid value. In this case, we set the incoming score as the new high score. This would work out in the case where the current persisted value is invalid, or not there (which would be the case the very first time the game loads).

Next, once we have a valid score retried from local storage, we check if the new value is higher than the old, persisted value. If we have a higher score, we persist that value, and display it to the screen. If the new value is not higher than the existing value, we don't persist anything, but display the saved value, since that is the real high score at the time.

Taking screenshots of the game

This feature is not as trivial as saving the user's high score, but is nonetheless very straightforward to implement. Since we don't care about snapshots that we captured more than one game ago, we'll use sessionStorage to save data from the game, in real time as the player progresses.

Behind the scenes, all we do to take these snapshots is save the game state into sessionStorage, then at the end of the game we retrieve all of the pieces that we'd been saving, and reconstruct the game at those points in time into an invisible canvas. We then use the canvas.toDataURL() function to extract that data as an image:

function saveEvent(event, snake, fruit) {
var eventObj = sessionStorage.getItem(event);
// If this is the first time the event is set, create its structure
if (!eventObj) {
eventObj = {
snake: new Array(),
fruit: new Array()
};
eventObj.snake.push(snake);
eventObj.fruit.push(fruit);
eventObj = JSON.stringify(eventObj);
sessionStorage.setItem(event, eventObj);
} else {
eventObj = JSON.parse(eventObj);
eventObj.snake.push(snake);
eventObj.fruit.push(fruit);
eventObj = JSON.stringify(eventObj);
sessionStorage.setItem(event, eventObj);
}
return JSON.parse(eventObj);
}

Each time the player eats a fruit, we call this function, passing it a reference to the snake (our hero in this game), and the fruit (the goal of this game) objects. What we do is really quite simple: we create an array representing the state of the snake and of the fruit at each event that we capture. Each element in this array is a string representing the serialized array that keeps track of where the fruit was, and where each body part of the snake was located as well.

First, we check if this object currently exists in sessionStorage. For the first time we start the game, this object will not yet exist. Thus, we create an object that references those two objects, namely the snake and the fruit object. Next, we stringify the buffers keeping track of the locations of the elements we want to track. Each time we add a new event, we simply append to those two buffers.

Of course, if the user closes down the browser, that data will be erased by the browser itself, since that's how sessionStorage works. However, we probably don't want to hold on to data from a previous game, so we also need a way to clear out our own data after each game.

function clearEvent(event) {
return sessionStorage.removeItem(event);
}

Easy enough. All we need is to know the name of the key that we use to hold each element. For our purposes, we simply call the snapshots of the snake eating "eat", and the buffer with the snapshot of the snake dying "die". So before each game starts, we can simply call clearEvent() with those two global key values, and the cache will be cleared a new each time.

Next, as each event takes place, we simply call the first function we defined, sending it the appropriate data as shown in the following code snippet:

if (fruit.isAt(head.x, head.y)) {
// Save current game state
saveEvent("eat", snake.getBody(), fruit.position);
fruit.reset();
snake.grow();
score.up();
// Save high score if needed
setHighScore(document.querySelector("#scores h3:first-child span").
textContent);
}
// …
if (!snake.isAlive()) {
saveEvent("die", snake.getBody(), fruit.position);
}

Finally, whenever we wish to display all of these snapshots, we just need to create a separate canvas with the same dimensions as the one used in the game (so that the buffers we saved don't go out of bounds), and draw the buffers to that canvas. The reason we need a separate canvas element is because we don't want to draw on the same canvas that the player can see. This way, the process of producing these snapshots is more seamless and natural. Once each state is drawn, we can extract each image, resize it, and display it back to the user as shown in the following code:

// Use each cached buffer to generate each screen shot
function getEventPictures(event, canvas) {
// Take the buffer from session storage
var obj = sessionStorage.getItem(event);
// Create an array to hold the generated images
var screenShots = new Array();
if (!obj)
return screenShots
obj = JSON.parse(obj);
var canvas = canvas.cloneNode();
var renderer = new Renderer(canvas);
// Go through each game state, and simply draw the data as though it
// was being drawn for the actual game in action
for (var i = 0, len = obj.snake.length; i < len; i++) {
renderer.clear();
renderer.draw(obj.snake[i], snake.getSkin());
renderer.draw(obj.fruit[i], fruit.img);
var screenShot = renderer.toImg();
screenShots.push(screenShot);
}
return screenShots;
}
// Display a list of images to the user
function drawScreenShots(imgs) {
var panel = document.querySelector("#screenShots");
for (var i = 0, len = imgs.length; i < len; i++) {
var a = document.createElement("a");
a.target = "_blank";
a.href = imgs[i].src;
a.appendChild(imgs[i]);
panel.appendChild(a);
}
}

Observe that we simply draw the points representing the snake and the fruit into that canvas. All of the other points in the canvas are ignored, meaning that we generate a transparent image. If we want the image to have an actual background color (even if it is just white), we can either call fillRect() over the entire canvas surface before drawing the snake and the fruit, or we can traverse each pixel in the pixelData array from the rendering context, and set the alpha channel to 100 percent opaque. Even if we set a color to each pixel by hand, but leave off the alpha channel, we'd have colorful pixels, but 100 percent transparent.

Summary

In this article we took a few extra steps into the fascinating world of 2D rendering using the long-awaited canvas API. We took advantage of the canvas' ability to export images to make our game more engaging, and potentially more social. We also made the game more engaging and social by adding a persistence layer on top of the game, whereby we were able to save a player's high score.

Two other new powerful features of HTML5, web messaging and IndexedDB, were explored in this article, although there were no uses for these features in this version of the game. The web messaging API provides a mechanism for two or more windows to communicate directly through message passing. The exciting bit is that these windows (or HTML contexts) do not need to be in the same domain. Although this could sound like a security issue, there are several systems in place to ensure that cross-document and cross-domain messaging is secure and efficient.

The web storage interface brings with it three distinct solutions for long term data persistence on the client. These are session storage, local storage, and IndexedDB. While IndexedDB is a full-blown, built-in, fully transactional and asynchronous NoSQL object store, local and session storage provide a very simple key-value pair storage for simpler needs. All three of these systems introduce great benefits and gains over the traditional cookie-based data storage, including the fact that the total amount of data that can be persisted in the browser is much greater, and none of the data saved in the user's browser ever travels back and forth between the server and the client through HTTP requests.

Resources for Article :


Further resources on this subject:


Learn HTML5 by Creating Fun Games Learn one of the most popular markup languages by creating simple yet fun games with this book and ebook
Published: June 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Rodrigo Silveira

Rodrigo Silveira is a web engineer at Deseret Digital Media. His responsibilities include back-end system development, tools, and maintenance, front-end application development and design, and more recently, he's been involved in mobile development of various products on the Android platform.

He received his Bachelor's of Science in Computer Science from Brigham Young University, Idaho, as well as an Associate's Degree in Business Management from LDS Business College in Salt Lake City, Utah.

His fascination for web development began in his early teenage years, and his skills grew as he discovered the power of a library subscription, a curious and willing mind, and supportive parents and friends. Today Rodrigo balances his time between the three great passions of his life—his family, software development, and video games (with the last two usually being mingled together).

Books From Packt


HTML5 Data and Services Cookbook
HTML5 Data and Services Cookbook

Instant HTML5 Responsive Table Design How-to [Instant]
Instant HTML5 Responsive Table Design How-to [Instant]

Mastering Mambo : E-Commerce, Templates, Module Development, SEO, Security, and Performance
Instant Migration to HTML5 and CSS3 How-to [Instant]

HTML5 Boilerplate Web Development
HTML5 Boilerplate Web Development

HTML5 Multimedia Development Cookbook
HTML5 Multimedia Development Cookbook

HTML5 Mobile Development Cookbook
HTML5 Mobile Development Cookbook

HTML5 Games Development by Example: Beginner’s Guide
HTML5 Games Development by Example: Beginner’s Guide

HTML5 Canvas Cookbook
HTML5 Canvas Cookbook


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
h
1
c
R
d
W
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software