Useful JavaScript Game Extensions: Number#round

Part 13

Here’s another small one, in the same vein as yesterday’s. When you can take for granted that numbers behave as objects, it really cleans up unnecessary references to static Math methods and extra helper methods.

/**
 * @returns The number rounded to the nearest integer.
 *
 * (4.5).round(); // => 5
 * (4.4).round(); // => 4
 */
Number.prototype.round = function() {
  return Math.round(this);
};

Take a look back at the original useful JavaScript game extension Number#Clamp. Though global helper functions have the same number of semantic elements, I find that it’s easier to break down in my head if they are attached to objects. Also, the order of the parameters may be more obvious if you reduce it from 3 to 2.

Useful JavaScript Game Extensions: Number#sign and Number#abs

Part 11 and 12

In an object oriented perspective it can be useful to think of numbers as objects. Why have to deal with “everything is an object, except numbers, those are different and require special methods”, when you can have a more consistent programing environment where numbers are objects too, and have the same interfaces and methods you’d expect.

JavaScript’s prototype based inheritance is perfect for extending the behavior various types of objects, and fortunately for us, unlike in Java, in JavaScript numbers really are objects. Though unfortunately for us, as is usual in JavaScript, the API is seriously lacking.

Getting the sign of a number can often be useful in games. For example, I wanted to have camera tracking where the camera would look ahead by the square of the velocity of the object. But if the object were moving in the negative direction the squaring would obliterate the sign. Number#sign to the rescue!

/**
 * @returns The sign of this number, 0 if the number is 0.
 */
Number.prototype.sign = function() {
  if(this > 0) {
    return 1;
  } else if (this < 0) {
    return -1;
  } else {
    return 0;
  }
}

// Example, using the sign to maintain direction when squaring
var weightedX = dinoPosition.x + (1.25 * dinoVelocity.x * dinoVelocity.x * dinoVelocity.x.sign());

Another useful number method is abs. Why do you need some external object to get the absolute value of a number? Shouldn’t a number know it’s own absolute value? Now they can:

/**
 * @returns The absolute value of the number.
 */
Number.prototype.abs = function() {
  return Math.abs(this);
};

I’m not always against the prototype feature of JavaScript, just against using prototype based inheritance to simulate class and module based inheritance. Stick around towards the end of the series to see some great examples.

See you next time!

Quest for Meaning a game made in two days for Mini-LD #21

Here it is, my entry for the mini-Ludum Dare competition. The competition theme is “biggest fear”, and one of my biggest fears is a meaningless life. Not only that, but a meaningless eternity. Pictures for Sad Children has a very similar theme at times and it helped inspire parts of this game (though I couldn’t find a good way to work in “monster most vulnerable when heaving with sobs”).

This was my first 2 day competition and I’ve learned some things. First, two days is a long time. Second, having real tools would make me very, very happy. Third, I thought that doing all the art and all the programming for a game would be hard, but it seems to use different parts of the brain, so when working on art the programming part of my brain is relaxing and vice versa.

This was the first moderately legit game that I’ve done all my own art on (title screen and chest graphics contributed by Lana). Also, my first game with a 4 color grayscale pallet. And additionally, my first major undertaking on the Pixie platform.

Working with the Pixie platform had some serious trade-offs. JavaScript is a surprisingly productive language with it’s functional and dynamic nature, but it has a harsh and brutal syntax. The platform libraries helped a lot to smooth some things out, and as they become more complete it will get better and better. I have high hopes for CoffeeScript, now that it is getting close to 1.0 I’m going to try using it on all my new projects and hopefully never go back. Another advantage was the tight art and code integration. It was trivial to create an image and have it appear in the game seconds later. The biggest drawback of Pixie right now is that the code “editor” is pretty much just a text area. There are no tabs, no integrated source navigation, no auto-save, no version control, and all kinds of other terrible issues. Also, there is no real tile editor, though Noel Berry pioneered the way by using the pixel editor as a tile editor before, and the surprising thing is that it’s actually not too bad.

Using Pixie to make art is awesome, but the game “platform” is not fleshed out enough for me to recommend making an entire game in it to everyone yet.

A special thanks to everyone who helped playtest and discuss various elements of the game throughout it’s stages: Boltz, McGrue, DavMo, Lan, MW… props.

So check out the game and let me know what you think. By making heavy use of Pixie, especially in time limited competitions, I hope to really iron out the core usage scenarios and make it amazing.

The future is bright and full of meaning.

Useful JavaScript Game Extensions: Array#first and Array#last

Part 9 and 10 of 256: Array#first and Array#last

The first and last methods of array objects provide a nice semantic wrapper for the concepts. They aren’t really a big time saver, though it is probably very slightly easier to type first than [0]. It is also fairly uncommon to need these methods with much regularity, but when you do need them it’s nice to have them.

/**
 * Returns the first element of the array, undefined if the array is empty.
 *
 * @returns The first element, or undefined if the array is empty.
 * @type Object
 */
Array.prototype.first = function() {
  return this[0];
};

/**
 * Returns the last element of the array, undefined if the array is empty.
 *
 * @returns The last element, or undefined if the array is empty.
 * @type Object
 */
Array.prototype.last = function() {
  return this[this.length - 1];
};

JavaScript Instance Variables Do Exist

In JavaScript you can use a closure to create private member variables. Many, many, many, people refer to these private member variables as instance variables. They are wrong.

An instance variable should be accessible to any methods of the class, including methods from superclasses and modules. So, I suppose private member variables provided via a closure are indeed “instance variables” if you live in a world without any superclasses or modules. In fact that is the world that most JavaScript lives in, a dark and terrifying world… but let’s not speak of the darkness, instead let’s turn towards the light…

Instance Variable Pattern

function Person(I) {
  I = I || {};

  Object.reverseMerge(I, {
    name: "McLovin",
    age: 25,
    homeState: "Hawaii"
  });

  return {
    introduce: function() {
      return "Hi I'm " + I.name + " and I'm " + I.age;
    }
  };
}

var fogel = Person({
  age: "old enough"
});
fogel.introduce(); // "Hi I'm McLovin and I'm old enough"

function Ninja(I) {
  I = I || {};

  Object.reverseMerge(I, {
    belt: "black"
  });

  return Object.extend(Person(I), {
    greetChallenger: function() {
      return "In all my " + I.age + " years as a ninja, I've never met a challenger as worthy as you...";
    }
  });
}

var resig = Ninja({name: "John Resig"});

resig.introduce(); // "Hi I'm John Resig and I'm 25"

Notice how it doesn’t matter which class declares a method, the instance variables are accessible to the instance of the class. I know what you’re thinking, I can see you there with your jaw gaping, slacking in the wind with disbelief. You’re saying “.. buh … buh .. Object.extend? Object.reverseMerge?? Those aren’t even real JavaScript!!” And you’re right. If I had a dime for every time an important method wasn’t part of “real JavaScript” I’d easily be a multi-thousand-aire.

If you’ve used jQuery, prototype, or probably any other decent JavaScript framework, or just a decent amount of JavaScript, you should be familiar with Object.extend, $.extend, _.extend. Extend copies properties from one or more objects to a destination object, overriding them if they share the same key.

reverseMerge is less common, but equally useful. It does the same as extend, but does not override keys that are already present in the destination. This makes it perfect for adding defaults without crushing existing values.

The I variable is a convention to let you know that you are accessing instance variables, similar to Ruby’s @ prefix. It is very important to pass the reference to this variable to the superclass, otherwise you will not actually have a shared instance variable space. Any method can add a new instance variable by something like I.foo = "bar"; The dynamic nature of JavaScript makes this legit. Though in practice it is polite to declare any defaults for instance variables your class or module uses in the reverseMerge so someone can just glance there to see what a class or module declares and depends on.

The line I = I || {}; is to allow you to instantiate a class without passing any configuration options and to just accept the default values. “Wait, WHAT? Configuration options? I thought this was an article about instance variables!!” That’s right, configuration options. Now that we have instance variables it would be silly to have two different ways of doing a very similar type of thing. It is a common jQuery convention to do $('.someClass').somePlugin(someOptions); Those options override the defaults if present, how eerily similar. The classic jQuery plugin convention however creates a new empty object and merges in the defaults as well as the overrides. Again this is fine in a world without inheritance, but once inheritance becomes involved you’ll be glad you have true instance variables.

Now, back to the issue of private variables. Private variables are very useful and I use them regularly. A good programmer makes use of all privacy levels: public, private, and protected/instance. Knowing what level of access to make a component is important. If everything is public then your API becomes a morass of incoherence. If everything is private then modifying and configuring behavior can become arduous. The right blend leaves your code elegant, coherent, configurable, and flexible. Remember, true instance variables do exist in JavaScript and they can be a valuable addition to any programmer’s toolkit!

Useful JavaScript Game Extensions Part 8, Number#mod

Part 8/258 Number#mod

For some bizarre reason, JavaScript does not constrain the result of the % operator to be between 0 and the base. This can make computing the index into an array or “wrapping” a negative number a small pain. This method gives all numbers an improved mod method that will guarantee they end up inside the array.

/**
 * A mod method useful for array wrapping. The range of the function is
 * constrained to remain in bounds of array indices.
 *
 * Example:
 * (-1).mod(5) === 4
 *
 * @param {Number} base
 * @returns An integer between 0 and (base - 1) if base is positive.
 * @type Number
 */
Number.prototype.mod = function(base) {
  var result = this % base;

  if(result  0) {
    result += base;
  }

  return result;
};

This makes jumping into an index much easier.

// Example usage
var result = array[n.mod(array.length)];

Though still not quite as nice as in Ruby where you can do:

result = array[n] # Ruby cares enough to make it happen

I love Ruby…

2hr HTML5 Tetris

I’ve taken an interest in limited time game competitions recently and figured I’d better practice up. So as an exercise I tried to make Tetris in 1hr in Pixie. Except for the blocks getting stuck in the walls and that one thing about the lines, it was pretty good for an hour.

I decided that I got pretty close to a “working” game and forked the app to do the 2hr version. I learned that some beveled block graphics really make a difference! As well as actually removing completed lines. There is one bug where sometimes blocks overlap or won’t move into what appears to be empty space, as well as the “choice” of rotation points, but hey, times up.

Useful JavaScript Game Extensions: Array#shuffle

Do the shuffle! Array#shuffle

Part 7/256

Shuffling is important, especially in card games.

/**
 * Returns a new array with the elements all shuffled up.
 *
 * @returns A new array that is randomly shuffled.
 * @type Array
 */
Array.prototype.shuffle = function() {
  var shuffledArray = [];

  this.each(function(element) {
    shuffledArray.splice(rand(shuffledArray.length + 1), 0, element);
  });

  return shuffledArray;
};

Notice how building on the previous components of rand and each makes this method much easier to write. You’ll find that when you surround yourself with great APIs things constantly become easier and easier, whereas when you are surrounded with terrible APIs things become harder and harder.

Using Google Font API to Render Inconsolata in HTML5 Canvas

In Contrasaurus we wanted some cooler fonts to add some extra ambiance to the game. I knew that adding a custom font from Google Font API was easy for classic HTML elements, but would it be easy for HTML5 Canvas elements? 5 minutes later I knew the answer… Yes!

// In the  tag


// In your js code
context.font = "bold 1.2em 'Inconsolata'";