enchant.js | Fundamentals

enchantjs-fundamentals-1

We’ve entered Phase Two of my game programming course, and to help support this phase, I’m putting together enchant.js | Fundamentals.

While currently not as interactive nor as descriptive as what I developed for Phase One, I’m hoping these incremental examples will make it easy for those new to programming to grok some fundamental techniques and concepts.

Again, feedback is appreciated.

Just Enough JavaScript

just-enough-js-1

I got a last-minute opportunity to teach an introduction to game programing course for people with no programming experience. I decided to base it around an open source HTML5 framework*. When I started looking around for a crash course with which to build basic JavaScript programming skills, I found none that were appropriate. Hence, Just Enough Javascript was born.

I’m creating it as a just-in-time resource for the course. There a little bad-but-expedient practice in there, but it’s working quite well for the course so far. Each page is resource-complete in itself—meaning you can download just a single HTML document and later view it without a live Internet connection.

I would love to hear any feedback about it.

* I considered enchant.js, Phaser, and melonJS. There were pros and cons to each, but I ultimately went with enchant.js because I like it’s event-driven nature (better reflects how JS “should” work) and it has a smaller (and therefore less intimidating for beginners) API.

(Over)thinking JavaScript objects 3

tally-clicker

Defining objects inside self-invoked anonymous functions

In our previous episode, we saw a canonical way to create objects in JavaScript that suggested code reuse and facilitated automatic object initialization, but it didn’t let you implement private attributes nor did it go out of its way to keep from polluting the global namespace.

What follows is the simplest way I’ve seen that accomplishes all of the above. And boy is it a ride! We are going to create a self-invoking anonymous function and inside the function we will define the object and create a single point of connection to the window with a closure.

Here we go:

// == Begin definition ==============================
(function(window) {
  // -- Constructor ---------------------------------
  var Clicker3 = function() {

    // -- Private properties --
    var _numClicks = 0;

    // -- Private methods --
    // Methods defined in this scope and not on
    // 'this' are private'.
    var _update = function() {
      console.log("Clicker3 obj: " + _numClicks);
    };

    // -- Public methods --
    // Methods defined on 'this' are public, can
    // access private and public members.
    this.click = function () {
      _numClicks++;
      _update();
    };

    this.reset = function () {
      _numClicks = 0;
      _update();
    };

    this.getNumClicks = function () {
      return _numClicks;
    };

    // -- Initialize state --
    this.reset(); // reset is redundant here;
                  // for demo only.
    _update();
  }; // !Clicker3()

  // -- "Hyper-public" methods ----------------------
  // Methods defined on the prototype can only access
  // public members!
  Clicker3.prototype.showInfo = function() {
    alert("I am a Clicker3 object who is at " +
      this.getNumClicks() + " clicks.");
  };

  // -- Publish -------------------------------------
  // Expose Clicker3 (and only Clicker3) to the
  // global window (i.e., make it public).
  window.Clicker3 = Clicker3;

}(window));
// == End definition ================================

The self-invoking function creates a new scope in which everything is defined. Passing in window as a parameter allows easy access to global window from within that new scope. This setup lets you:

  • Prevent pollution of global namespace.
  • Expose what you want to the global window and keep the rest private.

So, now we  have something that:

  • Has, “Reuse me!” written all over it.
  • Allows for automatic object initialization.
  • Lets you fully encapsulate objects.*
  • Protects the global namespace.

But it’s not totally cool because none of the above are code-level constructs. In other words, it’s neither readable or writable. JavaScipt is/isn’t fun. :-\

Just as a reminder, I am not (yet) taking on the following:

  • Inheritance-like stuff
  • “Class” (i.e., static) members*
  • Polymorphism

*An issue of religious importance.

(Over)thinking JavaScript objects 2

tally-clicker

Objects with constructors and prototyped methods

In this installment, I am going to look at building a tally clicker using what seems to be the canonical form for building class-like entities in JavaScript. The idea is simple:

  • Use a constructor function to create a scope/context with the object’s properties.
  • Use the constructor function’s prototype property to attach methods.

Attaching methods to the constructor’s prototype allows a single method instance to be shared among all objects instantiated from the constructor function.

Here’s how we might do it:

// == Begin Clicker2 definition =====================
// -- Constructor -----------------------------------
var Clicker2 = function() {
  // properties:
  this._numClicks = 0;

  // initialize state:
  this._update();
};

// -- Methods ---------------------------------------
Clicker2.prototype.click = function() {
  this._numClicks++;
  this._update();
};

Clicker2.prototype.reset = function() {
  this._numClicks = 0;
  this._update();
};

Clicker2.prototype._update = function() {
  console.log("Clicker2 obj: " + this._numClicks);
};

Clicker2.prototype.showInfo = function() {
  alert("I am a Clicker2 object who is at " +
    this._numClicks + " clicks.");
};
// == End Clicker 2 definition ======================

The HTML might then have something like:

<button onclick="yourClicker.click();">Click</button>
<button onclick="yourClicker.reset();">Reset</button>
<button onclick="yourClicker.showInfo();">Info</button>
...
<script>
  // Wait for DOM to be ready and then instantiate a
  // Clicker2 object:
  document.addEventListener('DOMContentLoaded',
    function() {
      document.yourClicker = new Clicker2();
    });
</script>

Compared to the approach using object literals, this approach has the following advantages:

  • It allows for automatic object initialization.
  • The object abstraction has, “Reuse me!” written all over it.

However, it still has a couple issues:

  • It violates encapsulation because everything is still public.*
  • It still pollutes the global namespace.

In the next installment, we’ll look at a way to fix these remaining problems. Just as a reminder, I am not (yet) taking on the following:

  • Inheritance-like stuff
  • “Class” (i.e., static) members*
  • Polymorphism

*An issue of religious importance.

(Over)thinking JavaScript objects 1

tally-clicker

I’ve always found JavaScript’s approach(es) to OOP a little cumbersome. I’m not talking here about prototypal vs. class-based OOP. Rather, I’m talking about the readability, etc. of the actual code you have to write to build objects. I want to take a few blog entries to try to put the maze into some kind of cohesive perspective.

I like to use a tally clicker to explore objects in languages I am learning. A tally clicker is a real-world object with a minimal set of features that are easy to implement and that map to basic but salient OOP concepts.

Object literals

I’m going to start this exploration with plain-Jane object literals. This is one of the canonical ways and often the first way shown to implement objects in JavaScript. Here’s how I might implement a tally clicker with a JavaScript literal:

// == Create a tally clicker ========
var myClicker = {

    // pseudo-private property
    _numClicks: 0,         

    // pseudo-private method
    _update: function() {
        console.log("myClicker1: " + this._numClicks);
    },

    // public methods
    click: function() {
        this._numClicks++;
        this._update();
    },

    reset: function() {
        this._numClicks = 0;
        this._update();
    },

    showInfo: function() {
        alert('I am "myClicker" and am at ' +
            this._numClicks + ' clicks.');
    }
}; // == End tally clicker ========

I might then stick something like this into the HTML:

<button onclick="myClicker.click();">Click</button>
<button onclick="myClicker.reset();">Reset</button>
<button onclick="myClicker.showInfo();">Info</button>

The object literal approach is a seductively easy and pretty readable way to build an object—but it’s got issues. Namely:

  • There’s no automatic initialization apart from property values.
  • It violates encapsulation because everything is public.*
  • It pollutes the global namespace (sort of). As is, the name of the object is in the global namespace.
  • The object abstraction doesn’t scream, “Reuse me!” (This may be a cognitive style issue more than anything else.)

In the next couple installments, I’ll consider some alternative implementations specifically with regard to the above criteria. For the moment, I will not deal with:

  • Inheritance-like stuff
  • “Class” (i.e., static) members*
  • Polymorphism

*An issue of religious importance.

Android VM Manager

I just released a tiny Qt widgets-based app that makes it more convenient to connect an Android virtual machine to your development environment. Here’s a quick (but possibly not quick enough) demo of configuring it to work with AndroVM and the Eclipse-based ADT Bundle:

I’ve successfully used it with Android-x86 as well. I gotta say that doing development with either of these VMs is much faster and more rewarding than using the emulator that ships with the ADT.

The code is available on my Bitbucket at https://bitbucket.org/mithat/androidvmgr and is licensed under the GPLv3.

Changing Processing’s Look and Feel

processing-lnf-metal

The Java Look and Feel that Processing uses by default on Linux can get a bit wonky. Depending on the GTK theme you are using, menubars can actually become unusable!

processing-menubar-adwaita-x-dark
Where’s the menu?

You can change the Look and Feel to something that works by editing the file:

/home/USERNAME/.processing/preferences.txt

Be sure that Processing is not running when you do this. To use the standard Swing Metal Look and Feel, change the lines that read:

editor.laf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel
editor.laf.linux=com.sun.java.swing.plaf.gtk.GTKLookAndFeel

to:

editor.laf=javax.swing.plaf.metal.MetalLookAndFeel
editor.laf.linux=javax.swing.plaf.metal.MetalLookAndFeel
processing-menubar-lnf-metal
Metalized menubar

Metal may not be pretty, but it seems to be pretty robust!

Note that because Processing uses its own JRE, it will ignore LnF and other settings you may have configured for your default JRE.