Material

Game loops in JavaScript

I'm learning JavaScript! I mean, I already wrote some crap in it before, but now I'm learning enough to write something substantial. Like a (non-Perlenspiel) game.

One of the things you need for a game is a game loop. In large games these are increasingly tricky affairs spread out over multiple threads and designed to optimize memory access patterns. In JavaScript, you can't do that, but you can at least implement the basics correctly. The canonical tutorial on this stuff is deWiTTERS Game Loop which goes over several implementation strategies. Only one of those implementations, "Constant Game Speed independent of Variable FPS," is worth pursuing. (To know why, read the article.) So how to do it in JavaScript?


This post used to be a lot longer and full of bad advice. Here is good advice: Use only requestAnimationFrame. Just do everything the deWitters article says inside of requestAnimationFrame. After more testing I've discovered browsers' schedulers are basically awful, unreliable, and this is the only way to make a main loop appropriate for a game. If you are targeting one specific version of one browser on one platform, you can maybe manage a better loop with the setInterval-based method I had described before, but if you're doing that you're better off writing a native application in the first place.

Linkspam, May 11th, 2013

A bit over a hundred years ago, California was all set to build a great-looking bike highway. Unfortunately they built car highways instead and pretty much doomed good urban planning, air quality, international politics, etc. More alternate history stories should pick events like this as divergence points, rather than boring crap like who won wars.

California continues its century-plus history of bad decisions through to today, as documented in a beautiful letter from Robert Meister to Daphne Koller about Coursera's state lobbying efforts to delegitimize and destroy public education:

I will know my course has been successful when my students understand Coursera’s business model behind offering free higher education globally (along with the promise of greater social equality) as an exciting venture capital investment opportunity through which to increase privately-held wealth and lock in existing educational hierarchies.

Relatedly (I promise) bees are still dying for unknown reasons:

Rising food prices led farmers to plant crops in fields previously considered marginal or set aside as grasslands. Honeybees forage in those grasslands, and can’t get the nutrition they need from flowering crops alone.

This is a positive feedback loop, since without bees fruits don't get pollinated and food gets even more expensive. If this was, say, a college education, or health care, the solution is obvious: large-scale private pollination efforts. If you want fruit, you'd better spend your lunch hour pollinating that garden to earn a fruit certificate to exchange for a shitty melon. (Hah hah, just kidding, who gets a lunch hour anymore?)

Shane Carruth has released his new film, Upstream Color, as a $20 DRM-free download. His previous film Primer is one of my favorites. I don't feel quite as good about Upstream Color, but I still recommend it.

Someone (an adult) reviewed every Goosebumps book. Eight-year-old-me is jealous. Today-me hopes the reviewer is still okay.

Here is a version of Astroids that is also a security hole and the author, Michal Zalewski, explaining how it works. This attack is oblique, involves multiple levels of the platform stack, and the information immediately leaked is not usually thought of as a security problem by those under attack. This also describes things like cache timing attacks or the BEAST and CRIME TLS attacks. The biggest challenge facing computer security right now isn't even just plugging all the holes, but explaining to laypeople and novice programmers what kinds of things are risks and threats.

God of Blades came out for personal computers (a while ago, and I missed it). I'd previously played it on iOS. Satisfying slow-paced hack-and-slash with an underused aesthetic. A bourbon to Devil May Cry's wine. (Bayonetta's tequila? God of War's jello shots?)

Porpentine's essay, 7 Thoughts on Women in Games had a line that I thought was a critical takeaway for any kind of activism, because it succinctly sums up what's broken about the hyper-libertarianism in so many parts of the Internet today:

Communities aren’t “just friends”. Sure, they’re often groups of friends based around a common interest, but when a community of friends overlaps or encompasses technical resources, they must take responsibility.

Configuring Emacs on Mac OS X

I wanted a nice experience using Emacs for Mac OS X. By "nice" I mean:

You too can bring several hours and three separate scripting tools to bear on this, or follow the simple (hah hah) instructions below.

First, install Emacs For Mac OS X. The Emacs that comes with OS X is old and crusty, and the one at that site is new and Cocoa-ready and Retina-enabled and so on. Put it in /Applications - if you put it somewhere else, you'll need to correct all the other scripts I'm mentioning in this post.

Emacs Server at Login

Open up the AppleScript Editor. If you're an Emacs user this probably looks awful and confusing to you. Paste the following into it:

tell application "Terminal"
   do shell script "/Applications/Emacs.app/Contents/MacOS/Emacs --daemon"
end tell

Press ⌘K to compile it, then ⌘S and save it in /Applications/Development. (This subfolder keeps your Applications menu clean, and has an important effect on sort order later.) To give it a nice icon, select the original Emacs.app; press ⌘I; click the icon in the top-left; press ⌘C; select on your new Emacs Server.app bundle; press ⌘I; click the icon in the top-left; press ⌘V.

Open up System Preferences > Users & Groups > Login Items and now you can press the + button and choose Emacs Server.

The server is invisible until you first connect a client to it. Then it will appear in the dock, as the regular Emacs.app.

New Frame Dock Icon

To make a dock icon that opens up a new Emacs frame - a client if the server is available, a standalone instance otherwise - create the following script in the AppleScript Editor and save it as an Application named Emacs Client. in /Applications/Development.

tell application "Terminal"
    try
        do shell script "/Applications/Emacs.app/Contents/MacOS/bin/emacsclient -c -n &"
        tell application "Emacs" to activate
    on error
        do shell script "/Applications/Emacs.app/Contents/MacOS/Emacs"
    end try
end tell

Then drag this from the Applications folder to your dock. This will also make it so typing emacs into Spotlight selects this as the first item ("Development" sorts before "Emacs", "Client" sorts before "Server").

If connected to the server, this opens up a new client frame each click, by design. To just raise existing frames, click the other Emacs icon on the dock, representing the running application.

Server-aware Shell Scripts

I put these in ~/local/bin. You'll need to add that to your $PATH if you haven't already. First, two simple ones. These will start new instances, not clients, but they're necessary to properly handle shell arguments for fallbacks for clients. They're also nice to have if you actually want to start a new instance.

Start a new Cocoa instance - emacsc:

#!/bin/sh
set -e
/Applications/Emacs.app/Contents/MacOS/Emacs "$@"

Start a new terminal instance - emacst:

#!/bin/sh
set -e
/Applications/Emacs.app/Contents/MacOS/Emacs -nw "$@"

Now for something ma little ore complicated - ec, start a Cocoa client or fall back to a new instance (via the above emacsc) if the server is unavailable.

set -e
EMACSCLIENT=/Applications/Emacs.app/Contents/MacOS/bin/emacsclient
exec $EMACSCLIENT -c -a ~/local/bin/emacsc "$@"

Similarly, et, for a terminal client or new terminal instance.

set -e
EMACSCLIENT=/Applications/Emacs.app/Contents/MacOS/bin/emacsclient
exec $EMACSCLIENT -t -a ~/local/bin/emacst "$@"

Why are ec and et scripts instead of aliases? Many tools will fail if $EDITOR does not resolve to an actual executable somewhere in $PATH because they invoke the tool directly instead of invoking a shell to run it.

Finally: Some aliases for ~/.bash_profile, to override the ancient version of Emacs that Mac OS X comes with by default.

alias emacsclient="/Applications/Emacs.app/Contents/MacOS/bin/emacsclient"
alias emacs="ec"
export EDITOR="ec"

Activate Emacs on New Frames

If you start emacsc or ec from Terminal, Mac OS X doesn't realize you probably want to switch focus to the Emacs session automatically. There are also plenty of other ways you might start Emacs besides typing a command into Terminal, and you probably want the new frames focused then as well.

To do this, we can take advantage of the ns features in Emacs Lisp and the frame-creation hooks. Add the following to your ~/.emacs or some file it loads:

(when (featurep 'ns)
  (defun ns-raise-emacs ()
    "Raise Emacs."
    (ns-do-applescript "tell application \"Emacs\" to activate"))

  (defun ns-raise-emacs-with-frame (frame)
    "Raise Emacs and select the provided frame."
    (with-selected-frame frame
      (when (display-graphic-p)
        (ns-raise-emacs))))

  (add-hook 'after-make-frame-functions 'ns-raise-emacs-with-frame)

  (when (display-graphic-p)
    (ns-raise-emacs)))

Now anything that opens or selects a frame will also activate Emacs for Finder. The featurep check means this is harmless to load on non-OS X platforms, and ns-raise-emacs is not (interactive) for reasons that will be self-evident if you think about them.

Remaining Issues

Launch Services is happy to start the Emacs Server instance but loses track of it afterwards. This is mostly harmless but annoying.

The second Emacs icon on the dock (the one for the main Emacs.app rather than your custom Emacs Client.app) behaves oddly when no frames are visible. Its menu bar and context menu don't work, and you can't start a new frame from it directly. This is likely an issue because both Emacs and Finder assume any graphical application has at least one main window / frame, even if it might not be visible.

(Thanks to Dan Gerrity for pointing out a typo in the original posted emacst script, and Sean B. Palmer for Emacs Lisp improvements that led to much simpler shell scripts.)

I played: Candy Box

Candy Box is getting a lot of attention. I'm enjoying it. You should probably go start playing it before you read on, because it's kind of like Frog Fractions or Drop a Beat, Giuseppe! or Dragon Drop (and if you're not sure what I'm talking about, go play all those too).1


I'm spending way more time with Candy Box that I expected. Even after it opened up what I saw at first was an ordinary energy-waiting-spending mechanism. These are common in F2P games but lately they're found even in other styles2 of game, and I hate them.

But for Candy Box this is another layer of trickery. If you're really paying attention you get on an exponential feedback loop within about an hour of play. There's the "opening up" after a few minutes, but then also a second at that point, where you start to get meaningful choices on intervals comparable to the time it takes to make the choice. The candy energy becomes almost irrelevant (say, as relevant as how many potions you have in a Final Fantasy game) as you start to consider how you can use the potions and scrolls available. Eventually you get the cauldron and navigable levels and it's more like animation lockdowns than waiting for energy; the scales are so short and there's so many near-term options at each juncture.

What really drew me in was the mechanism of the Wishing Well (although a similar choice appears with smaller magnitude at other points in the game). It gives you a one-time ability to gain items proportional to the items you have. In a game where the decision space unlocks gradually a one-time ability comes with worries that you might not even know what's important. Between the exponential power curve and granting this ability it becomes a game about patience rather than just a game in which I must be patient.

When you have to wait two days and can pay $10 to remove that, it's abusive or at least stressful in a bad way. But what is it when you can wait an hour or two days or five days and then invoke an ability - exactly once - to multiply your energy by eight? Then it becomes a game of patience and suspicion. How long can I wait before invoking this? I know if I do it after an hour I'll get to do this new thing. I don't know, but suspect, if I wait a day it's going to open up much more. I don't suspect, but might believe, that if I wait a another day it's going to open even more.

So it's kind of a game of chicken, but against a static system: When do I think the designer stopped implementing new things? Inevitably the comparison, when would I stop adding new things? How much do I think I don't know? It's constantly asking me that, and I think that's an uncommon question in videogames.


  1. I'm pretty sure there's a new genre forming here. Which is cool; games today need more secrets. 

  2. That "how the game might make money" is now a "style" or "genre" is a frustrating issue in itself. 

Linkspam, May 4th, 2013

Mike Joffe deconstructs Super Princess Peach and finds that, although it continues Nintendo's history of problematic character design, it also has some unlikely subtext that helped him resonate with Peach's character:

Bowser's giant vibrating phallus of emotion is too strong for other men, but it leaves him irrational and emotive, allowing the collected, in-control female hero to defeat him with her logical use and understanding of her emotions.

An essay by Jordan Erica Webber in the latest issue of Five out of Ten, Reflecting Reality, covers similar ground but with a different conclusion while considering Patricia Tannis in Borderlands 2. (There's other good stuff in the magazine too.)

Aniwey's Candy Box was pretty cool until I accidentally hit backspace and lost a couple (critical) hours of progress.

High-resolution background art from Final Fantasy IX, cut from the game (probably for size reasons). FFIX is the only one in the series I've respected more as I age (and probably mature). I would love to see these put into a re-release or hacked into the existing game.

Some recommendations after a week of playing Ludum Dare games:

I had planned to have more than videogame links here but between Ludum Dare and me being completely disorganized I have forgotten them all.

Ludum Dare 26 - 123456789

I made a game called 1234567891 for Ludum Dare 26. It's a short web-based puzzle game. At first I didn't much like the theme and wasn't going to do anything. (I prefer to view themes as prompts for something the game should be about, not just a style for the game to be in.) But my wife was playing Hyperdimension Neptunia V all day so I had to do something other than Monster Hunter for a change. It probably took about five hours to make playable and then another two to add sound, playtest and make some interface tweaks.

I don't really like puzzle three but it's doing double-duty as a hint for puzzle nine, which is inscrutable enough even with it. People are having more trouble with puzzle six than I expected.2 Puzzle eight is perfect.

The core mechanics and feel are inspired by Nemesis Factor, a toy that felt like something you'd find in an abandoned Martian daycare center. The form is inspired by Anna Anthropy, Leon Arnott, and Liz Ryerson's Triad - a quick riff on a theme and then it's over, no time wasted on a 255 board checklist or "infinite procedural levels!" no one will play.

Like my last completed Ludum Dare game it uses Perlenspiel and should run properly in any modern-ish browser, including phones and tablets (for which a secret button appears since you can't just press Escape).


  1. No relation to 86856527. Which you should totally play. 

  2. Vs lbh'er fghpx, cerff Pgey+Fcnpr gb fxvc gb gur arkg chmmyr. 

Lego stuff

I put up the Lego stuff from my old site. LDraw parts for Heroica and a page about X-Pod Play Off. Modified Heroica rules are on hiatus for a while until I figure out the best way to integrate stuff from Ilrion and plug a few new balance holes.

As far as I can tell Heroica is canceled, though. Lego needs to figure out how to keep their (good) games around for more than a year and a half. They've been scaling back the whole Games line and the only mainstays seem to be Creationary (fine, but not very interesting) and LEGO Champion (horrible, and yet still the only way to get female microfigures who are not an unlicensed Cho Chang).

We Have Never Been Hunters

I'm playing a ton of Monster Hunter 3 Ultimate. It's the first in the series I've really dug into - I played through the first few village quest levels of Freedom Unite but quit for various reasons. Monster Hunter's a really big game, wide and deep, and my thoughts about it - aside from "I like it, it's fun" - are vague and meandering right now.

It slowly morphs between a couple different games, each one acting as a tutorial for the next. There are a lot of moving parts and each one feeds into the next one, and some of them feed back as well. You gather and farm (literally, organizing agricultural production; figuratively, performing repetitive actions) to get resources to build tools to let you farm more effectively to hire and train assistants to take on bigger challenges, and repeat. The change is slow, but when you compare one star vs. five star vs. challenge quests, it's sort of like proceeding from gomoku to capture go to proper go. (If you also had to fell and cut lumber for the board and find shells and mine rock for the stones.) Same parts, similar mechanisms, very different game. Each step I have to pick up some new tactic or tool or I risk losing more often.

This also means it's very slow - I've "beaten" it after around 50 hours, but that really just means I'm now doing high-rank quests. I suspect that high-rank to G-rank is going to be another slow ramp up to a new kind of game.

The size of the game also dominates online discussion. There's a lot of explanation of what and how because there's a lot to learn (and I don't want to downplay the friendly community) but not much critical analysis of if and why.


I have a complicated relationship with physical violence in games. I play a lot of horror games (and watch a lot of bloody horror films) and that doesn't bug me; Grand Theft Auto: San Andreas doesn't bug me; Hotline Miami bugs me in what I suspect is exactly the way it's designed to; Saint's Row 3 was really troubling for me; I found Grand Theft Auto 4 more or less unplayable. Intent, magnitude and amount, fidelity, agency, a bunch of different (and non-orthogonal) axes make it difficult for me to guess how I might react or tease out what exactly bothers me.

Monster Hunter doesn't bother me. There's a fair amount of blood, and everything about it is really brutal: the hits and knockdowns, breaks and carves, bites and smashes. It knows it's toeing some kind of line, and so when you attack the speaking Lynians or the cute Kelbi, it's careful to show them retreating rather than dying.


There's probably something to say about Monster Hunter and ecology. I'm not smart enough to really dig in, but that won't stop me from writing a bunch of crap.

First, it's a game that has an ecology in the normal sense. There are fictional books styled as notes from naturalists who have studied the monsters. This offers an ecological interpretation of its game mechanics: The research is a tool for players to learn how to deal with (fight, avoid, steal from, etc.) monsters. Take this description of Qurupeco, an early monster:

Bird Wyverns with unique plumage. Well known for using their thoracic vocal organs to imitate others monsters calls, first summoning them, then using the distraction to flee. Spits a dangerous combustible body fluid.

We have the veneer of "real" natural history with a reference to the genus "bird wyvern". This tells the player about its general shape and behavior. It also offers an outline of how it interacts with other monsters in the area and its unique behaviors. Every monster and many other objects in the game have descriptions in this form.

But Monster Hunter isn't an ecological simulation in the sense of e.g. SimCity where you take on the role of a transcendent planner and explore ecological potentials1. Instead it has an ecology, and you - the player/character - are part of it, unable to cause macro-level change on your own, and instead must prepare and learn about it in order to survive and enable a series of micro-level changes.

Second, the games' plots usually concern the relationship between particular human settlements and the surrounding environment. Humans in the world of Monster Hunter seem constantly at risk of extinction through large-scale ecological disaster. In the case of 3 Ultimate, a giant monster butting its head against the ocean floor nearby is causing earthquakes.

Humans don't have any dominion over that space (e.g. the ocean floor), they only mitigate, course-correct, survive. They also aren't very interested in developing a dominion. By the end of the game your village's interaction is broader, but it's not physically larger, and it interacts with the larger space in the same way it did with the smaller one. You can displace the cause of the quakes, but it comes back, or creates a space for other problems - you achieve an equilibrium, not ownership, control, or transcendence.

But it's also not a "primitive" society. There's global travel, money and trade, advanced metalworking and steam power, domesticated animals, division of labor, bureaucracy, books and scientific research. Some aspects are tribal and agrarian, but most of the culture is late-Enlightenment at the earliest.

Is it particularly good at any of this? Does it really put forward a coherent viewpoint when considered over the course of all games / quests? Can we learn anything about ecology from it? I've got no idea so far.

My hypothesis - which like the previous ones, is too coarse - is that we are going to have to slow down, reorient and regulate the proliferation of monsters... Bruno Latour, "We Have Never Been Modern"


  1. But wow, how cool would it be to have a SimCity-like game where you had to live in the city you built. 

Nigoro's "Problem of Faith"

One of the difficult things when Japanese make games for foreign countries is the problems with faith. From the historical background of Japan the interest in faith has been weak. It’s difficult to understand the feeling of things such as making vows with a hand over the Bible during the presidential inauguration; or how Islamic faith views the absolute moral...

And it can’t just end there, so what’s OK and what’s bad needs to be thought out, but there is no such rule existing.

Nigoro, developers of La-Mulana, "Problem of Faith"

I'm an atheist and I don't necessarily agree with the choices they've made in this instance. But I also see it's a difficult problem, and I can't read their minds and see what they were trying to do in the first place.

What I do know is that this kind of public discussion about how we use cultural symbols - especially other's cultural symbols - is desperately needed. In the West it really only happens among tiny development teams, one or two people. So to read a reflection on it, from a "large" independent studio whose native language is not English, is a rare treasure.

The comments, unfortunately but expectedly, are horrible.

I played: The Guardian

I played Nicole Brauer's The Guardian. It's a Flash-based sidescroller and takes about 20 minutes. (I think? I took a break in the middle.)

Screenshot of the village in the game

It suffers from some pacing problems. I hardly ever enjoy screens with slowly appearing text.

What's cool is how the scale of the game - you're a single pixel - changes how you parse the landscape. Shapes that would be irrelevant details in other games take on an active role helping/hindering you. The scale also changes the primary verb. It's mechanically identical to "jump" but the sizes and angles involved make it feel more like climbing.

(via Shawn Trautman's Discover Games)

« Page 5 / 6 »