I was screwing around in our “home office” last night, and a floppy disk fell off a shelf. It was my Hunt the Wumpus program, the final project for my C++ class at Harper. I took that class in the Fall of 1999, almost ten years ago, and thought it might be fun to convert the game to run in a browser.
A big part of that class was exploring object-oriented concepts. And, since one of my New Years Resolutions this year was to use more OOP in my Javascript code, I figured Javascript would be the way to go.
It started off well enough. After a few hours, I had the thing pretty much running using document.write and prompt(). It felt like I was back in 1996, on some of the earliest Javascript sites. We’ve come so far since then. So, I threw together a class I called jsTTY, which turned a textarea into something resembling a text console like you’d see in the old DOS days. I even used CSS to give it green text on a black background.
As I started integrating jsTTY into Hunt the Wumpus, I realized that a game like that wouldn’t convert directly into Javascript — I’d have to rewrite a large chunk of the Wumpus code for Javascript’s programming model. Specifically, Javascript lacks blocking I/O or any sort of sleep() command. I wanted something like cin.getline(), which waits until the user hit “enter” before returning a string. jsTTY.line() worked like that, but it had to spin in a do/while() loop, eating up all the CPU and crashing Safari.
Normally, the way to deal with something like this is to sleep in the middle of the loop. Even if it’s just for 1/1000 of a second, that’s an eternity for a modern CPU. The closest thing Javascript offers is setTimeout(), which sets up a timer to run some function and returns right away, something akin to spawning a thread, but not quite.
I realized that my main loop, the core of pretty much any video game, needed to be replaced by a ballet of asynchronous events. That’s only, oh, half the Wumpus code, and certainly more than I want to tackle right now.
Still, it was an interesting experience, and I look forward to getting jsTTY working in some fashion.

Previous Entries