First glance: Unreal.js

With Christmas coming up, I don’t exactly have the time to write those 2,000-word monologues that I’ve been doing. But I want to post something, if only because laziness would intervene otherwise. Inertia would take over, and I’d stop posting anything at all. I know it would happen. I’ve done it once before. So, these last few Wednesdays of 2015 will be short and sweet.

This time around, I want to talk about something I recently found on a wonderful site called Game From Scratch. It’s called Unreal.js, and it’s open-source (Apache license). What does it do? Well, that’s the interesting thing, and that’s what I’m going to ramble on about.

You’ve probably heard of UnrealEngine. It’s the latest iteration of the game engine used to power a wide array of games, from Unreal Tournament to AAA titles like the newest Street Fighter and Tekken to hundreds of up-and-coming indie games. The most recent version, UnrealEngine 4, is getting a lot of press mainly because of its remarkably open development and friendly pricing scheme. (Compared to other professional game engines, anyway.) Lately, Unreal has become a serious competitor to Unity for the middle tier of game development, and competition is an indisputably good thing.

But Unreal has a problem compared to Unity. You see, Unity runs on Microsoft’s .NET framework. (Strictly speaking, it runs on Mono, which is a Microsoft-approved knockoff of .NET that used to be fully open, to the point where most Linux distributions preinstalled it a few years ago. Now…not so much.) Anyway, Unity uses .NET, and one of the nifty things about .NET is that, like the JVM, it’s not restricted to a single language. Sure, you’re most likely to use C#, but you don’t have to. Unity explicitly supports JavaScript, and it used to have full support for a Python clone called Boo. (Supposedly, there are ways to get other languages like F# to work with it, but I don’t know why anyone would want to.)

Unreal, on the other hand, uses C++. From a performance perspective, that’s a great thing. C++ is fast, it can use far less memory than even C#, and it’s closer to the hardware, making it easier to take advantage of platform-specific optimizations. However, C++ is (in my experienced opinion) one of the hardest programming languages to learn well. It’s also fairly ugly. The recent C++11 standard helps a lot with both of these problems, but full support just isn’t there yet, even 4 years later. C++17 looks like it will go a few steps further in the “ease of use” direction, but you’ll be lucky to use it before 2020.

The makers of UnrealEngine know all of this, so they included a “visual” programming language, Blueprints. Great idea, in theory, but there are a lot of languages out there that you don’t need to invent. Why not use one of them? Well, that’s where Unreal.js comes in. Its developers (some guys called NCSoft; you may have heard of them) have made a plugin that connects the V8 JavaScript engine from Chrome/Safari/Node.js/everywhere into Unreal. The whole thing is still in a very early stage, but it’s shaping up to be something interesting.

If Unreal.js takes off, then it can put Unreal well ahead of Unity, even among hobbyists and lower-end indies. JavaScript is a lot easier on the brain than C++ (take it from someone who knows both). And it has a huge following, not just for webapps and server stuff. The Unreal.js project page claims support for “(Full) access to existing javascript libraries via npm, bower, …”

That’s huge. Sure, not all npm packages are of the highest quality, but there are plenty that are, and this would let you use all of them to help make a game. Game engines, historically, have been some of the worst about code reuse, 3rd-party libraries, and other niceties that “normal” applications get to use. Well, that can change.

And then there’s one other factor: other languages. Since Unreal.js is pretty much just the V8 engine from Node, and it can load most Node packages, that opens the possibility of using some of the many “transpiled” languages that are transformed to Node-friendly JavaScript. Think CoffeeScript, TypeScript (which recently released its new 1.7 version), or even my April Fools’ Day joke language Elan.

Maybe I’m wrong. Maybe Unreal.js will fizzle. Perhaps it’s destined to join the legions of other failed attempts at integrating game development with the rest of the programming world. I hope not. The past few years have seen a real move in the direction of democratizing the art of game-making again. I’d like to see that trend continue in 2016 and beyond.

ES6 iterators and generators

With ES6, JavaScript now has much better support for iteration. Before, all we had to work with was the usual for loop, either as a C-style loop or the property-based for...in. Then we got the functional programming tools for arrays: forEach, map, reduce, and so on. Now we have even more options that can save us from needing an error-prone C-style loop or the cumbersome for...in.

The new loop

ES6 adds a new subtype of for loop: for...of. At first glance, it looks almost exactly the same as for...in, but it has one very important difference: for...in works on property names, while for...of loops over property values. Prettified JavaScript variants (like CoffeeScript) have had this for years, but now it comes to the base language, and we get to do things like this:

var vowels = ['a','e','i','o','u','y'];

for (var v of vowels) {
    if (v != 'y') {
        console.log(v);
    } else {
        if (Math.random() < 0.5) {
            console.log("and sometimes " + v);
        }
    }
}

Most developers will, at first, use for...of to iterate through arrays, and it excels at that. Just giving the value in each iteration, instead of the index, will save the sanity of thousands of JavaScript programmers. And it’s a good substitute for Array.forEach() for those of you that don’t like the FP style of coding.

But for...of isn’t just for arrays. It works on other objects, too. For strings, it gives you each character (properly supporting Unicode, thanks to other ES6 updates), and the new Map and Set objects work in the way you’d expect (i.e., each entry, but in no particular order). Even better, you can write your own classes to support the new loop, because it can work with anything that uses the new iterable protocol.

Iterables

Protocols are technically a new addition to ES6. They lurked behind the scenes in ES5, but they were out of sight of programmers. Now, though, they’re front and center, and the iterable protocol is one such example.

If you’ve ever written code in Java, C#, C++, Python, or even TypeScript, then you already have a good idea of what a protocol entails. It’s an interface. An object conforms to a protocol if it (or some other object up its prototype chain) properly implements the protocol’s methods. That’s all there is to it.

The iterable protocol is almost too easy. For a custom iterable object, all you need to do is implement a method called @@iterator that returns an object that meets the iterator protocol.

Okay, I know you’re thinking, “How do I make a @@iterator method? I can’t use at-signs in names!” And you’re right. You can’t, and they don’t even want you to try. @@iterator is a special method name that basically means “a symbol with the name of iterator“.

So now we need to know what a symbol is. In ES6, it’s a new data type that we can use as a property identifier. There’s a lot of info about creating your own symbols out there, but we don’t actually need that for the iterable protocol. Instead, we can use a special symbol that comes built-in: Symbol.iterator. We can use it like this:

var myIterable = {
    [Symbol.iterator]: function() {
        // return an iterator object
    }
}

The square brackets mean we’re using a symbol as the name of the property, and Symbol.iterator internally converts to @@iterator, which is exactly what we need.

Iterators

That gets us halfway to a proper iterable, but now we need to create an object that conforms to the iterator protocol. That’s not that hard. The protocol only requires one method, next(), which must be callable without arguments. It returns another object that has two properties:

  • value: Whatever value the iterator wants to return. This can be a string, number, object, or anything you like. Internally, String returns each character, Array each successive value, and so on.

  • done: A boolean that states whether the iterator has reached the end of its sequence. If it’s true, then value becomes the return value of the whole iterator. Setting it to false is saying that you can keep getting more out of the iterator.

So, by implementing a single method, we can make any kind of sequence, like this:

var evens = function(limit) {
    return {
        [Symbol.iterator]: function() {
            var nextValue = 0;
            return {
                next: function() {
                    nextValue += 2;
                    return { done: nextValue > limit, value: nextValue };
                }
            }
        }
    }
}

for (var e of evens(20)) {
    console.log(e);
} // prints 2, 4, 6..., each on its own line

This is a toy example, but it shows the general layout of an iterable. It’s a great idea, and it’s very reminiscent of Python’s iteration support, but it’s not without its flaws. Mainly, just look at it. We have to go three objects deep to actually get to a return value. With ES6’s shorthand object literals, that’s a bit simplified, but it’s still unnecessary clutter.

Generators

Enter the generator. Another new addition to ES6, generators are special functions that give us most of the power of iterators with much cleaner syntax. To make a function that’s a generator, in fact, we only need to make two changes.

First, generators are defined as function*, not the usual function. The added star indicates a generator definition, and it can be used for function statements and expressions.

Second, generators don’t return like normal functions. Instead, they yield a value. The new yield keyword works just like its Python equivalent, immediately returning a value but “saving” their position. The next time the generator is called, it picks up right where it left off, immediately after the yield that ended it. You can have multiple yield statements, and they will be executed in order, one for each time you call the function:

function* threeYields() {
    yield "foo";
    yield "bar";
    yield "The End";
}

var gen = threeYields();

gen.next().value; // returns "foo"
gen.next().value; // returns "bar"
gen.next().value; // returns "The End"
gen.next().value; // undefined

You can also use a loop in your generators, giving us an easier way of writing our evens function above:

var evens = function(limit) {
    return {
        [Symbol.iterator]: function*() {
            var nextValue = 0;
            while (nextValue < limit) {
                nextValue += 2;
                yield nextValue;
            }
        }
    }
}

It’s still a little too deep, but it’s better than writing it all yourself.

Conclusion

Generators, iterators, and the for...of loop all have a common goal: to make it easier to work with sequences. With these new tools, we can now use a sequence as the sequence itself, getting its values as we need them instead of loading the whole thing into memory at once. This lazy loading is common in FP languages like Haskell, and it’s found its way into others like Python, but it’s new to JavaScript, and it will take some getting used to. But it allows a new way of programming. We can even have infinite sequences, which would have been impossible before now.

Iterators encapsulate state, meaning that generators can replace the old pattern of defining state variables and returning an IIFE that closes over them. (For a game-specific example, think of random number generators. These can now actually be generators.) Coroutines and async programming are two other areas where generators come into play, and a lot of people are already working on this kind of stuff. Looking ahead, there’s a very early ES7 proposal to add comprehensions, and these would be able to use generators, too.

Like most other ES6 features, these aren’t usable by everyone, at least not yet. Firefox and Chrome currently have most of the spec, while the others pretty much have nothing at all. For now, you’ll need to use something like Babel if you need to support all browsers, but it’s almost worth it.

Phaser 2.4 released

A while back I mentioned that I thought Phaser was a good choice for beginners of game development. It’s well-supported, it’s popular on browsers and mobile devices, and it uses the current most popular language: JavaScript.

Now, the guys behind Phaser have released version 2.4, and it has quite a few changes and updates. Most people will be gushing over the support for boned animation and video, but there are a few nuggets hidden in the changelog that might be just as useful. Let’s see what we can find, eh?

  • Phaser.Text no longer extends PIXI.Text but replaces it entirely. Phaser.Text now natively extends a Phaser Sprite, meaning it can be enabled for physics, damaged, etc.

On the surface, not a huge change, mostly just back-end stuff. But look at the second half of the entry: text objects are now sprites in their own right. That actually makes the code for a lot of games much easier, simply because we can use all the sprite methods on text. Think of, say, a word puzzle, where every word (or letter) can be made into its own sprite.

  • Mouse.button and MSPointer.button have been deprecated and are no longer set (they remain at -1). They never supported complex button events such as holding down 2 buttons and releasing just one, or any buttons other than left and right. They have been replaced with the far more robust and accurate Pointer DeviceButton properties such as Pointer.leftButton, Pointer.rightButton and so on.

This (and a handful of entries following it) is another step towards “unifying” control schemes. It’s annoying to have to write separate code to handle the mouse and a touchscreen. Now we don’t have to. Of course, you still need to compensate for the fact that a mouse can have nearly pixel-perfect accuracy, whereas fingers are lucky to get within about a centimeter of their target.

  • Added support for the Creature Automated Animation Tool. You can now create a Phaser.Creature object which uses json data and a texture atlas for the animations. Creature is a powerful animation tool, similar to Spriter or Spine. It is currently limited to WebGL games only, but the new libs should prove a solid starting point for anyone wanting to incorporate Creature animations into their games.

This is the one everybody’s talking about. To be honest, it doesn’t intrigue me as much. Creature is just one commercial, proprietary tool among many. Show me an open standard for 2D bones, and then I’ll get excited.

  • Loader.video allows you to load a video file into Phaser. It works in the same way as Loader.audio, allowing you to pass an array of video files – and it will load the first one the device is capable of playing back. You can optionally load the video via xhr where the video data is converted to a Blob upon successful load.

Video is cool, no doubt about it. But the whole field of in-browser video is a disaster area. Format support, patents, DRM, it’s all enough to make somebody swear off the whole thing forever. Still, if you can figure out a way to use it safely and easily, more power to you. Maybe it’ll lead to a revival of FMV games.

  • Text.setTextBounds is a rectangular region that allows you to align your text within it, regardless of the number of lines of text or position within the world. [ed: I removed the example, shout-out, and issue number]

More text rendering goodness. I can’t complain. This and other additions simplify the task of making a text-heavy game, something most game engines (not only HTML5, and not only free) make absurdly difficult.

  • Keyboard.addKeys is a practical way to create an object containing user selected hotkeys. [ed: Same removals here.]

Better keyboard support is a good thing in any engine, especially as so many are trying to forget that a physical keyboard even exists. And an easier way to support hotkeys can never be bad, because they’re one of the most annoying parts of a control scheme.

  • All Game Objects and Groups have a new boolean property called pendingDestroy. If you set this to true then the object will automatically destroy itself in the next logic update, rather than immediately. [ed: Removed use case and call-out.]

Godot has this same thing (as queue_free()), and it’s very helpful there. In a language full of callbacks (like JS), it’s even more necessary. Again, this isn’t something you want to scream out from the rooftop, but it’s a subtle change that eliminates a whole class of coding errors. Who could ever argue with that?

  • All Signals now have the ability to carry extra custom arguments with them, which are passed on to the callback you define after any internal arguments. [ed: Same removals here.]

A good customization point that’s never going to be important enough to mention in a press release. But it’s nice to have, and it simplifies some common tasks.

  • Phaser.Create is a new class that allows you to dynamically generate sprite textures from an array of pixel data, without needing any external files. We’ll continue to improve this over the coming releases, but for now please see the new examples showing how to use it.

Depending on how this plays out, it could be a great addition to an already excellent engine. A lot of designers absolutely hate generated textures, but I like them. Get some good noise algorithms in there, and you could do some wonderful things.


There’s a lot more in there, and I do mean a lot. And Phaser 3 should be coming within the next year or so, although release dates always have a tendency to…slip. But this 2.4 release does help cement Phaser as the forerunner for HTML5 game development. For coders rather than designers, there’s really not a better option, and I’ll continue to recommend Phaser for anybody that wants to get started with game coding. Unity’s great and all, but it’s a lot more complicated than popping open a text editor and a browser, you know?

Introduction to ES6 Modules for Game Programmers

As an application (be it a game or anything else) grows, so does the need for some sort of organization. Also, all but the simplest programs will require the use of some sort of additional libraries. For both of these reasons, just about every programming language meant for serious use has a way to separate code into logical, self-contained blocks. Even lowly C has its header files, but more modern languages can do more.

JavaScript, however, used to be sorely lacking in this department. Sure, you can load additional scripts in a web page, and jQuery (to name one example) managed an entire plugin architecture using DOM onload events. But everyone recognized that this wasn’t enough, and thus modules were born.

The problem is, they weren’t a part of the JavaScript “core”, so there was no standard way of making or using a module. Node made its own module system based off the CommonJS spec (later used by Browserify), while Require.js championed a slightly different style called AMD. In general, server-side and other “app”-style JS used Node’s modules, since they were already using Node itself, while purely browser-based libraries went with AMD. As with any case where there are two competing standards, developers are left having to learn both of them.

Now, with ES6, all that can change. Modules are now a core part of the language. Once browsers fully support them, you can use them anywhere. (Babel can convert ES6 modules into AMD or CommonJS, though, if you want to use modules right now.) And this is a case where you’ll definitely want to, no matter what you’re writing.

Using Modules

Most of the discussions out there focus on writing modules, rather than using them. But game developers, in particular, are going to be more likely to use somebody else’s module first, so I’m starting there.

The import keyword is your gateway to modularity. If you’ve ever used require() in Node, you’re halfway there, but you’ve still got more to learn. The idea is pretty simple, though. Let’s say that we’re using some made-up game library that’s fully modularized, so that all its classes (because it’s all ES6, see?) are in their own module files. Well, we can do this:

import Vec2d from "lib/vector2d";

Now Vec2d is available for us to use in the rest of that script, and it will be whatever the vector2d module exported. Presumably, that would be a class or a function that created a 2D vector.

That’s the most basic import. For modules that export a single value (class, function, or even a constant), it’s all you have to do. In fact, the way the standard was made, it’s actually the preferred way of doing things. But it’s not the only way. What if we have a module that gives us multiple exports?

import {normalize, dotProduct} from "lib/vector2d";

That gives us names for two functions that might be defined (and exported) in our hypothetical vector2d module. Of course, we can combine these two:

import Vec2d, {normalize, dotProduct} from "lib/vector2d";

Here, the default export (see below) is assigned to the name Vec2d, while the braces indicate exports that we’re “picking” from the module. If we don’t like the names the module gives us, no problem:

import Vec2d, {normalize, dotProduct as dotP} from "lib/vector2d";

Finally, if we have a module that has a lot of exports (maybe something like jQuery), we can use a “wildcard” import that brings in the whole module as an object:

import * as $ from "lib/jquery";

We do have to name the object we’re importing into. (I used the traditional $ for jQuery.) After we use this import, anything the module exported with a name will be available as a property on the $ object.

Note that all importing is done statically, so you can’t “conditionally” import like this. (This is one downside to ES6 modules compared to earlier attempts like Node’s.) For that, you need to use the new Module Loader API, which would look something like AMD:

System.import("lib/jquery")
    .then(function($) {
        // Use jquery module as $, just like always
    });

Creating Modules

Eventually, you’ll want to make your own modules. For a game, you might be using a classical OO approach, where all your game entities (enemies, powerups, etc.) are ES6 classes, each in their own file. Like we did above, we’ll start with the simplest case, where your module only has one value, particularly a class.

/* enemy.js */
export default class {
    // Class definition...
};

That’s all there is to it. export default is the magic phrase that tells your JS interpreter that you’re defining a module and that you want it to export a single value. That value could be anything: class, function, constant, or even another module. And, when you want to use your enemy, all you have to do is import it like we did earlier.

If you want a module with more than one export (maybe a library of independent functions), then you can use a syntax that’s almost the reverse of that for importing multiple values:

/* utils.js */
export function log(msg) {
    console.log(msg);
}

export function foo(bar) {
    // Some other function
}

export const MAX_FPS = 60;  // TODO: Lower to 30 for console builds

All of these will be exported, and they can be imported using the “braces” or “wildcard” versions of import. (Since there’s no default export, these are, in fact, the only two ways to use the module. A simple import utils from "utils"; wouldn’t help us here.)

If you don’t like writing export everywhere in a module like this, you have an alternative. Instead, you can write the module as you normally would, then add an export declaration at the end. This declaration consists of export followed by the name of each expression you’re exporting, all of them put in braces, like an object literal. In other words, like this:

/* utils2.js */
function log(msg) {
    console.log(msg);
}

function foo(bar) {
    // Some other function
}

const MAX_FPS = 60; // TODO: Lower to 30 for console builds

export {log, foo, MAX_FPS};

The main advantage of this style is that you can export a function (or whatever) under a different name, using as like we can when importing. So, for example, we could instead write the last line as export {log as debug, foo, MAX_FPS};.

In Closing

So modules are good, and ES6 modules make JavaScript even better. Combined with classes, we now have a language that makes writing programs (including games) much easier. Once support for modules becomes widespread in browsers, all JS game developers will reap the benefits that “native” devs already enjoy.

Thoughts on ES6

ES6 is out, and the world will never be the same. Or something like that. JavaScript won’t be the same, at least once the browsers finish implementing the new standard. Of course, by that time, ES7 will be completed. It’s just like every other standardized language. Almost no compilers fully support C++14, even in 2015, and there will certainly be holes in their coverage two years from now, when C++17 (hopefully) arrives. C# and Java programmers are lucky, since their releases are dictated by the languages’ owners, who don’t have to worry about compatibility. The price of a standard, huh?

Anyway, ES6 does bring a lot to the table. It’s almost a total overhaul of JavaScript, in my opinion, and most of it looks to be for the better. New idioms and patterns will arise over the coming years. Eventually, we may even start talking about “Modern JavaScript” the way we do “Modern C++” or “Modern Perl”, indicating that the “old” way of thinking is antiquated, deprecated. The new JS coder in 2020 might wonder why we ever did half the things we did, the same way kids today wonder how anyone got by with only 4 MB of memory or a 250 MB hard drive (like my first PC).

Babel has an overview of the new features of ES6, so I won’t repeat them here. I will offer my opinions on them, though.

Classes and Object Literals

I already did a post on classes, with a focus on using them in games. But they’re useful everywhere, especially as so many JavaScript programmers come in from languages with a more “traditional” approach to objects. Even for veterans, they come in handy. We no longer have to reinvent the wheel or use an external library for simple inheritance. That’s a good thing.

The enhancements to object literals are nice, too. Mostly, I like the support for prototype objects, methods, and super. Those will give a big boost to the places where we don’t use classes. The shorthand assignments are pure sugar, but that’s really par for the course in ES6: lots of syntactic conveniences to help us do the things we were already doing.

Modules

I will do a post on modules for game development, I promise. For now, I’d like to say that I like the idea of modules, though I’m not totally sold on their implementation and syntax. I get why the standards people did it the way they did, but it feels odd, especially as someone who has been using CommonJS and AMD modules for a couple of years.

No matter what you think of them, modules will be one of the defining points of ES6. Once modules become widespread, Browserify becomes almost obsolete, RequireJS entirely so. The old pattern of adding a property to the global window goes…out the window. (Sorry.) ES6 modules are a little more restrictive than those of Node, but I’d start looking into them as soon as the browsers start supporting them.

Promises

Async programming is the hot thing right now, and promises are ES6’s answer. It’s not full on threading, and it’s distinct from Web Workers, but this could be another area to watch. Having a language-supplied async system will mean that everybody can use it, just like C++11’s threads and futures. Once people can use something, they will use it.

Promises, I think, will definitely come into their own for AJAX-type uses. If JavaScript ever gets truly big for desktop apps, then event-driven programming will become even more necessary, and that’s another place I see promises becoming important. Games will probably make use of them, too, if they don’t cause to much of a hit to speed.

Generators and Iterators

Both of these really help a lot of programming styles. (Comprehensions do, too, but they were pushed back to ES7.) Iterators finally give us an easy way of looping over an array’s values, something I’ve longed for. They also work for custom objects, so we can make our own collections and other nifty things.

You might recognize generators from Python. (That’s where I know them from.) When you use them, it will most likely be for making your own iterable objects. They’ll also be handy for async programming and coroutines, if they’re anything like their Python counterparts.

Syntactic Sugar

A lot of additions to ES6 are purely for aesthetic purposes, so I’ll lump them all together here, in the same order as Babel’s “Learn ES2015” page that I linked above.

  • Arrows: Every JavaScript clone (CoffeeScript, et al.) has a shortcut for function literals, so there’s no reason not to put one in the core language. ES6 uses the “fat” arrow =>, which stands out. I like that, and I’ll be using it as soon as possible, especially for lambda-like functions. The only gotcha here? Arrow functions don’t get their own this, so watch out for that.

  • Template Strings: String interpolation using ${}. Took long enough. This will save pinkies everywhere from over-stretching. Anyway, there’s nothing much to complain about here. It’s pretty much the same thing as PHP, and everybody likes that. Oh, wait…

  • Destructuring: One of those ideas where you go, “Why didn’t they think of it sooner?”

  • Function Parameters: All these seem to be meant to get rid of any use for arguments, which is probably a good thing. Default parameters were sorely needed, and “rest” parameters will mean one more way to prevent off-by-one errors. My advice? Start using these ASAP.

  • let & const: Everybody complains about JavaScript’s scoping rules. let is the answer to those complaints. It gives you block-scoped variables, just like you know from C, C++, Java, and C#. var is still there, though, as it should be. For newer JS coders coming from other languages, I’d use let everywhere to start. const gives you, well, constants. Those are nice, but module exports remove one reason for constants, so I don’t see const getting quite as much use.

  • Binary & Octal Literals: Uh, yeah, sure. I honestly don’t know how much use these are in any higher-level language nowadays. But they don’t hurt me just by being there, so I’m not complaining.

Library Additions

This is kind of an “everything else” category. ES6 adds quite a bit to the standard library. Everything that I don’t feel is big enough to warrant its own section goes here, again in the order shown on “Learn ES2015”.

  • Unicode: It’s about time. Not just the Unicode literal strings, but the String and RegExp support for higher characters. For anyone working with Unicode, ES6 is a godsend. Especially if you’re doing anything with emoji, like, say, making a language that uses them.

  • Maps and Sets: If these turn out to be more efficient than plain objects, then they’ll be perfect; otherwise, I don’t think they are terribly important. In fact, they’re not that hard to make yourself, and it’s a good programming exercise. WeakMap and WeakSet are more specialized; if you need them, then you know you need them, and you probably won’t care about raw performance.

  • Proxies: These are going to be bigger on the server side, I think. Testing will get a big boost, too, but I don’t see proxies being a must-have feature in the browser. I’d love to be proven wrong, though.

  • Symbols: Library makers might like symbols. With the exception of the builtins, though, some of us might not even notice they’re there. Still, they could be a performance boost if they’re faster than strings as property keys.

  • Subclassing: Builtin objects like Array and Date can be subclassed in ES6. I’m not sure how I feel on that. On the plus side, it’s good for consistency and for the times when you really do need a custom array that acts like the real thing. However, I can see this being overused at first.

  • New APIs: The new builtin methods are all welcome additions. The Array stuff, particularly, is going to be helpful. Math.imul() and friends will speed up low-level tasks, too. And the new methods for String (like startsWith()) should have already been there years ago. (Of all the ES6 features, these are the most widely implemented, so you might be able to use them now.)

  • Reflection: Reflection is always a cool feature, but it almost cries out to be overused and misused. Time will tell.

Conclusions

ES6 has a lot of new, exciting features, but it’ll take a while before we can use them everywhere. Still, I think there’s enough in there to get started learning right now. But there are going to be a lot of projects that will soon become needless. Well, that’s the future for you, and what a bright future it is. One thing’s for sure: JavaScript will never be the same.

Introduction to ES6 Classes for Game Programmers

If you’ve used JavaScript for game programming, you probably already know some of its shortcomings. One of those is its object system. Where most languages that have objects are class-based (think C++, Java, etc.), JavaScript is unusual in that it’s prototype-based. If you have experience with the language, you know this already, of course. And you know that the syntax can leave a lot to be desired, especially if you come from a background in, say, any other language. (Well, any class-based language, at least. If you’re used to something like Lisp or Haskell, then nothing will surprise you.)

With the newest standard, ES6, that’s going to change. It’s supposed to come out by the end of this month, and maybe that’s true. I’m writing this on June 15th, so it might even be released before this post goes up. If that’s the case, great! (I still remember when C++11 was codenamed C++0x, so I remain skeptical.) Anyway, some of the new features of ES6 are incredibly useful for all developers, but we’ll start with classes, because they’re simple yet powerful, and game development has always been one of the main uses of object-oriented programming. (EDIT 6/18: ES6 is now out! I’m amazed, and I’m happy to admit that I was wrong. Even though the release happened between writing this and posting it, I won’t remove what I already said.)

(By the way, most browsers don’t support much of ES6 yet, and even Node.js support is spotty. You’ll likely need to use a transformer like Babel to turn your ES6 code into something usable under the current standard, ES5.)

Basic Syntax

Let’s take a look at a little class that we can use to represent an enemy in a game. In ES6, it might look something like this:

class Enemy {
    constructor(id, name) {
        // Some properties that are passed into the constructor
        this.id = id;
        this.name = name;

        // A property we can define ourselves
        this.health = 100;
    }

    doAI() {
        /* Do some AI work here */
    }

    kill() {
        /* Play a death animation or something */
    }

    hit(damage) {
        this.health -= damage;
        if (this.health <= 0) {
            this.kill();
        }
    }
}

If you’ve ever worked with Java, C++, C#, ActionScript, or any other language like that, then the syntax will be familiar. Inside the class definition, you can define methods, both instance methods (like all of those here) and static methods. Instance methods are basically the same as the prototype methods already in JavaScript. You call them on an instance of an object, and they can use that object as this. Static methods don’t require an instance of the class; they’re called on the class itself, like the functions of the Math object.

Using this class is as easy as any object constructor. var myEnemy = new Enemy(0, 'myEnemy'); is exactly the same as what you’d use if we defined Enemy in the traditional JS way, defining methods on the prototype and so on. That’s the beauty (if you want to call it that) of ES6 classes: deep down, they’re the same thing as before, but prettier, like CoffeeScript and Typescript claim to be.

constructor is a special method. (I wonder what it does…), but you can define any other method you like. You can also use get and set before method names, just like with the object literal syntax. Static methods are prefixed with static. And that’s pretty much it.

Inheritance

If ES6 classes could just do that, they’d be a pretty good bit of syntactic sugar, but they’d definitely be missing something. Subclassing (AKA inheritance) is that something. Like their counterparts in other languages, ES6 classes can derive from another class, adding or redefining methods and properties. Taking our Enemy class from above, we can make a couple of different enemies using subclasses:

class ToughEnemy extends Enemy {
    constructor(id, name) {
        super(id, name);

        this.health = 200;
    }
}

class BossEnemy extends ToughEnemy {
    constructor(id, name) {
        super(id, name);

        this.lives = 3;
    }

    kill() {
        if (this.lives > 0) {
            this.lives--;
            this.health = 200;

            /* say something cheesy
            e.g., "Ha! You thought I would go down that easy?"
            and play a regeneration animation */
        } else {
            // All lives are gone, so he's really dead
            super.kill();
    }
}

Now we have two new classes. ToughEnemy is a generic bad guy with double health. There’s not much to change for him, but it shows the super keyword that we can use to call methods of the superclass. In the constructor, you can use it by itself to call the superclass constructor. Actually, you have to. Otherwise, you can’t use this anywhere in the derived class’ constructor. Since we want to change the this.health property, we do call super, forwarding the constructor parameters to it, which also means we don’t have to deal with them.

For BossEnemy, we further subclass ToughEnemy, but with a little added logic. First, we give him a property this.lives, set to 3. Then, we change his kill() method as you can see above. If he goes down to 0 health, he loses a life, but he goes back to full health. That continues until he’s out of lives, when we call the superclass kill() method. Since we didn’t define one for ToughEnemy, the call goes up another level, to Enemy, which does have kill().

So, to make a subclass, define a class as usual, but add extends and the name of the base class after your derived class’ name. Everything else is the same, except for the caveat about super in the constructor. You can change methods to your heart’s content, and any that you leave out will stay the same as they were in the base class. Just like any other OO language. Like it should be.

The only downside (and a lot of people wouldn’t see it as such) is that you only get single inheritance, meaning you can only derive from one base class. That’s okay for JS, since we didn’t have anything else to begin with. And Java doesn’t have multiple inheritance, nor does C#. C++ and Python do, but it takes a lot of extra work on the programmer’s part to use it well. Basically, once you truly need multiple inheritance, you’ll know how to fake it, no matter what language you’re using.

For Games

Since ES6 classes are just a fancier way of writing JS prototypes, you can use them wherever you’d use those: pretty much anywhere. And, due to the way they’re defined, you can subclass “traditional” JS objects by extending a constructor. This includes builtins like Array (but not Math, as it’s not a constructor). If you’re using a game library like Phaser, you can extend its objects with classes, too. Basically, wherever you’d already use objects and prototypes, classes fit right in.

Compatibility

ES6 is new, and not everything supports it. According to this compatibility table, nothing actually has full support for classes yet. Firefox 39 will have just about everything, and Chrome 42 allows classes, but not completely. Internet Explorer, as usual, is hopeless, but Edge has quite a bit of support if you enable “experimental” JavaScript. Safari and iOS are out of the question right now. Realistically, if you want to use ES6 classes at the moment, you’ll need a transformer. But that will change, and the next generation of programmers might wonder why we ever bothered with prototype at all.

Repeatable Random Numbers with xorshift+ (JS)

Like most languages, JavaScript has a random number generator: Math.random(). It’s not the best, but it’s good enough for many purposes, including some we’ve seen before. Like the RNGs of most languages, though, Math.random() has its drawbacks. Of these drawbacks, one is very important for game developers: there’s no way to seed! Why is this bad? That cuts to the very heart of random number generation on computers.

True randomness is hard to come by. On a computer, you have a few ways of creating it, such as noise circuits or measurements of user input. This randomness (entropy) is then converted by code into something usable, such as numbers or bits. On Linux and similar systems, there is a special file, /dev/random, that provides access to the random data. Some programming languages then allow developers to use the data through mechanisms like C++’s std::random_device.

All well and good, right? As long as your source has enough randomness, you can generate all the numbers you need. But, contrary to thermodynamics, a computer’s entropy can run out. When that happens, /dev/random stops working, waiting until it can conjure up enough random bits to meet your needs. Other systems fare no better.

Fortunately for us, games don’t often need true random numbers for gameplay. (Authentication and encryption are a different story.) So we can get away with something that only looks random. That’s good for us, because there are plenty of algorithms out there that can make a convincing string of numbers, including Math.random(). Technically, they aren’t “true” random numbers, and they all have a weakness that can allow someone with enough data to guess the next numbers in the sequence. But that very predictability comes in handy for game development. Starting from a little bit of data (from one number to a few, depending on the algorithm used), we get a whole set of numbers, billions of them or more. That starting data is the seed.

Most languages that I’ve used allow you to set the seed on the RNG. C, for example, has the srand() function, while Python provides random.seed(). But JavaScript doesn’t have this. Instead, the RNG is seeded for you when your program/app/page loads, and it will be different every time. Usually, that’s not a problem.

Sometimes, though, you need the predictable sequence that comes from using a seed. Procedural generation is one notable example. Look at Minecraft: a whole world can be created from a simple string of text. Obviously, there’s randomness injected in the process, but it’s made on-demand. Think how hard it would be to store the whole world after creating it. But, if you only had JavaScript’s RNG, you wouldn’t have much of a choice.

There are better RNG implementations out there. Indeed, many have written JS versions of them. Here’s my attempt at the popular algorithm known as xorshift+.

module.exports = (function() {
    // xorshift128+ requires 128 bits of state (we'll seed later)
    var state = new Uint32Array(4);

    // Scaling factor (2^32) to convert Math.random floats into integers
    var MAXINT_PLUS_1 = Math.pow(2,32)

    // Pre-fill the state array (can later be seeded)
    // This is required because xorshift can't have state of all zero
    for (var i = 0; i < state.length; i++) {
        state[i] = Math.random() * MAXINT_PLUS_1;
    }

    // A saved random number, since we're returning 32-bit numbers
    var saved;

    return {
        // Seeds the internal RNG.
        seed: function(s) {
            if (s === 0 || s == null) {
                // Can't use a zero seed (maybe throw an exception?)
                return;
            }

            // TODO Handle various types of arguments (just numbers/arrays for now)
            if (typeof s === 'number') {
                // Use only the lowest 32 bits right now
                state[0] = s >>> 0;
            } else if (s.constructor && s.constructor.name === 'Uint32Array') {
                for (var i = 0; i < state.length; i++) {
                    if (s[i] !== undefined) {
                        state[i] = s[i];
                    } else {
                        state[i] = 0;
                    }
                }
            }
        },

        // Returns a random float between 0 and 1 (exclusive),
        // with 32 bits of precision.
        random: function() {
            // If we already have a saved number, return it,
            // also clearing it for later use.
            if (saved != null) {
                var temp = saved;
                saved = null;
                return temp / MAXINT_PLUS_1;
            }

            // x = s[0]
            var x = new Uint32Array(2);
            x[0] = state[0];
            x[1] = state[1];

            // y = s[1]
            var y = new Uint32Array(2);
            y[0] = state[2];
            y[1] = state[3];

            // s[0] = y
            state[0] = y[0];
            state[1] = y[1];

            // (a): x ^= x << 23
            var xl23 = new Uint32Array(2);
            xl23[0] = x[0] << 23;
            xl23[1] = (x[1] << 23) & (x[0] >> 11);
            x[0] ^= xl23[0];
            x[1] ^= xl23[1];

            // (b): x ^= x >> 17
            var xr17 = new Uint32Array(2);
            xr17[1] = x[1] >>> 17;
            xr17[0] = (x[0] >>> 17) & (x[1] << 19);
            x[0] ^= xr17[0];
            x[1] ^= xr17[1];

            // (c): x ^= y ^ (y >> 26)
            var yr26 = new Uint32Array(2);
            yr26[1] = y[1] >>> 26;
            yr26[0] = (y[0] >>> 26) & (y[1] << 6);
            x[0] ^= y[0] ^ yr26[0];
            x[1] ^= y[1] ^ yr26[1];

            // s[1] = x
            state[2] = x[0];
            state[3] = x[1];

            // return x + y
            var retval = new Uint32Array(2);
            retval[0] = x[0] + y[0];
            retval[1] = x[1] + y[1] + (retval[0] < x[0]);
            saved = retval[1];
            return retval[0] / MAXINT_PLUS_1;
        }
    };
})();

I’ve written it as a Node.js module, but you can easily adapt it to a browser environment by changing module.exports on line 1 to window.xorshift or whatever you like. Whether it’s attached to the global window (browser) or loaded with require() (Node), the function creates an object with two methods: random() and seed(), both of which are explained below.

This isn’t a perfect implementation, and it does have a limitation that the original doesn’t have. This is because of JavaScript’s number handling, which might best be termed as “special”. JS only really has 64-bit floats for numbers, unless you do even more TypedArray contortions than I did here. So I had to compromise by making the random() function output numbers between 0 and 1 with 32 bits of resolution. Each run of the algorithm creates 64 bits of randomness, so I split that into two numbers, saving the second for the next call to the RNG. Changing the function to return integers instead of floats is easy enough: remove the two divisions by MAXINT_PLUS_1.

The whole reason for making this thing was to have a predictable RNG for JavaScript. That’s what the seed() function does. Pass in a single 32-bit integer or a typed array of them, and it will seed the algorithm using that. (One good way to extend this would be to use a hash such as MD5 to allow strings and other objects. That’s why the “TODO” comment is there.) If you don’t, it will use a few numbers generated from Math.random().

Another benefit of this (or any similar RNG) over the stock implementation is that you can create more than one, each tied to its own seed. This means that, for example, you can have your world generator running off a different sequence than your AI. You would then only have to save the seed for the world RNG, while the AI RNG gets reseeded when you reload the game. This would prevent players from, say, repeatedly reloading to get a good outcome of a battle in a strategy game.

As usual, I didn’t make the algorithm; I only wrote the code in this post. You can use it for whatever purpose you like, but I’m sure there are better implementations out there. I didn’t check, mostly because I wanted to try my hand at writing it first. It’s good practice.

Until next time, have fun!

Random Number Distributions (JS)

Last week, I talked about a method for choosing random values within a set, one of the many uses for random numbers in a game. This time, I’ll go deeper into the notion of probability distributions, and how you can make use of them in game development and other kinds of programming. A word of warning: this post will have code (usually Javascript) and might use a lot of math!

Simply Random

The uniform distribution is the one you already know. It’s behind all the simple RNG functions we saw before, like C’s rand() or Javascript’s Math.random(), and it’s what you get when you roll a single die: every number has an equal chance of coming up. In math terms, if there are n possibilities, then the chance of getting any specific one is 1/n. Couldn’t be simpler, really. For most game uses, this is your main tool, and the “weighted set” from the other post is a handy add-on.

The Bell Curve

I mentioned the bell curve and the normal distribution last time, but here I’ll go into a little bit more detail. The bell curve, of course, is often an early introduction to the world of statistics and terms like “standard deviation”, and (as we saw in the other post) it’s what you start getting when you roll more and more dice at a time.

Obviously, that’s one way to get a normal distribution: roll a bunch of dice and add them together:

var dieRoll = function() { return Math.floor(Math.random() * 6) + 1; }
var bellCurveRoll = 0;
for (var i = 0; i < 10; i++) {
    bellCurveRoll += dieRoll();
}

This gives us something close (though not perfect): random numbers will range from 10 to 60, with 35 being the most common. If we need something better (i.e., more accurate), we’ll need to delve into probability theory. Don’t worry, it’s only a short dive.

Side Quest

The mean might be familiar to you, since it’s not much more than another name for “average”. For a normal distribution, the mean is the center point of the curve, the part where it’s at its highest.

Less familiar is the standard deviation, although you may remember that from high school or early college. It’s important in a lot of stats-based fields, because it measures how “clustered” a group of data points is.

Now, for a set of data, you can calculate the mean and standard deviation. That’s pretty much how things like grading curves work: you take the data and make a distribution that fits. For RNGs, however, we have to work backwards. Instead of calculating the mean and standard deviation for the data, we choose them at the start, and our RNG uses them to provide the proper distribution of values. For the normal distribution, this means that about 68% of the values will be within 1 standard deviation of the mean, 95% within 2, and 99.7% within 3. (By the way, the standard deviation is usually identified in math by the Greek letter sigma: σ. “3-sigma” confidence, then, is 99.7% likelihood that something is true. “Six sigma” encompasses everything within 6 standard deviations of the mean, or about 99.9999998%; it’s not quite “one in a billion”, but it’s pretty close.)

Back to Normal

So, knowing all this boring math, you can start getting your random numbers. Here’s one way of doing it in Javascript:

function normalDistribution (mu, sigma) {
    var u1 = Math.random();
    var u2 = Math.random();

    var z0 = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(Math.PI*2 * u2);
    var z1 = Math.sqrt(-2.0 * Math.log(u1)) * Math.sin(Math.PI*2 * u2);

    return z0 * sigma + mu;
}

This uses a method called the Box-Muller transform to generate a random number on a bell curve. (The astute reader will notice that the function actually generates two random numbers, but throws one of them away. If you like, you can make a better function that stores the second value and returns it as the next random number.) The two parameters are our mean (mu, because it is often written as the Greek letter μ) and the standard deviation (sigma). The Wikipedia link above explains the theory behind this method, as well as giving links to other ways, some of which might be faster.

Exponential Randomness

Normal distributions have their uses, and they’re about as far as most people get in studying randomness. But we won’t stop there. We’ll move on.

Next up is the exponential distribution. This one isn’t that hard to make in code:

function expoDistribution (lambda) {
    return -Math.log(1.0 - Math.random()) / lambda;
}

But you might wonder if it’s really useful. Well, as it turns out, it does come in handy sometimes. Basically, the exponential distribution can be used anywhere you need a “time between events” type of randomness, like random events firing in a strategy game.

The lambda parameter is what’s called a “rate parameter”, and it’s intimately related to the mean; in fact, it’s the reciprocal: the exponential distribution’s mean is 1 / lambda. But what does it mean? Let’s take an example: say you’re making a game where special power-ups appear, on average, twice every minute. Using the above function with lambda as 2, the result would be the time (in minutes) until the next power-up. (The mean would then be 1/2, or 30 seconds, which makes intuitive sense.)

Pareto, Principle, and Power

If you’ve ever heard of the “Pareto Principle” or the “80-20 rule”, then you’ve got a head start on learning about the Pareto distribution. The general idea is thus: there are a few with a lot, and a lot with a little. “The top 20% control 80% of the wealth” is the most common way to state this particular idea, but a random distribution with these properties can be surprisingly useful in games. Here’s the code:

function paretoDistribution (minimum, alpha) {
    var u = 1.0 - Math.random();
    return minimum / Math.pow(u, 1.0 / alpha);
}

We have two parameters we can control this time. minimum is the lowest possible value that can be returned, while alpha controls the “shape” of the distribution. (Generally, higher values of alpha have a faster drop-off, meaning that lower values have higher probability. The “80-20” distribution has an alpha of log(5) / log(4), or about 1.161.)

The Pareto distribution isn’t just used for wealth, though. Anywhere you have a “long tail”, it might be what you’re looking for. Random city sizes (or star sizes, for an interstellar game) follow a Pareto distribution, and it might be a good way to model “loot drops” in an RPG; less powerful objects are far more common than the Ultimate Sword of Smiting, after all.

In Closing

These aren’t all that’s available, but the four distributions I’ve shown are probably the most useful for programmers, especially game developers. As before, I didn’t originally come up with any of this; it’s all been known since before I was born. Some code is converted from Python’s extensive random module, specifically the functions random.expovariate() and random.paretovariate(). The code for the normal distribution is my Javascript conversion of the Box-Muller transform example at the Wikipedia link above. (By the way, if you want me to post examples for a different language, just ask!)

A lot of people already know all this material, and there are plenty of other sites detailing them better than I can, but I hope that this is enough to get you interested.

Weighted Random Choices (JS)

In programming, we often need to generate random numbers, especially for games. Almost any game will use at least some kind of random number generator (RNG), and most need lots of them to drive the AI, make new levels, and so on.

Any programming language worth using (for games, anyway) will have some way of making an RNG. C has rand(), Javascript has Math.random(), and so on. Game engines usually add in their own ways, like Unity’s Random.value, constructed out of the base provided by whatever language they’re written in. All of these work in basically the same way: you ask the RNG for a value, and it gives you one. Usually, it’s a floating-point number between 0 and 1, which is good if that’s what you need.

Beginners starting out in game development quickly learn how to turn the float value from 0 to 1 (not so useful) into a number in the right range (more useful). The code for rolling a regular, six-sided die usually looks something like this (in Javascript):

var roll = Math.floor(Math.random() * 6) + 1;

It’s a pretty standard technique, and many languages and game engines now have functions that do this for you. And, again, if that’s what you need, then it’s perfect. Sometimes, though, it’s not what you need. This post is for one of those times. Specifically, the case where you need to choose one value from a list.

Simple Choices

When you simply need to pick a single value out of a list (array, vector, whatever), that’s easy. All you’re really doing is the same thing as rolling a die:

var index = Math.floor(Math.random() * array.length);
var choice = array[index];

In effect, we’re choosing a random array index. Easy. Like rolling a die, it gives you an equal chance for each possible value. (If your array contains the numbers from 1 to 6, then you’ve just created a less efficient method of rolling a die.)

Harder Choices

Not everything has an equal probability, though. (Statistics as a science wouldn’t exist if it did. Whether that’s a good or bad thing depends on the way you look at it, I guess.)

Some things can be approximated with the die-rolling method above. Lotteries, for example, work the same way, as do raffles. For some games, that may be all you really need. But other games require more from their RNGs than this.

Take the case of rolling multiple dice. Anybody who has played a role-playing game, or craps in a casino, or even Monopoly knows that, while every number on a die has an equal chance of popping up, things get more complicated when you add more dice. With two dice, for example, a total of 7 is more common than a 2 or 12, because there are more ways to roll numbers that add up to 7: 1+6, 6+1, 2+5, 5+2, 3+4, and 4+3. Add more dice, and the numbers get bigger, the range gets wider, but the idea stays the same: numbers “in the middle” are more likely than those on the outside. (Due to what’s called the central limit theorem, the more dice you roll, the more the graph of possible outcomes starts to resemble a bell curve.)

Rolling a lot of dice is impractical, even on a computer. The probabilities aren’t always so nice and neat that a bell curve works. Maybe you need to choose from a set where the ends are more common than the middle, or a list with a weird distribution of frequencies like the letters in English text. (One out of every eight letters, on average, is E, but Z is over a hundred times less common.) A word game, for instance, would certainly need to do something like this.

Now, there are plenty of different ways of generating random numbers based on frequencies. Here, I’m only going to describe what I think is the simplest. First, we need a problem. Let’s say you’re making a word game that, for whatever reason, uses the letter tiles from Scrabble. (You probably wouldn’t be making an actual Scrabble game, because some people or lawyers might not like that, but we’ll say you’re using the letter frequencies.) Looking at that link, you can probably see that just using random choices won’t help you. We need something different.

First things first, let’s define the set we’re choosing from (note the space at the end, which represents the blank tiles):

var letters = ['a','b','c','d','e','f','g','h',
    'i','j','k','l','m','n','o','p','q','r','s',
    't','u','v','w','x','y','z',' '];

Since this is an uneven distribution, we need some way of representing each probability. In this method, we do this by “weighting” each value. We’ll store these weights in their own array:

var weights = [9, 2, 2, 4, 12, 2, 3, 2,
    9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4,
    6, 4, 2, 2, 1, 2, 1, 2];

In this case, the sum of all the weights is 102 (100 letters, 2 blanks). Therefore, the ratio of each weight to that sum is the frequency of the letter. (For example, there are 12 E tiles, so E’s frequency is 12/102, or about 11.8%.) That’s the key to this method. Basically, we do something like this:

function randomLetter() {
    var totalWeight = 0;

    for (var w in weights) {
        totalWeight += w;
    }

    var random = Math.floor(Math.random() * totalWeight);

    for (var i = 0; i < letters.length; i++) {
        random -= weights[i];

        if (random < 0) {
            return letters[i];
        }
    }
}

(Obviously, in a real game, we’d need something much more robust, with better error handling, etc., but this is enough to illustrate the point. Also, this isn’t normally how I’d write this function, but I’ve simplified for the same reason.)

The function works by picking a random number from 0 up to the sum of the weights. We then use that as an “index”, but not directly into the array. Instead, we count down from our chosen number, each time subtracting successive weights, until we go below zero, where we produce the corresponding letter.

Let’s say that our random number is 15. We go through the weights array, starting with 9. Subtracting 9 from 15 leaves 6, so we keep going, down by 2 to 4, then by 2 again to 2, then by 4 down to -2. That’s below zero, so that’s where we stop, returning 'd'.

This method isn’t just limited to choosing letters. You can use it anywhere you need a biased sample. Think of a game that has five different types of enemies, each with different chances of spawning. Set up a list of enemy types, another holding their appearance frequencies, and the same method will give you waves of bad guys.

(Note: I’m not claiming credit for any of this. It was all figured out a long time ago, and certainly not by me. I’m not even the first to write about it online. But it’s definitely something beginners should learn, and I hope to post more little “tutorial” articles like this in the coming months, because we were all young, once.)