Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, December 3, 2012

Another season, another game programming contest

   Just when I thought I could relax, waiting for the results of the Liberated Pixel Cup (not really thinking about winning, but hoping at least to have a decent score), here comes GitHub with a context of its own: Game-Off 2012. One month to come up with a game that should be web-playable and loosely based on git concepts: branches, clones, forks, pushes and pulls. What was I supposed to do? Well, of course, participate.

   I thought about some concepts on my own. The first idea was to go all out on the theme, with an action platformer where you would run and jump on branches, pushing and pulling clones with forks. Nothing really original for gameplay. My second idea was to play the French touch by using French words that sound close to the theme: poule (chicken) for pull, phoque (seal, the animal) for fork, clown for clone. I did not venture further. I'm not sure I want to imagine what a game with clowns, chickens and seals would be. My third idea was to make a puzzle game. They are generally easier to make than real-time action games, and it's possible to end up with something acceptable, even without a real artist: you can always go the "abstract" way. The first puzzle idea was about a tree that you have to grow somehow, using actions like "fork" to add branches, "push" to bend them and cut to stop them growing. I even started a proof of concept, to see if it had any potential. Since GitHub required the game to be web-playable, I settled for HTML and JavaScript. Let's even say HTML5, for buzzword compliance, because it uses the fantastic <canvas> element.

Orphaned tree game concept

   At about that time, I asked for volunteers among my coworkers to help me. I met with two of them, and after our first brainstorming session, the tree growing concept was abandoned. We could not see clearly enough what the goal could be or how to make the game challenging. I thought the goal could be to fill a predefined shape with a set of available actions, but I was afraid all levels would end up being too easy to solve. Being short on time, we focused instead on a domino game, for which the goals and constraints were easier to imagine. In each level, you would have starting points, goals to reach and an assorted set of pieces to make a path from start to goal. Oh, and the board would use hexagons, not squares, to give it an original touch.

   At that point, there were three and a half weeks left. I had already set up the "infrastructure" (github repo, Google Group) so we started coding, slowly, on the low-level parts: how to handle hexagons and their coordinates, how to draw them, how to match a mouse position to an hexagon. Nothing technically hard. The only problem is that it is difficult for several people to start coding from scratch simultaneously. Even more so when the other guys are not so fluent with JavaScript. Anyway, I did most of the initial coding, and we had one formal work meeting every Tuesday to share ideas and build momentum for the next week. As you can see on the graph below, representing the number of commits for the last seven weeks, momentum took some time to build, but when we stopped, we had quite a lot.

Project commit history

   The idea we had, to be able to share a bit of the workload, was to make pieces and levels as independent and pluggable as possible. I refactored a big part of the code to allow that, and one of my coworker coded some of the missing pieces, the ones that fork the path. I also coded the basic UI allowing to select pieces and to put them on the board. From that, it was quite easy to make a basic level editor. The other guy was then able to completely rewrite the drawing code, replacing my ugly looking black and white rectangles that were supposed to be dominos, by a more abstract look that was more pleasant and easier to animate. We thought about making 3D models and realistic domino renderings in Blender, but had to ditch it, by lack of time and competency.

The last tutorial level

   One week before the deadline, we had all the low-level mechanics and pieces we needed, but we had not yet produced a single level, and the global look was not very engaging. That's what we focused on in that last sprint. I wrote nine entry level tutorials, with texts explaining all the mechanics and each one of us tried to design about seven levels to reach about thirty. We got exactly there: 30 levels + 1 level editor.
   We enrolled a few more coworkers for beta-testing and mobile platform testing. I coded some important stuff on the last two days (level locking and in-place rotation and delete) in response to our limited user tests. My team mates worked hard the very last days to find or draw pleasing images and icons, and the game was finally ready. 

   You can play it on GitHub. And you can browse the source also on GitHub.

   For those of you who like numbers (like me), the game contains 3.500 lines of JavaScript code (blank and comment lines excluded), which is about a third of my port of Desktop Dungeons. 
The glorious splash screen, committed during the last 24 hours

Lessons learned

   Doing a game jam is nice, doing it with other people is nicer still, at least in a small team. Different opinions can combine to produce things that would not have been possible alone. And being a small team, we could avoid the "design by committee" pitfalls.
    JavaScript is really cool for short prototype-y projects like this one. And apart from Opera that has poor canvas rendering performance, the game works very well on all desktop and mobile browsers.
    Doing HTML5 makes it easy to target mobile platforms, but their specificity regarding screen size and input methods must be taken into account to produce a good experience. We'll try to find hardware for tests sooner in the project next time. Hopefully, we'll win an iPad from GitHub, and the problem will be solved.

Friday, November 18, 2011

The making of Web Desktop Dungeons

As promised in the previous post, I will explain how I made the web version of Desktop Dungeons. I already told why I embarked on that project; here is the how.

When I first got the idea to port the game to the browser, I looked at what kind of game libraries were available. Back in April, nothing seemed to fit what I was looking for. Lots of libraries and frameworks, both free and proprietary, have appeared or blossomed only last summer. And most of the ones I browsed focused on fast-paced shooters and platformers, with animations, collision detection, particle systems, physics simulation and other features that were clearly not needed for Desktop Dungeons. So I quickly decided that I would code everything myself. It did not seem too big too handle.

The other thing that I decided immediately at start (I don't even know if I should call it a decision) was to use only HTML and CSS for rendering: no canvas drawing. I thought that I would be able to ensure compatibility with older browsers that way. And since the game is tile-based, it was a very natural choice. I did not need real drawing capabilities. I only wanted to show images at predefined positions, rectangular buttons and areas, all things possible with <img>s, <div>s, <a>s and a bit of CSS styling. I abandoned compatibility with older browsers (yes, IE 7 and 8, I'm talking of you) along the way, but for other reasons.

The early days

On the first day, I was able to display the 20x20 board with a predefined maze, a yellow placeholder for all the status information, a hero sprite that I could control with the keyboard and move even through walls, and a mouse-following 'cursor'. And all that with one HTML file, two JavaScript (one for utilities/compatibility layer and one for the game itself) and all the bitmaps from the original game. I used git immediately to track my changes and backup my work. I made five revisions on that first day.

Web Desktop Dungeons at one day

After three weeks of (after hours) work, the game started to look a bit better: the info panel at the right was a bit more fleshed out, moving the hero worked both with the keyboard and the mouse, thanks to the pathfinding algorithm, the maze (still fixed) was filled with lots of intersting stuff and the combat system was in place, somewhat. Except it was not yet possible to die. The JavaScript code had now expanded to four files, totaling 1.200 lines. Three refactorings had already taken place, one of them labelled as "big" in the change log.

Web Desktop Dungeons at three weeks

Then, I reorganized the code in true MVC fashion, began to develop individual widgets (buttons, gauges, images, tooltips, dialogs), continued to improve support of game mechanics (magic spells, special states, regeneration, power ups), added the basic logic of the menu screen and mid-June, I contacted QCF Design to present my creation. Danny (Day aka Dislekcia) answered me and has always been very positive and supportive. At that time, I wanted to open-source the whole thing and publish it on Github, with permission. Danny convinced me it was not a good idea: the project was still far from finished or even playable. Had I gone public at that time, I would probably have received only negative reactions.

So I resumed work on implementing all the "content": hero classes and races with their unique abilities, monsters, bosses, gods (oh! boy!) and items. I was guided by the content of the wiki and by personal experiments with the desktop version. I contributed a few elements back to the wiki. But after three months, I began to realize that play-testing was not going to be enough to ensure correct implementation of all the details and prevent regressions. I was now at 4.000 lines of JavaScript and I needed an automated test system. Otherwise, it was impossible to manually reproduce rare situations, like finding an altar to Jehora Jeheyu while being immune to poison. 

Growing up, gathering tools

I chose JsTestDriver as my unit testing library. It's mature. It can be added to an automated build. It runs the tests in real browsers, not in some kind of virtual JavaScript environment. It can drive several browsers at once. It produces reports that are compatible with JUnit. Sometimes the server gets stuck and needs a restart, but that's really bearable. I started with version 1.3.2 and later migrated to 1.3.3 when it became available. I chose to only write unit tests with it for the game mechanics. I did not invest in automated UI testing. I thought the return on investment for those kinds of tests was not worth it. Breaking something at the UI level would become obvious quickly with some play tests: that could not be said of subtle game logic regression. In hindsight, it was a good choice.

The test suite started with 75 lines of JavaScript in July. At the begginning of August, the code base was 5.600 lines and the test suite more that 600, mainly focusing on hero classes and beasts. In September, 7.800 lines of game code, 1.700 lines of test code, more than half for all the exquisitely detailed behaviour of divine entities.

Yeah! Tests ok across five browsers!

Mid-August I got interested in JavaScript minification or compilation. I found two possible tools: Doug Crockford's jsmin minifier and Google closure compiler. closure being written in Java was a better fit for my environment and promised more than just minification, with its advanced compilation mode. However, trying to apply it to the project at that time, with several thousands lines of existing code proved too hard. The advanced compiler made wrong assumptions that broke the game and needed me to explain everything and possibly apply deep refactorings, ultimately ruining some of my JavaScript techniques. I gave up on the advanced compilation mode and kept only the basic one. It's still very useful for two reasons. The first is that it packs all the JavaScript code into one single file. It means I can structure my code any way I want, for easy development and still end up with one compact file, better for deployment. The second advantage of compilation is size reduction: closure manages to shave off a good third of the initial size with whitespace and comment elimination and local variable reduction.

On my next project, still in a very early phase, I used closure from the start, and took precautions to keep advanced compilation working. I don't know if it enhances runtime performance, but size reduction is still more impressive. My 50kB of JavaScript become 22kB with standard compilation and a mere 13kB with advanced mode. After all, maybe it's only useless optimization, when the complete JavaScript code is smaller than the image for the splash screen...

Original sources and HTML5

In early September, probably bored at answering my nitpicking questions, QCF Design agreed to send me the GameMaker project of the original game. I discovered both the tool and the game source with mixed reactions. First, GameMaker is primarily targeted at hobbyists and not at programmers or software engineers. Versioning source code is impossible up to version 8.1. Code is scattered all around the place: sometimes as real code, sometimes as graphical constructions. The design screens have somewhat inconsistent conventions of interaction. From a software engineer point of view, it's ugly.
But after doing the tutorials, I began to appreciate its philosophy. I am now convinced that it's a great tool for either hobbyists or rapid prototyping. In each case, it makes it possible to focus on the game itself and not on technical issues (How do I display an animation? How do I play a sound? How do I code collision detection?) It's also probably a great way to introduce children to programming. It's easy and quick to have something working. Afterwards, it's open to experiment.

Is that code??

Overall, the game source became my source of answers, and I shamelessly copied the maze generation algorithm.

During the summer, I added a few things that required HTML5 features and definitively lost any hope of supporting older browsers. The first one is anecdotal. I need to use a <canvas> element behind the scenes in Chrome and Opera to scale up bitmaps and keep the pixellated look. The second one is central to the game: saving progress using localStorage. You could argue that it would be better if progress was saved on the server side. But that was not the point. I wanted to provide saved games on the client side, to allow deploying the game anywhere, without server support over simple HTTP transfer, much like what Flash games do. The third HTML5 feature has been added later: sound support. It was a bit tricky (different browsers support different encodings, Safari requires QuickTime before it can play anything, Firefox 3.6 requires <audio> tags to be part of the DOM tree) but otherwise quiet easy to add.

Finishing touches

That's definitely the hard part. At least for me. Most of the interesting bits of code were done. Most of the tools had lost their shine. What helped me was my moral commitment towards Danny and QCF Design. Some psychological studies - yes, I read some of them - suggest that great achievers always have a mental picture of the goal they are targetting and focus on it, whereas under-achievers keep looking in the past at all the work they have already done... and generally stop their effort before finishing, when they consider they have done a lot. I am often guilty of that sort of behaviour. That time at least I finished. The fact that it was a port of an existing game, with a clearly defined goal that I could use to estimate the path left must have played a role in helping me succeed. I must keep that in mind for my future projects.

On the 2nd of October, after exactly six months of work, 9.800 lines of game code and 3.100 lines of unit tests, I told Danny that I was ready for deployment. It still took about a month to add a splash screen to monitor the loading progress over slow connections and iron out a few bugs. And on the 5th of November the game was finally uploaded to the official Desktop Dungeons web site and announced in the news. I took two weeks of vacations in the Bahamas to celebrate and write this account of the complete journey ;)

Bonus

I made a visualization of the development history, if you're curious. It represents the tree structure of the project at each commit. Each type of file has a distinct color. The size of the file is show as the width of the segment (at logarithmic scale). Enjoy! And don't forget to play the game.

The final project structure


Sunday, November 6, 2011

Desktop Dungeons in your browser!

Here it is! My HTML port of Desktop Dungeons alpha is done and available on the site of the original Desktop Dungeons. It's free, fully playable, up to the Lothlorien campaign, and works on all recent browsers (Chrome, Firefox 3.6 & over, Safari, Opera and even IE9).

Desktop Dungeons on the web
I started working on porting the free alpha version in April. At that time, only that version was available. QCF Design, the creators, were busy working on their own port (to Unity3D) that they quickly showed during E3. They then published the new version as private beta, open to people pre-ordering the full game. Of course, their goal is to make a polished game, exploiting all the possibilities of the design, that can be played on a large array of devices. The alpha was done with GameMaker and could only be run on Windows and MacOSX. And that's why I did the port: I wanted to make it available to a larger public (for instance Linux users).

After a few months of after-work coding, I showed my progress to the nice people of QCF Design, and they agreed to send me the GameMaker code, so that I could make the port as faithful as possible. And they even agreed to deploy it on their site once finished. How cool is that!

I did all the coding with JavaScript and mostly HTML4 (using DOM for graphics), but a few features need HTML5: audio support and localstorage to save your progress across levels and classes. For the record, the whole game is about 10k lines of JavaScript and took me six months to code. It might seem long for a simple game like that, but as I said, I could only put a few hours in it now and then. And the mechanics and contents are quite rich: almost twenty hero classes with strange powers, ten gods with different tempers, ten spells and lots of possible items available in shops.

Go play it and tell me or the forums what you think!

In a future post, I'll cover my development tools, just in case someone is interested.

Friday, September 23, 2011

Post-it art is sooo old!

Why not waste your company's money on stickers instead. You know, the small round ones universally used by any self-respecting "agile" team:

Stickers (gommettes in French) about to be misused


Well, now it's easy! Just go to polychrome and try the options. The application is a small and quick hack and does not look like much for now, but it will improve. The next things to be built are image upload, and parallel processing using webworkers.

In the meantime, you can still display a few sample models, ready to be used.

Model for the Firefox logo made from 7-color stickers

Monday, August 15, 2011

Grunt work going on

For the last four months, I've been using almost all my free time writing a web port of a free game. That's why I did not post any new inflammatory benchmark or computer-aided game solution.

It might seem strange, but the game I'm porting, whose name I will not reveal yet, is only available as a Windows or OSX binary. I like the game very much and wanted to share it with some of my Linuxy friends, so I thought: "Rebuilding the game based on HTML/JS should not be that hard, and then, everybody with an Internet access and a modern browser could enjoy the game, without OS dependency or installation."

I'm making good progress on the game itself. It's not a graphics-heavy game, but more of a content-rich game and although the main game mechanics have been in place for a good time now, I'm still adding all the content, and that takes time. It doubly takes time, because I have to do research on the original game, to discover what needs to be implemented, and after that, I have to replicate it into the new game.

So what's the game? Sorry, but I will not reveal it just now. I have been in touch with the original developers because it's a free game, but not an open source one. I don't want to steal anything from them, and I hope we can reach some kind of agreement. They are currently trying to transform the original free game into a commercial one, far richer both in terms of graphics and content. I only want to replicate the free one, without killing their sales. Maybe it could even help their sales: like the current free version, it acts as a free appetizer.

Sunday, May 29, 2011

Web Workers faster than (naive) C++ [edited]


[EDIT] The main problem with the C++ version was probably the platform (Cygwin). So I re-ran the same program on Linux inside VirtualBox on the same machine and the results are not so catastrophic. I also ran the Python program with PyPy and it's twice as fast as CPython on that problem (Thanks to Alex Gaynor for trying it first).

I don't mean that to stir the controversy. If someone with great C++ skills could explain what I did wrong, I'd be glad to learn. So here is the story.

Multi-language parallel processing comparisons

It all began last week with Google Code Jam problem B in round 1A. The problem is the following. Two guys are playing hangman. They have a common dictionary of allowed words. The guy who tries to guess has a very simple strategy. He has a fixed list of letters that he will propose in order. However, he will skip letters that cannot appear in the word in the current state of the game. Each time he proposes a letter that does not appear in the word, the other guy makes one point. Your goal is to find the word that will make the most points, knowing the dictionary and the ordered list of letters of the guy who guesses.
I have written a solution with the same algorithm in four languages: Python, Java, C++ and JavaScript. I also wanted to get some knowledge of the parallel processing capabilities of those languages. In Python, I used the multiprocessing module, in Java, package java.util.concurrent with ExecutorService, in C++, OpenMP and in JavaScript HTML5 web workers. Here are the running times.

Single
Multi
1 worker 4 workers 6 workers
Java 26" 27" 18.5" 17.5"
C++ Linux 33" 33" 20" 21"
C++ Cygwin 58" 59" 30'00" 28'00"
PyPy 1'04" 1'08" 27" 26.5"
Python 2'30" 2'35" 50" 44"
JS Chrome 44" 45" 15.3" 14"
JS Opera 1'17" 1'17" 1'21" 1'35"
JS IE 1'30" No web workers
JS Firefox 1'34" crash
1'14" for 9
crash crash

Best times are highlighted in green in each column, worst times in red, crashing or unavailable solutions in black.

The code is available in github, with extensive explanations on how to build and run it. The HTML5 web workers solution can be tested right in your browser. To run the program in non-web worker mode, just click the "Run without workers" button. Be aware that the browser will probably tell you every few seconds that a script is making the page unresponsive. You need to allow it to continue if you want it to finish.
To run the program with web workers, you need to create a pool first. When you do that, a row of green squares will appear, to track the activity of allocated workers. Then, launch the computation with "Run". The "Queue size" will move briefly to 10, workers will turn red when busy. The result will appear once the queue is empty and all workers have finished.

Observations

About the C++ program

My first surprise is that I could not make my C++ program run as fast as the Java solution. My C++ skills are rusty, for sure, but when I wrote some numerical things not too long ago, I had no problem making them go two or three times faster than Java. This time, there is a lot of string and map handling and I guess my performance problems might come from too much memory allocation. I used gprof to locate potential hotspots, but nothing meaningful appears. I would genuinely be interested if some C++ wizard could explain how to fix that. [At least on Linux it's better than with Cygwin]
C++ 4-workers CPU profile

The second suprise is that using parallel processing actually made things worse, much much worse! Read the numbers: 30 minutes for the 4-workers C++ when Chrome takes 15 seconds. Actually it reinforces the hypothesis that my performance problems come from memory allocation. The multiple threads of execution are fighting each other for memory and provoke contention. That would explain the fact that the program only consumes 25% CPU, a big part of which is system time. [Yet again, on Linux the multi-threaded version sees a good increase in performance. Cygwin probably has to do much more work.]

About Firefox 4

The sequential solution, using only the main JavaScript thread, has a very curious memory profile.
Firefox non-worker solution

It looks like memory is never reclaimed during the execution, only after the function has finished running.

When running the 4-worker solution, Firefox CPU profile is similar to the C++ one: only 40% used and at least three quarters of that is system time. Using Process Explorer, I would conclude that Firefox uses threads for workers and probably meets memory contention too.

What is more troublesome is that Firefox cannot reliably compute the solution using web workers. Firebug catches some exceptions during execution. But those exceptions never occur in other browsers, or even in Firefox when running without workers. Among the ten tasks that workers have to process, there is generally one or two that produce an exception. It is sometimes possible to solve nine of the ten cases with one worker, but not always. And with four workers, it cannot even finish four cases. I have really no idea what is wrong.

About Opera 11

Opera performs quite well without workers. With workers, it performs the same. In fact, the more workers you add, the worse it performs. I guess that it uses "green threads", not native ones. No new threads appear in Process Explorer when launching workers and CPU use is always around 25%. With more workers, there is more work for the internal scheduler and some more seralization of data to do. That's what explains the slight degradation of running times.

About Internet Explorer 9

IE9 does not support web workers, so I only tested the standard solution. The performance is reasonable. It is worse than Chrome and Opera, but a bit better than Firefox.

About Chrome 13

Chrome is impressive, no doubt about that. The standard JavaScript solution is already the fastest of the browser pack (twice faster than Firefox and IE), and it benefits greatly from added workers. Using separate OS processes (like Python multiprocessing module) makes it immune to memory contention.

About Java

Java is a still a bit faster than Chrome V8 JavaScript in single-threaded mode. However, the gain when using multiple workers is not as big as expected: only 1.5 times faster with four workers when Python or Chrome go three times faster with four processes. I don't know why this is so and I don't have a precise idea how to diagnose. It might be a kind of memory contention, as with other multi-threaded implementations, except it does not appear as system time, because the JVM manages memory by itself.

About Python

I initially wrote my solution in Python, because the language feels so good. When ran with PyPy (1.5.0-alpha0) it can perform twice as fast as with CPython. That's great news!

Conclusions and open questions

I welcome all comments, on why my C++ solution is so slow, why Firefox fails with workers, and anything else. In the meantime, I will finish and release my micro-library to provide a Python-like Pool API above web workers, knowing that today, only Chrome can use it for heavy lifting.

Thursday, May 26, 2011

Taking advantage of multiple cores with JavaScript web workers

I'm at it again! 

This time, I wanted to test the performance of JavaScript for solving the same problem I already described previously. And I chose to jump at the chance to perfect my knowledge of HTML5 web workers.

My main resource for learning how to use web workers was this introduction on HTML5Rocks. I used Chrome v13 for my tests. If you try this at home and point to local filesystem files, don't forget to launch a fresh Chrome instance with the --allow-file-access-from-files command-line switch, otherwise you will receive some strange security errors. The other possiblity is to run from a local web server.

At first, I couldn't seem to start a worker correctly. Or at least, my worker did not seem to receive messages. I was calling:
self.addEventListener('message', handleMessageFunction, false);

I had to change it to the following form to make it work:
self.addEventListener('message', function(e) { slave.handleMessage(e); }, false);

So, passing just a function reference as second argument did not seem to work, even though the function existed, was valid, was not a prototype method and had the right signature.

Once I had overcome that "glitch", everything went smoothly. I re-implemented my Python algorithm in pure JavaScript. I tried it directly (without workers). I had to acknowledge a few times that, indeed, a script on the page was taking some time to complete. And it finished in about 45". Nice performance for JavaScript!

To the core(s)

Having been spoilt by the nice Pool API from Python multiprocessing package, I embarked upon a journey to implement something similar with web workers. Basically, I created a protocol of messages to be exchanged between the workers and the pool driver. It is not polished, but it works well already. You can see the result here. Quick explanation:
  • "Create pool" creates the worker pool with the requested number of workers. Workers are materialized by colored squares with a number. When the square is red, the worker is busy; when green, it's idle.
  • "Run" sends all problem cases to the pool. The size of the queue should increase. It is the number of tasks not yet taken by a worker.
  • "Kill" kills all workers and drops the pool, so that you can create a new one with a different number of workers.

Web worker pool demo
The input field is preloaded with the large problem set. On Chrome with four workers, the runtime is divided by three, compared to the single-threaded version: the problem is solved in about 15". Chrome does not seem to impose limitations on the number of workers that can be started. I tried with ten, and the results was almost identical. My machine was, of course, 100% busy.

Opera performs nicely on this one too, with the same code. Single-threaded solution in 75", four-worker solution in 75". Opera correcly creates the requested number of workers, but it probably does not use OS-level threads. They might only be "green-threads", with an internal scheduler, which would explain why only 25% of the CPU is consumed.

Firefox 4 gives me some problems, maybe because of memory limits or the size of the input value. The program runs unmodified, but you have to change the first input line from 10 to 8. I don't know why it chokes on the ninth and tenth cases. The single-worker version runs in 76". The four-worker one does not consume all available CPU. It's stuck at about 50% and consumes a lot of system time. Only three workers are busy simultaneously. And it runs in 230". So much for the performance gain.

And IE9, with its native HTML5 support... just kidding.

tl;dr

Chrome is fast, has great support for web workers. Demo here.