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

Our application hasn’t looked very… applicationy up until this point.  The menu area was basically a space full with “coming soon”.  In this post we will address adding a menu to our HTML app and show how we can pass fire and handle menu click events.

 

First change I suppose, we need a menu.  We will be using the YUI menu plugin MenuNav.  If I am honest, it is unweildy compared to some HTML UI widgets I have used in the past, but since we are using YUI, might as well use it for everything.

 

We make the following changes to mainMenu.Template

 

<div style="width:100%" class="yui3-skin-sam">
    <div id="appmenu" class="yui3-menu yui3-menu-horizontal"><!-- Bounding box -->
        <div class="yui3-menu-content" ><!-- Content box -->
            <ul>
                <li>
                <a class="yui3-menu-label" href="#file">File</a>
                <div id="file" class="yui3-menu">
                    <div class="yui3-menu-content">
                        <ul>
                            <li class="yui3-menuitem" id="menuFileExit">
                                <a class="yui3-menuitem-content" href="#">Exit</a>
                            </li>
                        </ul>
                    </div>
                </div>
                </li>
            </ul>
        </div>
    </div>
</div>

Read the link above for more details about exactly what is going on here.  The key things to notice are the id’s for the menu (appmenu) and menu item (menuFileExit), both of those will be used shortly.  It is also of key importance to give the containing div the class yui3-skin-sam, as this is what brings in all of the YUI3 css and formatting.  You could also add this to the <BODY> tag in editor.View.js, which we may do as we add more YUI controls.  Just be aware that a parent node within the DOM needs to have this class declared.

 

So, that’s is our markup, lets look at the code side of things.  Open up and change mainMenu.View.js

YUI.add('mainMenuView',function(Y){
    Y.MainMenuView = Y.Base.create('mainMenuView', Y.View, [], {
        initializer:function(){
            var results = Y.io('/scripts/views/templates/mainMenu.Template',{"sync":true});
            // No need to compile, nothing in template but HTML 
            // this.template = Y.Handlebars.compile(results.responseText);
            this.template = results.responseText;
        },
        render:function(){
            this.get('container').setHTML(this.template);
            var container = this.get('container');

            var menu = container.one("#appmenu");
            menu.plug(Y.Plugin.NodeMenuNav);

            //Register menu handlers
            var menuFileExit = container.one('#menuFileExit');

            menuFileExit.on("click",function(e){
                alert("Publishing");
                Y.Global.fire('menu:fileExit', {
                    msg:"Hello"
                });
            });

            var menuFileAddSpriteSheet = container.one('#menuFileAddSpriteSheet');
            menuFileAddSpriteSheet.on("click", function(e){
                Y.Global.fire('menu:fileAddSpriteSheet', {msg:null});
            });

            return this;
        }
    });
}, '0.0.1', { requires: ['view','io-base','node-menunav','event','handlebars']});

Here we changed our initializer to load synchronously as well, otherwise the basics are pretty much the same.  Not that we added the ‘node-menunav’ and ‘event’ dependencies to our requires array.  Otherwise the key changes are:

var menu = container.one("#appmenu");
menu.plug(Y.Plugin.NodeMenuNav);

This locates our appmenu div and plugs the NodeMenuNav into it, turning our DIV into a YUI3 style menu.  Basically this is where the magic happens.  Then:

var menuFileExit = container.one('#menuFileExit');
menuFileExit.on("click",function(e){
    alert("Publishing");
    Y.Global.fire('menu:fileExit', {
        msg:"Hello"
    });
});

Next we find our menuFileExit menu item and register an onClick handler for it.  When a click occurs we fire a global event named “menu:fileExit”, with a msg of Hello.  The name menu:fileExit was chosen by me and can be anything.  So, when the user clicks the Exit item in the menu, this event will be fired.  Let’s look at how you handle “catching” this event.  Open up editor.View.js and at the bottom of the initializer() function, add the following code:

Y.Global.on('menu:fileExit', function(e){
   alert(e.msg);
});

Basically, this monitors for a menu:fileExit event being fired, and simple alerts the contents.  This illustrates a simple way to provide a global menu which can be handled across multiple views.

 

Here is our project in action now:

Basically, it is exactly the same as before, but now it has a menu.

 

You can download the complete source code here.

Design Programming


8. October 2012

 

As per this post I am currently going through the process of creating some simple game creation tools using HTML5, more specifically using the YUI 3 library as well as the EaselJS canvas library.

 

This post illustrates the very skeleton upon which we are going to create our app.  YUI3 provides a full MVC framework which you can use to create your application so I decided to make use of it.  The end result of this code is remarkably minimal, it just creates a single page web application with different views representing different portions of the UI.  Specifically, we will create a top zone where the menu will go, a left hand area where the level editing will occur, then a right hand panel which will change contextually.  I also created a very simple data class, to illustrate how data works within the YUI MVC environment.

 

First off, if you have never heard of MVC, it is the acronym of Model View Controller.  MVC is a popular design practice for separating your application in to logically consistent pieces.  This allows you to separate your UI from your logic and your logic from your data ( the last two get a little gray in the end ).  It adds a bit of upfront complexity, but makes it easier to develop, maintain and test non-trivial applications… or at least, that’s the sales pitch.

 

The simplest two minute description of MVC is as follows.  The Model is your application’s data.  The View is the part of your application that is responsible for displaying to the end user.  The Controller part is easily the most confusing part, and this is the bit that handles communications between the model and view, and is where you actual “logic” presides.  We aren’t going to be completely pure in this level in this example ( MVC apps seldom are actually ), as the Controller part of our application is actually going to be a couple pieces, you will see later.  For now just realize, if it aint a view and it aint a model, it’s probably a controller.

 

It is also worth clarifying that MVC isn’t the only option.  There is also MVVM ( Model-View-ViewModel ) and MVP ( Model-View-Presenter ), and semantics aside, they are all remarkably similar and accomplish pretty much the same thing.  MVC is simply the most common/popular of the three.

 

Put simply, it will look initially more complex ( and it is more complex ), but this upfront work makes life easier down the road, making it generally a fair trade off.

 

Alright, enough chatter, now some code!  The code is going to be split over a number of files.  A lot of the following code is simply the style I chose to use, and is completely optional.  It is generally considered good practice though.

 

image 

At the top level of our hierarchy we have a pair of files, index.html and server.js.  server.js is fairly optional for now, I am using it because I will (might?) be hosting this application using NodeJS.  If you are running your own web server, you don’t need this guy, and won’t unless we add some server-side complexity down the road.

 

index.html is pretty much the heart of our application, but most of the actual logic has been parted out to other parts of the code, so it isn’t particularly complex.  We will be looking at it last, as all of our other pieces need to be in place first.

 

Now within our scripts folder, you will notice two sub-folders models and views.  These predictable enough are where our models and views reside.  In addition, inside the views directory is a folder named templates. This is where our moustache templates are.  Think of templates like simple HTML snippets that support very simple additional mark-up, allowing for things like dynamically populating a form with data, etc.  If you’ve ever used PHP, ASP or JSP, this concept should be immediately familiar to you.  If you haven’t, don’t worry, our templates are remarkably simple, and for now can just be thought of as HTML snippets.  The .Template naming convention is simply something I chose, inside they are basically just HTML.

 

If you are basing your own product on any of this code, please be sure to check out here, where I refactored a great deal of this code, removing gross hacks and cleaning things up substantially!

 

Let’s start off with our only model person.js, which is the datatype for a person entry.  Let’s look at the code now:

 

person.js

YUI.add('personModel',function(Y){
    Y.Person = Y.Base.create('person', Y.Model, [],{
            getName:function(){
                return this.get('name');
            }
        },{
            ATTRS:{
                name: {
                    value: 'Mike'
                },
                height: {
                    value: 6
                },
                age: {
                    value:35
                }
            }
        }
    );
}, '0.0.1', { requires: ['model']});

The starting syntax may be a bit jarring and you will see it a lot going forward.  The YUI.add() call is registering ‘personModel’ as a re-usable module, allowing us to use it in other code files.  You will see this in action shortly, and this solves one of the biggest shortcomings of JavaScript, organizing code.

 

The line Y.Person = Y.base.create() is creating a new object type in the Y namespace, named ‘person’ and inheriting all of the properties of Y.Model.  This is YUI’s way of providing OOP to a relatively un-OOP language.  We then define a member function getName and 3 member variables name, height and age, giving each of the three default values… just cause.  Of course, they aren’t really member variables, they are entries in the object ATTRS, but you can effectively think of them as member variables if you are from a traditional OOP background.  Next we pass in a version stamp ( 0.0.1 ), chosen pretty much at random by me.  Next is a very important array named requires, which is a list of all the modules ( YUI, or user defined ) that this module depends on.  We only need the model module.  YUI is very modular and only includes the code bits you explicitly request, meaning you only get the JavaScript code of the classes you use.

 

So that is the basic form your code objects are going to take.  Don’t worry, it’s nowhere near as scary as it looks.  Now let’s take a look at a view that consumes a person model.  That of course would be person.View.js.  Again, the .View. part of that file name was just something I chose to do and is completely optional.

person.View.js

YUI.add('personView',function(Y){
        Y.PersonView = Y.Base.create('personView', Y.View, [], {
        initializer:function(){
            var that=this,
                request = Y.io('/scripts/views/templates/person.Template',{
                    on:{
                        complete:function(id,response){
                            var template = Y.Handlebars.compile(response.responseText);
                            that.get('container').setHTML(template(that.get('model').getAttrs(['name','age','height'])));
                        }
                    }
                });
        },
        render:function(){
            return this;
        }
    });
}, '0.0.1', { requires: ['view','io-base','personModel','handlebars']});

Just like with our person model, we are going to make a custom module using YUI.add(), this one named ‘personView’.  Within that module we have a single class, Y.PersonView, which is to say a class PersonView in the Y namespace.  PersonView inherits from Y.View and we are defining a pair of methods, initializer() which is called when the object is created and render() which is called when the View needs to be displayed.

 

In initializer, we perform an AJAX callback to retrieve the template person.Template from the server.  When the download is complete, the complete event will fire, with the contents of our file in the response.responseText field ( or an error, which we wrongly do not handle ).  Once we have our template text downloaded, we “compile” it, which turns it into a JavaScript object. The next line looks obscenely complicated:

that.get('container').setHTML(template(that.get('model').getAttrs(['name','age','height'])));

A couple things are happening here.  First we are using that because this is contextual in JavaScript.  Within the callback function, it has a completely different value, so we cached the value going in.  Next we get the property container  that every Y.View object will have, and set it’s HTML using setHTML().  This is essentially how you render a view to the screen.  The parameter to setHTML is also a bit tricky to digest at first.  Essentially the method template() is what compiles a moustache template into actual HTML.  A template, as we will see in the moment, may be expecting some data to be bound, in this case name, age and height which all come from our Person model.  Don’t worry, this will make sense in a minute.

 

Our render method doesn’t particularly do anything, just returns itself.  Again we specify our modules dependency in the requires array, this time we depend on the modules view, io-base, personModel and handlebars.  As you can see, we are consuming our custom defined personModel module as if it was no different than any of the built-in YUI modules.  It is a pretty powerful way of handling code dependencies.

 

Now let’s take a look at our first template.

person.Template

<div style="width:20%;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>

As you can see, a template is pretty much just HTML, with a few small exceptions.  Remember a second ago when we passed data in to the template() call, this is where it is consumed.  The values surrounded by {{ }}  ( thus the name moustache! ) are going to be substituted when the HTML is generated.  Basically it looks for a value by the name within the {{ }} marks and substitutes it into the HTML.  For example, {{name}}, looks for a value named name, which it finds and substitutes it’s value mike in the results.  Using templates allows you to completely decouple your HTML from the rest of your application.  This allows you to source out the graphic work to a designer, perhaps using a tool like DreamWeaver, then simply add moustache markup for the bits that are data-driven.

 

What you may be asking yourself is, how the hell did the PersonView get it’s model populated in the first place?  That’s a very good question.

 

In our application, our view is actually going to be composed of a number of sub-views.  There is a view for the area the map is going to be edited in, a view for the context sensitive editing will occur ( currently our person view ), then finally a view where our menu will be rendered.  However, we also have a parent view that holds all of these child views, sometimes referred to as a composite view. This is ours:

editor.View.js

YUI.add('editorView',function(Y){
    Y.EditorView = Y.Base.create('editorView', Y.View, [], {
        initializer:function(){

            var person = new Y.Person();
            this.pv = new Y.PersonView({model:person});
            this.menu = new Y.MainMenuView();
            this.map = new Y.MapView();
        },
        render:function(){
            var content = Y.one(Y.config.doc.createDocumentFragment());
            content.append(this.menu.render().get('container'));

            var newDiv = Y.Node.create("<div style='width:100%'/>");
            newDiv.append(this.map.render().get('container'));
            newDiv.append(this.pv.render().get('container'));

            content.append(newDiv);
            this.get('container').setHTML(content);
            return this;
        }
    });
}, '0.0.1', { requires: ['view','io-base','personView','mainMenuView','mapView','handlebars']});

The start should all be pretty familiar by now.  We again are declaring a custom module editorView. This one also inherits from Y.View, the major difference is in our initializer() method, we create a Y.Person model, as well as our 3 custom sub-views, a PersonView, a MainMenuView and a MapView ( the last two we haven’t seen yet, and are basically empty at this point ).  As you can see in the constructor for PersonView, we pass in the Y.Person person we just created.  This is how a view gets it’s model, or at least, one way.

 

Our render() method is a bit more complicated, because it is responsible for creating each of it’s child views.  First we create a documentFragment, which is a chunk of HTML that isn’t yet part of the DOM, so it wont fire events or cause a redraw or anything else.  Basically think of it as a raw piece of HTML for us to write to, which is exactly what we do.  First we render our MainMenuView, which will ultimately draw the menu across the screen.  Then we create a new full width DIV to hold our other two views.  We then render the MapView to this newly created div, then render the PersonView to the div.  Finally we append our new div to our documentFragment.  Finally we set our view’s HTML to our newly created fragment, causing all the views to be rendered to the screen.

 

Once again, we set a version stamp, and declare our dependencies.  You may notice that we never had to include personModel, this is because personView will resolve this dependency for us.

 

Lets quickly look at each of those other classes  ( mainMenuView and mapView ) and their templates, although all of them are mostly placeholders for now.

 

mainMenu.View.js

YUI.add('mainMenuView',function(Y){
    Y.MainMenuView = Y.Base.create('mainMenuView', Y.View, [], {
        initializer:function(){
            var that=this,
                request = Y.io('/scripts/views/templates/mainMenu.Template',{
                    on:{
                        complete:function(id,response){
                            var template = Y.Handlebars.compile(response.responseText);
                            //that.get('container').setHTML(template(that.get('model').getAttrs(['name','age','height'])));
                            that.get('container').setHTML(template());
                        }
                    }
                });
        },
        render:function(){
            return this;
        }
    });
}, '0.0.1', { requires: ['view','io-base','handlebars']});

mainMenu.Template

<div style="width:100%">This is the area where the menu goes.  It should be across the entire screen</div>

 

map.View.js

YUI.add('mapView',function(Y){
    Y.MapView = Y.Base.create('mapView', Y.View, [], {
        initializer:function(){
            var that=this,
                request = Y.io('/scripts/views/templates/map.Template',{
                    on:{
                        complete:function(id,response){
                            var template = Y.Handlebars.compile(response.responseText);
                            that.get('container').setHTML(template());
                            //that.get('container').setHTML(template(that.get('model').getAttrs(['name','age','height'])));
                        }
                    }
                });
        },
        render:function(){
            return this;
        }
    });
}, '0.0.1', { requires: ['view','io-base','handlebars']});

map.Template

<div style="width:80%;float:left">
    This is where the canvas will go
</div>

Now, we let’s take a quickly look at server.js.  As mentioned earlier, this script simply provides a basic NODEJS based HTTP server capable of serving our app.

server.js

var express = require('express'),
    server = express();

server.use('/scripts', express.static(__dirname + '/scripts'));

server.get('/', function (req, res) {
    res.sendfile('index.html');
});

server.listen(process.env.PORT || 3000);

 

I wont really bother explaining what’s going on here.  If you are going to use Node, there is a ton of content on this site already about setting up a Node server.  Just click on the Node tag for more articles.

 

Finally, we have index.html which is the heart of our application and what ties everything together and this is the file that is first served to the users web browser, kicking everything off.

index.html

<!DOCTYPE html>

<html>
<head>
    <title>GameFromScratch example YUI Framework/NodeJS application</title>
</head>
<body>

<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>
<script src="/scripts/models/person.js"></script>
<script src="/scripts/views/person.View.js"></script>
<script src="/scripts/views/map.View.js"></script>
<script src="/scripts/views/mainMenu.View.js"></script>
<script src="/scripts/views/editor.View.js"></script>

<script>
    YUI().use('app','editorView', function (Y) {

        var app = new Y.App({
            views: {
                editorView: {type: 'EditorView'}
            }
        });

        app.route('/', function () {
            this.showView('editorView');//,{model:person});
        });

        app.render().dispatch();
    });
</script>


</body>
</html>

 

This sequence of <script> tags is very important, as it is what causes each of our custom modules to be evaluated in the first place.  There are cleaner ways of handling this, but this way is certainly easiest.  Basically for each module you add, include it here to cause that code to be evaluated.

 

Next we create our actual Y function/namespace.  You know how we kept adding our classes to Y., well this is where Y is defined.  YUI uses an app loader to create the script file that is served to your clients browser, which is exactly what YUI.use() is doing.  Just like the requires array we passed at the bottom of each module definition, you pass use() all of the modules you require, in this case we need the app module from YUI, as well as our custom defined editorView module.

 

Next we create a Y.App object.  This is the C part of MVC.  The App object is what creates individual views in response to different URL requests.  So far we only handle one request “/”, which causes the editorView to be created and shown.  Finally we call app.render().dispatch() to get the ball rolling, so our editorView will have it’s render() method called, which will in turn call the render method of each of it’s child views, which in turn will render their templates…

 

Don’t worry if that seemed scary as hell, that’s about it for infrastructure stuff and is a solid foundation to build a much more sophisticate application on top of.

 

Of course, there is nothing to say I haven’t made some brutal mistakes and need to rethink everything! Smile

 

Now, if you open it up in a browser ( localhost:3000/ if you used Node ), you will see:

image

 

Nothing too exciting as of yet, but as you can see, the menu template is rendered across the top of the screen, the map view is rendered to the left and the Person view is rendered on the right.  As you can see from the text, the data from our Person model is compiled and rendered in the resulting HTML.

 

You can download the complete project archive right here.

Design Programming


27. September 2012

 

The author contacted me a few weeks up with a heads up that he had a Moai friendly Lua IDE in development and I said I would look into it… and well, I didn’t.  Things came up, then something else and something else and frankly it got pushed into the back of my mind.  In the end, that was a good thing too, as since that point in time the author has added auto-completion… a critical feature.

 

As of writing though, this feature is only available from the github sources.  So long as you have cygwin configured ( assuming you are working with Moai, you should already ), and git installed, the process is fairly simple:

 

cd /cygdrive/c/folder/to/install/to

git clone https://github.com/pkulchenko/ZeroBraneStudio.git

 

This will create a folder ZeroBraneStudio with all the appropriate files. 

EDIT (29/09/2012): Author made update, should no longer need to set permissions described below

There is another catch, git mangles the executable permissions on Windows.  The long answer is well… long, the hackishly easy answer is to run:

chmod a+x –R ZeroBraneStudio

 

There is one last catch, you need to set the MOAI_BIN environment variable to point to your MOAI host folder, either that or add it to your PATH variable.  ( I suggest the former ).  To set the MOAI_BIN path, simply open a command prompt and type:

setx MOAI_BIN c:/path/to/moai/host

 

You can of course set the environment variables using the System control panel, but this will require you to reboot your computer for the change to take effect.  SetX simply requires you close the console to take effect.

 

Now you should be able to run the Studio, just double click zbstudio.exe to start it.  Hopefully the author will have a new release soon, that prevents all of this ( except the MOAI_BIN environment variable that is ).  Finally run ZeroBrane and this is what you see:

 

image

 

 

So then… why?  What does ZeroBraneStudio bring to the table that SublimeText or IntelliJ don’t have?

 

That’s an easy one.  I mentioned the first one earlier:

 

image

 

Auto-completion!  After years of using Visual Studio, this one is a gigantic must for me.  Granted as I covered earlier, IntelliJ can be configured to supported auto completion.  But ZeroBrane Studio has a massive head up on IntelliJ, watch this!

 

image

 

This you cannot do with IntelliJ, and it is a gigantic advantage.  But auto-completion isn’t the only thing ZB brings to the table, ZeroBrane Studio has the ability to debug running code!  You can set breakpoints, step in/over and out, set watches and do dynamic expression evaluations, pretty much most of what you expect to see in a debugger. Oddly enough, this needed a Windows Firewall exception.

 

To debug your code, select a line of text to set a breakpoint then hit F9 to create a breakpoint ( a red stop sign will appear in the margin ).  Then select Project->Start Debugging Server.  Then select Project->Start Debugging or hit F5 to run your code and voila:

image

 

Code execution stops at your breakpoint.  Use F10, Ctrl+F10 and Shift+F10 enable you to navigate through your code. You can hover your mouse over a variable to inspect it’s value.  You can also right-click a variable and create a watch window like this:

image

Unfortunately you can’t drill down into an individual Lua table, but hopefully this feature gets added soon!

 

Perhaps coolest of all, ZeroBrane Studio enables REPL interaction.  You can open the console and interact with your code directly:

image

 

As you can see, you can interact with your values in real time, and here are the results in the output:

image

 

It also has the ability to analyze your code, and show you the plethora of stupid mistakes you are making:

image

 

Not everything is perfect.  As mentioned earlier, watch expressions cant drill down into Lua tables, hopefully something that will change soon.  Additionally, it would be nice if the Moai host could be added using a configuration setting instead of using MOAI_BIN, as it makes it difficult to change between runtimes ( moai, moai-untz, release, debug, etc… ), but this is a minor point.  It would also be nice to be able to control more via context menu’s ( add breakpoint, step over/in, etc ). The code syntax highlighting could be improved a bit as well.  Of course, as a straight code editor, it isn’t going to give IntelliJ or SublimeText a run for it’s money just yet.

 

 

That said, this is an absolutely invaluable tool for people working with Moai or LOVE, the debugger and full auto-completion guarantee that this is going to be a stable part of my toolset going forward.  Hopefully the author is able to add more detailed debugging information soon.  If you are working in Moai or LOVE, you owe it to yourself to check out ZeroBrane Studio.

 

Speaking of which, you can get more information here.  Keep in mind, MOAI auto-completion is currently only available in the source distribution, at least as of version 0.32.  Hopefully the new release is bundled soon.

 

EDIT:

I have spoken with the author, and it appears a few of my issues aren’t issues after all.

The system will check for Moai executable in your PATH environment
variable. You can also set "path.moai = 'd:/lua/moai/moai'" in
cfg/user.lua (see cfg/user-sample.lua for example).

 

EDIT2:

ZeroBrane actually can drill down details into a Lua table, in my relative Lua newbishness, I made a pair of mistakes.  First off, it only works on local variables.  Second, Moai does not return tables, it returns Userdata, which ZeroBrane currently can’t parse ( fingers crossed he figures out a way! ).

 

image

 

Here is the behaviour I was expecting to see, and exactly what I got once I defined the table as a local.

General Programming


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


21. March 2012

 

 

Hey, I’m on time this time! Well, almost…

 

 

This weeks cool thing is in an area where there aren’t too many options, audio capture and manipulation tools.  On the “pro” side, the dominant player is probably Pro-Tools, which is in a word expensive.  With pricing starting at 700$ and going up from there, it is out of the reach of many peoples budget.  Truth of the matter is, it’s probably overkill for most people too.

 

 

In the mid range you have other, slightly cheaper options such as Adobe's SoundBooth or if you are the Mac type, Apple’s Logic Pro.  Both of these apps sell for about 200$.  If you’ve noticed one thing about me though, it’s I like free stuff, I really like free stuff.

 

 

Thankfully there is a free option, and it’s pretty damned good.  This weeks CTofW is Audacity.  In addition to being a rather clever pun, it is also a “free, open source, cross-platform software for recording and editing sounds.  It is available on Windows, Linux and Mac. 

 

 

Audacity in action editing a Wav file:

image

 

 

As is pretty typical of open-source projects, it’s a bit on the ugly side, although compared to it’s open-source peers, it is the belle of the ball.  However, unlike most open sourced projects, it’s incredibly well documented.  In addition to the included documentation, there are actually a few published books including Getting Started with Audacity 1.3 and The book of Audacity.  It’s a good thing too, even though Audacity is pretty simple to get started with, it’s an amazingly deep program.  The short form description for their site goes as follows:

 

You can use Audacity to:

  • Record live audio.
  • Convert tapes and records into digital recordings or CDs.
  • Edit Ogg Vorbis, MP3, WAV or AIFF sound files.
  • Cut, copy, splice or mix sounds together.
  • Change the speed or pitch of a recording.
  • And more!

 

 

 

Instead of going into depth here about what this program can do, I’ll refer you to their feature list.  And I promise you, that list just scratches the surface.

 

 

So, if you are looking for a audio capture and manipulation application and are doing things on a budget, you really can’t do better than Audacity.  Seeing as it’s free and only a 20MB download, what have you got to lose?

Cool Thing of the Week


GFS On YouTube

See More Tutorials on DevGa.me!

Month List