Javascript Tutorial – Namespaces

Namespaces can be a powerful tool for code organization and conflict avoidance. Unfortunately, Javascript does not have native support for this extremely useful construct. That being said, the language’s flexibility allows us to create a facsimile that works quite well.

Namespace Declaration

We’re going to use objects to simulate namespaces. At the top of each file where you want to include and use a namespace, add the following line.

var myNamespace = myNamespace || {};

This line will either create a new object to hold our namespace or return the existing one. Technically this line only needs to be added to the top of the first script file included on the page, but it’s much easier (and better for testing) to just add it to every file.

Usage

Now that we have an instance of an empty object, all we have to do is add objects to it.

var myNamespace = myNamespace || {};

// Declare a new object.
myNamespace.MyObject = function() {
  this.myProperty = "someValue";
};

// Create an instance of the object.
var myInstance = new myNamespace.MyObject();

console.log(myInstance.myProperty); // someValue

As you can see, by assigning a function (class) to the property myNamespace.MyObject, we’ve essentially simulated adding an object to a namespace. Any number of objects can be added to our namespace like this, and since MyObject is now inside myNamespace, we don’t have worry about conflicting with all the other Javascript that might be running on the page.

And there you have it – an extremely simple solution to namespacing your Javascript code. It’s probably a good idea to use namespaces whenever possible since you never know whether or not a type already exists that you’re about to redefine. If you’re building a public library, like jQuery, then it should be an absolute requirement.

Want to learn more about Javascript? Check out these great books:

Saving Canvas Data as an Image

Over the past few months, we have talked quite a bit about HTML5, more specifically canvases. There are plenty of other interesting HTML5 subjects canvases offer, which makes it by far the most fascinating and flexible object. We have covered topics ranging from simple rotations to photo filters. Today we are going to go over how to take your canvas and save it as an image.

Below we have a working demonstration of the concept this tutorial will cover. If you click “Image Tag”, a new image element will be inserted into the contents of this page. The image element will be populated by the contents of the canvas. If you click “New Window”, the contents of the canvas will be displayed as an image in a new browser window or tab. If you click “Download”, the browser will prompt you to download the contents of the canvas as an image file.

Introduction

Getting the pixel data from a canvas is fairly simple, as we learned in the grayscale filter tutorial. Luckily, getting “image ready” data is also extremely easy as well.

Before we get started with some code, it should be noted that you can only get image data, in any form, from sources on the same domain on the canvas. This means that, while you can draw cross-domain images, you cannot get pixel data nor image data from canvases that have cross-domain images drawn on them.

Digging In

Now, the code to get your image data is actually really straight forward. All you have to do is have some fun with a canvas, then get a data string and us it accordingly. So here is what our code looks like:

var can = document.getElementById(‘canvas’);
var ctx = can.getContext(‘2d’);

var imgA = new Image();
imgA.src = ‘vader.jpg’;

imgA.onload = function() {
  ctx.drawImage(imgA, 25, 0, imgA.width, imgA.height);
  ctx.restore();
};

var imgB = new Image();
imgB.src = ‘troopers.jpg’;

imgB.onload = function() {
  ctx.globalAlpha = 0.1
  ctx.drawImage(imgB, 100, 75, imgB.width, imgB.height);
  ctx.restore();
};

function toImage(returnType) {
  var dataURL = document.getElementById(‘canvas’).toDataURL("image/png");

  // The returnType argument specifies how to get the
  // the image.  ‘obj’ will set the source to an image element.
  // ‘window’ will open a new window and display the image.
  // ‘download’ will prompt the user to save the image.
  switch(returnType) {
    case ‘obj’:
      var imgObj = new Image();
      imgObj.src = dataURL;
      document.getElementById(‘graphics’).appendChild(imgObj);
      break;
    case ‘window’:
      window.open(dataURL, "Canvas Image");
      break;
    case ‘download’:
      dataURL = dataURL.replace("image/png", "image/octet-stream");
      document.location.href = dataURL;
      break;
  }
}

In our example, we take two images and layer them, with the on top image mostly transparent, to give us a trendy fade-in look.

So first thing we do is take two images and draw them to a canvas, with one being drawn on top of the other with 50% opacity. However, what you put on your fancy canvas is up to you, the important part is getting that data into an image.

The magic revolves around the call to toDataURL inside our toImage function, which actually returns a string that contains the image data (in URL form) for the canvas. Also notice that this call is on the canvas itself and not the 2d context we use to draw the images.

Once you have this string, you can use it many different ways. You can make an image and set the source to the data, open the data in a new window, or even point the location of the current document to the data which allows you to do a straight-up download of the image. All these methods offer a way to get the canvas data as an image, we have them all inside our function. All three methods have been included so you can see how they are each accomplished. Again, very simple code.

So there you have it. Saving canvas data as an image is quite easy, and you can present that data in any number of ways…as long as you don’t use cross-domain images. This is going to wrap it up for this tutorial, just remember when you need coding help, all you have to do is Switch On The Code.

HTML 5 Canvas Tutorial – Converting Images to Grayscale

HTML 5 and the Canvas tag has brought a whole world of possibilities when it comes to image manipulation. This tutorial will demonstrate one of those possibilities that is particularly powerful – getting raw image data and transforming it.

We’ve done a conversion to grayscale tutorial before using C# and this tutorial will look fairly similar to an approach outlined in that article.

Grayscale Example

There actually isn’t too much code, so I’m going to just throw the entire contents here and explain what’s going on after.

// Create an image object.     
var image = new Image();

// Can’t do anything until the image loads.
// Hook its onload event before setting the src property.
image.onload = function() {

   // Create a canvas.
   var canvas = document.createElement(‘canvas’);
   
   // Get the drawing context.
   var ctx = canvas.getContext(‘2d’);
   
   // Get the width/height of the image and set
   // the canvas to the same size.
   var width = image.width;
   var height = image.height;
   
   canvas.width = width;
   canvas.height = height;
   
   // Draw the image to the canvas.
   ctx.drawImage(image, 0, 0);
   
   // Get the image data from the canvas, which now
   // contains the contents of the image.
   var imageData = ctx.getImageData(0, 0, width, height);
   
   // The actual RGBA values are stored in the data property.
   var pixelData = imageData.data;
   
   // 4 bytes per pixels – RGBA
   var bytesPerPixel = 4;
   
   // Loop through every pixel – this could be slow for huge images.
   for(var y = 0; y < height; y++) {
      for(var x = 0; x < width; x++) {
         // Get the index of the first byte of the pixel.
         var startIdx = (y * bytesPerPixel * width) + (x * bytesPerPixel);
         
         // Get the RGB values.
         var red = pixelData[startIdx];
         var green = pixelData[startIdx + 1];
         var blue = pixelData[startIdx + 2];
         
         // Convert to grayscale.  An explanation of the ratios
         // can be found here: http://en.wikipedia.org/wiki/Grayscale
         var grayScale = (red * 0.3) + (green * 0.59) + (blue * .11);  
         
         // Set each RGB value to the same grayscale value.
         pixelData[startIdx] = grayScale;
         pixelData[startIdx + 1] = grayScale;
         pixelData[startIdx + 2] = grayScale;
      }
   }
   
   // Draw the converted image data back to the canvas.
   ctx.putImageData(imageData, 0, 0);
};

// Load an image to convert.
image.src = "myImage.png";

The first thing we need is an image to convert. There are multiple ways to get image objects, but this is one of the easiest. I hook the image’s onload event and then set the source to a URL. It’s important to note here that you can’t convert images that aren’t hosted on the same domain – the canvas is said to be tainted by a cross domain image and therefore getImageData and putImageData no longer work.

Since we can’t get information directly from an image, we have to draw it to a canvas first. I simply create a canvas the same size as the image and paint the image to it.

The conversion process is actually pretty simple. We just need to loop through every pixel, convert it to grayscale, and draw the new image back to the canvas. The conversion equation, (red * 0.3) + (green * 0.59) + (blue * 0.11), does a better job than just taking the average of the three values. You can read a little bit more about those values on Wikipedia’s Grayscale page.

After we’ve converted every pixel, we just call putImageData to draw the converted image back to the canvas. And that’s all there is to it – you now have a black and white version of your picture.

This is a pretty basic example of using an image’s raw data, but you can begin to see the power developers now have. If you’ve got any questions, feel free to leave them below.

Want to learn more about the HTML 5 Canvas? Check out these great books:

Objective-C Snippet Tutorial – The UIAlertView

Displaying a message box in an iPhone application is something I have to look up almost every time. I decided it was time to create a tutorial on the subject – then maybe I’d actually remember the syntax. This tutorial will be short, but should cover pretty much everything you’d need to know in order to show alerts in an iPhone application.

If you want to display a simple notification, the syntax is actually pretty short.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My Title"
                                                message:@"My Message"
                                               delegate:nil
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];

[alert show];

That will give you a message box that looks like this:

UIAlertView Example

Unlike a lot of other UI frameworks, the show function does not block until the alert is dismissed – execution will continue immediately. In order to know what button was pressed we’re going to have to specify a delegate object. In the above example, you’ll see the delegate argument is nil. Alternatively, we could provide an object that will act as a receiver for various actions.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My Title"
                                                message:@"My Message"
                                               delegate:self
                                      cancelButtonTitle:@"OK"
                   otherButtonTitles:@"Button 1", @"Button 2", @"Button 3", nil];

// otherButtonTitles is a comma delimited list of strings, terminated with a nil.

[alert show];

// This function will be called by the UIAlertView.
(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
  // The cancel button ("OK") is always index 0.
  // The index of the other buttons is the order they’re defined.
}

The UIAlertViewDelegate has lots of helpful callbacks that can be used to determine how a user is interacting with your message box. The example above is probably one of the most common – determining which button was pressed when the view is dismissed. The cancel button is always index 0. The index of the other buttons will start at 1 and then increment in the order they’re defined (“Button 1” = 1, “Button 2” = 2, etc).

That code gives us something that looks like this:

UIAlertView with multiple buttons

And I think that finishes up this tutorial. There’s not much to the UIAlertView, and I hope this tutorial at least points you in the direction of all the things it offers. If you’ve got any questions, feel free to drop them below.

Want to learn more about iPhone programming? Check out these great books:

?

Introduction to the Pulse Engine

One interesting corner of HTML5 development is web-based games. With a few well placed canvases and a healthy does of Javascript, you can create just about any game you can dream. However, the complex nature of Javascript has created the need for a few companies to release game engines built entirely in Javascript and HTML5. This is where Pulse comes in.

Pulse is a game engine built in Javascript. It utilizes HTML5 canvases to display and animate various elements and offers features like event handling, audio, and sprite sheet animations. With the recent release of the developer preview, I would like to take a few minutes and go over some of the neat features that Pulse has to offer.

Lets’s start with a simple sample. Note that all our game-specific code is bundled in the mygame.js file.

<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Paddle Game</title>
    <script src="pulse.js" type="text/javascript"></script>
    <script src="mygame.js" type="text/javascript"></script>
  </head>
  <body>
    <div style="width: 760px; height: 480px;" id="gameWindow"></div>
  </body>
</html>

Pulse comes as a single Javascript file and including it is as easy as adding a reference to that file. Now that Pulse is included, let’s take a look at our myGame.js Javascript file.

// Hook the ready event.  This will fire
// when the DOM and Pulse are both ready for use
pulse.ready(function() {

  // Create the engine, scene, and layer.
  var engine = new pulse.Engine({ gameWindow: ‘gameWindow’, width: 760, height: 480 });
  var scene = new pulse.Scene();
  var layer = new pulse.Layer();
 
  // Create a Score object.  The Score class extends pulse.CanvasLabel.
  var score = new Score( { text: "0 | 0" } );
  score.position.x = 300;
  score.position.y = 200;
 
  // Create a ball, position it, and set a few properties.
  var ball = new Ball({ src: ‘ball.png’, size: {width: 16, height: 16} });
  ball.position.x = 300;
  ball.position.y = 200;
  ball.velocity.x = .25;
  ball.velocity.y = .25;
  ball.score = score;
  layer.addNode(ball);
 
  //Create the paddles and position them.
  var paddle = new Paddle({ src: ‘paddle.png’ });
  paddle.ball = ball;
  paddle.position.x = 20;
  paddle.position.y = 150;
 
  var aiPaddle = new Paddle( { src: ‘paddle.png’ });
  aiPaddle.ball = ball;
  aiPaddle.position.x = 730;
  aiPaddle.position.y = 150;
  aiPaddle.auto = true;
 
  // Add the paddles and the score object to the layer.
  layer.addNode(paddle);
  layer.addNode(aiPaddle);
  layer.addNode(score);
 
  // Make the layer’s origin 0,0. The origin defines how objects
  // are positioned – by default objects are positioned by their centers.
  // (0,0) represents the top-left corner.
  layer.anchor.x = 0;
  layer.anchor.y = 0;
 
  // Add the layer to the scene, then add the scene to the engine.
  scene.addLayer(layer);
  engine.scenes.addScene(scene);

  // Activate the scene.
  engine.scenes.activateScene(scene);
 
  // Start the game loop and provide a callback, loop,
  // that will be invoked on each update loop.
  engine.go(20, loop);
});

This example is the start of a pong game, with a few things stripped out for simplicity. All the basic Pulse elements are there though. You create some game objects, in this case paddles and a ball, then add them to a layer. This layer then gets added to a scene. Finally the scene is added to the game.

Once all the objects, layers, and scenes are setup, you just create a main logic loop (which is empty here), then call engine.go(). All of this is wrapped in a ready call so the game is started when the browser is finished loading Pulse and the rest of the website.

Most engines follow this paradigm, but Pulse makes it extremely easy. With a few lines, you can have game objects loaded and update logic running. You just have to set up a few layers and a scene or two, and you are good to go. However, ease of use is not the only strong point of Pulse.

One of the more advanced features Pulse has is a very structured object hierarchy, all built to be extensible. Any, and I do mean any, Pulse object can be extended and added to. Not only is it possible to extend an object, it is extremely easy. In the example above the Paddle, Ball, and even the Score object are actually extensions of a base Pulse object. Here are the classes in full, take a look:

var Paddle = pulse.Sprite.extend({
  init: function(params) {
   
    // Call the base constructor.
    this._super(params);
   
    // Add properties to determine what arrow key has been pressed.
    this.arrowUp = false;
    this.arrowDown = false;
   
    this.size.width = 50;
    this.size.height = 200;
   
    // Bind the key events to set the arrow up/down properties.
    this.events.bind(‘keydown’,
      function(e) {
        if(e.keyCode == 38) {
          e.sender.arrowUp = true;
        }  
        else if(e.keyCode == 40) {
          e.sender.arrowDown = true;
        }
      });
     
    this.events.bind(‘keyup’,
      function(e) {
        if(e.keyCode == 38) {
          e.sender.arrowUp = false;
        }  
        else if(e.keyCode == 40) {
          e.sender.arrowDown = false;
        }
      });
  },
 
  /* The update function runs every game "tick." This update function
     will move the paddle based on what key is currently down, as long
     as it is in the bounds of the game canvas. */

  update: function(elapsed) {
    this._super(elapsed);
   
    if(this.auto) {
      if(this.ball.position.y < this.position.y) {
        this.position.y -= .15 * elapsed;
      }
      else if(this.ball.position.y > this.position.y) {
        this.position.y += .15 * elapsed;
      }
    }
    else {
      if(this.arrowUp) {
        this.position.y -= .15 * elapsed;
      }
      else if(this.arrowDown) {
        this.position.y += .15 * elapsed;
      }
    }
  }  
});
var Ball = pulse.Sprite.extend({
 
  init: function(params) {
   
    // Call the base constructor.
    this._super(params);
   
    // Setup a few velocities, which determine the ball’s speed.
    this.velocity = { };
    this.velocity.x = .25;
    this.velocity.y = .25;
   
    // The bounds of the area in which the ball can go.
    this.maxX = 760;
    this.maxY = 480;
  },
 
  /* Bounces the ball if it has made it to any of the bounds,
     at a 45 degree angle. Also increments the score if it has
     reached a horizontal bounds, IE has made it to a players side. */

  update: function(elapsed) {
    this._super(elapsed);
   
    this.position.x += elapsed * this.velocity.x;
    this.position.y += elapsed * this.velocity.y;
   
    var xMax = this.maxX (this.size.width / 2);
    var yMax = this.maxY (this.size.height / 2);
    var xMin = this.size.width / 2;
    var yMin = this.size.height / 2;
   
    if(this.position.x > xMax) {
      this.position.x = xMax;
      this.velocity.x *= 1;
      this.score.playerScore();
    }
   
    if(this.position.x < xMin) {
      this.position.x = xMin;
      this.velocity.x *= 1;
      this.score.aiScore();
    }
   
    if(this.position.y < yMin) {
      this.position.y = yMin;
      this.velocity.y *= 1;
    }
   
    if(this.position.y > yMax) {
      this.position.y = yMax;
      this.velocity.y *= 1;
    }
  },
});
// This class keeps track of the score and draws it to the canvas.
var Score = pulse.CanvasLabel.extend({
  init: function(params) {
    this._super(params);
   
    this.scoreA = 0;
    this.scoreB = 0;
  },
 
  playerScore : function() {
    this.scoreA++;
    this.text = this.scoreA + " | " + this.scoreB;
  },
 
  aiScore : function() {
    this.scoreB++;
    this.text = this.scoreA + " | " + this.scoreB;
  }
});

As you can see, all that it takes is a simple call to the extend method one any object and you have the ability to make your own subclass. In this case we are just overriding the update function, but the possibilities are endless.

Put all this together and you get a simple pong game that looks like so:

Pulse offers a lot to any web developer, whether they are building a game or an application. With this just being the developer preview, who knows what may be in store for the future. I know we will be keeping a close eye out here at Switch On The Code.

For more information on Pulse, visit the website and sign up for updates.

Disclaimer
We try to be impartial when reviewing or evaluating products like this. That being said, Pulse is being developed by the same team that created Switch On The Code, so of course we’re only ever going to have good things to say about it.

Switch On The Code – Year End Review

Another year has come and gone, which means it’s time for us to look back at 2011 and see what happened. This year marks the fifth anniversary of Switch On The Code and so far every year has been better than the last.

In February we saw our first ever month of 500k pageviews, and for the most part traffic has held steady ever since. We ended the year with an amazing 5.6 million pageviews – a 10% increase over the previous year.

Analytics Screenshot

Somehow we managed to publish 42 articles, which is pretty darn close to our goal of one article a week. If we look at every article, not just the ones created in 2011, the most popular last year were:

  1. Using jQuery Slider to Scroll a Div – 203,127
  2. An Absolute Beginner’s Guide to iPhone Development – 171,959
  3. C# Tutorial – Simple Threaded TCP Server – 168,562
  4. C# Tutorial – Binding a DataGridView to a Database – 161,566
  5. C# Tutorial – Image Editing: Saving, Cropping, and Resizing – 161,268

As always, we try to produce tutorials for newest and shiniest technologies, so last year we started creating tutorials for HTML 5, specifically canvas images and image rotation. We’re going to be publishing several more HTML 5 related tutorials throughout this year while continuing to explore whatever other new technologies 2012 throws our way.

We always have big plans for Switch On The Code, including moving to cloud hosting, upgrading to Drupal 7, redesigning it, and lots of other small things. Hopefully 2012 will see the fruition of some of our plans, but if not, we’ll continue to publish as many tutorials as possible and continue to grow with the community.

If you’ve got specific tutorial requests or any other random things to say – drop a line below in the comments or shoot us an email.

Regular Expressions – Grouping

As we learned in our Regular Expressions Primer, regular expressions can be simple or extremely complex. However, there are a few concepts that were left out. Today we are going to cover one of those concepts… grouping.

In regular expressions, grouping allows you to “chunk” parts of your expression and tell the regular expression engine to treat each “chunk” as a separate match. This allows you to, say, find the type of domain (com, eu, biz) of an email address, or possibly whether or not the uri is using encrytion (https). There are a whole lot of reasons you want to use grouping, but enough talk, let’s get to it. Today we will be using PHP yet again, but grouping is supported by any self-respecting regular expression engine.

The Basics of Grouping

Grouping is implemented with ()s. Anything inside the parentheses are considered a group, and are tracked by the order in which they appear in the expression. So if I have two groups, whichever appears first (from left to right) will be marked as match one, and match two will be the one that appears next. Some engines even allow sub-groups, but for today we will stick to single-scope groups.

Grouping has no effect on the matching itself, and only effects the way matches are returned for processing. Lets take a simple example, which finds (or validates) an email address:

//Without Grouping
$regex = "/[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.\w{2,3}/";

//With Grouping
$regex = "/([a-zA-Z0-9-_]+)@([a-zA-Z0-9-_]+)\.(\w{2,3})/";

As you can see, the only difference here is that some pieces of our expression are wrapped in parentheses. In PHP, when a match is returned, it will return the whole expression, followed by all the groups, or chunks, that were defined. In the case of our example, we will get given the user, the domain, and the top-level domain (com, edu, etc.), on top of the full match.

Let’s say for a second you have “[email protected]”. When you run it through our regular expression you will match “[email protected]”, “user”, “mydomain”, and “edu”. This is the essence of grouping, an easy way to check parts of a match.

Back References

When we are talking about regular expressions, back-references are references to groups that you can reference when replacing matches. In order to use back-references, you have groups defined in your expression.

Taking the example above, let’s say we want to replace all the domains in a set of emails with “awesomesite”. In PHP you use the preg_replace function, which uses regular expressions to replace text in a string. Let’s check out how to use back-references to replace the domain in our email.

$text = "my email is "user@domain.com" and allows me to send emails";
$regex = "/([a-zA-Z0-9-_]+)@([a-zA-Z0-9-_]+)\.(\w{2,3})/";

preg_replace($regex, "$1@awesomesite.$3", $text);

So this will replace “domain” with “awesomesite”, in turn making the email address “[email protected]”. Now the replacement text is the important part here. The “$1” and “$3” are the back-references, which reference the first and third group respectively. In this example we just drop the second group and replace it with whatever we want. It’s really that easy.

The only trick to using back-references like this, in PHP, is that you have to use a special syntax when you want to follow a back-reference with a number:

preg_replace($regex, "${1}1234@awesomesite.$3", $text);

This example will give us an email of “[email protected]”. The “${1} is a syntax used when you want to follow a back-reference with a number, although nothing is stopping the paranoid programmer from using that syntax all the time.

So that is the power of grouping. Pretty simple once you get the hang of regular expressions. Just remember, when you need coding help, all you have to do is Switch On The Code.

If you want to learn more, check out these great regular expression books:

Regular Expression Primer

Pattern recognition is a very hard thing to get right, and as a developer it can be as easy as a few lines of code or more than you can count with fingers and toes. Today we are going to go over a very common tool used for text pattern recognition: regular expression. So let’s get started and dive right in.

Regular expressions provide a standard framework for pattern recognition in strings. It allows you to define and find specific pieces of text, which can be slightly more complicated that it sounds. In fact, regular expressions are really a language unto themselves, albeit a small language.

Pretty much any high level language has an implementation of regular expressions. For this tutorial we will be using PHP for our examples, which using Perl-style regular expressions. However, keep in mind most regular expression engines use the same syntax, with just small variations in features being the difference.

Our First Example

The first rule to regular expression is to remember that we are searching more for patterns, rather than exact text. For example, I may want to validate that something is in the form of currency ($##.##), rather than a specific amount of money. In fact, let’s roll with that example first.

$regex = "/$\d+\.\d{2,}/";

Before we get too deep, let me explain exactly what this does. We start with encasing everything in / (forward slashes), IE “/…expression…/”. This is a requirement for Perl-style regular expressions.

Next we dive into the expression itself. First we have a literal “$”, followed by any number at least once, expressed as “\d+”. Then there it looks for a literal “.”, which has to be escaped, thus “\.”. Finally we look for two or more numbers, which accounts for the expression “\d{2,}.

So there are a few things that may need a bit more explanation here. While things like “\d” are pretty strait forward (“\d” being a match for any digit), things like a “+” are a bit confusing. The “+” and “{2,}” in our example both deal with matching things a certain number of times. In fact there are a few more these “number of occurrences” operators, so here is a super sweet table for reference.

Number of Occurrence Operators

Operator Matches…
? 0 or 1 times
* 0 or more times
+ 1 or more times
{min, max} between the min and max number of times. However, you can leave the max out to specify no max. For example, {2,} matches 2 or more times.

Ok, so we have some operators. What about things you use to actually create the pattern to match x number of times? Well, let’s start with a table for some reference.

Simple Expressions

Expression Matches…
\d Any digit (0-9)
\D Any non-digit
\w Any alpha numeric character
\W Any non-alpha numeric character
\s Any whitespace character (space, tab, etc.)
. Matches any character

Between these two tables we can start to wrap our heads around our example. Let’s take “\d+”. In simple terms it says “there must be a collection of one or more digits in a row”, IE “01”, “19”, “1”, “432”, etc. We also now know why we have to escape the “.”, as it is an expression used by the engine.

Digging Deeper

It is already pretty apparent that things can get pretty complex pretty fast…and this is only the tip of the iceberg. What if you have a specific group of acceptable characters? or maybe you just want to match lowercase alphabetic characters? Well this is where classes and []s come in.

Using []s, you can define a list of characters to match or use some built in “classes” that allow you to specify a range or alphabetic or numeric characters. As crazy as that sounds, it is extremely useful. Let’s go with another simple example:

$regex = "/[f-jA-C\sGKO]/";

So here we have an expression that is going to match a single character. However, that character has a lot of choices as what it could be.

First we have the range “f-j” which matches any lowercase letter between f and j. Keep in mind this is case sensitive, so our range only matches lowercase letters, while our next range of “A-C” only matches uppercase letters.

After our two ranges, we have “\s”, a space character, followed by a collection of single uppercase letters. Each letter is a separator, so the last three characters all count as a valid match.

So basically our expression is looking for a single character that is f, g, h, i, j, A, B, C, G, K, O, or a space of some kind.

Lets go ahead and mix things up a bit more. Lets say we modify our example to be:

$regex = "/^[f-jA-C\sGKO]$/";

What? Now we have a “^” and “$” in there? Well those are position operators. The “^” represents the start of a given string and the “$” represents the end. In essence, we have limited our expression to a one character string, containing one of the acceptable characters. Lets get a table going one last time:

Ranges, Classes, and Positions

Expression Effect
[] Used for specifying a collection of single characters or a range of characters. Any character defined is case sensitive.
Range specifier, case sensitive. Example: [a-fA-F]
^ Denotes pattern should start that the beginning of the string.
$ Denotes pattern should end the end of the string.

Closing

I can sit here and explain things to you all day, but in the end examples are really the best way to explain regular expressions. So here are few that might help to visualize how regular expressions come together.

A Few Examples

Expression Matches(Separated by commas)
/[Hh]ello\s?[Ww]orld/ hello world,Hello World,helloworld
/[bBfFHh]{1}a[a-zA-Z]+/ Bat,hat,Hall,ball,Fatt,bait,hate
/http[s]?/ http,https
/\d\.\d{2,4}/ 1.44,5.121,9.4356

Ok, so now we have a simple understanding of regular expressions and some examples to look through. Before I wrap this up officially though, I have compiled all of our reference tables in one super reference, or cheat sheet if you will, below.

Regular Expression Reference

Expression Effect
\d Any digit (0-9)
\D Any non-digit
\w Any alpha numeric character
\W Any non-alpha numeric character
\s Any whitespace character (space, tab, etc.)
. Matches any character
? 0 or 1 times
* 0 or more times
+ 1 or more times
{min, max} between the min and max number of times. However, you can leave the max out to specify no max. For example, {2,} matches 2 or more times.
[] Used for specifying a collection of single characters or a range of characters. Any character defined is case sensitive.
Range specifier, case sensitive. Example: [a-fA-F]
^ Denotes pattern should start that the beginning of the string.
$ Denotes pattern should end the end of the string.

This is going to wrap it up for our introduction to regular expressions. Keep an eye out for more, because things can be a lot crazier. Just remember, when you need coding help, all you have to do is Switch On The Code.

Introducing the Pulse Developer Preview

HTML5 is pretty much the web 3.0 standard these days, and there are plenty of neat neat HTML5 tutorials out there to prove it. In fact, there are even a few game engines out there that are built for HTML5. A recent development in this area was the release of the Pulse developer preview. Here is a short demo of what is possible with pulse:

Pulse is a game engine built in Javascript and utilizes HTML5 canvases to render content. It offers a lot of neat features, including:

  • Sprites
  • Sprite sheet animations
  • Bitmap & native fonts
  • Keyboard and mouse events
  • Drag & drop
  • Layers
  • Scenes

The Pulse website actually features a nice little megaman platformer demo that shows that the engine is more than capable of rendering high frame rates.

I could talk about Pulse all night, but let’s skip the talking and get to a small code example:

// Setup the game in the ready callback.  The ready callback
// will be fired when the DOM is loaded – a lot like
// jQuery’s ready callback.
pulse.ready(function() {

  // Create a pulse engine and tell it what element(div)
  // will contain the rendered content.  The element can
  // either be the id or the actual DOM object itself.
  var engine = new pulse.Engine({ gameWindow: "myElement" });
 
  // Create a scene.  Each game has a minimum of one scene.
  // Names are optional, but are useful when debugging or
  // retrieving node by name at a later time.
  var scene = new pulse.Scene({name: ‘cybertron’});

  // Add the scene to the engine and activate it.
  engine.scenes.addScene(scene);
  engine.scenes.activateScene(scene);
 
  // Create a layer.  Each game has a minimum of one layer.
  var world = new pulse.Layer({name: ‘layer’, x : 320, y : 240});

  // Add the layer to the scene.
  scene.addLayer(world);
 
  // Create a sprite with a diamond image.
  var diamond = new pulse.Sprite({ src: ‘img/diamond.png’ });
  diamond.position = {x: 320, y: 240};

  // Add the sprite to the layer.
  world.addNode(diamond);

  // Tell the engine to go and specify the delay between
  // frames (33 milliseconds) and an optional callback
  // that will be invoked on each update.
  engine.go(33, function (sceneManager) {
      // Rotate the diamond by 1/2 degree.
      diamond.rotation += 0.5;
  });
});

The following will produce a spinning diamond which looks a little bit like:

As you can see it is extremely simple to use, and I would suggest heading over to the website, signing up, and checking out the super sweet megaman demo.

Book Review – Learning Cocos2D

Learning to program is hard and one of the ways to make the process easier is by reading and using books. With our book reviews here at Switch On The Code we try to help you figure out which books are the best for any level of developer. In this review I’m going to go over the iOS game programming book Learning Cocos2D – A Hands-On Guide to Building iOS Games with Cocos2D, Box2D, and Chipmunk. written by Rod Strougo and Ray Wenderlich.

As with our other reviews we received the book free of charge from the publisher. This doesn’t mean I won’t give a book a bad review, I’m not that nice of a guy – just ask the other SOTC guys.

Learning Cocos2D: A Hands-On Guide to Building iOS Games with Cocos2D, Box2D, and Chipmunk
By Rod Strougo, Ray Wenderlich
Publisher: Addison-Wesley Professional
Pub. Date: Jun 22, 2011
ISBN-13: 978-0-321-73562-1
Pages: 640
List Price: $44.99
Buy it on Amazon

The first thing to say about the book is that aims at the developer who has some experience with the basic programming concepts and the tools surrounding iOS development. The main topic covered is Cocos2d, a 2D engine for creating iOS games, and also touches on Box2D and Chimpmunk – the two most popular physics libraries for iOS. The book is organized to help you create an entire game from beginning to end, along with a few other random smaller applications.

As you read through the book you’ll notice that the entire thing is basically one giant tutorial, the authors even mention this as a goal in the foreword. As you move through the book you continue to build a space viking themed game. Cocos2D is covered pretty thoroughly in the first 275 pages and then the more advanced physics topics are covered with building a level using Box2D and another using Chipmunk. I think this is an interesting way to do this because in a real game you would choose one physics library to use and create the entire experience using it. In the second to last chapter of the book the authors touch on gaming achievements and leaderboards using Game Center. The last chapter is dedicated to helping you get the maximum performance out of your games.

The book does a good job of going through the details of Cocos2D. As mentioned before, if you don’t know anything about programming for the iOS platform you’ll be lost for the most part. Game programming is inherently a complicated subject but approaching it using Cocos2D helps flatten the learning curve.

The authors have done a great job using code samples to step the reader through new concepts. As expected the complete source code is available, but not only that, the game in which you are creating throughout the book is available on the iOS app store.

There are a couple of items I didn’t love, the biggest is that the book reads very much like a college textbook, dry and without much emotion. Although, this is expected in a programming book. The other downside is that it only covers 2D games – again understandable considering Cocos2D is only a 2D engine.

I believe this book has excelled at what it was trying to do and am happy to recommend it to anyone who has some programming experience with iOS. I believe that an intermediate or expert programmer with little to no Cocos2D experience would get great use out of the book. We don’t give a score here, we simply say if we would recommend it for the different skill levels.

Beginners: Leave It
Even though it’s a good book I wouldn’t recommend it to a beginner because of the topics covered and there is no intro to iOS programming.

Intermediate: Get It
If you’re looking for a way to get into game programming and have an iOS development base this is the book for you.

Guru: Maybe
This is certainly for the programming guru who hasn’t spent a lot of time with Cocos2D and would quickly get you up to speed on the topic.

And if you looking for more iOS game programming books check out these:

 

 

 

Javascript – Highlighting Selected Text

I am sure we all have been at a point when we need to highlight something, and most note taking or sharing software allows you to pick and color and go selection crazy. Luckily, however, it is actually surprisingly easy to get a selection and highlight it with Javascript.

To start, why not take a second and just selected some text this tutorial. You should have just highlighted some text green, as I have included the necessarily Javascript to allow highlighting in any paragraph in the content section of the tutorial. That’s right, you can highlight any text you want in the confines of the tutorial.

It all is thanks to a simple span, which has a css class that changes the color of the text inside it. The only trick is to retrieve and surround the text that was selected by the user with this span. Thankfully, there is some simple code, that is cross-browser compatible, that will allow us to do this really easily. Let’s start with getting the selected text;

function highlightSelection()  {
  var selection;

  //Get the selected stuff
  if(window.getSelection)
    selection = window.getSelection();
  else if(typeof document.selection!="undefined")
    selection = document.selection;
}

The lines above get the selected text, with the only difference in the if statement being how you retrieve it in different browsers. Between these two methods, you can get text selections in any modern browser.

Next we have to get the selection “range” which represents a single block of selected text. In the case of just one selection, there will always be one range. However, it is possible to select more than one block of text, either by holding down the control button or using some other means. The point is that you have to retrieve a range object. In our case, we are keeping it simple and just retrieving the first range:

function highlightSelection()  {
  var selection;

  //Get the selected stuff
  if(window.getSelection)
    selection = window.getSelection();
  else if(typeof document.selection!="undefined")
    selection = document.selection;

  //Get a the selected content, in a range object
  var range = selection.getRangeAt(0);
}

That’s it. You just have to call a simple function and tell it what range you want. As noted above, we just want the first range, i.e. the range at index zero.

Now for the fun part. Next we have to take the range and wrap it in a span tag. Before we do this, we have to make a few checks. First we have to make sure the range is defined and that the selection is not “collapsed”, i.e. the start and end points of the selection are the same. This prevents us from trying to wrap an empty selection.

Second we are going to add a simple check that prevents wrapping tags inside our span, which could break our entire html document. This is a simple method that will save our poor HTML document from getting ripped apart. While it is possible to wrap text across multiple tags, for now we are playing it on the safe side and keeping things as simple as possible.

Our final function will look like so:

function highlightSelection()  {
  var selection;

  //Get the selected stuff
  if(window.getSelection)
    selection = window.getSelection();
  else if(typeof document.selection!="undefined")
    selection = document.selection;

  //Get a the selected content, in a range object
  var range = selection.getRangeAt(0);

  //If the range spans some text, and inside a tag, set its css class.
  if(range && !selection.isCollapsed)
  {
    if(selection.anchorNode.parentNode == selection.focusNode.parentNode)
    {
      var span = document.createElement(‘span’);
      span.className = ‘highlight-green’;
      range.surroundContents(span);
    }
  }
}

The first check we make is fairly straightforward, but the tricky part comes in the second check. Here we are checking the parent of the anchor node, which is where the selection started. Then we make sure the focus node’s parent is the same, which is where the selection has ended. Basically we make sure the range starts and ends in the same tag, thus preventing us from trying to wrap selections that span multiple tags.

Since we also use a css class, the style possibilities are endless. You can even have buttons that change the highlighter style. All you have to do is change the class of the span that is used to wrap the text. For example, the CSS I used in this demo looks like so:

.highlight-green {
  color: #00FF00;
}

So this wraps it up for this tutorial. Just remember when you need coding help, all you have to do is Switch On The Code.

HTML 5 Canvas Tutorial – Rotation

We here at Switch On The Code have been working with and playing around with the HTML5 canvas element. So, today’s tutorial is going to build on top of the previous Image drawing tutorial and show you how to rotate drawn images, or really whatever you want.

Rotating About Object’s Center

The first type of rotation we are going to take a look at is rotating an object about its center. This is one of the simplest types of rotation to achieve using the canvas element. We are going to be using the sweet Gorilla pic from last week.

The basic idea is that we are going to translate the canvas to the point we want to rotate around, rotate the canvas, and then translate the canvas back to 0,0. If you have some experience with graphics engines this should sound pretty familiar. In code this looks like the below snippet.

myImage = new Image();
myImage.onload = function() {
  var xpos = 300; // the x position of the center of the image
  var ypos = 200; // the y position of the center of the image
  ctx.save(); // save the current state of the canvas context
  ctx.translate(xpos, ypos);
  ctx.rotate(47 * Math.PI / 180); // rotate by 47 degrees and convert to radians
  ctx.translate(xpos, ypos);
  ctx.drawImage(myImage, xpos myImage.width / 2, ypos – myImage.height / 2);
  ctx.restore(); // restore the previous state of the canvas context
}
myImage.src = ‘image.png’;

The commented code should be pretty self explanatory but there are two out of the ordinary calls I would like to mention. The .save() and the .restore() are very useful because this is how we keep the canvas rotation from affecting all the other things we draw on the canvas. For a simple example this may not be needed but it will be for anything more complex. But really this is all you need to rotate an object around its center.

Rotating About A Point

The second type of rotation we are going to look at is rotating an object around a point in space (not the object’s center). This is a more complicated way to rotate objects. Now, you might be thinking why would I want to do this? Well, the common use case is when you want an object to rotate around another object. Take a look at the diagram below and I’ll go over some of the concepts. You’ll also notice we swapped out our big gorilla pic for a smaller one – makes the rotation easier to see.

As you can see above we are going to be interested in two points, the rotation point and the object’s center. The other value that we are interested in is the distance between the two points, the marked radius. The radius is used to update the actual draw position of the image. Alright, enough chatter let’s jump into some code.

// regular rotation about point
myImage = new Image();
myImage.onload = function() {
  // regular rotation about a point
  var angle = 124 * Math.PI / 180; // 124 degrees angle of rotation in radians
  var rx = 300, ry = 200; // the rotation x and y
  var px = 300, py = 50; // the objects center x and y
  var radius = ry py; // the difference in y positions or the radius
  var dx = rx + radius * Math.sin(angle); // the draw x
  var dy = ry radius * Math.cos(angle); // the draw y

  ctx.save();
  ctx.translate(dx, dy);
  ctx.rotate(angle);
  ctx.translate(dx, dy);
  ctx.drawImage(myImage, dx myImage.width / 2, dy – myImage.height / 2);
  ctx.restore();
}
myImage.src = ‘smallimage.png’;

So, what do we have going on up there? Well we first calculate the rotation angle in radians, then define some variables to hold the rotation point and the position of the object at 0 degrees. After that we figure out the radius. Next we figure out where the object should be drawn with some very basic triangle math. This point will also be where we translate to because we want to rotate the object like we did in the last example but draw it in the correct spot. The actual drawing code should be familiar from the first part of the tutorial. All this results in something that looks like the below image – minus the annotations.

That pretty much wraps it up for this tutorial. If you have any problems or questions feel free to leave a comment below. And keep an eye out for upcoming canvas tutorials.

Want to learn more? Check out these great HTML 5 Canvas books:

HTML 5 Canvas Tutorial – Displaying Images

The Canvas element was introduced a few years ago as part of the HTML 5 standard. This element has opened the doors to incredibly dynamic web applications that in the past were only possible using 3rd party plugins like Flash or Java. This tutorial covers a small but important piece of the canvas element – displaying and manipulating images.

Image Source

The most common way to draw images to a canvas element is to use a Javascript Image object. Which image formats are supported is dependent on the browser, however the typical formats (png, jpg, gif, etc) have very good cross-browser support.

The image can either be grabbed from an existing element already in the DOM or a new one can be constructed on demand.

// Grab an image that’s already on the page.
var myImage = document.getElementById(‘myimageid’);

// or create a new image.
myImage = new Image();
myImage.src = ‘image.png’;

In the current version of most canvas-supported browsers, drawing an image that hasn’t been fully loaded simply doesn’t do anything. This means, however, that if you want the image to show up, you must wait for it to be loaded before drawing it. This can be done by using the Image object’s onload function.

// Create an image.
myImage = new Image();
myImage.onload = function() {
  // Draw image.
}
myImage.src = ‘image.png’;

For the rest of my examples, the source image I’ll be using is the following 256×256 gorilla.

Gorilla source image

Basic Drawing

For the most basic form of drawing images, all that’s required is the position (x and y coordinates) of where you’d like to put the image. Images are positioned relative to their top-left corners. With this technique, images are simply displayed at their original size.

drawImage(image, x, y)
var canvas = document.getElementById(‘myCanvas’);
var ctx = canvas.getContext(‘2d’);

ctx.drawImage(myImage, 50, 50);
ctx.drawImage(myImage, 125, 125);
ctx.drawImage(myImage, 210, 210);

Basic Canvas Image Output

Resizing and Scaling

To change the size of the image, an overloaded version of drawImage is used that accepts the desired width and height.

drawImage(image, x, y, width, height)
var canvas = document.getElementById(‘myCanvas’);
var ctx = canvas.getContext(‘2d’);

ctx.drawImage(myImage, 50, 50, 100, 100);
ctx.drawImage(myImage, 125, 125, 200, 50);
ctx.drawImage(myImage, 210, 210, 500, 500);

This example demonstrates drawing an image smaller than the source, stretched to a different aspect ratio, and blown up larger than the source.

Canvas Scaled Images

Slice and Crop

The last variant of drawImage allows you to take a slice out of (or crop) the source image.

drawImage(image,
  sourceX,
  sourceY,
  sourceWidth,
  sourceHeight,
  destX,
  destY,
  destWidth,
  destHeight)

There’s a lot of parameters there, but basically you’re taking a rectangle out of the source image and drawing that rectangle into a destination rectangle somewhere on the canvas.

Canvas Slice Example
var canvas = document.getElementById(‘myCanvas’);
var ctx = canvas.getContext(‘2d’);

ctx.drawImage(myImage, 0, 0, 50, 50, 25, 25, 100, 100);
ctx.drawImage(myImage, 125, 125, 100, 100, 125, 125, 150, 150);
ctx.drawImage(myImage, 80, 80, 100, 100, 250, 250, 220, 220);

Canvas Slices

That does it for all the basic ways to draw and manipulate images using the HTML 5 canvas. Drawing images is a small part of what the canvas provides, and we’ll be posting more tutorials in the future that covers more of this element and its features. If you’ve got any questions or comments, feel free to leave them below.

Want to learn more? Check out these great HTML 5 Canvas books:

Book Review – iOS Programming, The Big Nerd Ranch Guide, 2nd Edition

It’s been a while since we’ve done a book review, and it’s time to rectify that. In this installment I’ll be reviewing The Big Nerd Ranch’s Guide to iOS Programming (2nd Edition). The Big Nerd Ranch has created a series of books around Mac, iOS, and Objective-C programming. This book is the latest in that series.

First off, here’s our standard disclaimer: I did receive this book free of charge from the publisher for review purposes. A free book does not equal a good review. I will provide honest opinions even if that means I never receive another book again. Now that that’s out of the way, let’s dive in.

iOS Programming, The Big Nerd Rance Guide, 2nd Edition
by Joe Conway and Aaron Hillegass
Publisher: Pearson Education
Pub. Date: Jun 22, 2011
ISBN-13: 978-0-321-77377-7
Pages: 590
List Price: $49.99
Buy it on Amazon

The first question you’re going to ask is, “does it include iOS 5 stuff?” The answer is, unfortunately, no. The flip-side to this is that Apple has been extremely good about providing a consistent and backwards compatible API, which means this book is still nearly 100% relevant. iOS 5, while it does add functionality, is by no means required to create awesome applications.

Right off the bat I found that the book was organized, not badly, but oddly. The very first chapter walks the reader through creating an iOS application. I think a novice developer may be overwhelmed by this – especially since a lot of explanation is intentionally deferred to later chapters. I can’t fault the author too much for this, since it’s clearly stated the intended audience does not include new developers – some amount of programming experience is required.

If you have programming experience, however, you’ll most likely find the first few chapters tedious. The amount of explanations and the use of metaphors is much more tailored to a novice developer. Fortunately this ends quickly in the later chapters, where the code-to-words ratio increases to a much more comfortable level.

The author makes excellent and frequent use of diagrams. I particularly liked Figure 7.16 – “Lifecycle of a view controller” – which nicely chronicles how a view is created, displayed, and removed – evening including what happens on memory warnings.

One thing I want to make perfectly clear is that this book is exhaustive. I think the only thing not covered by this book is OpenGL-ES, but doing so would easily make the book twice as large. If you want to create an application, chances are this book covers every piece of Cocoa Touch you’re likely to use.

We don’t score books on a scale or letter grade, we like to indicate which group of developer would benefit the most from the book. That being said, this book fits squarely in the intermediate category. Someone new to programming will not be able to effectively use this book. As for seasoned developers, I found the shear amount of words made using the book as a reference not as easy as I’d like. It was difficult to flip to a topic and quickly extract usage or syntax. I think, however, that intermediate developers is exactly what the authors were going for, and I think they excelled greatly in that respect.

Beginners: Probably Not
This is a good book, so I’m not going to outright not recommend it for beginners, but it may be hard to follow.

Intermediate: Absolutely
If you’re a programmer entering iOS or have already dabbled, this book will be a great introductory resource.

Guru: Maybe
Even if you’ve been programming iOS for years, there’s still knowledge in the book worth having. You may not want to take the time to find it, though.

Other books in the Big Nerd Ranch Guide Library:

Drop & Lock!

A few weeks ago, we here at Paranoid Ferret released a physics based puzzle game named Drop & Lock. It is not only fun, but extremely addicting. We would just like to take a quick break and tell (and show) you all the cool things that this new iPhone puzzler has to offer.

Drop & Lock takes you into a world of colored hexes and flying balls, all slammed together in a wild puzzle were your gamer hands are the key to everything. The idea is to take the balls and match them up with hexes of the same color…all before the ball’s timer runs out and turns it into a static piece of the hex collection. But, enough long winded explanations, here are a few highlights, including the Switch on The Code level!

Yes, Switch On The Code has it’s very own level, no programming required!

Everyone’s favorite level.

Special balls can either help you or hurt you…and some are just plain annoying.

You can find out more here, or you can just check out the app store and download it for yourself.