<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Christopher Bennage : javascript</title><link>http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx</link><description>Tags: javascript</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Building a Game With JavaScript: Making Things Move</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2013/03/13/building-a-game-with-javascript-making-things-move.aspx</link><pubDate>Wed, 13 Mar 2013 16:36:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:99712</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;&lt;i&gt;This is a continuation from the &lt;a href="http://dev.bennage.com/blog/2013/01/11/game-dev-02/" target="_blank"&gt;previous post&lt;/a&gt;.&lt;/i&gt;&lt;/p&gt;
&lt;h2&gt;Setting The Stage&lt;/h2&gt;

&lt;p&gt;The game we’re building will have waves of enemy ships fly in to attack the player’s units. Let’s begin by making a simple enemy as well as some dummy targets for them to attack. I’m going to keep the graphics very simple for the moment. Likewise we are going to focus on the enemy behavior and not worry about any player interaction just yet.&lt;/p&gt;

&lt;p&gt;&lt;img style="cursor:default;" class="right" src="http://dev.bennage.com/images/posts/game-dev-move-01.png" title="[little, yellow, different]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;Here’s a &lt;a href="http://jsfiddle.net/bennage/HqYeD/18/"&gt;demo&lt;/a&gt; of what we’ll make. Click on the start screen to transition into the game. The little yellow rectangles are our enemy ships. Each one projects its own target as a little red circle. Once it touches its target, it projects a new one and then flies toward it.&lt;/p&gt;

&lt;p&gt;Let’s start from the top down. Our enemy units will “live” in our main screen for the game. (At least for the time being.) This screen needs to expose the same interface that we had for the start screen we made in the last post. We’ll also add a &lt;code&gt;start&lt;/code&gt; method that we’ll call just once in order to initialize things.&lt;/p&gt;
&lt;h3&gt;Implementation&lt;/h3&gt;

&lt;p&gt;Here’s the implementation:&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;  var mainGameScreen = (function () {
    
        // the set of entities we&amp;#39;re updating and rendering
    var entities = [];
    // how many enemy ships do we want to start with
    var numOfEnemyShips = 12;
    
    // intitalize the screen, expected to be called
    // once when transitioning to the screen
    function start() {
        for (var i = 0; i &amp;lt;= numOfEnemyShips; i++) {
            // the numbers passed into `makeEnemyShip` could be anything 
            // they don&amp;#39;t need to be derived from `i`
            entities.push(makeEnemyShip(i * 10, i));
        }
    }

    // drawing the screen means drawing each of its constituents
    function draw(ctx) {
        // first, clean the canvas
        ctx.fillStyle = &amp;#39;black&amp;#39;;
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        // delegate the drawing of each entity to itself
        // note the difference in the way the for loop is set up
        var entityIndex = entities.length - 1;
        for (; entityIndex != 0; entityIndex--) {
            entities[entityIndex].draw(ctx);
        }
    }

    // much like draw, we update each of the screen&amp;#39;s constituents
    function update(elapsed) {
        var entityIndex = entities.length - 1;
        for (; entityIndex != 0; entityIndex--) {
            entities[entityIndex].update(elapsed);
        }
    }

    // this is the object that will be the main screen
    return {
        draw: draw,
        update: update,
        start: start
    };
}());&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;h3&gt;Explanation&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;entities&lt;/code&gt; array will contain a list of the enemies we’re tracking. I used the name “entity” because this is a common term in game development. In general, it means something that has behavior and is drawn to the screen. Thus, you can expect entities to have &lt;code&gt;update&lt;/code&gt; and &lt;code&gt;draw&lt;/code&gt; methods. This is not a hard and fast definition though. You’ll find that the specifics of the definition can vary among engines, frameworks, and developers.&lt;/p&gt;

&lt;p&gt;In our &lt;code&gt;start&lt;/code&gt; function we populate &lt;code&gt;entities&lt;/code&gt; by invoking our (as yet undefined) &lt;code&gt;makeEnemyShip&lt;/code&gt; function. I’m passing in two numbers that &lt;code&gt;makeEnemyShip&lt;/code&gt; will use to set the x and y position of the ship. I could have used random numbers or even hard coded values, however deriving from the loop’s controls makes it easy to cluster all the ships in the upper left corner of the screen.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;draw&lt;/code&gt; and &lt;code&gt;update&lt;/code&gt; functions for the screen are very similar. They both iterate over &lt;code&gt;entities&lt;/code&gt; and invoke the corresponding function on each entity. They also pass along the necessary context. For &lt;code&gt;draw&lt;/code&gt;, this is the 2D drawing context of the canvas and for &lt;code&gt;update&lt;/code&gt; it’s the elapsed time since the last frame.&lt;/p&gt;

&lt;p&gt;Notice how the loop is structured differently from the loop in &lt;code&gt;start&lt;/code&gt;. This is a performance optimization; though it has little consequence with so small an array. On some browsers, the call to &lt;code&gt;length&lt;/code&gt; is a bit expensive. (Especially in cases when the array isn’t an array, but something that is &lt;a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177"&gt;array-like&lt;/a&gt;.) This adds up when you make the call once per iteration of the loop. We move it out of the loop so that we only call it once. Check out &lt;a href="http://jsperf.com/loop-iteration-length-comparison-variations"&gt;this test&lt;/a&gt;. Performance optimizations are tricky and change every time new browsers are released. It’s easy to get confused, and I recommend profiling your code frequently to look for hot spots rather than just guessing about optimizations. I hope to talk more about them later, but if you want more now check out the book &lt;a href="http://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X"&gt;High Performance JavaScript&lt;/a&gt; by &lt;a href="http://www.nczonline.net/"&gt; Nicholas C. Zakas&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I had originally written my loops using the newer &lt;a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach"&gt;Array.forEach&lt;/a&gt; to iterate over &lt;code&gt;entities&lt;/code&gt;. However, this proved to be &lt;strong&gt;significantly&lt;/strong&gt; slower than a &lt;code&gt;for&lt;/code&gt; loop.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The screen’s &lt;code&gt;draw&lt;/code&gt; method also resets the canvas at the beginning of each iteration. If we did not do this, then every thing we drew on previous frames would still be present. For the start screen, I used &lt;code&gt;clearRect&lt;/code&gt; however here I used &lt;code&gt;fillRect&lt;/code&gt; with a solid color.&lt;/p&gt;

&lt;p&gt;Here’s a function that will produce a simple enemy. It follows the same structure we’ve been using, &lt;code&gt;update&lt;/code&gt; to handle the behavior and &lt;code&gt;draw&lt;/code&gt; to actually draw it on the screen.&lt;/p&gt;
&lt;h2&gt;Some Bad Guys&lt;/h2&gt;

&lt;p&gt;Our enemy ships are a little more complicated than the screen they live on. Visually, they &lt;em&gt;appear&lt;/em&gt; to have two components. The little yellow rectangle that moves about the screen and the phantom target that they project as a little red circle. In the final game, they will target one of the player’s units. However, the logic is very similar. In fact, it may become useful in debugging to how each enemy ship render something over it’s actual target.&lt;/p&gt;
&lt;h3&gt;Implementation&lt;/h3&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;// alias (and pre-compute) the angle of 
// a full circle (360°, but in radians)
var fullCircle = Math.PI * 2;

// invoke this function to create an emeny ship entity
// to add to the main game screen
function makeEnemyShip(x, y) {
    
    // position is set based upon the values
    // provided to the function
    var position = {
        x: x,
        y: y
    };
    // the diretion the ship is facing
    var orientation = 0;

    // how quickly can the ship turn?
    var turnSpeed = fullCircle / 50;
    // how quickly can the ship move?
    var speed = 2;
    
    // the phantom target the ship
    // is pursing
    var target = findNewTarget();    

    // the function invoked from the screen&amp;#39;s update
    function update(elapsed) {
        // determine how close we are to our target
        var y = target.y - position.y;
        var x = target.x - position.x;
        var d2 = Math.pow(x, 2) + Math.pow(y, 2);
        if (d2 &amp;lt; 16) {
            // we&amp;#39;ve essentially &amp;quot;touched&amp;quot; it,
            // so create a new target
            target = findNewTarget();
        } else {

            // what&amp;#39;s the different between our orientation
            // and the angle we want to face in order to 
            // move directly at our target
            var angle = Math.atan2(y, x);
            var delta = angle - orientation;
            var delta_abs = Math.abs(delta);

            // if the different is more than 180°, convert
            // the angle a corresponding negative value
            if (delta_abs &amp;gt; Math.PI) {
                delta = delta_abs - fullCircle;
            }

            // if the angle is already correct,
            // don&amp;#39;t bother adjusting
            if (delta !== 0) {
                // do we turn left or right?
                var direction = delta / delta_abs;
                // update our orientation
                orientation += (direction * Math.min(turnSpeed, delta_abs));
            }
            // constrain orientation to reasonable bounds
            orientation %= fullCircle;

            // use orientation and speed to update our position
            position.x += Math.cos(orientation) * speed;
            position.y += Math.sin(orientation) * speed;
        }

    }
    
    // the function invoked from the screen&amp;#39;s draw
    function draw(ctx) {
        
        // save the context&amp;#39;s state before we translate
        // and rotate
        ctx.save();

        // translate to the entity&amp;#39;s position
        ctx.translate(position.x, position.y);
        // rotate the canvas according to the 
        // entity&amp;#39;s orientation
        ctx.rotate(orientation);
        
        // now we begin the actual drawing
        ctx.fillStyle = &amp;#39;yellow&amp;#39;;
        // using negative number to center 
        // around the translated origin
        ctx.fillRect(-3, -1, 6, 2);
        // restore the canvas since we&amp;#39;re 
        // done drawing the entity 
        ctx.restore();

        // now we draw the phantom target
        // though we&amp;#39;ll do so without translating
        // since it&amp;#39;s so simle to draw
        ctx.beginPath();
        ctx.fillStyle = &amp;#39;rgba(255,0,0,0.5)&amp;#39;;
        ctx.arc(target.x, target.y, 2, 0, Math.PI * 2, true);
        ctx.fill();
    }

    // create a random x,y within the bounds of the canvas
    // note, we&amp;#39;ve hard coded the bounds
    function findNewTarget() {
        var target = {
            x: Math.round(Math.random() * 600),
            y: Math.round(Math.random() * 300)
        };

        return target;
    }

    // return an instance of the enemy,
    // it&amp;#39;s state is captured in the closure
    // of the functions
    return {
        draw: draw,
        update: update
    }
}&lt;/pre&gt;&lt;h3&gt;&lt;/h3&gt;&lt;h3&gt;Explanation&lt;/h3&gt;

&lt;p&gt;Each enemy ship will be responsible for tracking its own state. In this code, the state is captured in a closure. In later code, we’ll track the track in a more traditional way. (I haven’t ran tests yet but I think that using a closure may have a performance impact.)&lt;/p&gt;

&lt;p&gt;All of these variables represent the enemy ship’s state.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;var position = { x: 0, y: 0 };
var orientation = 0;
var turnSpeed = fullCircle / 50;
var speed = 2;
var target = findNewTarget();  
&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;position&lt;/code&gt; is the location on the screen where we will render our ship.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Technically, the is the position in “world space”. World space is the logical space that entities in your game “live in”. This is distinct from “screen space”, which corresponds to the actual pixels on the screens. You can think of it this way: in your game you might have a circle with a radius of 10 and located at (100,100). However, where you draw it on the screen will depend upon where the player is viewing it from. If the player zooms in, the circle will grow larger but this doesn’t change the logical position or radius of the circle. We use the term “projection” to describe this. We project from world space into screen space based upon how the player is viewing the game world. The simplest project of course is just 1:1. Which means that there is no difference between world space and screen space. That’s what will stick with for the moment.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;orientation&lt;/code&gt; is the direction the ship is currently facing. Our ship will always travel in the direction of its orientation. This constraints causes the ship travel in smooth arcs as opposed to abruptly changing its course.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;turnSpeed&lt;/code&gt; and &lt;code&gt;speed&lt;/code&gt; represent how quickly the ship can turn and how fast it can travel respectively. We won’t be modifying these values after setting them, which means the ship will turn and travel at constant rates. These values represent the rates of change for &lt;code&gt;orientation&lt;/code&gt; and &lt;code&gt;position&lt;/code&gt;. Note also, we defined &lt;code&gt;turnSpeed&lt;/code&gt; in terms of &lt;code&gt;fullCircle&lt;/code&gt;. This is an alias for &lt;code&gt;Math.PI * 2&lt;/code&gt;; we are dealing in &lt;a href="http://en.wikipedia.org/wiki/Radian"&gt;radians&lt;/a&gt; and not degrees.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;target&lt;/code&gt; is a value with the shape &lt;code&gt;{ x: Number, y: Number }&lt;/code&gt;. The ship will always attempt to move towards this value by adjusting its &lt;code&gt;orientation&lt;/code&gt;.&lt;/p&gt;
&lt;h4&gt;Update&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;update&lt;/code&gt; function is the real meat of the enemy ship. First, we check to see if we are close to our target. If we are close enough, we consider our goal accomplished and we set a new target. Otherwise, we change our &lt;code&gt;orientation&lt;/code&gt; so that we are flying toward our current target.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;var y = target.y - position.y;
var x = target.x - position.x;
var d2 = Math.pow(x, 2) + Math.pow(y, 2);&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
 
&lt;p&gt;&lt;img style="cursor:default;" class="right" src="http://dev.bennage.com/images/posts/game-dev-move-02.png" title="[calculating the distance]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;Here, &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; are really the distance between &lt;code&gt;target&lt;/code&gt; and &lt;code&gt;position&lt;/code&gt; along the respective axises. We want to know these values in order to calculate the distance between them. In general, you use the &lt;a href="http://en.wikipedia.org/wiki/Pythagorean_theorem"&gt;Pythagorean theorum&lt;/a&gt; to calculate distance. &lt;em&gt;For deeper dive into the math, watch &lt;a href="http://www.khanacademy.org/video/distance-formula"&gt;Distance Formula&lt;/a&gt; on Khan Academy.&lt;/em&gt; Finding the actual real distance uses a square root and calculating a square root is an expensive operation that’s best to avoid whenever you can.&lt;/p&gt;

&lt;p&gt;We can bypass the need by working with the distance² (hence the variable name &lt;code&gt;d2&lt;/code&gt;). We compare this against the hard-coded value of 16 (that’s 4²). In other words, if the distance between the ship and its target is less than 4 units we find a new target.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;if (d2 &amp;lt; 16) {
    target = findNewTarget();
}&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
 
&lt;p&gt;Once we’ve established what the ship’s target should be, we want the ship to move toward the target. As I’ve just mentioned, I’ve chosen to have the ship move at a constant speed. This means that it does not slow down or speed up. The only thing it can do is to change the direction it’s facing (&lt;code&gt;orientation&lt;/code&gt;). These sort of constraints determine the personality and character of your game. Bear in mind, you don’t need to simulate the physics to have a fun game. Instead, you need to establish behaviors for your game entities that are merely fun. Fortunately, fun behaviors can often be easier to implement that the actual physics. I recommend taking a look at &lt;a href="http://jsfiddle.net/bennage/HqYeD/18/"&gt;the demo&lt;/a&gt; and tweaking the &lt;code&gt;turnSpeed&lt;/code&gt; and &lt;code&gt;speed&lt;/code&gt; values to get a small taste for how the behavior can affect the game’s character.&lt;/p&gt;

&lt;p&gt;&lt;img style="cursor:default;width:336px;height:252px;" class="right" src="http://dev.bennage.com/images/posts/game-dev-move-03.png" title="[what&amp;#39;s the delta between the angles?]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;In order to change the ship’s orientation we need to first determine where the ship &lt;em&gt;ought&lt;/em&gt; to be facing. The values of &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; we just calculated can be interpreted as a &lt;a href="http://en.wikipedia.org/wiki/Euclidean_vector"&gt;vector&lt;/a&gt;. Meaning, it represents the direction and distance (magnitude) from the ship to the current target. To extract the actual angle (in radian) we use &lt;code&gt;Math.atan2(x,y)&lt;/code&gt;.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;var angle = Math.atan2(y, x);
var delta = angle - orientation;&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;So now we have the direction the ship &lt;em&gt;wants&lt;/em&gt; to face, &lt;code&gt;angle&lt;/code&gt;, and the direction that it &lt;em&gt;is&lt;/em&gt; facing, &lt;code&gt;orientation&lt;/code&gt;. We calculate the difference between them and store it as &lt;code&gt;delta&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img style="cursor:default;" class="right" src="http://dev.bennage.com/images/posts/game-dev-move-04.png" title="[turning the wrong way]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;The basic idea is that add the value of &lt;code&gt;turnSpeed&lt;/code&gt; to &lt;code&gt;orientation&lt;/code&gt; once each invocation of &lt;code&gt;udpate&lt;/code&gt; until &lt;code&gt;delta&lt;/code&gt; is 0 (meaning that the ship is flying directly at the target). However, some values of &lt;code&gt;delta&lt;/code&gt; will cause the ship to “turn the wrong way”. For example, imagine that the ship is facing the top of the screen and that we’ve defined that as &lt;code&gt;orientation === 0&lt;/code&gt;. Now, imagine that the target is directly to its right. The value of &lt;code&gt;angle&lt;/code&gt; would be π/2 (or 90°). Adding &lt;code&gt;turnSpeed&lt;/code&gt; to &lt;code&gt;orientation&lt;/code&gt; each frame increments the value from 0 to π/2. However, if the target is directly to the left, then the value of &lt;code&gt;angle&lt;/code&gt; would be 3π/2 (or 270°). Simply incrementing &lt;code&gt;orientation&lt;/code&gt; would cause the ship to turn right and keep turning right. This is unintuitive behavior; we expect the ship to turn the shorted distance. In order to accomplish this, we translate any value of &lt;code&gt;delta&lt;/code&gt; higher than π (180°) by subtracting &lt;code&gt;fullCircle&lt;/code&gt;. This normalizes the value of &lt;code&gt;delta&lt;/code&gt; between -π and π (or between -180° and 180°).&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;var delta_abs = Math.abs(delta);
if (delta_abs &amp;gt; Math.PI) {
    delta = delta_abs - fullCircle;
}
&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
 
&lt;p&gt;We take the absolute value of &lt;code&gt;delta&lt;/code&gt; because otherwise we’d have to check for &lt;code&gt;delta &amp;lt; -Math.PI&lt;/code&gt; as well. Also, we’ll use &lt;code&gt;delta_abs&lt;/code&gt; again.&lt;/p&gt;

&lt;p&gt;If &lt;code&gt;delta&lt;/code&gt; is 0, we don’t need to change &lt;code&gt;orientation&lt;/code&gt;. When it is different we need to modify the value of &lt;code&gt;orientation&lt;/code&gt;.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;if (delta !== 0) {
    var direction = delta / delta_abs;
    orientation += (direction * Math.min(turnSpeed, delta_abs));
    orientation %= fullCircle;
}
&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
 
&lt;p&gt;First, we decide &lt;em&gt;how much&lt;/em&gt; to change it using &lt;code&gt;Math.min(turnSpeed, delta_abs)&lt;/code&gt;. We could just use &lt;code&gt;turnSpeed&lt;/code&gt;. However if we did it’s likely that &lt;code&gt;delta&lt;/code&gt; would never quite be 0 and (depending on the size of &lt;code&gt;turnSpeed&lt;/code&gt;) it could result is jittery motion. Secondly, we want to decided which &lt;em&gt;direction&lt;/em&gt; to turn: positive values to the right and negative values to the left. We multiply the amount &lt;code&gt;direction&lt;/code&gt; to change the sign, because &lt;code&gt;direction&lt;/code&gt; will only ever be 1 or -1. Finally, we modulo &lt;code&gt;orientation&lt;/code&gt; to ensure that it stays within a range of -2π to 2π. Otherwise, the calculation of &lt;code&gt;delta&lt;/code&gt; would be off.&lt;/p&gt;

&lt;p&gt;Our last step in &lt;code&gt;update&lt;/code&gt; is to modifiy the actual position using the latest &lt;code&gt;orientation&lt;/code&gt; and &lt;code&gt;speed&lt;/code&gt;.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;position.x += Math.cos(orientation) * speed;
position.y += Math.sin(orientation) * speed;
&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;Some basic trigonometry is fairly fundamental for most game development. If you’re mathematically lost at this point, I recommend &lt;a href="https://www.khanacademy.org/math/trigonometry/basic-trigonometry"&gt;reviewing over at Khan Academey&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here’s the geometric interpretation of the code. We want the ship to move a distance of &lt;code&gt;speed&lt;/code&gt; in the direction of &lt;code&gt;orientation&lt;/code&gt;. To do this, we need to project this vector (distance and direction) on the x and y axises. Since the distance is the length of the hypothenuse of right triangle, cosine gives us the x part and sine gives us the y part. We can then add these values to the current position.&lt;/p&gt;
&lt;h4&gt;Draw&lt;/h4&gt;

&lt;p&gt;Drawing the ship to the screen is a bit easier to follow. Here’s the flow of the logic:&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;Save the state of the drawing context.&lt;/li&gt;
    &lt;li&gt;Transform the context to make it easier to draw our ship.&lt;/li&gt;
    &lt;li&gt;Draw the ship.&lt;/li&gt;
    &lt;li&gt;Restore the context back to its original state.&lt;/li&gt;
    &lt;li&gt;
&lt;p&gt;Draw the target&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;  function draw(ctx) {

      ctx.save();

      ctx.translate(position.x, position.y);
      ctx.rotate(orientation);

      ctx.fillStyle = &amp;#39;yellow&amp;#39;;
      ctx.fillRect(-3, -1, 6, 2);

      ctx.restore();

      ctx.beginPath();
      ctx.fillStyle = &amp;#39;rgba(255,0,0,0.5)&amp;#39;;
      ctx.arc(target.x, target.y, 2, 0, Math.PI * 2, true);
      ctx.fill();
  }&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Recall that &lt;code&gt;ctx&lt;/code&gt; is the drawing context for the canvas. The context provide a useful API that allows us to move it around before we draw on it. This is analgous to having a sheet of paper that you might shift and rotate in order to make it easier to draw something complicated. This is the purpose of the &lt;code&gt;translate&lt;/code&gt; and &lt;code&gt;rotate&lt;/code&gt; methods.&lt;/p&gt;

&lt;p&gt;First, we use ‘save’ to establishing a checkpoint for the drawing context that we can easily revert back to using ‘restore.’ The calls to &lt;code&gt;translate&lt;/code&gt; and &lt;code&gt;rotate&lt;/code&gt; modify the state of the drawing context. This modified state is very specific to the drawing of our enemy ship. If we didn’t translate and rotate the canvas, we’d have to do a lot more work to figure out where to draw the four corners of the rectangle.&lt;/p&gt;

&lt;p&gt;I decided that I want my ship to be 6px long and 2px wide. Since I want the middle of the middle of my ship to be the point where it rotates, I shift by half the length and half the width. Hence, the values passed to &lt;code&gt;ctx.fillRect(-3, -1, 6, 2)&lt;/code&gt;. This point the new origin (0,0) at the middle of the rectangle, and it makes our call to &lt;code&gt;rotate&lt;/code&gt; behave intuitively. If we used &lt;code&gt;ctx.fillRect(0, 0, 6, 2)&lt;/code&gt; instead, then the ship would appear to rotate around its upper left corner. We’ll use these same techniques once we switch to using &lt;em&gt;sprites&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;After we restore the context’s state, we draw the target. We don’t bother using &lt;code&gt;rotate&lt;/code&gt; because it’s meaningless to rotate a simple circle. Likewise, we don’t bother &lt;code&gt;translate&lt;/code&gt; since the drawing logic is so simple.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The canvas is a broad topic in itself. I recommend taking a look at the tutorials over at &lt;a href="https://developer.mozilla.org/en-US/docs/HTML/Canvas"&gt;MDN&lt;/a&gt;. A handy reference for the APIs themselves can be found on &lt;a href="http://msdn.microsoft.com/en-us/library/ff975057"&gt;MSDN&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2013/03/05/game-dev-03/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=99712" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Game+Development/default.aspx">Game Development</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx">HTML</category></item><item><title>Building a Game With JavaScript: Start Screen</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2013/01/14/building-a-game-with-javascript-start-screen.aspx</link><pubDate>Mon, 14 Jan 2013 19:58:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70774</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;&lt;em&gt;This is a continuation from the &lt;a href="http://dev.bennage.com/blog/2012/12/07/game-dev-01/"&gt;previous post&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Specification&lt;/h2&gt;

&lt;p&gt;Many games have a start screen or main menu of some sort. (Though I love games like &lt;a href="http://www.braid-game.com/"&gt;Braid&lt;/a&gt; that bypass the whole notion.) Let&amp;#8217;s begin by designing our start screen.&lt;/p&gt;

&lt;p&gt;&lt;img class="right" src="http://dev.bennage.com/images/posts/game-dev-startscreen-01.png" title="[our simple start screen]" style="width:600px;" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;We&amp;#8217;ll have a solid color background. Perhaps the ever lovely cornflower blue. Then we&amp;#8217;ll draw the name of our game and provide an instruction to the player. In order to make sure we have the player&amp;#8217;s attention, we&amp;#8217;ll animate the color of the instruction. It will morph from black to red and back again.&lt;/p&gt;

&lt;p&gt;Finally, when the player clicks the screen we&amp;#8217;ll transition to the main game. Or at least we&amp;#8217;ll stub out the transition.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s a &lt;a href="http://jsfiddle.net/bennage/HqYeD/2/"&gt;demo&lt;/a&gt; based on the code we&amp;#8217;ll cover later in this post (as well as that from the previous post.)&lt;/p&gt;

&lt;h2&gt;Implementation&lt;/h2&gt;

&lt;p&gt;Here&amp;#8217;s the code to implement our start screen.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://gist.github.com/4371311#file-startscreen-js"&gt;(Go look at the Gist.)&lt;/a&gt;&lt;/p&gt;


&lt;h2&gt;Explanation&lt;/h2&gt;

&lt;p&gt;Recall that our start screen is meant to be invoked by our game loop. The game loop doesn&amp;#8217;t know about the specifics of the start screen, but it does expect it to have a &lt;em&gt;certain shape&lt;/em&gt;. This enables us to swap out screen objects without having to modify the game loop itself. The shape that the game loop expects is this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
    update: function(timeElapsedSinceLastFrame) { },
    draw: function(drawingContext) { }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Update&lt;/h3&gt;

&lt;p&gt;Let&amp;#8217;s begin with the start screen&amp;#8217;s &lt;code&gt;update&lt;/code&gt; function. The first bit of logic is this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;hue += 1 * direction;
if (hue &amp;gt; 255) direction = -1;
if (hue &amp;lt; 0) direction = 1;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Perhaps &lt;code&gt;hue&lt;/code&gt; is not the best choice of variable names. It represents the red component for an &lt;a href="http://en.wikipedia.org/wiki/RGB_color_model"&gt;RGB color&lt;/a&gt; value. The range of values for this component is &lt;code&gt;0&lt;/code&gt; (no red) to &lt;code&gt;255&lt;/code&gt; (all the reds!). On each iteration of our loop we &amp;#8220;move&amp;#8221; the hue towards either the red or black.&lt;/p&gt;

&lt;p&gt;The variable &lt;code&gt;direction&lt;/code&gt; can be either &lt;code&gt;1&lt;/code&gt; or &lt;code&gt;-1&lt;/code&gt;. A value of &lt;code&gt;1&lt;/code&gt; means we are moving towards &lt;code&gt;255&lt;/code&gt; and a value of &lt;code&gt;-1&lt;/code&gt; means we are moving towards &lt;code&gt;0&lt;/code&gt;. When we cross a boundary, we flip the direction.&lt;/p&gt;

&lt;p&gt;Keen observers will ask why we bother with &lt;code&gt;1 * direction&lt;/code&gt;. In our current logic, it&amp;#8217;s an unnecessary step and unnecessary steps in game development are generally bad. In this case, I wanted to separate the rate of change from the direction. In order words, you could modify that expression to &lt;code&gt;2 * direction&lt;/code&gt; and the color would change twice as fast.&lt;/p&gt;

&lt;p&gt;This leads us to another important point. Our rate of change is tied to how quickly our loop iterates; most likely 60fps. However, it&amp;#8217;s not guaranteed to be 60fps and that makes this approach a dangerous practice. Once way to detach ourselves from the loop&amp;#8217;s speed would be to use the elapsed time that is being passed into our &lt;code&gt;update&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s say that we want to it to take 2 full seconds to go from red to black regardless of how often the &lt;code&gt;update&lt;/code&gt; function is called. There&amp;#8217;s a span of 256 discrete values between red and black. To make our calculations clear, let&amp;#8217;s say there are 256 units and we&amp;#8217;ll label these units &lt;strong&gt;R&lt;/strong&gt;. Also, the elapsed time will be in milliseconds (ms). For a given frame, if were are given a slice of elapsed time in ms, we&amp;#8217;ll want to calculate how many &lt;strong&gt;R&lt;/strong&gt; units to increase (or decrease) &lt;code&gt;hue&lt;/code&gt; by for that slice. Our rate of change can be defined as &lt;code&gt;256 **R** / 2000 **ms**&lt;/code&gt; or 0.128 &lt;strong&gt;R/ms&lt;/strong&gt;. (You can read that as &amp;#8220;0.128 units of red per millisecond&amp;#8221;.) This rate of change is a constant for our start screen and as such we can define it once (as opposed to calculating it inside the &lt;code&gt;update&lt;/code&gt; function).&lt;/p&gt;

&lt;p&gt;Now that we have the rate of change , we only need to multiply it by the elapsed time received in &lt;code&gt;update&lt;/code&gt; to determine how many &lt;strong&gt;R&lt;/strong&gt;s we want. A revised version of the function would look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var rate = 0.128; // R/ms

function update(elapsed) {
    var amount = rate * elapsed;
    hue += amount * direction;
    if (hue &amp;gt; 255) direction = -1;
    if (hue &amp;lt; 0) direction = 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One consequence of this change is that hue will no longer be integral values (as much as that can be said in JavaScript.) This means that we&amp;#8217;d really want to have two values for the hue: an actual value and a rounded value. This is because the RBG model requires an integral value for each color component.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function update(elapsed) {
    var amount = rate * elapsed;
    hue += amount * direction;
    if (hue &amp;gt; 255) direction = -1;
    if (hue &amp;lt; 0) direction = 1;

    rounded_hue = Math.round(hue);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Draw&lt;/h3&gt;

&lt;p&gt;Let&amp;#8217;s turn our attention to &lt;code&gt;draw&lt;/code&gt; for a moment. One of the first things you &lt;em&gt;generally&lt;/em&gt; do is to clear the entire screen. This is simple to do with the canvas API&amp;#8217;s &lt;code&gt;clearRect&lt;/code&gt; method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that &lt;code&gt;ctx&lt;/code&gt; is an instance of &lt;a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#canvasrenderingcontext2d"&gt;CanvasRenderingContext2D&lt;/a&gt; and not a &lt;a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element"&gt;HTMLCanvasElement&lt;/a&gt;. However, there is a handy back reference to the canvas element that we use to grab the actual width and height.&lt;/p&gt;

&lt;p&gt;There are other options other than clearing the entire canvas, but I&amp;#8217;m not going to address this in this post. Also, there are some performance considerations. See the article listed under references.&lt;/p&gt;

&lt;p&gt;After clearing the screen, we want to draw something new. In this case, the game title and the instructions. In both cases I want to center the text horizontally. I created a helper function that I can provide with the text to render as well as the vertical position (y).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function centerText(ctx, text, y) {
    var measurement = ctx.measureText(text);
    var x = (ctx.canvas.width - measurement.width) / 2;
    ctx.fillText(text, x, y);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;measureText&lt;/code&gt; returns the width in pixels that the rendered text will take up. We use this in combination with the canvas element&amp;#8217;s width to determine the x position for the text. &lt;code&gt;fillText&lt;/code&gt; is responsible for actually drawing the text.&lt;/p&gt;

&lt;p&gt;The rendering context &lt;code&gt;ctx&lt;/code&gt; is stateful. Meaning that, what happens when you call methods like &lt;code&gt;measureText&lt;/code&gt; or &lt;code&gt;fillText&lt;/code&gt; depends on the state of the rendering context. The state can be modified by setting its properties.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var y = ctx.canvas.height / 2;
ctx.fillStyle = &amp;#39;white&amp;#39;;
ctx.font = &amp;#39;48px monospace&amp;#39;;
centerText(ctx, &amp;#39;My Awesome Game&amp;#39;, y);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The properties &lt;code&gt;fillStyle&lt;/code&gt; and &lt;code&gt;font&lt;/code&gt; change the state of the rendering context and hence affect the methods calls inside of &lt;code&gt;centerText&lt;/code&gt;. This state applies to all future methods calls. This means that all calls to &lt;code&gt;fillText&lt;/code&gt; will use the color white until you can the &lt;code&gt;fillStyle&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Notice too that we are calculating the x and y values for the text on every frame. This is potentially wasteful since these values are unlikely to change. However, if we want to respond to changes in canvas size (or even changes to the text itself) then we&amp;#8217;d want to continue calculating these on every frame. Otherwise, if we were confident that we didn&amp;#8217;t need to do this, we could calculate these values once and cache them.&lt;/p&gt;

&lt;p&gt;Now let&amp;#8217;s use the red component calculated in &lt;code&gt;update&lt;/code&gt; to render the instructional text.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var color = &amp;#39;rgb(&amp;#39; + hue + &amp;#39;,0,0)&amp;#39;;

ctx.fillStyle = color;
ctx.font = &amp;#39;24px monospace&amp;#39;;
centerText(ctx, &amp;#39;click to begin&amp;#39;, y + 30);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;fillStyle&lt;/code&gt; can be set in a number of ways. Earlier, we used the simple value &lt;code&gt;white&lt;/code&gt;. Here were are using &lt;code&gt;rgb()&lt;/code&gt; to set the individual components explicitly. Any &lt;a href="https://developer.mozilla.org/en-US/docs/CSS/color"&gt;CSS color&lt;/a&gt; &lt;em&gt;should&lt;/em&gt; work with &lt;code&gt;fillStyle&lt;/code&gt;.  (I won&amp;#8217;t be too surprised if some don&amp;#8217;t though.)&lt;/p&gt;

&lt;p&gt;Now you might be wondering why we bothered calculating &lt;code&gt;hue&lt;/code&gt; inside &lt;code&gt;update&lt;/code&gt; since &lt;code&gt;hue&lt;/code&gt; is all about what to draw on the screen. The reason is that &lt;code&gt;draw&lt;/code&gt; is concerned with the &lt;em&gt;mechanics&lt;/em&gt; of rendering. Anything that is modeling the game state should live in &lt;code&gt;update&lt;/code&gt;. The tell in this example is that &lt;code&gt;hue&lt;/code&gt; is dependent on elapsed time and the &lt;code&gt;draw&lt;/code&gt; doesn&amp;#8217;t know anything about that.&lt;/p&gt;

&lt;h3&gt;Update (again)&lt;/h3&gt;

&lt;p&gt;Moving back to &lt;code&gt;update&lt;/code&gt;, the next bit deals with input from the player. In the sample code I&amp;#8217;ve extracted the input logic away. The key thing here is that we are not relying on events to tell us about input from the player. Instead we have some helper, &lt;code&gt;input&lt;/code&gt; in this case, that gives us the current state of the input. If event-driven logic says &amp;#8220;tell me when this happens&amp;#8221; then our game logic says &amp;#8220;tell me if this is happening now&amp;#8221;. The primary reason for this is to be deterministic. We can establish at the beginning of our &lt;code&gt;update&lt;/code&gt; what the current input state is and that it won&amp;#8217;t change before the next invocation of the function. In simple games this might be inconsequential, but in others it can be a subtle source of bugs.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var isButtonDown = input.isButtonDown();

var mouseJustClicked = !isButtonDown &amp;amp;&amp;amp; wasButtonDown;

if (mouseJustClicked &amp;amp;&amp;amp; !transitioning) {
    transitioning = true;
    // do something here to transition to the actual game
}

wasButtonDown = isButtonDown;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We only want transition when the mouse button has been released. In this case, &amp;#8220;released&amp;#8221; is defined as &amp;#8220;down on the last frame but up on this one&amp;#8221;. Hence, we need to track what the mouse button&amp;#8217;s state was on the &lt;em&gt;last&lt;/em&gt; frame. That&amp;#8217;s &lt;code&gt;wasButtonDown&lt;/code&gt; and it lives outside of &lt;code&gt;update&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Secondly, we don&amp;#8217;t want to trigger multiple transitions. That is, if our transition takes some time (perhaps due to animation) then we want to ignore subsequent clicks. We have our &lt;code&gt;transitioning&lt;/code&gt; variable outside of &lt;code&gt;update&lt;/code&gt; to track that for us.&lt;/p&gt;

&lt;p&gt;More to come&amp;#8230;&lt;/p&gt;

&lt;h2&gt;Reference&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.html5rocks.com/en/tutorials/canvas/performance/"&gt;Canvas Performace&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2013/01/11/game-dev-02/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70774" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Game+Development/default.aspx">Game Development</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx">HTML</category></item><item><title>Building a Game With JavaScript</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2012/12/10/building-a-game-with-javascript.aspx</link><pubDate>Mon, 10 Dec 2012 08:32:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70577</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;em&gt;&lt;strong&gt;update:&lt;/strong&gt; I just realized that the gist was not being rendered here. I&amp;#39;ve added the code inline.&lt;/em&gt;
&lt;div class="entry-content"&gt;&lt;p&gt;&lt;em&gt;See the &lt;a href="http://dev.bennage.com/blog/2012/12/07/a-n00bs-look-at-html5-game-development/"&gt;introduction post&lt;/a&gt; for context.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;The Loop&lt;/h2&gt;

&lt;p&gt;In general, game development begins with the game loop. If you come from the business world of software development, this will be strange. You don&amp;#8217;t rely on events. &lt;a href="http://haacked.com/"&gt;Phil Haack&lt;/a&gt; once asked me &amp;#8220;why a loop?&amp;#8221;, to which I responded &amp;#8220;uh&amp;#8230;&amp;#8221;. However, a much better answer would have been &lt;a href="http://stackoverflow.com/questions/2565677/why-is-a-main-game-loop-is-necessary-for-developing-a-game"&gt;this one on stackoverflow&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Okay, so we should use a master loop. If our runtime is the browser, how do setup this loop? There&amp;#8217;s a relatively new API called &lt;a href="http://www.w3.org/TR/animation-timing/"&gt;&lt;code&gt;requestAnimationFrame&lt;/code&gt;&lt;/a&gt; and that&amp;#8217;s what most folks recommend. Check out these for details:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://paulirish.com/2011/requestanimationframe-for-smart-animating/"&gt;Paul Irish&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://ie.microsoft.com/testdrive/Graphics/RequestAnimationFrame/Default.html"&gt;The IE Team&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;(I do recall reading something negative along the way about the API, but I couldn&amp;#8217;t find it again.)&lt;/p&gt;

&lt;p&gt;I used the &lt;code&gt;requestAnimationFrame&lt;/code&gt; &lt;a href="https://gist.github.com/1579671"&gt;shim&lt;/a&gt; referenced in the Paul Irish post above. The shim is only necessary for older browsers that have not implemented the API. &lt;em&gt;By the way, we refer to each iteration of the loop as a &amp;#8220;frame&amp;#8221; because of the analogy with traditional animation.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;Implementation&lt;/h3&gt;

&lt;p&gt;Now that we&amp;#8217;ve ensured that &lt;code&gt;requestAnimationFrame&lt;/code&gt; is present we can get to our game loop. Here is my game&amp;#8217;s bootstrap code (well, an early version of it):&lt;/p&gt;

&lt;pre&gt;
var canvas,        // the visible canvas element    
    surface,       // the 2d context of `canvas`
    currentScreen; // the currently rendered screen for the game

function beginLoop() {
    var frameId = 0;
    var lastFrame = Date.now();

    function loop() {
        var thisFrame = Date.now();

        var elapsed = thisFrame - lastFrame;

        frameId = window.requestAnimationFrame(loop);

        currentScreen.update(elapsed);
        currentScreen.draw(surface);

        lastFrame = thisFrame;
    }

    loop();
}


canvas = document.querySelector(&amp;#39;canvas#board&amp;#39;);
canvas.setAttribute(&amp;#39;width&amp;#39;, 800);
canvas.setAttribute(&amp;#39;height&amp;#39;, 600);

surface = canvas.getContext(&amp;#39;2d&amp;#39;);

currentScreen = startScreen;
beginLoop();
&lt;/pre&gt;
&lt;p&gt;The &lt;a href="https://gist.github.com/4238210"&gt;gist is also available&lt;/a&gt;.&lt;/p&gt;


&lt;p&gt;The heart of this the &lt;code&gt;loop&lt;/code&gt; function. It has the following step:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;capture the current time&lt;/li&gt;
&lt;li&gt;calculate the time that has elasped since the last frame&lt;/li&gt;
&lt;li&gt;execute the game&amp;#8217;s logic for the frame (that&amp;#8217;s the update and draw invocations)&lt;/li&gt;
&lt;li&gt;request the next invocation of &lt;code&gt;loop&lt;/code&gt; using &lt;code&gt;requestAnimationFrame&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;record the current time of the this frame for calculations in the next one&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&lt;em&gt;N.B. This code doesn&amp;#8217;t use &lt;code&gt;frameId&lt;/code&gt; yet. The idea is that this handle could be used to halt the loop.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;beginLoop&lt;/code&gt; function is there merely to provide a closure for some of the variables used to track the state of the loop. It kicks off the loop with its initial invocation of &lt;code&gt;loop&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The big mystery inside of &lt;code&gt;loop&lt;/code&gt; is the &lt;code&gt;currentScreen&lt;/code&gt; object. Here I was thinking ahead (which can be dangerous). I know that my game will have at least two &amp;#8220;screens&amp;#8221;, possibly more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;start menu screen&lt;/li&gt;
&lt;li&gt;main game screen (where the action takes place)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;I wanted the loop logic to work with both (as well as any future screens). I expect screen objects to have two methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;update&lt;/code&gt; takes the time elapsed since the last frame and is responsible for updating the state of the game.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;draw&lt;/code&gt; takes the drawing context (from the canvas) and is responsible for rendering the current state of the game.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;You&amp;#8217;ll also see that I grab a canvas element and capture its drawing context. If you are not familiar with the canvas APIs, I recommend that you &lt;a href="https://developer.mozilla.org/en-US/docs/HTML/Canvas"&gt;start here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Why two different methods for game logic?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Keeping the &lt;code&gt;update&lt;/code&gt; and &lt;code&gt;draw&lt;/code&gt; functions separate is important. When frames becomes expensive to compute, the game may respond with lag or non-deterministic behavior. Too avoid this, you might want your game to skip over some logic during a particular iteration of the loop. However, it&amp;#8217;s very likely that you &lt;em&gt;won&amp;#8217;t&lt;/em&gt; want to drop calls to &lt;code&gt;update&lt;/code&gt;. It&amp;#8217;s not necessary a big deal if you skip &lt;em&gt;rendering&lt;/em&gt; a couple of frames, however if skip calculating the location of a projectile then it might mysteriously &amp;#8220;pass through&amp;#8221; its target. This will become more relevant to us in particular, because I&amp;#8217;d like to all the player to control the speed of game (a common feature of many tower defense games).&lt;/p&gt;

&lt;p&gt;Right now &lt;code&gt;update&lt;/code&gt; and &lt;code&gt;draw&lt;/code&gt; are always called for each iteration of the loop, so the distinction is academic in this context. We could though calculate our frame rate in &lt;code&gt;loop&lt;/code&gt; and occasionally skip invoking &lt;code&gt;draw&lt;/code&gt; if the rate slowed down.&lt;/p&gt;

&lt;p&gt;Now we have enough in place to begin working on our start menu screen.&lt;/p&gt;

&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2012/12/07/game-dev-01/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70577" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Game+Development/default.aspx">Game Development</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx">HTML</category></item><item><title>a n00b’s Look at HTML5 Game Development</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2012/12/08/a-n00b-s-look-at-html5-game-development.aspx</link><pubDate>Sat, 08 Dec 2012 18:45:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70574</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;h2&gt;Preamble&lt;/h2&gt;

&lt;p&gt;Something disgusting, like six years ago, I &lt;a href="http://www.43things.com/things/view/33927/develop-a-video-game"&gt;listed on 43Things&lt;/a&gt; that I wanted to write a video game. I&amp;#8217;ve actually made numerous arrested attempts ever since I started programming with my TI-94a back in 1983. My last attempt has been much less arrested (though still incomplete).&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve learned a lot in my most recent endeavor, so it&amp;#8217;s time to share. You can follow the &lt;a href="https://github.com/bennage/sidera"&gt;actual work in progress&lt;/a&gt;, but my plan it to recreate the steps I&amp;#8217;ve gone though over the course of a few posts.&lt;/p&gt;

&lt;h2&gt;Goals&lt;/h2&gt;

&lt;p&gt;I am too ambitious. With that in mind, I created a set of constraints for making a game.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;keep gameplay simple&lt;/li&gt;
&lt;li&gt;don&amp;#8217;t worry about art (that can come later)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;I started off wanting to make a game for the Windows 8 store. I decided afterwards that I will target modern browsers in general. This means that I took no dependencies on the WinJS libraries. (Though the Windows store is still my endgame.)&lt;/p&gt;

&lt;p&gt;I also decided to &lt;em&gt;not&lt;/em&gt; use any frameworks (such as &lt;a href="http://impactjs.com/"&gt;ImpactJS&lt;/a&gt;). Not because they are bad, but because I want to learn why I need them.&lt;/p&gt;

&lt;h2&gt;Gameplay&lt;/h2&gt;

&lt;p&gt;&lt;img class="right" src="http://dev.bennage.com/images/posts/sidera-early-build.png" title="[screen capture of the current build of my game]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;This is my spec (well, more or less).&lt;/p&gt;

&lt;p&gt;I decided to make a simple &lt;a href="http://en.wikipedia.org/wiki/Tower_defense"&gt;tower defense&lt;/a&gt; game. My inspiration is &lt;a href="http://old.casualcollective.com/#games/TSG"&gt;The Space Game&lt;/a&gt; from the Casual Collective, as well as plenty of influence from StarCraft.&lt;/p&gt;

&lt;p&gt;The player will build structures in an asteroid field. Waves of enemy ships will attempt to destroy those structures. The player has to manage resources such as minerals and solar power, and fend of the attacks. Structures will cost minerals to build and require power to operate.&lt;/p&gt;

&lt;p&gt;The player can navigate the map (up, down, left, right) as well as zooming in and out. There will be a minimap.&lt;/p&gt;

&lt;p&gt;Graphics will be sprite-based. The game should be touch-friendly (really, I want touch to be primary).&lt;/p&gt;

&lt;h2&gt;Resources&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="http://buildnewgames.com/"&gt;Build New Games&lt;/a&gt;, a collaboration between Microsoft and &lt;a href="http://bocoup.com/"&gt;Bocoup&lt;/a&gt;, is an excellent set of articles on HTML/JavaScript game development.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;My friend, &lt;a href="http://mattmadegames.com/"&gt;Matt Peterson&lt;/a&gt;, currently a graduate student at &lt;a href="https://www.digipen.edu/"&gt;DigiPen&lt;/a&gt;, who&amp;#8217;s advice and guidance has been most useful.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
&lt;a href="http://dev.bennage.com/blog/2012/12/07/game-dev-01/"&gt;next »&lt;/a&gt;
&lt;/div&gt;
&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2012/12/07/a-n00bs-look-at-html5-game-development/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70574" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Game+Development/default.aspx">Game Development</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx">HTML</category></item><item><title>WinJS: Unpacking Promises</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2012/08/22/winjs-unpacking-promises.aspx</link><pubDate>Wed, 22 Aug 2012 06:15:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70289</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;N.B. &lt;em&gt;If you don’t know anything about WinJS, take a moment to peruse &lt;a href="http://dev.bennage.com/blog/2012/08/01/a-brief-introduction-to-winjs/"&gt;this primer&lt;/a&gt;. Also, the context of this post is the &lt;a href="http://hilojs.codeplex.com/"&gt;p&amp;amp;p Hilo project&lt;/a&gt;. Derick Bailey also wrote &lt;a href="http://lostechies.com/derickbailey/2012/07/19/want-to-build-win8winjs-apps-you-need-to-understand-promises/"&gt;about promises&lt;/a&gt; on his blog.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;A Bit About Promises&lt;/h2&gt;

&lt;p&gt;Promises are an abstraction for asynchronous programming. If you don’t know anything about them, I recommend that you first read &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx"&gt;asynchronous programming in JavaScript&lt;/a&gt; before you continue.&lt;/p&gt;

&lt;p&gt;A promise is an object. It is not a function and it is not the &lt;em&gt;value&lt;/em&gt; returned from the async operation. To get to the value, you need to call the &lt;code&gt;then&lt;/code&gt; method on the promise object. You pass a callback function as an argument to &lt;code&gt;then&lt;/code&gt;. The promise invokes the callback and passes the value you’re interested in into the callback. Clear as mud, right?&lt;/p&gt;

&lt;p&gt;Here’s a fictitious example that pretends like calculating a random number requires an async operation:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;getRandomNumberAsync().then(function(someNumber) { 
    // do stuff with `someNumber`
});
&lt;/pre&gt;

&lt;p&gt;The call to &lt;code&gt;then&lt;/code&gt; returns a promise itself. You could do this:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;var afterRandomNumber = getRandomNumberAsync().then(function(someNumber) { 
    // do stuff with `someNumber`
});

afterRandomNumber.then(function() {
    // more stuff
});
&lt;/pre&gt;

&lt;p&gt;Or written another way:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;getRandomNumberAsync().then(function(someNumber) { 
    // do stuff with `someNumber`
}).then(function() {
    // more stuff
});
&lt;/pre&gt;

&lt;p&gt;The two example above are the &lt;em&gt;same&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Now if our callback function returns a value, that value is passed along to the next promise’s callback.&lt;/p&gt;

&lt;pre name="code" class="js"&gt;getRandomNumberAsync().then(function(someNumber) { 
    return someNumber + 1;
}).then(function(someNumberPlusOne) {

});
&lt;/pre&gt;

&lt;p&gt;This allows you to easily chain promises, piping the output of one into the next callback in the chain.&lt;/p&gt;

&lt;pre name="code" class="js"&gt;getRandomNumberAsync().then(function(someNumber) { 
    return someNumber + 1;
}).then(function(someNumberPlusOne) {
    return someNumberPlusOne + 1;
}).then(function(someNumberPlusTwo) {

});
&lt;/pre&gt;

&lt;p&gt;Of course, this is a bit silly when then operations are not async. It’s more interesting when the thing you return from the callback is also a promise. Let’s make a another fictitious async function, this time one that needs input:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;getRandomNumberHigherThanAsync(10).then(function(someNumberOverTen){
    // do something with `someNumberOverTen`
});
&lt;/pre&gt;

&lt;p&gt;Now we can do this:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;getRandomNumberAsync().then(function(someNumber) { 
    return getRandomNumberHigherThanAsync(someNumber);
}).then(function(something){
    // What will `something` be?
});
&lt;/pre&gt;

&lt;p&gt;In the example above, you might think that &lt;code&gt;something&lt;/code&gt; will be the promise returned from &lt;code&gt;getRandomNumberHigherThanAsync&lt;/code&gt;. It’s not. Instead, it’s the &lt;em&gt;value&lt;/em&gt; that &lt;code&gt;getRandomNumberHigherThanAsync&lt;/code&gt; produces and would pass into its callback. &lt;em&gt;Returning another promise from within the callback for a promise is a special case.&lt;/em&gt; Though it’s probably the most frequent case.&lt;/p&gt;

&lt;h2&gt;Putting Promises Together&lt;/h2&gt;

&lt;p&gt;Now let’s pretend we have a set of functions that all return promises, named &lt;code&gt;A&lt;/code&gt; through &lt;code&gt;E&lt;/code&gt;. If we wanted to execute them in sequence, passing the results from one to the next, we &lt;em&gt;could&lt;/em&gt; write it this:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;A().then(function(a) {
    return B(a).then(function(b){
        return C(b).then(function(c){
            return D(c).then(function(d){
                return E(d);
            });
        });
    });
});
&lt;/pre&gt;

&lt;p&gt;Yeah, that hurts my eyes too. Though I found that I was writing my code &lt;em&gt;just like this&lt;/em&gt; at first.&lt;/p&gt;

&lt;p&gt;However, we should realize that &lt;code&gt;A.then()&lt;/code&gt; returns a promise and that that promise completes only when all of the nested promises have completed. If we wanted to execute a new function &lt;code&gt;F&lt;/code&gt; after all these steps, we could do it like this:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;var waitForAllToBeDone = A().then(function(a) {
    return B(a).then(function(b){
        return C(b).then(function(c){
            return D(c).then(function(d){
                return E(d);
            });
        });
    });
});

waitForAllToBeDone().then(function(e){
    return F(e);
});
&lt;/pre&gt;

&lt;p&gt;However, that last inline callback has the same signature as &lt;code&gt;F&lt;/code&gt;. That means that we can simplify to this:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;waitForAllToBeDone().then(F);
&lt;/pre&gt;

&lt;p&gt;Now we realize that what we did for &lt;code&gt;F&lt;/code&gt; is also true for &lt;code&gt;E&lt;/code&gt;. In fact, it is true for the entire chain. We can simplify that nasty nested beast to:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;A().then(B).then(C).then(D).then(E).then(F);
&lt;/pre&gt;

&lt;p&gt;Much nicer.&lt;/p&gt;

&lt;h2&gt;A Real Example&lt;/h2&gt;

&lt;p&gt;Let’s bring this home. While working on &lt;a href="http://hilojs.codeplex.com/"&gt;HiloJS&lt;/a&gt; we needed to copy an image thumbnail to a new file. It sounds simple, but it requires the following steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open a file that we will write &lt;em&gt;to&lt;/em&gt;. We’ll call this the &lt;strong&gt;target&lt;/strong&gt; file.&lt;/li&gt;
&lt;li&gt;Get the thumbnail image from another file. We’ll call this the &lt;strong&gt;source&lt;/strong&gt; file. (WinRT creates the thumbnail for us from the source.)&lt;/li&gt;
&lt;li&gt;Copy the stream from the thumbnail source to the target file’s input stream.&lt;/li&gt;
&lt;li&gt;Flush the output stream.&lt;/li&gt;
&lt;li&gt;Close both the input and the output stream.&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;(Actually we don’t really care about the order of the first two steps. They could be switched.)&lt;/p&gt;

&lt;p&gt;Our initial implementation looked liked this:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;function writeThumbnailToFile(sourceFile, targetFile) {

    var whenFileIsOpen = targetFile.openAsync(fileAccessMode.readWrite);

    return whenFileIsOpen.then(function (outputStream) {

        return sourceFile.getThumbnailAsync(thumbnailMode.singleItem)).then(function (thumbnail) {
            var inputStream = thumbnail.getInputStreamAt(0);
            return randomAccessStream.copyAsync(inputStream, outputStream).then(function () {
                return outputStream.flushAsync().then(function () {
                    inputStream.close();
                    outputStream.close();
                });
            });
        });
    });
}
&lt;/pre&gt;

&lt;p&gt;Then we had a code review with the always helpful Chris Tavares. He pointed us in a more excellent direction. We were able to change the code to this:&lt;/p&gt;

&lt;pre name="code" class="js"&gt;function writeThumbnailToFile(sourceFile, targetFile) {

    var whenFileIsOpen = targetFile.openAsync(fileAccessMode.readWrite);
    var whenThumbailIsReady = sourceFile.getThumbnailAsync(thumbnailMode.singleItem);

    var whenEverythingIsReady = WinJS.Promise.join([whenFileIsOpen, whenThumbailIsReady]);

    var inputStream, outputStream;

    whenEverythingIsReady.then(function (args) {
        outputStream = args[0];
        var thumbnail = args[1];
        inputStream = thumbnail.getInputStreamAt(0);
        return randomAccessStream.copyAsync(inputStream, outputStream);

    }).then(function () {
        return outputStream.flushAsync();

    }).then(function () {
        inputStream.close();
        outputStream.close();
    });
}
&lt;/pre&gt;

&lt;p&gt;A couple of notable differences:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;In the first implementation, we passed along some values via the closure (e.g., &lt;code&gt;inputStream&lt;/code&gt; and &lt;code&gt;outputStream&lt;/code&gt;). In the second, we had to declare them in the outer scope because there was no common closure.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the first implementation, we chained &lt;code&gt;targetFile.openAsync&lt;/code&gt; and &lt;code&gt;sourceFile.getThumbnailAsync&lt;/code&gt;, but we didn’t really need to. We made the real relationship more explicit in the second using &lt;code&gt;WinJS.Promise.join&lt;/code&gt;. That mean the values of these two promises came to us in an arrays (we named it &lt;code&gt;args&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;Understanding how promises can be composed really helped us to make the code more readable. It can be difficult to wrap your head around the way they work, but (like it or not) promises are an essential part of writing apps with WinJS.&lt;/p&gt;

&lt;h2&gt;Fictitious Functions Implementations&lt;/h2&gt;

&lt;pre name="code" class="js"&gt;// an example implementation of getRandomNumberAsync

function getRandomNumberAsync() {
    return WinJS.Promise.as(Math.random());
}

// an example implementation of getRandomNumberHigherThanAsync

function getRandomNumberHigherThanAsync(minimum) {
    var someNumber = Math.random() + minimum;
    return WinJS.Promise.as(someNumber);
}
&lt;/pre&gt;
&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2012/08/21/winjs-unpacking-promises/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70289" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WinJS/default.aspx">WinJS</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Windows+8/default.aspx">Windows 8</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/async/default.aspx">async</category></item><item><title>Unit Testing WinJS: First Steps</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2012/08/16/unit-testing-winjs-first-steps.aspx</link><pubDate>Thu, 16 Aug 2012 23:21:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70280</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;N.B. &lt;em&gt;If you don&amp;#8217;t know anything about WinJS, take a moment to peruse &lt;a href="http://dev.bennage.com/blog/2012/08/01/a-brief-introduction-to-winjs/"&gt;this primer&lt;/a&gt;. Also, the context of this post is the &lt;a href="http://hilojs.codeplex.com/"&gt;p&amp;amp;p Hilo project&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;One of the first questions we&amp;#8217;ve been struggling with is how to best test a WinJS app.  (I&amp;#8217;m going to use the term &amp;#8220;unit test&amp;#8221; somewhat loosely. Some of our tests would technically be classified as &amp;#8220;integration tests&amp;#8221;.)&lt;/p&gt;

&lt;h2&gt;Where to run the tests&lt;/h2&gt;

&lt;p&gt;Our first barrier to unit testing a WinJS app was finding a convenient way to run the tests.
The primary difficulty is that the WinRT APIs are only available in the context of a Windows 8 app (and that&amp;#8217;s also practicially the case for WinJS as well). So if your tests need to touch either one, the only choice you currently have is to run the tests inside a Windows 8 app.&lt;/p&gt;

&lt;p&gt;&lt;img class="right" src="http://dev.bennage.com/images/posts/winjs-test-solution.png" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;After some experimentation, we choose to include a second app in our solution to host the unit tests. (At one point, we had the tests embedded in the actual app itself; executing them with a hidden keyboard shortcut.) Having two apps means that we have to share the source that&amp;#8217;s under test. Currently, we&amp;#8217;re just &lt;a href="http://msdn.microsoft.com/en-us/library/9f4t9t92.aspx"&gt;manually linking the files&lt;/a&gt;. I also have to manually go into the default.html and add references to the scripts. Ultimately, I&amp;#8217;d like to have this automated, but that&amp;#8217;s a task for another day.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Notice in the screen shot of the solution explorer, that the &lt;code&gt;Hilo&lt;/code&gt; folder in the &lt;code&gt;Hilo.Specifications&lt;/code&gt; project has a little red &lt;strong&gt;x&lt;/strong&gt;. This is because the folder doesn&amp;#8217;t physically exist there. Instead, there are just links to the corresponding files in the main &lt;code&gt;Hilo&lt;/code&gt; project.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;How to run the tests&lt;/h2&gt;

&lt;p&gt;We settled on &lt;a href="http://visionmedia.github.com/mocha/"&gt;Mocha&lt;/a&gt; for running our unit tests. Mocha is popular in the &lt;a href="http://nodejs.org/"&gt;Node.js&lt;/a&gt; and it has (in my opinion) one of the better async test stories. This is really important when building Windows 8 apps because (much like Node.js) all the APIs are asynchronous.&lt;/p&gt;

&lt;p&gt;We also choose to use a &lt;a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development"&gt;BDD-style&lt;/a&gt; for the tests. However, Mocha supports several styles, including a QUnit style.&lt;/p&gt;

&lt;p&gt;Mocha will pass a function into your tests for you to call once the asynchronous work is complete. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;it(&amp;#39;test something asynchronous using a promise&amp;#39;, function(done) {

    doSomeWork().then(function(result){

        if(!result) { // or whatever assertion is appropriate
            throw new Error(&amp;#39;test failed&amp;#39;) 
        } else {
            done(); // we call the function after the async work is complete
        }

    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you don&amp;#8217;t understand the call to &lt;code&gt;then&lt;/code&gt;, take a moment to read about &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx"&gt;async programming in WinJS apps&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;What&amp;#8217;s great about Mocha is that if you omit the &lt;code&gt;done&lt;/code&gt; parameter, then the harness automagically assumes the test is synchronous. Very nice.&lt;/p&gt;

&lt;p&gt;We did have &lt;a href="https://github.com/visionmedia/mocha/issues/502"&gt;one problem&lt;/a&gt; with Mocha. It has an internal recursive process that can cause a stack overflow in IE. &lt;a href="http://lostechies.com/derickbailey/"&gt;Derick Bailey&lt;/a&gt; came up with a quick workaround by resetting the stack before each test with a call to &lt;code&gt;setTimeout&lt;/code&gt; in our &lt;a href="http://hilojs.codeplex.com/SourceControl/changeset/view/13593c579fb6#Hilo.Specifications%2fspec.helpers.js"&gt;test helper script&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;beforeEach(function (done) {
    setTimeout(done, 0);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As mentioned before, Mocha is primarly for Node. However Mocha&amp;#8217;s creator &lt;a href="http://tjholowaychuk.com/"&gt;TJ Holowaychuk&lt;/a&gt;, graciously allowed me to setup a &lt;a href="http://nuget.org/packages/mochajs-browseronly"&gt;Nuget package&lt;/a&gt; to make it easier for Windows developers to use Mocha.&lt;/p&gt;

&lt;h3&gt;Steps to install Mocha&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Right-click on the test project and select Manage Nuget Packages&lt;/li&gt;
&lt;li&gt;Seach for &amp;#8220;mocha&amp;#8221;&lt;/li&gt;
&lt;li&gt;Select &amp;#8220;mocha for browsers&amp;#8221; and click Install&lt;/li&gt;
&lt;li&gt;Open the default.html page and reference the scripts. They are located in the \lib folder. (see below)&lt;/li&gt;
&lt;li&gt;Open the default.js file and add &lt;code&gt;mocha.run()&lt;/code&gt; some where after app is ready.&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;In my &lt;a href="http://hilojs.codeplex.com/SourceControl/changeset/view/13593c579fb6#Hilo.Specifications%2fdefault.html"&gt;default.html&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;link rel=&amp;quot;stylesheet&amp;quot; type=&amp;quot;text/css&amp;quot; href=&amp;quot;/lib/mocha.css&amp;quot;&amp;gt;
&amp;lt;script src=&amp;quot;/lib/mocha.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
 &amp;lt;!-- choose the style that you want for tests first --&amp;gt;
&amp;lt;script&amp;gt;mocha.setup(&amp;#39;bdd&amp;#39;)&amp;lt;/script&amp;gt;

&amp;lt;!-- then reference your actual test script --&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A simplified &lt;a href="http://hilojs.codeplex.com/SourceControl/changeset/view/13593c579fb6#Hilo.Specifications%2fdefault.js"&gt;default.js&lt;/a&gt; might be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;﻿(function () {
    &amp;#39;use strict&amp;#39;;

    var activation = Windows.ApplicationModel.Activation,
        app = WinJS.Application,
        nav = WinJS.Navigation;

    app.addEventListener(&amp;#39;activated&amp;#39;, function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            args.setPromise(WinJS.UI.processAll().then(function () {
                mocha.run();
            }));
        }
    }, false);

    app.start();
})(this);
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;What to mock?&lt;/h2&gt;

&lt;p&gt;The next big question was about making our code &amp;#8220;testable&amp;#8221;. I don&amp;#8217;t like saying that because, in general, we don&amp;#8217;t want test concerns to be bleed into the code. (I have some &lt;a href="http://dev.bennage.com/blog/2008/03/30/the-roots-of-best-practices/"&gt;personal principles&lt;/a&gt; about these sorts of practices.)&lt;/p&gt;

&lt;p&gt;At first, I tried to create a system that would completely mock out every WinRT API. I modeled it after &lt;a href="http://www.commonjs.org/specs/modules/1.0/"&gt;CommonJS Modules&lt;/a&gt;. In essence, I made every &amp;#8220;module&amp;#8221; in my app use a &lt;code&gt;require&lt;/code&gt; function to locate its dependencies. Using this approach you had to reference the WinRT API in the very unnatural form of:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var knownFolders = require(&amp;#39;Windows.Storage.KnownFolders&amp;#39;); 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;instead of the standard:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var knownFolders = Windows.Storage.KnownFolders;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This made it easy (ish) to mock out the WinRT call in my tests. However, there were a &lt;a href="http://hilojs.codeplex.com/discussions/364538"&gt;number&lt;/a&gt; of &lt;a href="http://hilojs.codeplex.com/discussions/366305"&gt;negatives&lt;/a&gt; to this approach. Mostly, it added an extra layers of complexity and it broke tooling (such as Intellisense and code navigation).&lt;/p&gt;

&lt;p&gt;Instead, we decided to take a more &lt;a href="http://dev.bennage.com/blog/2010/09/06/what-is-functional-programming/"&gt;functional&lt;/a&gt; approach to our code. As much as was reasonable, we tried to write our code as &lt;em&gt;functions with inputs&lt;/em&gt; instead of as &lt;em&gt;objects with dependencies&lt;/em&gt;. Then in our tests we could invoke the functions passing in &amp;#8220;mocks&amp;#8221; that were shaped like the necessary WinRT dependencies. This mean that we had thin layers in our app that invoked the functions and passed in the necessary bits. It also meant that in a few cases, we had to run tests against the actual WinRT objects. (Technically, I would call these &amp;#8220;integration&amp;#8221; tests instead of &amp;#8220;unit&amp;#8221; tests).&lt;/p&gt;

&lt;p&gt;The best example of this approach in the HiloJS project (so far) can be found in &lt;a href="http://hilojs.codeplex.com/SourceControl/changeset/view/13593c579fb6#Hilo%2fHilo%2fTiles%2ftileUpdater.js"&gt;tileUdater.js&lt;/a&gt;. In that file, we create a simple object that coordinates the real work using a set of functions. The major functions are defined in their own files (all inside the \Hilo\Tiles folder). We &amp;#8220;export&amp;#8221; these functions using &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/br212667.aspx"&gt;&lt;code&gt;WinJS.Namespace.define&lt;/code&gt;&lt;/a&gt;. Exporting them makes them available to the code in tileUpdater.js as well as our tests.&lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;So far this arrangement has worked really well for us. Working with Mocha has been a lot of fun. The test authoring experience isn&amp;#8217;t quite as smooth as I&amp;#8217;d like, but I&amp;#8217;m sure that will come as we gain more experience.
Remember though, this project is very much a journey, so keep on eye on the &lt;a href="http://hilojs.codeplex.com/"&gt;project site&lt;/a&gt;. We&amp;#8217;ll be writing more about it as we learn.&lt;/p&gt;

&lt;p&gt;As always, your feedback is greatly desired. Do you have a better way? How does this approach strike? Feel free to speak up our the &lt;a href="http://hilojs.codeplex.com/discussions"&gt;project&amp;#8217;s discussion board&lt;/a&gt;.&lt;/p&gt;

&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2012/08/15/unit-testing-winjs/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70280" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/unit+testing/default.aspx">unit testing</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WinJS/default.aspx">WinJS</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Windows+8/default.aspx">Windows 8</category></item><item><title>Getting Started with JavaScript… again</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2011/10/29/getting-started-with-javascript-again.aspx</link><pubDate>Sun, 30 Oct 2011 03:56:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:68342</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;I&amp;#8217;ve alluded before that I did a large chunk of my development in some form of &lt;a href="http://en.wikipedia.org/wiki/ECMAScript"&gt;ECMAScript&lt;/a&gt; for the first ten years of my professional life. Now, JavaScript is cool again for the first time. Everyone wants to learn it.&lt;/p&gt; &lt;p&gt;So, like me, you probably already kinda maybe knew JavaScript. But times have changed and now it&amp;#8217;s a serious language. How do you get up to speed? Here&amp;#8217;s what I did.&lt;/p&gt; &lt;h2&gt;Read Some Books&lt;/h2&gt; &lt;h3&gt;&lt;a href="http://eloquentjavascript.net/"&gt;Eloquent JavaScript&lt;/a&gt;&lt;/h3&gt; &lt;p&gt;This is probably the best book to start with if you are &lt;em&gt;really&lt;/em&gt; rusty (which also includes plain ol&amp;#8217; &lt;em&gt;new&lt;/em&gt; as well). Personally, I found the book a bit tedious and I didn&amp;#8217;t quite finish.&lt;/p&gt; &lt;p&gt;Did I mention that it&amp;#8217;s free?&lt;/p&gt; &lt;h3&gt;&lt;a href="http://shop.oreilly.com/product/9780596517748.do"&gt;JavaScript: The Good Parts&lt;/a&gt;&lt;/h3&gt; &lt;p&gt;An essential read for modern JavaScript development. It&amp;#8217;s short and terse and easy to read. Douglas Crockford is highly regarded, though he can get occasionally &lt;a href="http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/"&gt;harsh some mellow&lt;/a&gt;. He&amp;#8217;s the &lt;strike&gt;supreme overlord&lt;/strike&gt; author of &lt;a href="http://jslint.com/"&gt;JSLint&lt;/a&gt;, a nifty tool that&amp;#8217;s useful for detecting the &lt;em&gt;not so good&lt;/em&gt; parts in your own JavaScript. The information in this book is foundational and I recommend reading it soon.&lt;/p&gt; &lt;h3&gt;&lt;a href="http://shop.oreilly.com/product/9780596806767.do"&gt;JavaScript Patterns&lt;/a&gt;&lt;/h3&gt; &lt;p&gt;This book is awesome. Seriously. Someone should give &lt;a href="http://twitter.com/#!/stoyanstefanov"&gt;Stoyan&lt;/a&gt; a trophy. It deals with higher level patterns in your JavaScript applications. Be sure to read it after you become comfortable with core language concepts.&lt;/p&gt; &lt;h3&gt;&lt;a href="http://shop.oreilly.com/product/9780596802806.do"&gt;High Performance JavaScript&lt;/a&gt;&lt;/h3&gt; &lt;p&gt;I haven&amp;#8217;t actually read this one yet, but it&amp;#8217;s on my list. I have however heard &lt;a href="http://twitter.com/#!/slicknet"&gt;Nicholas C. Zakas&lt;/a&gt; speak and from that I suspect that the content will be excellent.&lt;/p&gt; &lt;h2&gt;Staying in Touch&lt;/h2&gt; &lt;p&gt;I&amp;#8217;ve found it a little difficult to stay abreast of what&amp;#8217;s having in the JavaSCript community.&lt;/p&gt; &lt;h3&gt;&lt;a href="http://javascriptweekly.com/"&gt;JavaScript Weekly&lt;/a&gt;&lt;/h3&gt; &lt;p&gt;The weekly podcast and its associated newsletter have been excellent. Highly recommended.&lt;/p&gt; &lt;h3&gt;On the Interwebz&lt;/h3&gt; &lt;p&gt;Start with &lt;a href="http://www.elijahmanor.com/"&gt;Elijah Manor&lt;/a&gt;. Aside from just being a good guy, Elijah is a perpetual fountain of information. So, you&amp;#8217;ll want to &lt;a href="http://twitter.com/#!/elijahmanor"&gt;follow him&lt;/a&gt; on Twitter. &lt;em&gt;Caveat: Following Elijah is drinking from a firehouse.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;I also recommend:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://twitter.com/#!/mattpodwysocki"&gt;Matthew Podwysocki&lt;/a&gt; A fellow &amp;#8216;softie who is aware of all things JavaScripty.&lt;/li&gt; &lt;li&gt;&lt;a href="http://twitter.com/#!/stoyanstefanov"&gt;Stoyan Stefanov&lt;/a&gt; from Yahoo&lt;/li&gt; &lt;li&gt;&lt;a href="http://twitter.com/#!/jeresig"&gt;John Resig&lt;/a&gt; of jQuery fame&lt;/li&gt; &lt;li&gt;&lt;a href="http://twitter.com/#!/slicknet"&gt;Nicholas C. Zakas&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://twitter.com/#!/reybango"&gt;Rey Bango&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/scriptjunkie/default.aspx"&gt;script junkies {}&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt; I&amp;#8217;m sure there are many other resources. Please add additional ones in the comments.&lt;/p&gt; &lt;h2&gt;Some Thoughts&lt;/h2&gt; &lt;p&gt;Here&amp;#8217;s a few thoughts about learning JavaScript. Take them or leave them, but these are my current opinions.&lt;/p&gt; &lt;h3&gt;Prototypes, not classes&lt;/h3&gt; &lt;p&gt;JavaScript is not a classical language (that&amp;#8217;s fancy talk for &amp;#8216;class based&amp;#8217; language). Sometimes it looks classical, and may even taste a little classical, but really it&amp;#8217;s not. Don&amp;#8217;t try to force it. I think you&amp;#8217;ll be happier and you&amp;#8217;ll write &lt;a href="http://bobross.com/"&gt;happy little functions&lt;/a&gt; if you embrace it&amp;#8217;s prototypical nature. If you don&amp;#8217;t understand the difference, that&amp;#8217;s okay. You will after reading the books I listed above.&lt;/p&gt; &lt;h3&gt;Don&amp;#8217;t confuse the language and the environment&lt;/h3&gt; &lt;p&gt;We mostly know JavaScript through browser development. As such, we&amp;#8217;ve generally confused the inside evil of the &lt;a href="http://www.w3.org/DOM/"&gt;DOM&lt;/a&gt; with JavaScript itself. Or at least we did before jQuery rescued us.&lt;/p&gt; &lt;p&gt;However the browser isn&amp;#8217;t the only environment. For the troglodytes amongst us, you can use &lt;a href="http://nodejs.org/"&gt;Node.js&lt;/a&gt; and write JavaScript on the server.&lt;/p&gt; &lt;h3&gt;Leverage the natural strengths&lt;/h3&gt; &lt;p&gt;Each of these concepts deserves a post (or more) on their own, so I won&amp;#8217;t go into details.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;It&amp;#8217;s a &lt;em&gt;dynamic&lt;/em&gt; language. JavaScript is squishy and that&amp;#8217;s good.&lt;/li&gt; &lt;li&gt;It has many &lt;a href="http://dev.bennage.com/blog/2010/09/06/what-is-functional-programming/"&gt;&lt;em&gt;functional&lt;/em&gt;&lt;/a&gt; characteristics.&lt;/li&gt; &lt;li&gt;It favors &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh464930%28v=VS.85%29.aspx"&gt;&lt;em&gt;asynchronous patterns&lt;/em&gt;&lt;/a&gt;.&lt;/li&gt; &lt;/ul&gt; &lt;h3&gt;K.I.S.S.&lt;/h3&gt; &lt;p&gt;Don&amp;#8217;t mix trying to learn JavaScript with trying to learn a framework or library. My initial attempt to learn Ruby was thwarted by Rails. I know that some folks will disagree with me on this point. Here are my reasons:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;It&amp;#8217;s likely that you&amp;#8217;ll encounter many new concepts &lt;em&gt;just learning&lt;/em&gt; the language.&lt;/li&gt; &lt;li&gt;Sometimes it&amp;#8217;s difficult to discern between a language feature and a framework feature.&lt;/li&gt; &lt;li&gt;Many frameworks embody an opinions that can (unintentionally) mislead you about the language (e.g., many frameworks attempt to make JavaScript classy).&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Now, having said that, I do recommend exploring the vast diversity of frameworks and libraries out there after you&amp;#8217;ve become comfortable with JavaScript.&lt;/p&gt; &lt;h2&gt;Some Resource&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;p&gt;&lt;a href="http://www.jshint.com/about/"&gt;JSHint&lt;/a&gt; a community-driven port of the aforementioned JSLint. It&amp;#8217;s groovy. There&amp;#8217;s an &lt;a href="http://jslint4vs2010.codeplex.com/"&gt;extension for Visual Studio 2010&lt;/a&gt;. I also like to use it with the sublime &lt;a href="http://www.sublimetext.com/download"&gt;Sublime Text 2&lt;/a&gt; by way of the the &lt;a href="https://github.com/Kronuz/SublimeLinter"&gt;SublimeLinter package&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt; &lt;li&gt;&lt;p&gt;&lt;a href="http://jsfiddle.net/"&gt;jsfiddle&lt;/a&gt; and &lt;a href="http://jsbin.com"&gt;jsbin&lt;/a&gt; are two cool little online playgrounds for sharing bits of JavaScript.&lt;/p&gt;&lt;/li&gt; &lt;li&gt;&lt;p&gt;&lt;a href="http://nodejs.org/"&gt;NodeJS&lt;/a&gt; can be very good for playing around with JavaScript. Be careful though of trying to learn all about Node at the same time. Here&amp;#8217;s a &lt;a href="http://dev.bennage.com/blog/2011/07/28/node-js-on-windows/"&gt;Windows-friendly quick start&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;What else can you add?&lt;/p&gt;

&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2011/10/27/getting-started-with-javascript-again/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=68342" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category></item><item><title>Restarting Node.js When Your Source Changes</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2011/08/09/restarting-node-js-when-your-source-changes.aspx</link><pubDate>Tue, 09 Aug 2011 08:47:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:68080</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>7</slash:comments><description>&lt;p&gt;I’m lazy. I remember reading somewhere that that was a desirable trait to have in a developer. I’m not sure where though, and honestly it’s just too much effort to &lt;span title="Bing + Google = Bingle!"&gt;bingle&lt;/span&gt; it. This laziness came to the forefront recently as I was playing with Node. &lt;/p&gt;  &lt;p&gt;In my &lt;a href="http://devlicio.us/blogs/christopher_bennage/archive/2011/07/28/node-js-on-windows.aspx" target="_blank"&gt;last post&lt;/a&gt;, I showed you how to spin up a quick web app using Node. As I was playing with this app, I found that I had to restart Node every time I made a change to the source. This meant I had to switch to the console, stop the process, start the process and THEN refresh my page to see the effect of my change. Too much work I say.&lt;/p&gt;  &lt;p&gt;So I wondered if Node had something built-in for monitoring changes to the file. I didn’t see anything useful from &lt;strong&gt;node.exe –help&lt;/strong&gt; and researching it on the Web is just &lt;em&gt;so&lt;/em&gt; tedious, so I decided to write my own solution.&lt;/p&gt;  &lt;h3&gt;Looking for Some Change&lt;/h3&gt;  &lt;p&gt;In .NET, there is a class &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" target="_blank"&gt;System.IO.FileSystemWatcher&lt;/a&gt;. With an instance of this class you can monitor the files in a directory for changes. I set it up like this:&lt;/p&gt;  &lt;p&gt;var watcher = new FileSystemWatcher();    &lt;br /&gt;watcher.Path = @&amp;quot;C:\node.js\stuff&amp;quot;;     &lt;br /&gt;watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;     &lt;br /&gt;watcher.Filter = &amp;quot;*.js&amp;quot;;     &lt;br /&gt;    &lt;br /&gt;watcher.Changed += Changed;     &lt;br /&gt;watcher.Created += Changed;     &lt;br /&gt;watcher.Deleted += Changed;     &lt;br /&gt;watcher.Renamed += Renamed;     &lt;br /&gt;    &lt;br /&gt;// Begin watching     &lt;br /&gt;watcher.EnableRaisingEvents = true;&lt;/p&gt;  &lt;p&gt;The NotifyFilter property allows you to specify the sort of changes you are interested in. You can check out the full list &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.notifyfilters.aspx" target="_blank"&gt;here&lt;/a&gt;. You’ll also notice that I used the Filter property to narrow it down just to js files.&lt;/p&gt;  &lt;p&gt;Next, there are a number of events to wire to respond to changes. I reused the same handler as much as I could because I always want to do the same thing: restart Node. It’s also not entirely obvious how these events relate to NotifyFilter, but I didn’t dig too deep into that. (I’m lazy remember.)&lt;/p&gt;  &lt;p&gt;It’s also important to set EnableRaisingEvents. If you don’t, then the (guess what) no event are raised.&lt;/p&gt;  &lt;h3&gt;Kill, Kill, Kill&lt;/h3&gt;  &lt;p&gt;Now whenever a significant change occurs, it’ll be time to restart Node. For this I used &lt;a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx" target="_blank"&gt;System.Diagnostics.Process&lt;/a&gt;. This is a bit of a tricky classs, with a number of not-so-obvious knobs to turn.&lt;/p&gt;  &lt;p&gt;First, I’ll need to get a reference to the Node process. I noticed in Task Manager that the process name was “node”. So I used &lt;/p&gt;  &lt;pre class="c#:nogutter:nocontrols" name="code"&gt;Process.GetProcessesByName(&amp;quot;node&amp;quot;)&lt;/pre&gt;

&lt;p&gt;This returns an array of processes, and so I did this:&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;var matches = Process.GetProcessesByName(&amp;quot;node&amp;quot;);

matches.ToList().ForEach(match =&amp;gt; {
    Console.WriteLine(&amp;quot;attempting to close node.js [&amp;quot; + match.Id + &amp;quot;]&amp;quot;);
    match.Kill();
    match.WaitForExit(300); // it shouldn’t take this long, we’re just being cautious
    Console.WriteLine(&amp;quot;successfully closed&amp;quot;);&lt;/pre&gt;
Admittedly, this is hitting it with a hammer. It’s okay, because this is just a &lt;strong&gt;quick&lt;/strong&gt; and &lt;strong&gt;dirty&lt;/strong&gt; helper tool for me and not a production application. 

&lt;p&gt;After killing the process, I’ll want to start another one. Now, I don’t care for another console window to pop up each time I restart, instead I’d like to simply redirect the input and output to my little helper app. This can be a little tricky, and I had to do some experimentation to find the right combination in order keep things from hanging. If you find it misbehaving, I recommend &lt;a href="http://stackoverflow.com/search?q=processstartinfo" target="_blank"&gt;searching StackOverflow&lt;/a&gt;. I found several useful questions there. One of the keys that came up more than once was capturing &lt;em&gt;and&lt;/em&gt; closing the stream for the standard input.&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;var start = new ProcessStartInfo();
start.FileName = @&amp;quot;C:\node.js\node.exe&amp;quot;;
start.UseShellExecute = false; // the starts the process directly, as opposed to going thu the shell
start.CreateNoWindow = true; // we don’t want a new window
start.RedirectStandardOutput = true;
start.RedirectStandardInput = true;
start.Arguments = Path.Combine(@&amp;quot;C:\node.js\stuff&amp;quot;, @&amp;quot;server.js&amp;quot;);

var node = new Process();
node.EnableRaisingEvents = true;
node.OutputDataReceived += OutputHandler;
node.StartInfo = start;
node.Start();

node.Refresh(); // refreshing the metadata stored in the instance of Process 
Console.WriteLine(node.ProcessName);
Console.WriteLine(&amp;quot;[&amp;quot; + node.Id + &amp;quot;] node.exe started&amp;quot;);

// close the input, we won&amp;#39;t use it
var input = node.StandardInput;
input.Close();

// and now for the output
node.BeginOutputReadLine();&lt;/pre&gt;

&lt;p&gt;First we create an object that contains the configuration for starting an instance of Node. Notice that we are passing in the server.js file as an argument. &lt;/p&gt;

&lt;p&gt;Also note that after starting the process, I call Refresh. I need to do this so that I’ll have the correct info to write out to the console. This data is not captured automatically.&lt;/p&gt;

&lt;p&gt;Finally, I handled the redirection of the input and output.&lt;/p&gt;

&lt;p&gt;The complete code for the app is available at &lt;a href="https://gist.github.com/1108727"&gt;https://gist.github.com/1108727&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Epilogue&lt;/h3&gt;

&lt;p&gt;This is very much a hack and I am not an expert on the proper usage of these classes. Please feel free to offer improvements.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=68080" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/development+tools/default.aspx">development tools</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/web/default.aspx">web</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Tips+_2600_amp_3B00_+Tricks/default.aspx">Tips &amp;amp; Tricks</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/nodejs/default.aspx">nodejs</category></item><item><title>Node.js on Windows (or JavaScript for the backend)</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2011/07/28/node-js-on-windows.aspx</link><pubDate>Thu, 28 Jul 2011 08:04:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:68036</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>18</slash:comments><description>&lt;h3&gt;What is Node?&lt;/h3&gt;  &lt;p&gt;The simplest answer, albeit a &lt;em&gt;simplistic&lt;/em&gt; answer, is that Node (or Node.js) is JavaScript on the server. Actually, it’s a more than just that, but you can read about the &lt;em&gt;more&lt;/em&gt; in &lt;a href="http://www.nodejs.org/#about" target="_blank"&gt;other&lt;/a&gt; &lt;a href="http://redmonk.com/sogrady/2010/05/13/node-js/" target="_blank"&gt;places&lt;/a&gt;. This is a good enough answer for us n00bs.&lt;/p&gt;  &lt;p&gt;Unless you’ve been living in in cave, you might have noticed that JavaScript is all the rage now. It’s the new &lt;a href="http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebSematicMarkupIsDeadCleanVsMachinecodedHTML.aspx" target="_blank"&gt;assembly&lt;/a&gt; &lt;a href="http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebPart2MadnessOrJustInsanity.aspx" target="_blank"&gt;language&lt;/a&gt; of the Web. (It’s even for the &lt;a href="http://enterprise-js.com/" target="_blank"&gt;enterprise&lt;/a&gt;.) With Node, you can now take that webby clienty goodness to your server applications.&lt;/p&gt;  &lt;p&gt;The reason I’m brining all this up is because there’s now a &lt;a href="http://www.nodejs.org/#download" target="_blank"&gt;version of Node.js for Windows&lt;/a&gt;. It’s currently the unstable release only, but it’s a sign of coolness to come. Furthermore, Microsoft has partnered with Joyent and Rackspace to make it happen. You can read about it &lt;a href="http://blogs.msdn.com/b/interoperability/archive/2011/06/23/microsoft-working-with-joyent-and-the-node-community-to-bring-node-js-to-windows.aspx" target="_blank"&gt;here&lt;/a&gt; and &lt;a href="http://blog.nodejs.org/2011/06/23/porting-node-to-windows-with-microsoft%E2%80%99s-help/" target="_blank"&gt;here&lt;/a&gt;. The ultimate goal (according to the posts) is for Node.js to run on both Windows and Azure.&lt;/p&gt;  &lt;p&gt;Now, I want to be clear too, since I have been &lt;a href="http://devlicious.com/blogs/christopher_bennage/archive/2011/04/06/a-punctuated-life.aspx" target="_blank"&gt;newly assimilated&lt;/a&gt;, Node is &lt;em&gt;not&lt;/em&gt; a Microsoft product..&lt;/p&gt;  &lt;h3&gt;Tutorial&lt;/h3&gt;  &lt;p&gt;I want to show you how easy it is to try out Node. &lt;/p&gt;  &lt;p&gt;First, &lt;a href="http://www.nodejs.org/#download" target="_blank"&gt;download the exe&lt;/a&gt;. I grabbed v0.5.2.&lt;/p&gt;  &lt;p&gt;Next, run it. Yeah, it’s that easy. It used to be &lt;a href="http://codebetter.com/matthewpodwysocki/2010/09/08/getting-started-with-node-js-on-windows/" target="_blank"&gt;way&lt;/a&gt; &lt;a href="http://www.lazycoder.com/weblog/2010/03/18/getting-started-with-node-js-on-windows/" target="_blank"&gt;harder&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;You’ll be presented with a prompt and you can start writing JavaScript in paradigm-shifting &lt;a href="http://en.wikipedia.org/wiki/REPL" target="_blank"&gt;REPL&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/node_2D00_repl_5F00_77A5864B.png"&gt;&lt;img style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" title="node-repl" border="0" alt="node-repl" src="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/node_2D00_repl_5F00_thumb_5F00_7D8029E4.png" width="527" height="267" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Now, let’s say you want to create a web server. We’ll begin by yanking the ‘hello world’ snippet from &lt;a href="http://www.nodejs.org/" target="_blank"&gt;nodejs.org&lt;/a&gt;.&lt;/p&gt;  &lt;pre class="js:nogutter:nocontrols" name="code"&gt;var http = require(&amp;#39;http&amp;#39;);
http.createServer(function (req, res) {
  res.writeHead(200, {&amp;#39;Content-Type&amp;#39;: &amp;#39;text/plain&amp;#39;});
  res.end(&amp;#39;Hello World\n&amp;#39;);
}).listen(8124, &amp;quot;127.0.0.1&amp;quot;);
console.log(&amp;#39;Server running at &lt;a href="http://127.0.0.1:8124/&amp;#39;"&gt;http://127.0.0.1:8124/&amp;#39;&lt;/a&gt;);&lt;/pre&gt;

&lt;p&gt;I saved this snippet into a file named &lt;strong&gt;server.js&lt;/strong&gt;. Then from a PowerShell prompt, I ran&lt;/p&gt;

&lt;pre&gt; .node.exe .\server.js&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/node_2D00_server_5F00_7CA7C3FA.png"&gt;&lt;img style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" title="node server" border="0" alt="node server" src="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/node_2D00_server_5F00_thumb_5F00_73D7BBAE.png" width="617" height="533" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, I hit http://localhost:8124 with a browser and I got exactly what you’d expect.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/hello_5F00_6B07B362.png"&gt;&lt;img style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" title="hello" border="0" alt="hello" src="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/hello_5F00_thumb_5F00_4A1440BB.png" width="476" height="222" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now you know enough to be dangerous. &lt;img style="border-bottom-style:none;border-left-style:none;border-top-style:none;border-right-style:none;" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/wlEmoticon_2D00_winkingsmile_5F00_28B49B1F.png" /&gt;&lt;/p&gt;

&lt;p&gt;Of course, you have to restart Node when you make changes to the file (use Ctrl + C). I’ll show you how I got around that in another post.&lt;/p&gt;

&lt;p&gt;Have fun!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=68036" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category></item><item><title>JavaScript Gotcha in IE7</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2009/05/03/javascript-gotcha-in-ie7.aspx</link><pubDate>Sun, 03 May 2009 22:10:22 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:46466</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>5</slash:comments><description>&lt;p&gt;I thought for a while that I was done with Web development. I mean the HTML, CSS, JavaScript stack specifically. WPF and Silverlight have just been so much more fun.&lt;/p&gt;  &lt;p&gt;Well, despite that sentiment my weekends have been full for the last couple of months with HTML, CSS, and JavaScript work for &lt;a href="http://www.silverarcade.com/" target="_blank"&gt;Silver Arcade&lt;/a&gt;. Surprisingly, I have found it refreshing.&lt;/p&gt;  &lt;p&gt;In fact, it’s even influenced my WPF development, but that’s another post.&lt;/p&gt;  &lt;p&gt;Silver Arcade passes around a lot of data using JSON. I kept having problems with IE7 and spent too much time scratching my head.&lt;/p&gt;  &lt;p&gt;Take a look at this little bit of jQuery that wires up the featured games rotator on the home page.&lt;/p&gt;  &lt;pre class="js:nogutter:nocontrols" name="code"&gt;jQuery(function($) {
    $(&amp;#39;#rotator-content&amp;#39;).cycle({
        fx: &amp;#39;scrollLeft&amp;#39;,
        easing: &amp;#39;easeOutQuad&amp;#39;, 
        speed: 1000,
        timeout: 6000,
        next: &amp;#39;#next-feature&amp;#39;,
        prev: &amp;#39;#prev-feature&amp;#39; ,
        pause:1,
    });
});&lt;/pre&gt;

&lt;p&gt;This code executes correctly in IE 8, Firefox 3, Safari 4, and Chrome. It breaks in IE 7. (It also works in Opera, but there are other problems there.)&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The problem is the comma on the last line&lt;/em&gt;. IE 7 expects something more because of the comma. Specifically, the error is:&lt;/p&gt;

&lt;p&gt;“Expected identifier, string or number”&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=46466" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/json/default.aspx">json</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/browser+bugs/default.aspx">browser bugs</category></item><item><title>Bellware: Classic ASP Syntax is Bad?</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2007/09/23/bellware-classic-asp-syntax-is-bad.aspx</link><pubDate>Sun, 23 Sep 2007 19:08:36 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:38466</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>7</slash:comments><description>&lt;p&gt;I want to link to Scott Bellware&amp;#39;s &lt;a href="http://codebetter.com/blogs/scott.bellware/archive/2007/09/22/168410.aspx" target="_blank"&gt;post&lt;/a&gt; on attitudes regarding classic ASP. He makes an excellent point, and I agree with him.&lt;/p&gt; &lt;p&gt;About four years ago, I remember telling my former employer about the epic superiority of ASP.NET over classic ASP. I could not deride classic ASP enough.&lt;em&gt; Boy, was I a jerk!&lt;/em&gt;&lt;/p&gt; &lt;p&gt;Now, I don&amp;#39;t want to return to classic ASP, but I have learned to appreciate it again.&amp;nbsp; Just as Scott points out, you can have good code in classic ASP and bad code in ASP.NET (quite easily).&lt;/p&gt; &lt;p&gt;Not too long ago I had to create a classic ASP page for some reason or the other, and I recall thinking being surprised at how simple it was (translate that as &amp;quot;easy&amp;quot;).&amp;nbsp; This reminds a bit of the &lt;a href="http://blogs.msdn.com/nickkramer/archive/2006/11/21/javascript-the-underappreciated-language.aspx" target="_blank"&gt;rediscovery of JavaScript&lt;/a&gt; last year.&lt;/p&gt; &lt;p&gt;So, what&amp;#39;s the point of saying this?&amp;nbsp; I&amp;#39;m not going to starting working with classic ASP again, but the lesson for me is to be more thoughtful in forming my opinions about a technologies. We developers are quite punctilious and we consider our views are as sacrosanct. (I was vividly reminded of this at our Tallahassee Code Camp, as well as being dealt a crushing lesson in humility, but more on that later...)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=38466" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/ASP.NET/default.aspx">ASP.NET</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Musings/default.aspx">Musings</category></item><item><title>Get Firebug</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2007/03/06/get-firebug.aspx</link><pubDate>Tue, 06 Mar 2007 22:23:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:14682</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>6</slash:comments><description>&lt;p&gt;If you are a Web developer, and you are not using Firebug, stop what you are doing and go &lt;a href="http://www.getfirebug.com/"&gt;install it immediately&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I first heard about Firebug on &lt;a href="http://west-wind.com/WebLog/posts/10019.aspx"&gt;Rick Strahl's blog&lt;/a&gt; a couple of months ago, but in the flurry of work I promptly forgot it.&amp;nbsp; A couple of days ago a friend was listing the reasons that why Firefox pwns IE and Firebug was the first.&lt;br&gt;&lt;/p&gt;&lt;p&gt;Firebug is an add-on for Firefox.&amp;nbsp; It allows you to inspect the details of the currently loaded page.&amp;nbsp; You can visually inspect the DOM, execute JavaScript snippets on the fly, and more.&amp;nbsp; I'm thoroughly impressed.&lt;/p&gt;&lt;p&gt;My feature du jour is the way it displays the &lt;a href="http://www.brainjar.com/css/positioning/"&gt;CSS box model&lt;/a&gt; for the currently selected element.&lt;/p&gt;&lt;p&gt; &lt;img src="http://bluespireconsulting.com/blogPostPics/firebug.jpg" title="Firebug Screenshot" alt="Firebug Screenshot" height="384" width="442"&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;I'm not going to repeat the list of features here, you can get that from the &lt;a href="http://www.getfirebug.com/"&gt;Firebug page&lt;/a&gt;.&amp;nbsp; If you have not tried it, go check it out.&lt;br&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=14682" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/web/default.aspx">web</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/dom/default.aspx">dom</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/css/default.aspx">css</category></item></channel></rss>