HTML5 Crash Course: Digging into Javascript’s Weirdness

POSTED Wed Feb.13.2013 by Dave Seah UNDER Project TAGGED

This is a series of posts where I'm familiarizing myself with HTML5, which is new to me, presented as a series of notes to myself. The articles are tagged h5cc


Today I looked at the HTML5 Boilerplate and KnockoutJS.

  • HTML5 Boilerplate is an application framework, meaning it’s a bare-bones way of structuring the way your HTML5 app loads resources and starts up. The alternative is to come up with your own organization.

  • KnockoutJS is a pure Javascript library that implements a “Model – View – ViewModel” pattern in a clean, declarative way. I don’t yet know exactly what the ramifications are, but there’s an awesome interactive tutorial that walks you through it.

Exploring these two environments today gave me additional insight into Javascript Weirdness related to its super-flexible object-oriented underpinnings. Basically everything is an object, even the ones that look like they might be functions or expressions. Writing Javascript is like living on the frontier, where STREET JUSTICE prevails over centralized language specification. There are no police. It’s up to you to enforce good programming habits, because Javascript doesn’t have any built-in to save you from shooting yourself in the foot.

As a result, you need to explore the Javascript community for a bit to understand what the law of the land is. Here’s some of the ones that I collected yesterday:

Functions and Parenthesis

The jQuery library is used everywhere, as it is one of those libraries that makes cross-browser DOM manipulation more “write-once” than “hope and pray it works in every browser”, which was the reason I avoided Javascript for so many years. To start executing your code that uses jQuery, though, you need to make sure it’s loaded. Since browsers load resources asynchronously, and also have slightly different ways they do it, jQuery itself provides a means to call your important startup function: $(document).ready(). The ready() call takes a function as an argument, which is executed when it’s time to run.

Unfortunately, in the non-trivial code examples, the ready() sometimes looks like this:

(function($) { 
    $(function() {
        // code using $ as alias to jQuery
    });
})(jQuery);

Note the enclosing parenthesis. WHAT IS THIS? The short answer is that it converts the function() definition into an object expression which is then executed immediately, with the jQuery object passed to it as a parameter. WHY IN THE WORLD would you want to do something as convoluted as this? It’s to make the variables in your code private through the implicit creation of a Javascript “Closure”, which is the variable scope/state within a function. Since scripts in a browser all run in the same global namespace, they can overwrite each other. The code here creates an anonymous function, which in turn has its own closure with the $ variable assigned to the jQuery object. Everything inside has its own private space to declare whatever variables it wishes. Furthermore, the variable state exists after the code finishes running (another aspect of closures which is a bit different from other compiled languages), so you can safely assign event handler functions that refer to variables inside; they remain persistent.

The enclosing parenthesis is not necessary, but is added so you can tell right away that this is the case. Technically, Javascript will do the closure thing because of the (jQuery) tacked on the end, but it is unclear that it’s not a function definition until the very end. Adding the explicit () around it turns it into an explicit EXPRESSION instead of a function declaration; this is pure coding style because the () at the end also turns the function declaration syntax into an expression, but you see it all the way at the end and then you’re like, “damn, this isn’t a definition that’s called, it’s something that runs right now”.

You also see stuff like:

!function($) { 
    $(function() {
        // code using $ as alias to jQuery
    });
}(jQuery);

I KNOW…WHAT? The ! is the unary negation operator, and it has the side effect of telling Javascript that an expression follows it. This is the same effect as using (), which is the arithmetic precedence operator. Both, being operators, turn the function into an expression, which is OK because expressions can be executed when a () is after them to turn it into a function invocation. That executes immediately. You could also use + or – as well and get the same effects…it’s purely for code readability.

It seems stupid, but it’s necessary to establish a private namespace (via closures) so you can write code without side effects like name collisions. Other languages have explicit ways of establishing a namespace, but Javascript does not.

Well, there is stuff like this:

var myNameSpace = myNameSpace || {}
myNameSpace.myProperty = 1;
myNameSpace.myFunction = function(x) {};

This creates an object with objects assigned on-the-fly. Although since I used var, it’s local to the closure that the namespace is declared in. If I didn’t use var, I think that means it would be in the global namespace. Argh.

Anyway, that is enough of this for the day. Here’s the links that helped me understand this:

  • http://michaux.ca/articles/an-important-pair-of-parens
  • http://blog.themeforest.net/tutorials/ask-jw-decoding-self-invoking-anonymous-functions/
  • http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Leave a comment

HTML5 Crash Course: Some Starting Specification

POSTED Tue Feb.12.2013 by Dave Seah UNDER Project TAGGED

This is a series of posts where I'm familiarizing myself with HTML5, which is new to me, presented as a series of notes to myself. The articles are tagged h5cc


Yesterday I’d started to gather materials on HTML5 online before remembering that I had a book. I septn a little bit of time before going to sleep skimming the HTML5 and Javascript references I have, and came to the conclusion that HTML5 itself is just a bunch of new features. The ones I’m interested in are the Canvas, Sound, and Event models.

I need a very basic app to get focused. It might be instructive to write a simple GUI that gets something done. That would familiarize myself with a few things

  1. Basic HTML5 Layout of Elements
  2. Using jQuery to bind events to the Elements
  3. Writing some Javascript core code to send events and data requests to my own server using JSON or something

I think I’d like to make a basic two-column text editor. This is something that’s been on my mind for a while.

I’m kind of tired, so I think I’ll do the setup of a framework later today or tomorrow. My testbed will be the davidseah.net server, where my other experiments live.

Here’s what the HTML5 page needs:

  • HTML5 markup!
  • A place to LOAD script libraries!
  • A way to detect no javascript and gracefully degrade
  • A way to debug!

That’s a good enough starting list.

Leave a comment

HTML5 Crash Course: Kickoff

POSTED Mon Feb.11.2013 by Dave Seah UNDER Kickoff TAGGED ,

This is a series of posts where I'm familiarizing myself with HTML5, which is new to me, presented as a series of notes to myself. The articles are tagged h5cc


I’m starting an HTML5 crash course for myself. I’m applying the 15 minute ritual to this. This is the first 15 minutes.

What I know about HTML5 is this:

  • There are a bunch of new semantic elements, like <section>. I’ve read that this should be ignored because they’re really not the point.
  • More interestingly, there is a refined DOM and new Javascript features related to new objects like <canvas> and <audio>.

To get my head wrapped around HTML5, I need to do the following:

  • Find a good reference for HTML5 features, in a nutshell. I know I’ve seen them.
  • Consolidate my Javascript knowledge and workflow for editing and debugging.
  • Set up a development environment where I can play and keep track of samples, maybe in a VM
  • Maybe pick a framework to start with?
  • Or a project to build?

There are some issues with HTML5 that prevent adoption by a broader base of users, I suspect.

Getting Familiar

These references, so far, kind of really don’t give me a starting place. Let’s look for Javascript HTML5 next. Oh, I forgot I had this book:

  • HTML5 Up and Running – by Mark Pilgrim. My cousin Ben recommended this to me.

Development

  • HTML5 Shiv – some kind of IE9 enabling script
  • CreativeJS – neat javascript examples.
  • CraftyJS – some kind of framework, it looks like.
  • Maintainable Javascript – by Nicholas C. Zakas, also recommended by Ben.

OOOPS, out of time!


Post Notes

  • Dive Into HTML5 – Apparently this is the source for the HTML5 book, maintained by the community.
  • Ben mentioned “Phonegap, HTML5 Boilerplate, jQuery Mobile”. What are those? Hm.
  • HTML Boiler Plate – Ben said this was worth looking into.
  • The question: Do I want to make HTML5 my new interactive platform for development? That’s what I’m trying to find out.
  • Can I alternatively just have other people do my interactive work? My thoughts: no. I want control over this so I can wield it as an expressive medium for demonstrating my ideas. It would take a pretty exceptional developer to meet my needs. Perhaps if I could afford to pay someone, it’s worthwhile.
Leave a comment

AS3 and Flash Document Class

POSTED Wed Oct.31.2012 by Dave Seah UNDER Tips

I’ve been thinking about porting some old ActionScript 2 code to ActionScript 3 and building an AIR app. The big advantage of ActionScript 3 is that it’s faster AND has a new package hierarchy that makes way more sense than the old one. For example, you can now instantiate a MovieClip or TextField with var mc:MovieClip = new MovieClip(), which looks totally normal. In ActionScript 2, you’d actually have to call DuplicateMovieClip() on an existing MovieClip instance.

Anyway, there’s always a little bit of magic involved in setting up a new “Hello World” style program. As is the norm, the official “Getting Started” material that I could find is simplistic to the point of uselessness…who writes these things? I don’t want to print “hello world”; I want to set up the basis of a rich flourishing application. Here’s the basic steps I followed with Flash Professional CS 5.5.

1. Create a New Project

Switched to the “Developer” Workspace Layout, which exposes the Project Panel. Created a new project, which creates a Flash .FLA stub file. We’ll be setting properties here later.

On a side note, the Project Manager is as terrible as I remember it from 2007, but at least it is just a mirror of an underlying directory structure. Nothing fancy here!

2. Create the Startup Class

The Flash file will end up holding any static library assets I create such as animations and graphics, but I will be using code attached to instances I create dynamically with my own scripting. Rather than stuff this all in Frame 1 of the timeline, there’s a way of binding a particular class to the Flash file. This is a class that is instantiated on startup. It’s known officially as the document class, and you set it under Properties for the .FLA file.

Class files in Actionscript 3 have the .as extension, and the filename must match the class name. There is also the notion of packages. I created a package path of dseah, which is implemented as a folder relative to the .FLA file.

project_folder/
    dseah/
        MainClass.as
    DaveTest01.fla
    DaveTest01.swf

My DaveTest01.fla file is at the same level as the dseah folder. Inside this folder I created MainClass.as, which is declared as follows:

package dseah { 
    
    import flash.display.MovieClip; 

    public class MainClass extends MovieClip { 
        public function MainClass() { 
            trace ('Hello World'); 
        }
    } 
}

Two Important Notes:

  • See how MainClass extends MovieClip? That’s because the class we’re setting as the document class is a representation of the .FLA file, which is a MovieClip.
  • When we go to properties to set the document class, we also have to use the entire package path, which here is dseah.MainClass.

3.0 Compile and Test!

I clicked the “Test Project” button and did see that the trace worked, outputing “Hello World” to the console. Whee! So that’s it. Took me 90 minutes to dig up these basic setup facts while I was at Starbucks. I suppose that if I’d had a copy of Colin Moock’s Actionscript 3: The Complete Reference I would have saved myself some time. Grumble grumble.

Leave a comment

XNABS2: XML Read Routines

POSTED Thu Sep.13.2012 by Dave Seah UNDER Project TAGGED

It’s been a while since I worked on this project. I want to get the XMLReader code to work right, then I’m going to see how the 3d model import workflow works. Which means I need to be able to make 3D models to import in the first place. First things first: let’s get this XMLReader to work.

There were a few bugs leftover from the last attempt. I needed to specify the data directory, get rid of some overzealous try/catch exceptions which masked some important errors, and also add a specific enclosing XML tag in the data files. Updated the GameData.XML reader routines in BaseGameData, as well. Its XML reading is set up differently that in SettingsManager, which bugs me a bit, but I’m going to leave it alone.

And that about does it for the XML reading. I now have the following capabilities:

  • Read key/value pairs from an XML file for common settings
  • Read Game setup data from an XML file

Next up: Exporting a textured 3D model from Modo, Importing into XNA, Refactoring the View and Camera Classes.

Leave a comment

XNABS2: Pondering the Next Stage, Loader Code

POSTED Sat Aug.25.2012 by Dave Seah UNDER Project TAGGED

Yesterday I finished cobbling together the first rudimentary bits of plumbing, clarifying some architectural issues that would make this version of the codebase a little easier to work with. There are a few interesting rabbit holes to explore along the way too, because .NET is a gigantic framework that encompasses all manner of programming tomfoolery.

Anyway, what’s in the current codebase is this:

  • A startup sequence that works within the confines of XNA’s notion of a Game Loop + Initialiation.
  • A pretty well-defined procedure for handling the creation of my own main game objects of various type and vintage within the context of the XNA Game Loop + Initialization.
  • A rudimentary Debugger and Console, though I haven’t rewritten the command stuff yet
  • An Input Manager
  • A Settings Manager
  • A package hierarchy
  • A Mercurial repository and central Bitbucket.org repository
  • A rudimentary event listener structure and inter-object communication setup for main game objects
  • Graphics Initialization and Debug messages written to the console

What was most important to me was to get the procedures, settings, and debugger setup so I could start building the rest and have some way to debug it. There are a lot of different things I could implement next, and I’d love to just dive write in and port the graphics routines. However, this routines are already written; what I should work on first is a new object creation language.

Currently, game engine 1.0 uses XML files to define everything that appears in the game at the Piece, Visual, and Player level. However, all this does is declare and name pieces and their associations visuals, along with players and their associated pieces. Also, the XML definition is a bit cumbersome, requiring multiple definitions to set up even a simple test. What I’d like for it to do is be a lot less redundant, and scale from very simple declarations of a handful of pieces in a space to complex hierarchies with behaviors attached to them. This GameXML language should be strive to minimally describe any game startup sequence. Each GameXML file also should serve as the defining datastructure for any level, presuming there are multiple levels in the game.

I’m thinking of something like this:

  • [piece name="uniquePieceName" [attributes]] is the way to declare any piece. This automatically adds the piece to a global piece dictionary if the name doesn’t exist, or updates its attributes if it already does. If the name attribute doesn’t exist, the piece is created with a unique name.

  • If the piece declaration occurs inside a [player] declaration, then the piece is created as described above AND it is added to the player’s piece array.

  • A piece can appear in multiple contexts like [player] and possibly other groups that are of interest to the game.

Pieces have the following attributes:

  • name = unique identifier of this piece
  • template = a piece name to copy attributes from

Initialization that may execute a script somewhere to complete the initialization as well as tagging the pieces with this role

  • type = type of piece, as defined in the game
  • visual = the type of visual to associate with this piece
  • role = logical role(s), comma separated
  • tag = logical tag(s), comma separated
  • behavior = an AI behavior
  • init = an initializing script to use to initialize any other parameters

3D world representations

  • position = vector3 coordinate of where this piece exists in space
  • scale = the size of the piece, defaults to unit 1 meter
  • direction = vector3 pointing
  • speed, maxspeed = how fast this can go up to maximum
  • turn, maxturn = how many degrees per second this object is allowed to turn

So, the next step would be to write the parser that reads this information and calls a myriad of functions and factories to set all this stuff up. Not the most fun, but it will make creation much easier. After that, we’ll port the visual classes to verify that it’s working correctly. Then, we can port the physics engine and AI behaviors. Then, we can write game logic for the referee classes.

AFTER SLEEPING ON IT

The very minimal piece would be to do the piece reading, and maybe read player and visual data structures. So let me start by porting the GameScreen.Prologue() routines XML reader, and see what I can do to encapsulate it.

Where to put this routine? GameScreen.Prologue() is executed as soon as the screen is created and pushed on the stack, which is handled in the LoadContent() part of the call. So that’s where I’m going to put it in the new architecture, except we don’t have a GameScreen to hold this data. So where does this live now?

For now, I think it makes sense to store this information in BaseGame somewhere. Creating a BaseGame Data.cs partial class and a Game.XML file. I also need to create a rudimentary piece class now.

PORTING

BaseGame Data has a new InitalizeDataStructures() and LoadDataStructures() methods that are called from the corresponding BaseGame.Initalize() and BaseGame.LoadContent() master entry points.

The piece-building logic is built around XmlReader, and there’s the option of having a validating reader that using an XmlSchema. I’m going to disable this for now. Related to this, though, is a class called StringUtility that converts the strings in the XML file. The current implementation uses default values in case the attribute being read doesn’t exist. This makes the code not only harder to read, but it also will mask problems with the game initialization XML file. I’m going to remove this feature.

Leave a comment

IOS Session 01: Installing the environment

POSTED Fri Aug.24.2012 by Dave Seah UNDER Kickoff, Project

As part of the ETP on iPad initiative, Al Briggs has opened the nascent source code to me so I can see what a real app looks like in the dev environment! It’s also my hope to be able to implement some of the drawing code directly.

First thing first…setting up!

  1. Installed Mountain Lion, Clean, on my MacBook Pro 17″ from late 2007. It’s old, but it works.

  2. Installed Xcode via the App Store.

  3. Installed GitHub for Mac.

  4. Downloaded the project from Github.

  5. Tried to open the project file and run it. BOOM. Missing header files. I wondered if I had to install the TestFlight SDK, so I emailed Al.

  6. He emailed back that he was using CocoaPods, which is a “library dependency manager” for Objective-C. You can specify the library you want to use, and CocoaPods takes care of grabbing everything that this library needs to work properly so you don’t have to do it manually. It relies on something called /ruby, which is a package manager for programs written in the ruby language, which I needed to install.

After some farting around, I found I had to go to XCode’s Preferences and under Components select “Install Command Line Components” so I could run the sudo gem install cocoapods command (gem was already installed as part of the dev tools, I believe), followed by pod setup. I also had to run sudo gem update --system to get the most up-to-date version of whatever gem is.

After that, I went to the directory where I downloaded Al’s source, and typed pod install per Al’s instructions. It started doing this:

    Installing Objection (0.13.0)
    Installing TestFlightSDK (1.0
    Installing OCMock (2.0.1)
    Using Objection (0.13.0)
    Using TestFlightSDK (1.0)
    Generating support files

Al then said to look at the “workspace file” that has been created, which I’m guessing is the file that ends with .xcworkspace. I double-clicked it to see what would happen. I was able to build the project and run it in a simulator. Very exciting!

I poked around the file explorer in xcode, and was reminded of just how old-school Objective-C is compared to C#. I’ll have to read up a bit on this.

Leave a comment

Project: XNABS2 Session 02

POSTED Thu Aug.23.2012 by Dave Seah UNDER Project TAGGED ,

SUMMARY: Last time, I got as far as creating the beginning of a Screen architecture and supporting concepts. The short-term goal is to get enough of this hooked in so I can just write debug messages to a console. That’s really all I want to shoot for tonight. >>> Continue reading

Leave a comment

Project: XNABS2

POSTED Tue Aug.21.2012 by Dave Seah UNDER Project TAGGED

SUMMARY: One of my long-term projects is to create a simple reusable 3D engine for playing with interactivity. I have a bunch of code from an earlier project that I’m refactoring into something that will serve as an example of a more complex XNA application. These notes are pretty rough, as they reflect speculative thinking about work in progress. These notes are also actively edited, so the contents may change unexpectedly. >>> Continue reading

Leave a comment

001 BaseSystem2 Kickoff

POSTED Tue Aug.07.2012 by Dave Seah UNDER Project TAGGED , ,

I’ve been intending to update the XNA 2.0 game engine we made for Take a Stand into something cleaner running under XNA 4.0. Code notes follow on setting up the project and porting the first bit of code over: error logging classes. >>> Continue reading

Leave a comment
Page 1 of 41234