Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
14. October 2012

 

I don’t think there are many people out there that would argue that JavaScript isn’t an important language.  It certainly is, and with the recent death of Flash and Silverlight in the browser and the hype behind HTML5, to say nothing of Node, it is actually getting more popular

 

I also don’t think there are many people out there that would argue that JavaScript is a heavily broken language too.  As systems written in JavaScript become larger and more complex, the language flaws become more and more pronounced.  Just as C++ ultimately came about from C’s (arguable by some) inability to deal with complexity, a number of companies and groups are looking at possible successors to JavaScript.  Generally all of these languages are backward compatible with JavaScript in some form.  Let’s take a look at the contenders for the short term future of JavaScript.

 

 

ECMAScript 6 AKA Harmony AKA ES.next

 

When talking about the future of JavaScript, the most logical place to start is … well, the future of JavaScript, the next version.  The spec is a work in progress and you can read it here, the most recent revision as of writing (September 27th, 2012).  It would seem obvious that the next version of JavaScript would be ECMAScript 6, but don’t bet the farm just yet.  After all, ECMAScript 6 is effectively a scaled back version of ECMAScript 4, while ECMAScript 5 (the JavaScript version in common usage today), is essentially a fork of ECMAScript 3.  Firefox and Chrome already support bits of ECMAScript 6, so it’s future is quite bright, but by no means are things certain.  Plus there is no way of knowing how long until ECMAScript 6 is supported enough to actually make it useful.  For an idea of where ECMAScript support in various browsers is, check out this handy table.

 

This has opened the door to a number of alternatives, many are languages that compile down to JavaScript making them useful today. Others (like Dart) compile down to JavaScript as a fallback, but perform better in their native environment.

 

 

The 900lb gorillas.

 

Two of the companies are very interested in the future of JavaScript are Google and Microsoft.  Each has created a language they hope will be the future of JavaScript, Dart and TypeScript respectively.

 

This interview between Anders Hejlsberg ( Microsoft, creator of Delphi, C# and now TypeScript ) and Lars Bak ( Google, creator of V8 JavaScript engine and Dart ) is very good summary.  It allows each developer to describe their opinions of the existing problems with JavaScript ( on which they largely agree ) and describe the strengths of each of their companies offerings.

 

Anders Heljsberg & Lars Bak on TypeScript/Dart and the problems with JavaScript today

 

 

Google Dart

 

http://code.google.com/p/dart/ or http://www.dartlang.org/

image

 

In Their Words:

Why Dart?

At Google we've written our share of web apps, and we've tried in many ways to make improvements to that development process, short of introducing a new language. Now we think it's time to take that leap. We designed Dart to be easy to write development tools for, well-suited to modern app development, and capable of high-performance implementations.

 

Dynamic or Static Typed?

Dynamic

 

Key language features

Compiles down to JavaScript, or to the Dart VM ( which is currently only available in Chrome ).  Code running in the Dart VM will perform better.

Language is basically JavaScript with prototypes removed and classes added.  They’ve added lexical closures, sane this management, optional static types, named parameters, cleaner event and DOM programming and more.

The language also comes with an IDE, the Dart Editor, which is a mash-up of Eclipse, Chromium and the DartVM.  For those like me that prefer WebStorm/IntelliJ over Eclipse, they also have a plugin available.  There used to be a cloud based editor, but it appears to have been retired.

 

My 2 cents

Dart technically solves most of the problems with JavaScript and is compatible with existing JavaScript.  That said, I checked out Dart shortly after it was released, then again 6 months later and as usual, Google’s developer support stunk.  They just don’t put the extra effort in to making the experience easy on developers ( at the time, the Windows build didn’t work, you need to compile everything yourself, etc… this lack of polish is just as common with other Google developer tools such as GWT, NativeClient even Android), but the package seems to be improved quite a bit.  Just a warning though, if you aren’t experienced with Google developer support, be prepared for a ton of frustrations if you run in to any problems.

Probably the biggest flaw with Dart is going to be the lack of adoption.  Dart compiles to JavaScript as a fall back, but the VM is obviously the preferred platform.  Google announced their intention of submitting Dart to a standards body, but do you see Microsoft or Mozilla adopting Dart?  Yeah, me neither.  That said, Chrome is getting a pretty big install base.

My biggest problems are the above mentioned Google support, and their tendency to kill off projects at the drop of a hat lately. 

 

 

Microsoft TypeScript

 

http://www.typescriptlang.org/

 

image

In Their Words:

Why TypeScript?

TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.

Dynamic or Static Typed?

Static

 

Key language features

TypeScript is compiled down to JavaScript.

Language allows you to add static types to JavaScript, allowing you to catch type errors during the compilation process ( although the compilation will still generate a JS file ).  Allows you to mix and match TypeScript and JavaScript in existing files.  Adds new constructs to the language such as classes, interfaces and modules.

IDE support is available in the form of a Visual Studio 2012 plugin, as well as plugins for Sublime Text, Vi and Emacs.  They also have Node support out of the box and you can download TypeScript using NPM.

 

My 2 cents

I will admit, I am a bit of a Anders fanboy, so that has gotten me excited about this language.  Language design is all about pragmatic choices, and Anders just seems to pick the right compromises.

At the end of the day, TypeScript is less of a gamble than Dart, and this has it’s advantages and disadvantages.  As Lars said in that video above, TypeScript is “the safe bet” and that is a pretty apt description.  It is a layer on top of JavaScript and nothing more, in many ways it is quite similar to CoffeeScript.  In the end though, TypeScript is probably the one that will best integrate with existing Javascript and given the massive variety of existing code, that is probably a pretty big advantage.  At the end of the day though, TypeScript is ends up being JavaScript, so don’t expect any performance improvements.

The tooling support is shockingly not Microsoft.  Would you have ever expected Vi and Emacs support from day 1?  What about Node support?  There is a noted lack of documentation at this point, which is shocking for a Microsoft product.  They do however have a nifty Playground/Tutorial environment that allows you to type TypeScript and see the generated JavaScript.  Sadly for now, comments and whitespaces are mangled as part of the process, although this is a temporary flaw.

 

 

CoffeeScript

http://coffeescript.org/

 

In Their Words:

CoffeeScript is a little language that compiles into JavaScript. Underneath all those awkward braces and semicolons, JavaScript has alwaysimage had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

The golden rule of CoffeeScript is: "It's just JavaScript". The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime

 

Dynamic or Static Typed?

Dynamic

 

Key Language Features

Coffeescript is a whitespace ( as opposed to curly brace ) based language that compiles down to JavaScript.  It is certainly the elder statements of the group and has been around for a number of years.

Coffeescript provides a number of features to JavaScript including a class system, lexical scoping, splats (…) for variable arguments, array slicing and more.  Additionally it provides a layer of syntactical sugar over some of the JavaScript warts such as is instead of === or unless as the inverse of if.

Coffeescript also offers impressive tooling support.  Like TypeScript, it is available as a Node utility, making installation via NPM trivial.  Most IDEs support Coffeescript ( IntelliJ, Eclipse, WebStorm, Netbeans, Sublime Text, etc ) out of the box.

 

My 2 cents

I only gave CoffeeScript the smallest of evaluations and that was a few years back.  You see, I have an irrational hatred of whitespace based languages.  What I found most irksome ( and TypeScript fixed this ), is that it’s a language on-top of JavaScript, not within Javascript.  So you had to program things the Coffeescript way, then compile it to JavaScript.  Coffeescript felt like a completely different language than JavaScript, while neither Dart nor TypeScript gave me that impression.  Mostly though, I never got over my hatred of whitespace based languages.

All that said, CoffeeScript solved many of the problems that Dart and TypeScript are setting out to solve, and it solved them years ago.  It’s by far the most mature and as a result had the most time to iron out the kinks.

 

 

Other Options

 

Dart, TypeScript and CoffeeScript are by no means the only options when it comes to more programmer friendly JavaScript programming languages, but they are the three that are closest to JavaScript itself.  The following are a selection of other languages that will compile to JavaScript.

 

 

GWT – Google Web Toolkit

 

https://developers.google.com/web-toolkit/

Google Web Toolkit (GWT) is a development toolkit for building and optimizing complex browser-based applications. GWT is used by many products atimage Google, including Google AdWords and Orkut. It's open source, completely free, and used by thousands of developers around the world.

Basically GTW is a Java –> JavaScript compiler.  That is over generalizing, but basically you write your code using a subset of libraries in the Java language, and it is compiled down to JavaScript.  Or a bit of mix and match, with Java running on the server and JavaScript on the client.  The programmer never really works in JavaScript when working with GWT.

 

As is pretty typical with Google projects, IDE support is mostly Eclipse based.  There are a few published books available for GWT.  GWT has been around for quite a while and integrates nicely with Google App Engine.  That said, if you aren’t a Java developer, GWT really isn’t for you.

 

 

 

Haxe

 

http://haxe.org/

Haxe is a powerful modern language with many compelling features. It is aimed at giving developers a tool to create websites & applications using aimage single unified programming language. Whether you use Haxe for its cross-platform features, or focus on a single platform, there are many reasons to adopt it.

Haxe is a language that allows you to compile down to JavaScript, Flash, NekoVM, PHP, C++, C# and Java.  It provides a standard language and library that compiles down to the mentioned languages, while filling in the missing pieces of each language, such as packages and typing for JavaScript, reflection for C++, etc.  The Haxe language itself is derived from ActionScript 3, which itself is a ECMAScript language. Haxe has pretty good IDE support. Haxe also has a few published books which is always handy.

 

I’ve not yet used Haxe, mostly because I have no prior ActionScript experience and because I never really had the time to look into it further. That said, HaxeNME, which is a gaming library targeting web, mobile and desktop certainly has piqued my interests.

 

 

 

Other other options…

 

This doesn’t even come close to listing all of the languages that compile to JavaScript, for a more complete list see this.  This does however cover the major players, at least as I see them.  If you think I made a major omission or mistake in this list, please let me know!

 

JavaScript is becoming more important and JavaScript programs are becoming more complex.  The language does have a number of flaws, but fortunately there are a number of options to help you cope, at least until ECMAScript 6 arrives.

General Programming


9. October 2012

As we saw in the last part, our application is made up of a single view composed of 3 child views.  In this post I am going to focus on the left hand view, which is where the actual map will be drawn.  This is easily the most important part.

 

All I hoped to accomplish today was to get an EaselJS stage integrated in to a YUI View, which with some horrific hacking, I have accomplished.  There are a few very important requirements.

 

First, we need to have a canvas element that EaselJS can work with.

Second, we want the canvas element to take up as much room on the UI as possible.  The right hand view is going to be fixed at 280 pixels in width, so we want the map editing area to consume the rest of the screen.

Finally, I want the whole thing to resize if the window is resized, so our application can support any resolution.

 

To accomplish this, I have altered the person.Template ( the right hand side placeholder for now ), to look like this:

<div style="width:280px;min-width:280px;max-width: 280px;float:right">
    <div align=right>
        <img src="https://www.gamefromscratch.com/image.axd?picture=HTML-5-RPG_thumb_1.png" 
             alt="GameFromScratch HTML5 RPG logo" />
    </div>
    <p><hr /></p>
    <div>
        <h2>About {{name}}:</h2>
        <ul>
            <li>{{name}} is {{height}} feet tall and {{age}} years of age.</li>
        </ul>
    </div>
</div>

Only real change here is the alteration to the parent div.

 

In editor.View.js I made the following simple change that the bottom of the render() function:

Y.one('body').setStyle("margin",0);
return this;

This is simply overriding the YUI default BODY styling, as I do not want any margins, padding or spaces between elements.

 

Then I altered map.Template as follows:

<div style="margin:0px;float:left;display:block" id="panel">
    <canvas width=300 height=300 id="mainCanvas" style="background-color: black;">
        Your browser doesn't support the canvas tag.
    </canvas>
</div>

I needed a named div to access programmatically, so I created one called “panel”.  I also changed the styling on the canvas so the background color would be black, making debugging a bit easier.  The dimensions passed to the canvas are going to be completely ignored.  Why the heck Canvas didn’t support % layout, I will never understand.

 

Finally, the majority of changes are in map.View.js, which I basically re-wrote:

YUI.add('mapView',function(Y){
    var Instance = null;
    Y.MapView = Y.Base.create('mapView', Y.View, [], {
        events:{
          "#mainCanvas": {
              click:function(e)
              {
                  alert("Blah");
              }
          }
        },
        initializer:function(){
            Instance = this;
            var results = Y.io('/scripts/views/templates/map.Template',{"sync":true});
            template = Y.Handlebars.compile(results.responseText);
        },
        prepareCanvas:function(){
            this.resizeEvent();
            createjs.Ticker.setFPS(30);
            createjs.Ticker.addListener(this.gameloop);

            Y.on('windowresize',this.resizeEvent);
        },
        render:function(){
            if(this.template === null)
                this.initializer();
            this.get('container').setHTML(template());
            this.prepareCanvas();
            return this;
        },
        gameloop:function(){
            Instance.stage.update();
            Instance.stage.getChildAt(0).x++;
            if(Instance.stage.getChildAt(0).x > Instance.stage.canvas.width)
                Instance.stage.getChildAt(0).x = 0;
        },
        resizeEvent:function(){
            var container = Instance.get('container');
            var canvas = container.one("#mainCanvas");
            var panel = container.one('#panel');

            var body = Y.one("body");
            var screenWidth = body.get("clientWidth");
            var screenHeight = body.get("scrollHeight");

            var width = Math.floor(screenWidth -280);
            var height = Math.floor(screenHeight );

            canvas.setStyle("width",width);
            canvas.setStyle("height",height);

            this.stage = new createjs.Stage(canvas.getDOMNode());
            // for some reason, easel doesn't pick up our updated canvas size so set it manually
            this.stage.canvas.width = width;
            this.stage.canvas.height = height;

            var shape1 = new createjs.Shape();
            shape1.graphics.beginFill(createjs.Graphics.getRGB(0,255,0));
            shape1.graphics.drawCircle(200,200,200);

            this.stage.addChild(shape1);
        }
    });
}, '0.0.1', { requires: ['view','event','io-base','handlebars']});

 

The variable Instance is a horrible hack, that I intend to replace at some point in the future.  That’s the joy of exercises like this, I can refactor out my hacks later on.  So, why does it exist… well you see, I make a couple of functions that are called back by external code, which completely clobber my this pointer.  I suppose it’s a poor mans singleton of sorts.

 

The end result of this code:

 

 

First thing I did within MapView is declare an event if someone clicks on our canvas ( which needs the id mainCanvas… this is another hackish solution that should possibly be factored away, although frankly, I am OK with requiring the canvas tag to have a certain ID, so I probably wont ) this function is called.  It was simply written to figure out how YUI views handled events.  All it does is pops up an alert with the text Blah.  As you can see, handling element level events in relatively simple, although sadly I couldn’t figure out how to capture document level events here.  Another thing on the todo list.

 

In the initializer function I take a copy of the this pointer in the Instance variable ( *hack* *hack* ), and have changed the template fetching code to no longer be asynchronous, to completely remove some unnecessary race conditions that can result from a network delay retrieving the template. Frankly in this case, async bought us nothing but headaches.

 

prepareCanvas is the method responsible for setting up the easelJS integration.  It starts off by calling resizeEvents, which is where the bulk of the actual work is done.  resizeEvents was factored out to a separate function, because this logic is the same on initial creation as it is when the window is resized.  When resizeEvent() is called, we first find the BODY tag, and get its width and height using clientWidth and scrollHeight.  You would think the obvious value would be clientHeight, but you would be wrong, this is just one of those ways that HTML sucks.  Once we have the width and height, we then calculate our view dimensions, by subtracting the space needed for the other views ( or… will soon for height that is ).  We then set the canvas to those dimensions using setStyle(), which resizes the CANVAS in the browser.  We then create our Stage object from our canvas.  One thing to keep in mind, YUI get() and one() functions return YUI Node objects, not actual DOM objects, so when dealing with 3rd party libraries, you need to access the actual DOM item the node contains, that can be done with .getDOMNode().  Next we manually update the stage.canvas width and height, because of what I can only assume is a bug, EaselJS doesn’t pick up the modifications we made to the Canvas dimenions… who knows, there might be something else going on behind the scenes.  Next we create a circle… just so we have something visible on screen, and add it to our stage.

 

Now that resizeEvents is done, back in prepareCanvas we then set up a Ticker, which is an EaselJS callback mechanism, somewhat like setTimeout.  This is the heartbeat of your application, and due to the setFPS(30) call, it *should* be called 30 times per second.  This is your traditional game loop within the application and will probably be used quite a bit in the future.  Finally we handle windowresize events using the Y.on() handling mechanism, to catch the case the user resizes the screen, and if they do we call resizeEvents ( which being an eventhandler, will clobber all over our this pointer ).

 

Finally, we have the aforementioned gameloop, which is a function that is going to be called every time createjs.Ticker, um… Ticks.  For now we simply update our stage, then find the one and only item on our stage with getChildAt(0), which is our circle, and increment it’s X value until it scrolls off the screen.

 

It seems a bit more complicated than it is, but the basics of most of what we are going to want to deal with is now in place.  We can handle UI events via YUI, can render to the Canvas using the EaselJS library and best of all, take full advantage of the screen resolution, no matter how big or small, and gracefully handle changes in size, something Canvas doesn’t do easily.

 

Figuring out how everything interacted was more of a headache than I expected, but I am reasonably happy with this setup for now.  Of coure, I am going to need to add real functionality to the map view, and have it feed by a Map model instead of just drawing a circle on screen, but all things in time.

 

You can download the complete project as of this point right here.

You can see the project in action by clicking here.  As you resize, so will the canvas element.

Programming Design


4. October 2012

 

Earlier this morning, this news article came across my desk and caught my interest for a number of reasons.  Basically as the title states, Appcelerator - the makers of the popular Titanium mobile development suite have funded a game development technology startup Lanica.

 

Lanica Logo

So, why should you care?

 

Well first off, Appcelerator Titianium is a very nice development environment.  For a few different reasons I chose not to develop with Titanium, the inability to debug on Android devices being the biggest hindrance ( and mostly Google's fault for making such a terrible emulator ), however this fault may have been removed!  ( I will be looking into this very shortly ).

 

Next, while working in HTML5 on mobile is nice, the question still remains if it is feasible for high performance games.  PhoneGap brings HTML5 to mobile devices in native app form, but it doesn't bring the performance.  There are a number of other technologies working on this problem, but one more is always a nice thing.

 

Finally Lanica does have some pedigree.  One of the two founders is Carlos Icaza, who among other things, was the founder and first CEO of Ansca mobile, the people that make the popular Lua based Corona SDK.  ( Recently featured in this comparison of Lua game engines ).

 

So, they have funding, they have experience and they are creating a game engine using a technology I am interested in.  You can certainly colour me intrigued.

 

A little bit ( so far as I can gather ) about the engine itself, Platino:

Platino allows Titanium users to build casual to high-end games in JavaScript using a carefully optimized, C++ native-built, cross-platform game engine.

But wait, there’s more:

  • OpenGL ES 2.0:  We’re bringing you the industry standard in hardware-accelerated, cross-platform API for 2D and 3D graphics.  The OpenGL engine is a flexible and powerful low-level interface between software and graphics acceleration, so you get the best performance with the most efficient (i.e. lowest possible) use of resources.
  • Isometric Tile Engine:  We have developed our own internal isometric engine, written entirely in C++.  The best part? It features direct hardware rendering and occlusion detection for your maps to be rendered at full hardware speed, giving them near real-time interactivity.
  • Sprite Sheets:  We also have developed our own internal sprite sheet engine, which also is optimized for performance and rendering.
  • Box2D:  The same physics engine that drives Angry Birds and some of the most popular mobile games on the market is embedded in the Platino game engine.
  • Particles:  We know you’re too creative for a “one size fits all” approach. So, using our Particle Designer plug-in, you can now create stunning visual effects at hardware speeds by customizing every aspect of your particle emitters.
  • Shaders:  Our game engine leverages OpenGL’s shading language to calculate rendering effects on images, vertices, and pixels – giving you a high degree of flexibility and rendering capabilities for your games.
  • 2.5D Support:  Built natively (yet again!) to give your game that extra “depth” needed to create pseudo-3D effects.
  • Native Interface Access:  Full access to your creations, so you can tinker with the native UI, mouse events, accelerometer, and more through Titanium’s powerful JavaScript methods and classes.


So if you like to work in JavaScript, want to create a game targeting iOS and Android but with native performance, Lanica/Platino/Titanium are certainly worth keeping an eye on!

 

As of right now, they appear to be in the pre-beta stage, although there is a sign up page here.  Hopefully I am able to get more access to Platino shortly, so I can bring you a bit more information. Neither pricing nor a release date have been announced yet.

News


30. August 2012

 

In celebration of their 40th anniversary, Atari has re-released a number of their classic games as HTML5 in their newly launched web arcade.  Each of the titles has received a facelift, and the list includes:

  • Asteroids
  • Centipede
  • Combat
  • Lunar Lander
  • Missile Command
  • Pong
  • Super Breakout
  • Yar’s Revenge

 

 

As you can see, the games have received a facelift:

 

Asteroids:

image

 

Yar’s Revenge:

image

 

 

 

The project is a team up between Atari, CreateJS and Microsoft.  The Microsoft connection is Internet Explorer 10, which allows you to view the arcade ad free.  Atari is releasing an SDK for publishing on their arcade, the download and documentation page is currently down, so details are a bit sparse right now.  Their quick start pdf is currently available and gives a glimpse into the process. Presumably the arcade would work on a revenue sharing scheme, but that is just guesswork at the moment.

 

The library used to create all the games is called CreateJS, and is a bundling of HTML5 libraries including:

EaselJS – a HTML5 Canvas library with a Flash like API

TweenJS – a chainable tweening library

SoundJS – a HTML5 audio library

PreLoadJS – an asset loading and caching library

 

Plus the newly added tool, Zoe.  Zoe is a tool that takes SWF Flash animations and generates sprite sheets.

 

 

I look forward to looking in to Atari’s new API once their documentation page is back online.  Atari has also created a GitHub repository to support the project, but it is currently a little sparse.  In their own words:

 

Welcome to the Atari Arcade SDK.

This is the initial release of the SDK, which we hope to evolve over the next few weeks, adding
* more documentation
* examples
* updates

This repository contains
* Atari Arcade SDK classes in scripts/libs
* scripts necessary to run the SDK locally, in scripts/min
* API documentation and a quick start guide in docs/
* A test harness page to bootstrap and launch games

 

 

All told, a pretty cool project.  At the very least, check out the arcade, it’s a great deal of fun.

 

General


17. August 2012

 

In the past I mentioned and even recommended HTML5 developers give WebStorm a shot, this is the IDE I use personally when working in JavaScript, but I realized I never actually said why.  One of the big reasons is, its just a good solid text editor, with good project management and solid code completion, which is an area most tools fail at.  But one of the biggest reasons is, it gives a rock solid debugging experience… very similar to native code.  This is something that can make JavaScript development a WHOLE lot nicer.

EDIT: I should make it clear at this point, virtually nothing in this guide is specific to WebStorm, you can debug using the Chrome Developer Tools or using Firebug in FireFox. Webstorm however integrates the process directly within the IDE.  The process will change slightly ( different buttons/hotkeys ), but the instructions below basically apply to debugging in browser as well.

 

At the same time it dawned on me… if you don’t come from a compiled code background, you probably don’t even realize what you have been missing!  So, I have put this post together, it will hopefully make the developer experience better for at least a couple of you.  If you are currently debugging using a combination of alerts, console writes and breakpoints in the browser, listen up!

 

First off, you are going to need a project to debug.  I am going to use my most recent tutorial post on creating sprite sheets with Cocos2D if you want to download and follow along.  Of course, any project will work, but that particular project has an interesting… quirk that will come in useful.  Next, to get the most out of Webstorm debugging, you should also have Firefox installed.  If you are doing web development, I assume you do already anyways.  Alright, let’s get started.

 

Open the project up in WebStorm.

Now we want to create a debug profile.  In Webstorm, select Run->Edit Configurations…

image

 

In the resulting dialog, click the + icon:

image

 

Choose JavaScript Debug –> Local

image

 

On the left hand side, a new entry should appear.  Select it and file in the form like follows.  Navigate to your index.html or root HTML file, select Firefox from the browser dropdown and name it whatever you would like:

image

Click Apply then Ok when complete.

 

You are now ready to debug. 

Select Run-> Debug ‘Your App’ or press Shift + F9

image

 

Voila, or app should load up in our browser:

image

 

Now what we want to debug is debug the activity that occurs when the user presses a key.  Go back over to Webstorm, open MyFifthApp.js , locate the line with onKeyDown: function, and select the line right below it.  Here we want to set a breakpoint, which will cause our code to stop when the breakpoint is hit.  Set a breakpoint by hitting CTRL+F8 or selecting Run->Toggle Line Breakpoint.  You will see a red dot once your breakpoint is set, like so:

image

 

With the breakpoint set, now flip back to Firefox and hit a key.  This will immediately trigger the breakpoint, pausing your programs execution.  Now if you head back to Webstorm, there will be a wealth of information available to you:

 

image

 

There is quite a bit going on here.  Our code is currently paused executing on our breakpoint.  You can’t see it in the screenshot, but I am hovering my mouse over the e parameter, and it is popping up a tooltip showing its current value.  When debugging, you can interact with your code in a lot more detail.  Now lets take a closer look at the different bits of the interface here.

 

At the bottom left you have a very important window:

image

 

The toolbar on the left hand side can be used to resume program execution, stop completely, or to run from the beginning ( currently grayed out ).  When you are done with a breakpoint, you hit the resume button to continue your program execution.  The two buttons below on the toolbar are for managing breakpoints ( you can end up with a lot of them quickly! ), as well as to mute a breakpoint, which causes it not to fire DURING THIS DEBUGGING SESSION.  The next time you run your program, your breakpoint will be re-enabled unless you remove it.

 

To the right is something traditionally called a callstack, and it’s extremely useful.  Basically, it’s a hierarchy of the last functions called.  So in this case, you can see that our current ( anonymous) method inside MyFifthApp, was called by an anonymous method in CCKeyboardDispatcher, which was called by a different method in the same file.  Clicking the value in the callstack will immediately bring you to the line of code, where you can inspect the current value of any variables there.  Often the error actually occurs further up the callstack, so being able to trace backwards through a programs execution is incredible handy.

 

Next is an incredibly valuable toolbar, that controls your program’s execution while debugging.

 

image

These three are the most commonly used.

Step Over will cause your code to jump to the next line of code in the same file.

Step Into will jump into the code that you are currently on.  If it is a function for example, it will jump into the code for that function, even if it is in a different file.

Step Out backs you out, think of it like undoing a step into, you basically jump back into the calling code.

You use these 3 buttons ( or their hotkey/menu equivalents ) to run through your code as you debug.  There is also an option of run to cursor, which will run to whatever line of code your cursor is currently active on ( clicked on, not just hovering over ).

 

The program will update as it executes, so keep in mind, variable values will often be garbage, until the line they are allocated on is executed.

 

Next up is the Variables window.  Often called “Locals” in other IDEs:

image

 

This is a list of all locally declared variables.  Notice how indexAsString and prevPrefix are both shown, but valued as void?  This is because they haven’t been executed yet.  Lets take a closer look at that.  In WebStorm, locate the line this.removeChild(this.sprite), left click it to focus your cursor, then select run to cursor from the toolbar we just discussed:

image

 

As you can see from the blue line, or program execution continued to that point.  More importantly, if you look in the Variables window, they will now have values, since they have executed in the debugger:

image

 

You may also notice the + sign next to this.  That is because it isn’t a single value variable, so it is composed of other values.  Clicking the + icon will give you more details about the contents of that object:

image

 

Of course, often you want particular information about a specific variable.  This is where watches come in.  Say we want to see more details about this.sprite. In your code window, select all of this.sprite, right click and select Add To Watches.

image

 

Now details of that variable will be available in the watches window, at least, when it is in scope it will:

image

 

You can watch a number of variables at the same time.  Watches are especially useful for watching long lasting variables, like Director or when working in a browser, document.  Just like in the variables list, you can drill down to get more information on child values of the watched variable.

 

Another incredibly handy ability is the expression evaluator, invoked with this button:

image

 

The expression evaluator allows you to run any arbitrary code and see the value.  You can used it for example, to see what a function value would return.  Here for example, I am examining the results of calling this.sprite.getPosition().  Nicely, the expression evaluator has full code hints.

 

image

 

 

 

Finally, sometimes you want to debug code that is running from a server.  This is especially true if you are doing a number of AJAX or socket requests.  You can do this with Webstorm as well, with a few requirements.  First, you need to have a copy of the code installed locally, next you need to use Firefox for this part.

 

Let’s try it with our sample project, which exists on my servers at https://www.gamefromscratch.com/downloads/cocos2d/run/MyFifthApp/index.html while you can download the project source code at https://www.gamefromscratch.com/downloads/Cocos2d/zips/MyFifthApp.zip.

 

First we need to create a new remote debugging session.  In WebStorm, select Run->Edit Configurations…  Hit the + icon and selection JavaScript Debug->Remote.

image

 

Fill the resulting dialog out like so:

image

 

Click Apply then OK. Now everything else works exactly like it did before, with one exception.  Select Debug MyFifthApp Remote.

When you run your code and it hits a breakpoint, it will need you to tell it what file on the remote server matches the file the breakpoint is in.  Since we have a breakpoint set in MyFifthApp.js, when we run it, we will see:

 

image

 

Simply click the Set link, and a dialog will appear:

image

Simply type the URL of the remote file.  You only need to perform this once per file you set a breakpoint into.  You of course can perform this setup step in advance if you want.

 

Now you can locally debug code that is actually running on a remote server.

 

I hope you’ve found this guide handy.  In IDE debugging can make life a thousand times easier. 

General Programming


GFS On YouTube

See More Tutorials on DevGa.me!

Month List