<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>CodeUtopia - The blog of Jani Hartikainen &#187; Games</title>
	<atom:link href="http://codeutopia.net/blog/tag/games/feed/" rel="self" type="application/rss+xml" />
	<link>http://codeutopia.net/blog</link>
	<description>Software development with a focus on web-related technologies</description>
	<lastBuildDate>Wed, 08 Sep 2010 19:50:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Unity: The best game development platform?</title>
		<link>http://codeutopia.net/blog/2010/07/01/unity-the-best-game-development-platform/</link>
		<comments>http://codeutopia.net/blog/2010/07/01/unity-the-best-game-development-platform/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 15:29:46 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/?p=313</guid>
		<description><![CDATA[One day I saw a webpage which had some game, and wanted me to download the Unity web player plugin for my browser. I thought &#8220;What crap is this? I&#8217;m not going to install it!&#8221;. That was stupid, because Unity rocks as a game development tool! Why Unity rocks (in my opinion) In a matter [...]]]></description>
			<content:encoded><![CDATA[<p>One day I saw a webpage which had some game, and wanted me to download the Unity web player plugin for my browser.</p>
<p>I thought &#8220;What crap is this? I&#8217;m not going to install it!&#8221;. That was stupid, because Unity rocks as a game development tool!</p>
<p><span id="more-313"></span></p>
<h3>Why Unity rocks (in my opinion)</h3>
<p>In a matter of a few hours, I wrote a third person shooter prototype. </p>
<p>Of course, this was after I spent some days to get familiar with the environment. </p>
<p>The basic features my game had in about 8 or so hours:</p>
<ul>
<li>3D 3rd person &#8220;over the shoulder&#8221; camera</li>
<li>Enemies who moved around</li>
<li>The enemies could smartly aim at your current location</li>
<li>A spawner system where I could place a spawner object anywhere and it would automatically spawn more enemies</li>
<li>A waypoint based movement system</li>
<li>A simple user interface which displayed health and some other stuff</li>
</ul>
<h3>What is Unity?</h3>
<p><a href="http://unity3d.com/">Unity</a> is basically a game engine with an IDE sort of editor tool. It can be used to develop games for multiple platforms and the web (which uses their browser plugin).</p>
<p>It has a fast 3D engine, a PhysX based physics engine and libraries to work with all sorts of things you might need when developing a game (GUI, collisions, even multiplayer is quite straightforward to do).</p>
<p>The editor itself is kind of like a level editor for a 3D game &#8211; think Valve Hammer or WorldCraft &#8211; but it also has an asset list, scenes, input management etc. quite easily straight from the UI.</p>
<p>Oh, and did I mention it also works on Macs and not just Windows, and that you can write scripts for your game in JavaScript, C# or Boo?</p>
<h3>If you develop games, for fun or for profit, Unity is worth checking out</h3>
<p>Now I&#8217;m not very familiar with other 3D game engines, but Unity is the best I&#8217;ve seen. It does require some getting used to, especially how the scripts are attached into the game, but I can&#8217;t really think of many bad things about it.</p>
<p>ps: I&#8217;m not going to attach a screenshot of my game because it&#8217;s basically just a bunch of boxes. I&#8217;m not a 3D modeller, sorry <img src='http://codeutopia.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2010/07/01/unity-the-best-game-development-platform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The best old &#8220;indie&#8221; games</title>
		<link>http://codeutopia.net/blog/2010/06/19/the-best-old-indie-games/</link>
		<comments>http://codeutopia.net/blog/2010/06/19/the-best-old-indie-games/#comments</comments>
		<pubDate>Sat, 19 Jun 2010 12:28:52 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/?p=297</guid>
		<description><![CDATA[Just for fun, here&#8217;s a list of the best old shareware/freeware games I played before Windows XP and such even existed&#8230; The word indie is quoted because these games would probably be called that nowadays, but weren&#8217;t back then Finnish games Slicks &#8216;n&#8217; Slide &#8211; A great top-down racer with a track editor. I made [...]]]></description>
			<content:encoded><![CDATA[<p>Just for fun, here&#8217;s a list of the best old shareware/freeware games I played before Windows XP and such even existed&#8230; The word indie is quoted because these games would probably be called that nowadays, but weren&#8217;t back then <img src='http://codeutopia.net/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><span id="more-297"></span></p>
<h3>Finnish games</h3>
<ul class="biggerMargins">
<li><a href="http://www.digitalfootmark.com/?pr=slix">Slicks &#8216;n&#8217; Slide</a> &#8211; A great top-down racer with a track editor. I made a similar <a href="http://widgets.opera.com/widget/5681/">JavaScript based top down racer</a>.</li>
<li><a href="http://en.wikipedia.org/wiki/Triplane_Turmoil_series">Triplane Turmoil</a> &#8211; Side-scrolling multiplayer shooting with triplanes</li>
<li><a href="http://koti.mbnet.fi/~mvirpioj/wings/index.html">Wings</a> &#8211; Side-scrolling cave flying shooter with tons of weapons and maps etc. etc.</li>
<li><a href="http://www.youtube.com/watch?v=SCnUH5gqBb8&#038;">Minebombers</a> &#8211; Top-down shooter, a combination of bomberman and miner</li>
<li><a href="http://www.youtube.com/watch?v=hqyEjCU3-6A">Tapan Kaikki</a> &#8211; Top-down shooter</li>
<li><a href="http://www.youtube.com/watch?v=KE2XtQaMb5I">Liero</a> &#8211; Side-scrolling shooter where you are a worm and as usual the goal is to kill the other worms</li>
<li>Koiratappelu &#8211; Couldn&#8217;t find anything in english about this. This game was a bit like Triplane Turmoil</li>
<li>Areena 4 &#8211; As with Koiratappelu couldn&#8217;t find anything about this in english either. A great strategy game where you manage a team of gladiators in a fantasy world and fight in different leagues to be the best.</li>
<li><a href="http://www.pelikulma.net/pelit/raiskinta-ja-actionpelit/duck-mr-duck/">Duck, Mr. Duck</a> (in finnish, has a screenshot) &#8211; A very Worms-like turn-based shooter, except this time you are a duck.</li>
<li><a href="http://www.dosgamesonline.com/index/game/551/Alien_Phobia.html">Alien Phobia</a> &#8211; Top-down shooter, simple and fun: The only goal is to survive against an endless flood of aliens out to kill you. There is also <a href="http://www.redlynx.com/phobiaIII/download.html">Alien Phobia III</a>.</li>
</ul>
<h3>Others</h3>
<ul class="biggerMargins">
<li><a href="http://www.youtube.com/watch?v=6ULVtCOfbns">Action Supercross</a> &#8211; Possibly one of the first good physics based games? Side-scrolling motocross puzzle game</li>
<li><a href="http://www.dosgames.com/ss.php?filename=assaulttrooper.gif">Assault Trooper</a> &#8211; Isometric shooter</li>
<li><a href="http://en.wikipedia.org/wiki/C-Dogs">C-Dogs</a> &#8211; Isometric shooter with two-player support and I think there also was a map editor</li>
</ul>
<h3>What&#8217;s your favorite?</h3>
<p>I spent countless hours playing the above games, although there probably were others that I forgot about.</p>
<p>Share your favorite old games in the comments <img src='http://codeutopia.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2010/06/19/the-best-old-indie-games/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Rendering graphics in JavaScript games</title>
		<link>http://codeutopia.net/blog/2010/01/07/rendering-graphics-in-javascript-games/</link>
		<comments>http://codeutopia.net/blog/2010/01/07/rendering-graphics-in-javascript-games/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 12:49:42 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2010/01/07/rendering-graphics-in-javascript-games/</guid>
		<description><![CDATA[As I&#8217;ve been rewriting TankWar, I&#8217;ve been thinking of various approaches to displaying the game&#8217;s graphics. At the moment, I can count three feasible approaches for rendering game graphics: DHTML &#8211; In other words, using divs with images and moving them around Canvas A hybrid: Canvas with DHTML I&#8217;ve considered each of these, and they [...]]]></description>
			<content:encoded><![CDATA[<p>As I&#8217;ve been rewriting TankWar, I&#8217;ve been thinking of various approaches to displaying the game&#8217;s graphics. At the moment, I can count three feasible approaches for rendering game graphics:</p>
<ul>
<li>DHTML &#8211; In other words, using divs with images and moving them around</li>
<li>Canvas</li>
<li>A hybrid: Canvas with DHTML</li>
</ul>
<p>I&#8217;ve considered each of these, and they all have some pros and cons which we&#8217;ll look at next.</p>
<p><span id="more-276"></span></p>
<h3>DHTML</h3>
<p>This is the most compatible of the three: Even Internet Explorer supports creating divs and moving them around on the fly.</p>
<p>This approach is quite simple too. The APIs used are well-known and usually quite problem-free when used correctly.</p>
<p>Moving divs etc. around tends to be pretty fast too, so even if you have a big huge animated explosion or something, the performance should still be relatively good. Compared to canvas this is DHTML&#8217;s biggest win.</p>
<p>One of the downsides with DHTML is sometimes jerky movements: You always need to draw and move things pixel-precise, as you can&#8217;t tell a div to be exactly 15.5 pixels from something. Canvas can draw &#8220;between&#8221; pixels, as it automatically aliases the graphics to look more like it.</p>
<p>With DHTML you also can&#8217;t draw shapes like you can with canvas, so you&#8217;ll need to come up with the graphics in an image editor beforehand.</p>
<p>With CSS transitions and other tricks, you can bend DHTML surprisingly far. However if using transitions or other advanced features, you sacrifice compatibility with more browsers than you would if you were just using canvas.</p>
<h3>Canvas</h3>
<p>Canvas is great. I wish I could leave it at that.</p>
<p>However, in addition to being generally easy to use after getting familiar with the basic API, there is one significant downside: Canvas is slow. Slow slow slow slow slow.</p>
<p>Unless you apply considerable amount of thought into the code, getting stuff drawn at reasonable speeds with canvas is difficult. It&#8217;s like going back to the times when computers had 66 mhz CPUs.</p>
<p>Canvas does have a lot of good things though: You can draw on it directly, with direct pixel manipulation, a vector-like API, or images.. or compose a new image using another canvas.. It is certainly very flexible, and it makes it very simple to do complex and dynamic shapes that would be much trickier otherwise.</p>
<p>If you&#8217;ve been following the <a href="http://codeutopia.net/projects/tankwar-2.0/">TankWar 2.0 development</a>, you may have noticed it does draw some okay looking graphics but it still is somewhat reasonable quick. It only uses canvas for rendering, so yes, it is indeed doable, but it requires tricks.</p>
<p>I&#8217;ll be discussing the finer details of how to make canvas rendering faster in another post.</p>
<h3>Hybrid</h3>
<p>A hybrid graphics engine is exactly what it sounds like: It combines both DHTML and canvas to overcome the downsides of both approaches.</p>
<p>While this may sound like the stone to drop two birds with, it may not be.</p>
<p>One of the good things about this approach is easily seen when you need to display large graphics that move. Canvas can be very slow in cases where you update larger areas of it, so in a case like this using a div for the big graphic is good. Then, you can use canvas for the rest, to create different shapes etc. which would be tricky with divs.</p>
<p>The main downside of this approach is complexity. Since you need to deal with both canvas and DOM, it&#8217;ll become twice as complex as using either of the approaches alone.</p>
<h3>In closing</h3>
<p>The approach I&#8217;ve chosen for TankWar 2.0 is pure canvas. I may need to resort to a hybrid approach if the performance drops too low, but right now it&#8217;s still tolerable at least on a moderately quick PC.</p>
<p>In the past, I&#8217;ve used canvas on most of my games: TankWar, <a href="http://codeutopia.net/blog/2009/07/14/opera-command-javascript-based-missile-command-game/">Opera Command</a>, <a href="http://widgets.opera.com/widget/5681/">WidgetRacer</a>, Asteroids&#8230; but I&#8217;ve also used a DHTML-like approach in a Tetris game and in <a href="http://codeutopia.net/blog/2009/04/28/i-wrote-a-sim-city-clone-in-javascript/">WidgetCity</a>. In these cases the DHTML-based approach was simpler or had other reasons, such as being much faster in case of WidgetCity (<a href="http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/">My post about the table/CSS rendering in WidgetCity</a>).</p>
<p>I&#8217;ll be discussing the details of how the new TankWar 2.0 canvas engine works in a later post. I&#8217;ve had to do a significant amount of performance trickery for it too.</p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2010/01/07/rendering-graphics-in-javascript-games/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Rewriting TankWar: Assessing the damage</title>
		<link>http://codeutopia.net/blog/2009/12/16/rewriting-tankwar-assessing-the-damage/</link>
		<comments>http://codeutopia.net/blog/2009/12/16/rewriting-tankwar-assessing-the-damage/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 17:22:14 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[TankWar]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/12/16/rewriting-tankwar-assessing-the-damage/</guid>
		<description><![CDATA[I have decided to rewrite TankWar, and I&#8217;ll be writing a bunch of blog posts about the process. If you ever wanted to know how to write a scorched earth/worms-like game using just JavaScript, now is your chance to learn This is the first one: Assessing the damage. In other words, take a look at [...]]]></description>
			<content:encoded><![CDATA[<p>I have decided to rewrite <a href="http://codeutopia.net/projects/tankwar/">TankWar</a>, and I&#8217;ll be writing a bunch of blog posts about the process. If you ever wanted to know how to write a scorched earth/worms-like game using just JavaScript, now is your chance to learn <img src='http://codeutopia.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>This is the first one: Assessing the damage. In other words, take a look at the old code and see what can be salvaged. I&#8217;ll also list some issues with the current implementation, and how I plan on solving them in the new version.</p>
<p><span id="more-272"></span></p>
<h3>Issues in the current implementation</h3>
<p>I wrote the most of the code in the current version of TankWar somewhere in 2006. Let&#8217;s be frank: The codebase <em>sucks</em>.</p>
<p>It&#8217;s a mess.</p>
<p>I&#8217;m surprised some of it ever worked. At all.</p>
<p>My coworker <a href="http://daniliants.com">Artem</a> tells me recognizing your old code is crap is a good sign: It means you have improved &#8211; and I agree with him.</p>
<p>In addition to being pretty poor code, the current version does have some bugs too:</p>
<ol>
<li>If your bullet moves very fast, it can go through the ground.</li>
<li>The graphics system is poorly implemented which can be seen especially when using the bomber weapon &#8211; it can get pretty glitchy</li>
<li>The bullet trajectories deviate wildly depending on the computer&#8217;s speed</li>
</ol>
<p>While some of these issues could be patched into the current code, it would just make the code even more fragile.</p>
<h3>Damage control</h3>
<p>In most cases there&#8217;s some useful code even if most of the code is messy. </p>
<p>In the case of TankWar, the main implementation of the game engine, menus, etc. will be thrown away. They make most of the code, but they are also the worst parts of it.</p>
<p>The good parts of TankWar include the terrain generator, some vector math classes and some utility classes. </p>
<p>It seems we can apply the statistic that simpler code contain less problems here too.</p>
<h3>Solutions to the current problems</h3>
<p>First and foremost, the codebase will need to be organized better. Now it&#8217;s just a jumble of code and HTML, CSS and whatnot mixed together like <a href="http://hijinksensue.com/2009/11/27/the-special-sauce/">magic hobo gravy</a>.</p>
<p>The game engine itself will need to be more robust and be able to handle fast moving bullets properly, and the trajectories need to be correct.</p>
<h4>Bullet collision solution</h4>
<p>The solution to fast moving bullets going through stuff is improving the collision detection mechanism. Currently the implementation is quite simple: It simply moves the bullet each cycle and checks if the bullet intersects the ground or other objects. This is very easy to implement, as the <code>canvas</code> element has a function for it, but it&#8217;s not very accurate with fast moving objects.</p>
<p>A better approach with fast moving objects is using ray intersection detection. Put simply, this means we will check all the points in the trajectory, including the points between the positions the bullet actually is in. In the old implementation, depending on the speed, there could be tens of pixels of space which was never checked for hits.</p>
<h4>Glitchy graphics</h4>
<p>The solution to the issues with the graphics system is to make it separate from the other stuff. The current graphics engine was just quickly slapped on top of the physics engine to make it display pretty pictures. This is more of an architectural problem than an algorithmic issue as the collision detection.</p>
<p>Additionally, the graphics system may be a little problematic in general. While it works with the current simplistic graphics, I&#8217;m not sure whether it would function very well if I wanted to include more complex graphics.</p>
<h4>Bullet trajectory problems</h4>
<p>For the third problem &#8211; framerate dependent trajectories &#8211; the solution may be more problematic. The current version already attempts to fix this by using time-based movement. However, it does not quite work, meaning I&#8217;ve either implemented it wrong or the timer is not accurate enough.</p>
<p>If the timer turns out to be inaccurate, the solution may be to precalculate the trajectory using a predefined framerate. This means we would have to first calculate the trajectory, and only after it&#8217;s been calculated, we could render what happened. This might be difficult, because calculating the trajectory may take so long that the user would notice a significant delay between &#8220;shooting&#8221; and the game actually performing the shot.</p>
<p>Then again, the frame rate calculator was (as far as I can remember) also slapped on top of the existing stuff and never really properly planned. The timer itself works quite similar to <a href="http://codeutopia.net/blog/2009/08/21/using-canvas-to-do-bitmap-sprite-animation-in-javascript/">the timer in my JavaScript bitmap sprite animations post</a>.</p>
<h3>In closing</h3>
<p>The rewrite will probably take a while, depending on how much time I&#8217;ll have to work on it. I will probably put together some more posts on the topic as I have some progress. Let me know if there&#8217;s anything specific about it you&#8217;d like to hear.</p>
<p>Naturally the new version will generally be more awesome than the old version &#8211; it would be rather pointless to just rewrite it and add nothing else than better code.</p>
<p><b>Further reading:</b><br />
<a href="http://codeutopia.net/blog/2010/01/07/rendering-graphics-in-javascript-games/">Rendering graphics in JavaScript games</a></p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/12/16/rewriting-tankwar-assessing-the-damage/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>TankWar has online mode again: This time on Opera Unite</title>
		<link>http://codeutopia.net/blog/2009/12/02/tankwar-has-online-mode-again-this-time-on-opera-unite/</link>
		<comments>http://codeutopia.net/blog/2009/12/02/tankwar-has-online-mode-again-this-time-on-opera-unite/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 16:45:23 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Opera]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/12/02/tankwar-has-online-mode-again-this-time-on-opera-unite/</guid>
		<description><![CDATA[You may recall an earlier post about TankWar, my 100% JavaScript cannons-game. Back when I wrote it, I included online play, but the server went down with a hard disk failure. Now, I have rewritten the online mode &#8211; this time that part is also all JavaScript &#8211; continue reading to find out what makes [...]]]></description>
			<content:encoded><![CDATA[<p>You may recall an earlier post about <a href="http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/">TankWar, my 100% JavaScript cannons-game</a>. Back when I wrote it, I included online play, but the server went down with a hard disk failure.</p>
<p>Now, I have rewritten the online mode &#8211; this time that part is also all JavaScript &#8211; continue reading to find out what makes it tick.</p>
<p><span id="more-270"></span></p>
<h3>The original server</h3>
<p>I wrote the original server for TankWar using Python and the Twisted library. Now, since I had nothing left, I had to reverse-engineer how the server used to work from the client&#8217;s code.</p>
<p>It proved to be a bit tricky, but eventually I succeeded</p>
<h3>The new 100% JavaScript implementation</h3>
<p>I decided I wanted to write the server as an Opera Unite application, and Opera was conveniently running a competition for Unite apps too.</p>
<p>The latest version of the application uses Bayeux as the protocol. It&#8217;s a straightforward JSON-based protocol for Comet, supported by the Dojo Foundation, and with client libraries available for both Dojo and jQuery.</p>
<p>I decided to put the Bayeux protocol related server code on <a href="http://codeutopia.net/blog/2009/06/01/should-i-try-git-if-svncvsother-works-for-me/">GitHub</a> under project <a href="http://github.com/jhartikainen/JavaScript-Bayeux-server">JavaScript bayeux server</a>. The code doesn&#8217;t support all of the Bayeux protocol yet, but it can be used to implement applications already as I have done. I plan to continue working on some new features for the library, but if you want to contribute, feel free.</p>
<p>I call the application itself <a href="https://unite.opera.com/application/502/">TankWar on Unite</a>. As mentioned, it uses <a href="http://unite.opera.com/">Opera Unite</a> as its base. I hadn&#8217;t developed Unite applications before, but it turned out to be a relatively simple job, thanks to the fact that Unite uses JavaScript with few custom APIs.</p>
<p>Unite applications also have the ability to keep persistent state, so it was perfect for a game where I needed to keep things together over multiple requests.</p>
<h3>In closing</h3>
<p>I&#8217;m planning on doing some more stuff for the game, such as improving the engine itself as it&#8217;s a little bit glitchy. Perhaps also improving the graphics, maybe by using <a href="http://codeutopia.net/blog/2009/08/21/using-canvas-to-do-bitmap-sprite-animation-in-javascript/">bitmap sprites with canvas</a>.</p>
<p>If you want to check out the Unite application&#8217;s source code, simply download it from the mentioned site and rename the file to .zip. It should at least serve as a good example on how to use the Bayeux server for writing your own Comet-based Unite apps.</p>
<p>The Bayeux server itself might also work with other JavaScript runtimes like Rhino. You would most likely need to implement a custom RhinoConnection object though, as I have only used it with Unite so far.</p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/12/02/tankwar-has-online-mode-again-this-time-on-opera-unite/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using canvas to do bitmap sprite animation in JavaScript</title>
		<link>http://codeutopia.net/blog/2009/08/21/using-canvas-to-do-bitmap-sprite-animation-in-javascript/</link>
		<comments>http://codeutopia.net/blog/2009/08/21/using-canvas-to-do-bitmap-sprite-animation-in-javascript/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 17:02:48 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/08/21/using-canvas-to-do-bitmap-sprite-animation-in-javascript/</guid>
		<description><![CDATA[Have you ever thought about writing a game? If you have, you&#8217;ve probably wondered how to render animations for your game characters. In this post, I&#8217;ll show you how you can use JavaScript to do time-based sprite animations, drawing them on canvas &#8211; vital if you want to do a game. You can also apply [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever thought about writing a game? If you have, you&#8217;ve probably wondered how to render animations for your game characters. In this post, I&#8217;ll show you how you can use JavaScript to do time-based sprite animations, drawing them on canvas &#8211; vital if you want to do a game. You can also apply the same techniques I&#8217;ll show in other languages, such as ActionScript.</p>
<p><span id="more-251"></span></p>
<h3>What is &#8220;time-based&#8221; animation?</h3>
<p>We all know what animation means, but what does time-based add? </p>
<p>Let&#8217;s imagine we have a game. Our game runs at 60 frames per second (fps) on a powerful PC, and 20 fps on a slow PC.</p>
<p>Animation that isn&#8217;t time-based is frame-based. In this case, a frame means a &#8220;cycle&#8221; in the game: In each frame you typically calculate things like movement or AI, and draw things on the screen.</p>
<p>Let&#8217;s say we have a walk animation which changes every frame. This means that on the fast PC the animation is much faster than on the slow PC, since the framerate is much higher.</p>
<p>Time-based animation calculates how long each frame in your game takes, and uses this to calculate how long an animation should take. By using time instead of frames, we can achieve exactly the same speed on both the fast and slow PCs.</p>
<p>There is also a term &#8220;time-based movement&#8221;. This applies the same principle to movement of characters and other things on the screen so that everything moves at the same speed no matter what frame rate.</p>
<h3>The infrastructure</h3>
<p>There is some infrastructure we need before we can actually start animating things.</p>
<ul>
<li>We need a timer which can calculate how long each frame takes</li>
<li>We need a sprite sheet object, which we can use to keep track of different sprites in a big bitmap</li>
<li>Lastly, we need an animation object which handles choosing the correct sprite from a spritesheet and such.</li>
</ul>
<p>In addition to these, in a game you would also have things like animation and spritesheet loaders that load spritesheet and animation definitions from files so you won&#8217;t have to modify your code to change an animation. However, these are outside the scope of this post &#8211; if you&#8217;d like to see a post about loading this kind of things from files, leave a comment.</p>
<p>First, let&#8217;s look at making the class which will take care of timing the frames.</p>
<h3>Creating a frame timer</h3>
<p>The basic idea of a frame timer is that it should be called once every frame, usually after the processing is complete. At that point, it compares how much time has passed since the previous call. We can then use this value on the next frame to make a good guess of how long it&#8217;ll take this time.</p>
<p>To determine the time on each frame, we&#8217;ll use the Date object.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> FrameTimer <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">this</span>._lastTick <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
FrameTimer.<span style="color: #660066;">prototype</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
    getSeconds<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> seconds <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>._frameSpacing <span style="color: #339933;">/</span> <span style="color: #CC0000;">1000</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>isNaN<span style="color: #009900;">&#40;</span>seconds<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">return</span> seconds<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
    tick<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> currentTick <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">this</span>._frameSpacing <span style="color: #339933;">=</span> currentTick <span style="color: #339933;">-</span> <span style="color: #000066; font-weight: bold;">this</span>._lastTick<span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">this</span>._lastTick <span style="color: #339933;">=</span> currentTick<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This simple looking class simply tracks time spent during two &#8220;ticks&#8221;. With this we track the actual time spent between two frames, so that we can keep the animation&#8217;s speed constant in real time instead of application speed.</p>
<p>Using this object is simple:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> timer <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> FrameTimer<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #006600; font-style: italic;">//Tick once to initialize the time</span>
timer.<span style="color: #660066;">tick</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Now do processing</span>
<span style="color: #000066; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">//do things based on time</span>
  work<span style="color: #009900;">&#40;</span>timer.<span style="color: #660066;">getSeconds</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  timer.<span style="color: #660066;">tick</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Sprite sheet and animation objects</h3>
<p>To make our life a bit easier in the code, let&#8217;s abstract the code which calculates the exact location of a specific sprite on a spritesheet. Let&#8217;s also write a class which abstracts the animation and handling which frame should be displayed.</p>
<p>Since we&#8217;ll need the spritesheet class for the animation class, let&#8217;s look at that one first.</p>
<p>The idea is that we can create a spritesheet object that helps us in drawing sprites from a big sheet. As you know, to draw a specific sprite from a sheet, we need to know the location of it on the sheet &#8211; locating a specific sprite will be the main job of the spritesheet object, so that we won&#8217;t have to think of it all the time.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> SpriteSheet <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">load</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
SpriteSheet.<span style="color: #660066;">prototype</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
    _sprites<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
    _width<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
    _height<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
&nbsp;
    load<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">this</span>._height <span style="color: #339933;">=</span> data.<span style="color: #660066;">height</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">this</span>._width <span style="color: #339933;">=</span> data.<span style="color: #660066;">width</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">this</span>._sprites <span style="color: #339933;">=</span> data.<span style="color: #660066;">sprites</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
    getOffset<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>spriteName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">//Go through all sprites to find the required one</span>
        <span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> len <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>._sprites.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> len<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003366; font-weight: bold;">var</span> sprite <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>._sprites<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>sprite.<span style="color: #000066;">name</span> <span style="color: #339933;">==</span> spriteName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #006600; font-style: italic;">//To get the offset, multiply by sprite width</span>
                <span style="color: #006600; font-style: italic;">//Sprite-specific x and y offset is then added into it.</span>
                <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>
                    x<span style="color: #339933;">:</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">*</span> <span style="color: #000066; font-weight: bold;">this</span>._width<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span>sprite.<span style="color: #660066;">x</span><span style="color: #339933;">||</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
                    y<span style="color: #339933;">:</span> <span style="color: #009900;">&#40;</span>sprite.<span style="color: #660066;">y</span><span style="color: #339933;">||</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
                    width<span style="color: #339933;">:</span> <span style="color: #000066; font-weight: bold;">this</span>._width<span style="color: #339933;">,</span>
                    height<span style="color: #339933;">:</span> <span style="color: #000066; font-weight: bold;">this</span>._height
                <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The basic usage of this class is you create a data-structure which contains the spritesheet definition, and pass it to the object, such as this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> sprites <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> SpriteSheet<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    width<span style="color: #339933;">:</span> <span style="color: #CC0000;">32</span><span style="color: #339933;">,</span>
    height<span style="color: #339933;">:</span> <span style="color: #CC0000;">32</span><span style="color: #339933;">,</span>
    sprites<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>
        <span style="color: #009900;">&#123;</span> <span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'stand'</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #009900;">&#123;</span> <span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'walk_1'</span><span style="color: #339933;">,</span> x<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> y<span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        <span style="color: #009900;">&#123;</span> <span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'walk_2'</span><span style="color: #339933;">,</span> x<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> y<span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
    <span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The definition is simple: First, we define the width and height of a sprite, and then we define a name and x/y offsets for each sprite in the sheet.</p>
<p>When we apply this with an image which has three sprites, each 32&#215;32 in size, we can simply tell the spritesheet that we want the sprite called &#8216;walk_1&#8242;, and we get a nice object with the X and Y positions to draw it from the sheet. We&#8217;ll see this in action soon!</p>
<h3>The animation class</h3>
<p>Now that we have the spritesheet stuff done, we can do the last in the line: The animation class.</p>
<p>The animation class takes a definition, similar to how the spritesheet took, and then handles various things based on that. For example, as each animation comprises of specific frames, it calculates how long a frame has been visible, and changes to the next frame when it has been visible long enough.</p>
<p>On with the code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Animation <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #339933;">,</span> sprites<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">load</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">this</span>._sprites <span style="color: #339933;">=</span> sprites<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
Animation.<span style="color: #660066;">prototype</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
    _frames<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
    _frame<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">,</span>
    _frameDuration<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
&nbsp;
    load<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">this</span>._frames <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #006600; font-style: italic;">//Initialize the first frame</span>
        <span style="color: #000066; font-weight: bold;">this</span>._frameIndex <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">this</span>._frameDuration <span style="color: #339933;">=</span> data<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">time</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
    animate<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>deltaTime<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">//Reduce time passed from the duration to show a frame        </span>
        <span style="color: #000066; font-weight: bold;">this</span>._frameDuration <span style="color: #339933;">-=</span> deltaTime<span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #006600; font-style: italic;">//When the display duration has passed</span>
        <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>._frameDuration <span style="color: #339933;">&lt;=</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #006600; font-style: italic;">//Change to next frame, or the first if ran out of frames</span>
            <span style="color: #000066; font-weight: bold;">this</span>._frameIndex<span style="color: #339933;">++;</span>
            <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>._frameIndex <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">this</span>._frames.<span style="color: #660066;">length</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">this</span>._frameIndex <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            <span style="color: #006600; font-style: italic;">//Change duration to duration of new frame</span>
            <span style="color: #000066; font-weight: bold;">this</span>._frameDuration <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>._frames<span style="color: #009900;">&#91;</span><span style="color: #000066; font-weight: bold;">this</span>._frameIndex<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">time</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
    getSprite<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">//Return the sprite for the current frame</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>._sprites.<span style="color: #660066;">getOffset</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>._frames<span style="color: #009900;">&#91;</span><span style="color: #000066; font-weight: bold;">this</span>._frameIndex<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">sprite</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The comments should explain most of this class. The main point is that with this, we are done!</p>
<p>Now we only need to look at the animation definition format, and then we can combine these three into the most amazing animation machine the internet has ever seen&#8230; or something like that anyway.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> walk <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Animation<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>
    <span style="color: #009900;">&#123;</span> sprite<span style="color: #339933;">:</span> <span style="color: #3366CC;">'walk_1'</span><span style="color: #339933;">,</span> time<span style="color: #339933;">:</span> <span style="color: #CC0000;">0.2</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
    <span style="color: #009900;">&#123;</span> sprite<span style="color: #339933;">:</span> <span style="color: #3366CC;">'stand'</span><span style="color: #339933;">,</span> time<span style="color: #339933;">:</span> <span style="color: #CC0000;">0.2</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
    <span style="color: #009900;">&#123;</span> sprite<span style="color: #339933;">:</span> <span style="color: #3366CC;">'walk_2'</span><span style="color: #339933;">,</span> time<span style="color: #339933;">:</span> <span style="color: #CC0000;">0.2</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
    <span style="color: #009900;">&#123;</span> sprite<span style="color: #339933;">:</span> <span style="color: #3366CC;">'stand'</span><span style="color: #339933;">,</span> time<span style="color: #339933;">:</span> <span style="color: #CC0000;">0.2</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> sprites<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here we define a walk animation. The animation is defined by simply giving the object an array, which contains objects for each frame, defining the name of the sprite and the duration of the frame. The variable sprites in the end is the spritesheet we defined in the previous example. </p>
<h3>Putting it all together</h3>
<p>Now, let&#8217;s put all this together!</p>
<p>I have a spritesheet lying around from some old projects: <a href="http://codeutopia.net/blog-files/canvas-animation/img/kunio.gif">kunio.gif</a>. Let&#8217;s animate this.</p>
<p>You may be familiar with this character &#8211; He is Kunio from an old NES game known as Downtown Nekketsu Monogatari, released in english as <a href="http://en.wikipedia.org/wiki/River_City_Ransom">River City Ransom</a>, and he&#8217;s been featured on various flash-animations as well.</p>
<p>I&#8217;ve used this sprite in a few other projects:</p>
<ul>
<li><a href="http://codeutopia.net/projects/flex/main.swf">In this Flex-based game test</a> (use arrow keys to move, space to punch, doubletap arrows to run)</li>
<li><a href="http://www.youtube.com/watch?v=c2HpcwnM9wI">In my Palm Pre Accelerometer demo application</a>, which actually uses this same code shown here.</a></li>
</ul>
<p>But enough of that, let&#8217;s write a quick HTML page to put our code to work:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Canvas Spritesheet Animation&lt;/title&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;js/FrameTimer.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;js/SpriteSheet.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;js/Animation.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        window.onload = function() {
            var timer = new FrameTimer();
            timer.tick();
&nbsp;
            var sprites = new SpriteSheet({
                width: 32,
                height: 32,
                sprites: [
                    { name: 'stand' },
                    { name: 'walk_1', x: 0, y: 1 },
                    { name: 'walk_2', x: 0, y: 1 },
                ]
            });
            var ctx = document.getElementById('canvas').getContext('2d');
            var walk = new Animation([
                    { sprite: 'walk_1', time: 0.2 },
                    { sprite: 'stand', time: 0.2 },
                    { sprite: 'walk_2', time: 0.2 },
                    { sprite: 'stand', time: 0.2 }
            ], sprites);
            var kunioImage = new Image();
&nbsp;
            kunioImage.onload = function() {
                setInterval(function(){
                    walk.animate(timer.getSeconds());
                    var frame = walk.getSprite();
                    ctx.clearRect(0, 0, 300, 300);
                    ctx.drawImage(kunioImage, frame.x, frame.y, 32, 32, 0, 0, 32, 32);
                    timer.tick();
                }, 5);
            };
&nbsp;
            kunioImage.src = 'img/kunio.gif';
        };
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Canvas sprite animation demo&lt;/h1&gt;
&lt;canvas id=&quot;canvas&quot; width=&quot;300&quot; height=&quot;300&quot;&gt;&lt;/canvas&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>Here it is. Our great animation system!</p>
<h3>A live example and source code</h3>
<p>You can see this code in action <a href="http://codeutopia.net/blog-files/canvas-animation/">by clicking here</a></p>
<p>As usual, don&#8217;t expect it to work in Internet Explorer. It has been tested to work in Opera 10 and Firefox 3, probably works in other canvas-supporting browsers as well.</p>
<p>Source:</p>
<ul>
<li><a href="http://codeutopia.net/blog-files/canvas-animation/js/FrameTimer.js">FrameTimer</a></li>
<li><a href="http://codeutopia.net/blog-files/canvas-animation/js/SpriteSheet.js">SpriteSheet</a></li>
<li><a href="http://codeutopia.net/blog-files/canvas-animation/js/Animation.js">Animation</a></li>
</ul>
<h3>Conclusion</h3>
<p>Animating a spritesheet with canvas is quite simple. This is why JavaScript is quickly becoming a powerful platform for small games in my opinion &#8211; very easy to use, and quite ubiquitous.</p>
<p>You can use this same approach to animation in other languages too &#8211; For example, the Flex example I linked uses a very similar approach.</p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/08/21/using-canvas-to-do-bitmap-sprite-animation-in-javascript/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Opera Command, JavaScript based Missile Command game</title>
		<link>http://codeutopia.net/blog/2009/07/14/opera-command-javascript-based-missile-command-game/</link>
		<comments>http://codeutopia.net/blog/2009/07/14/opera-command-javascript-based-missile-command-game/#comments</comments>
		<pubDate>Tue, 14 Jul 2009 17:43:26 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/07/14/opera-command-javascript-based-missile-command-game/</guid>
		<description><![CDATA[Firstly I&#8217;d just like to let you know that the lack of posts lately is because I have a new full time job which I&#8217;m enjoying quite much so far, but it still means I have less time / motivation to write stuff. The unit testing series and other postings will continue (see how I [...]]]></description>
			<content:encoded><![CDATA[<p>Firstly I&#8217;d just like to let you know that the lack of posts lately is because I have a new full time job which I&#8217;m enjoying quite much so far, but it still means I have less time / motivation to write stuff. The unit testing series and other postings will continue (see how I didn&#8217;t say &#8220;next week&#8221;, but &#8220;next time&#8221; in part 5? <img src='http://codeutopia.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ), but probably on a bit slower schedule. </p>
<p>As for packageizer and few other things not working, that&#8217;s because I&#8217;m setting them up on a new server. They should be up soon&#8217;ish.</p>
<p>Now for the actual post!</p>
<p>Today I&#8217;ll talk a bit about my other popular JavaScript widget game, <a href="http://codeutopia.net/projects/opera-command/">Opera Command</a>. As you may have guessed, it&#8217;s a clone of Missile Command and I originally wrote it to run as an Opera Widget.</p>
<p>I recently modified it to run in other browsers, so you can <a href="http://codeutopia.net/projects/opera-command/">try it out</a> even if you don&#8217;t have Opera. There may be some issues regarding the Z, X and C keys being taken by the browser for other purproses but other than that it should work quite fine.</p>
<p><span id="more-244"></span></p>
<p>This game is technically less interesting and impressive than <a href="http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/">TankWar Online</a>, but it bears a few things of note.</p>
<p>Opera Command is possibly the only one of my games with a small &#8220;story&#8221; &#8211; The little snippet about Redmondians attacking Norway you get when you open the game. Also, it had an online high score table, which no longer functions due to same reasons as TankWar&#8217;s online play. Some people had also figured out what the game does to post your score and had &#8220;hacked&#8221; it and posted fake scores&#8230; </p>
<p>As usual, the graphics are done using the canvas element and the menus are plain old HTML divs and stuff. Despite quite simple I like how the graphics turned out, as they kind of look &#8220;old school&#8221; and the game runs pretty well even on a bit slower PCs despite canvas being quite expensive speed-wise. </p>
<p>Some of the graphics are simple images drawn on the canvas, like the city graphics. Rest are drawn using the canvas methods. The explosions particularily are something that turned out surprisingly nice after a random try: They are simply circles that get larger and are filled with a gradient.</p>
<p><br/><br/></p>
<p>I still have one or two JavaScript games that might be worth a post. Perhaps we&#8217;ll see some in the future</p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/07/14/opera-command-javascript-based-missile-command-game/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>TankWar Online, my JavaScript based cannons game</title>
		<link>http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/</link>
		<comments>http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/#comments</comments>
		<pubDate>Tue, 30 Jun 2009 15:38:15 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/</guid>
		<description><![CDATA[Back in late 2006 I wrote my most ambitious JavaScript/game project so far: TankWar Online, which as you may guess from the name was about tanks, shooting stuff, and it had a real-time online game mode &#8211; as far as I know, the first such ever in a JS based game. Originally the game was [...]]]></description>
			<content:encoded><![CDATA[<p>Back in late 2006 I wrote my most ambitious JavaScript/game project so far: <a href="http://codeutopia.net/projects/tankwar">TankWar Online</a>, which as you may guess from the name was about tanks, shooting stuff, and it had a real-time online game mode &#8211; as far as I know, the first such ever in a JS based game.</p>
<p>Originally the game was made for an older version of Opera 9, and only worked in it. However, I have now modified the game so it should work in most browsers (tested Firefox, Opera 9, 10). </p>
<p><a href="http://codeutopia.net/projects/tankwar/">Click here to play cross-browser version of the game</a>. The game should work for other parts than the online game mode, as the server is no longer functional.</p>
<p>Interested in hearing how the game works, such as terrain, physics and the computer AI? Keep reading!</p>
<p><span id="more-242"></span></p>
<h3>A disclaimer regarding the code</h3>
<p>If you want to go look into the code, feel free, but keep in mind I wrote this in late 2006 and the code is not really very good. It probably makes sense after you&#8217;re totally familiar with it, but even I who wrote the thing had problems finding the places I needed to modify to make it work once again.</p>
<h3>Main features of the game</h3>
<p>Let&#8217;s look at how some of the main features of the game work.</p>
<h3>Terrain</h3>
<p>The terrain in TankWar is generated randomly, based on a bunch of parameters. If you go into the map settings from the main menu, you can see and adjust these parameters.</p>
<p>The input fields in the map settings screen are actually Web Forms 2 (now <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#forms">a part of HTML5 forms</a>) elements, which still don&#8217;t seem to be supported by any other browser than Opera, even after many years. If you don&#8217;t have Opera handy, the main difference between the fields in other browsers and Opera is that in Opera, the fields get little arrows for increasing and decreasing the value.</p>
<p>The terrain generation algorithm itself is pretty simple. It takes the base height value, and then adds a number of points based on the height points value. The points&#8217; heights is randomized between the min height and max height values. Ta-dah, simple terrain generation.</p>
<h4>Destruction of terrain</h4>
<p>Another feature of the terrain is that it&#8217;s desctructible. If you fire a weapon at it, it&#8217;ll make a hole. You could even destroy the whole map if you destroyed all the ground.</p>
<p>To understand how the desctruction of the terrain works, we have to look at how the terrain itself is stored and rendered.</p>
<p>The terrain is stored as an array of points, which are converted into a canvas path. The path actually consists of the sky, and not the ground &#8211; the sky and ground are rendered by first filling the whole image with the ground color, and then using the terrain path to fill in the sky.</p>
<p>When some of the ground is destroyed, the game creates a circular path, which is then added to the terrain path. This way the destroyed areas of the ground get filled with the sky color as well, making it seem like the ground was destroyed, even though the terrain path itself remains unmodified.</p>
<h4>Terrain hit testing</h4>
<p>This is also used for testing hits on the ground: as long as a projectile (or a tank) is inside the terrain path, or inside one of the circular explosion paths, the projectile keeps moving. The hit check was performed by an Opera-specific method and a custom polygon hit checking function in the old code, as when I wrote it, there was no reliable way to detect whether a point was inside a path or not. In the new version, the hit is detected with the canvas method <code>isPointInPath</code>, which should work in all browsers with a modern canvas implementation.</p>
<h3>The physics engine</h3>
<p>The game features a simple physics engine, which simulates falling tanks and moving projectiles such as cannon shells. It also allows for wind.</p>
<p>It functions relatively simply: each &#8220;physics object&#8221; &#8211; tanks and shells &#8211; have some vectors which define their position and velocity. The engine has a constant gravity, and an optional wind (which is kind of like horizontal gravity), which affect objects when they move. The physics engine is not active until someone actually fires their cannon &#8211; it has no need to run when you take aim, so the engine was designed so it could be given a set of objects to simulate (tanks and the newly fired shell) and then it could run until all the objects are considered &#8220;dead&#8221;. Being dead simply means that each object has hit the ground, or for shells, hit a tank.</p>
<h3>Weapons</h3>
<p>Currently the game has eight weapons. Originally there were less, but I had wanted to add more interesting weapons, so the weapon system was designed to accomodate various kinds of weapons, as can be seen in the current selection.</p>
<p>The weapon system is based on the concept of a cannon and a shell (which is what cannons fire). The cannon acts as a kind of a factory for shells, defining how much damage they make, how large is their blast radius etc.</p>
<p>The system is also wired with some events such as an event for the time when a shell hits the ground. This enables the engine to have weapons like the teleport or the arty drop, which both have a special handler for the hit ground event, which moves the player&#8217;s tank and fires three more shells at the location from the sky, respectively.</p>
<p>The bomber weapon is a bit special. The weapon&#8217;s behavior is actually not intended &#8211; it&#8217;s a bug. It probably seems crazily overpowered sometimes, and I never meant it to drop an infinite stream of &#8220;bombs&#8221;, just five of them, but because of a bug it just turned out like that. I liked the unintended behavior and left it in, so it became a feature instead.</p>
<p>Some of the weapons were inspired by Worms 2, like the arty drop and teleport.</p>
<h3>Computer opponent</h3>
<p>This was one of the most interesting parts of writing the game. As I wanted to give players the possibility to play the game by themselves, I wanted it to have an AI player.</p>
<p>The game&#8217;s &#8220;player system&#8221; is quite flexible. It had to be, so that implementing a &#8220;local&#8221; player, a &#8220;network&#8221; player for online games and an &#8220;computer&#8221; player would be possible. Simply put, the players each implement a specific set of functions that are called in specific points during the game &#8211; the game itself doesn&#8217;t care much what the type of the player is, except in some special cases, and the player object itself handles things differently.</p>
<p>The computer AI is not very complex. To not give it a completely unfair advantage (and so that my head wouldn&#8217;t hurt too much because of the math involved), I didn&#8217;t give it a 100% precise aim &#8211; which would have been possible by computing where the shell will land, given the gravity, wind and required power and shooting angle. </p>
<p>Instead, the computer follows this graph (click to see a bigger image)<br />
<a href="http://codeutopia.net/projects/tankwar/tankwar_ai_diagram.PNG"><img src="http://codeutopia.net/projects/tankwar/tankwar_ai_diagram.PNG" width="550" alt="Diagram of how the AI works" /></a></p>
<p>The diagram is not 100% accurate, but that is the general idea of how the AI works. It does some small additional things, such as figuring if wind has changed.</p>
<h3>Currently defunct: Online play</h3>
<p>The coolest thing in the game no longer works: The online multiplay mode.</p>
<p>The online multiplayer mode was similar to what you can see in many PC games nowadays. It had a lobby where players could talk with each other, and a list of games which were active and joinable. It was also possible to protect your game with a password and choose a maximum amount of players.</p>
<p>There were some additional hidden features in the online lobby, such as the ability to join a custom room, a bit similar to joining channels on IRC. It also implemented some swearword filtering (schoolkids seemed to enojy abusing the chatroom during school hours) and an admin interface for getting rid of unwanted elements (which was implemented on the server and only worked for me)</p>
<p>The gameplay itself was the same, but in addition to the interface elements seen in a local game, the game showed you a chat box and the list of others in the game so you could talk with them during the game. As with local games, you could have up to eight players in a single game, which was a limitation I had chosen based on the map size &#8211; the game could have had 10, 20 or more players, but the map would&#8217;ve gotten very crowded.</p>
<h3>Online game server</h3>
<p>The server for the online play was lost in a fatal hard disk failure in 2008 or so. It was implemented in Python, using a library called Twisted to provide HTTP functionality.</p>
<p>The server received communications from clients with XMLHttpRequests, and sent responses using a Server-Sent DOM Events channel, which each client was required to open. Most of the stuff was quite normal client-server type of things &#8211; the clients would get an ID, send messages, receive responses and parse them etc.</p>
<p>There was quite much game related things to do on the server as well. While testing the game, I noticed a worrying inconsistency of where the shells landed on one PC compared to a slower PC &#8211; sometimes on slow PCs, the shells would land on completely different locations than on the fast PC. I fixed this by making each network player get synced from the server. Basically it meant that whenever a player&#8217;s turn was finished, the player&#8217;s game told the server where the shots had landed. The server would then broadcast this to all players in the game, and this way each player&#8217;s game was kept in perfect sync.</p>
<p>Sadly I no longer have the code as said, and it would be a rather big undertaking to write a new one &#8211; certainly possible, but I don&#8217;t have the time for it.</p>
<h3>Bottom line</h3>
<p>TankWar was, and maybe still is, my greatest widget. <a href="http://codeutopia.net/projects/city/">WidgetCity</a> was a large and complex project, but TankWar had a lot of special things in it and it was 100% written by me &#8211; WidgetCity shared a lot of algorithms with the original Sim City source code available online.</p>
<p>Here is <a href="http://codeutopia.net/projects/tankwar/tankwar_src.zip">the source code for TankWar</a>, if you want to take a look at it.</p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/30/tankwar-online-my-javascript-based-cannons-game/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How WidgetCity does a tile-based map using just CSS</title>
		<link>http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/</link>
		<comments>http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 12:38:18 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/</guid>
		<description><![CDATA[My city building game, WidgetCity, displays the city as a table, each cell of a table representing one tile. The tile map is done purely using just CSS, and CSS classes. The map is also scrollable. How is this all done? Multiple approaches As always, there is more than one approach to doing this type [...]]]></description>
			<content:encoded><![CDATA[<p>My city building game, <a href="http://codeutopia.net/projects/city/">WidgetCity</a>, displays the city as a table, each cell of a table representing one tile.</p>
<p>The tile map is done purely using just CSS, and CSS classes. The map is also scrollable.</p>
<p>How is this all done?</p>
<p><span id="more-239"></span></p>
<h3>Multiple approaches</h3>
<p>As always, there is more than one approach to doing this type of a tile map.</p>
<p>The most obvious approach is to chop down each graphic in the game to one tile sized small images. Then, each of the small images is applied using a background image to each of the tiles. For example, an industrial zone is 3&#215;3 tiles, so this would need 9 small images which each get applied to specific tiles to build the whole industrial zone.</p>
<p>This small image approach can be done in two ways: Using a CSS style to put the image as the background, or by inserting an img tag into the cell and changing its src.</p>
<p>There&#8217;s a lot of different graphics for just a single type of zone: Indstrial zones for example have different graphics for different land valued zones and different populations on the zone. The above approach would work, but it would require a lot of work to chop each big graphic into small ones and also each image would have to follow a specific naming scheme so it could be applied correctly.</p>
<p>Another approach is similar to what is used in <a href="http://www.alistapart.com/articles/sprites">CSS sprites</a>: Each larger graphic is contained in a single file, and the image is then mapped into the small cells using CSS&#8217; background-position.</p>
<h3>The chosen approach</h3>
<p>I decided to use the approach similar to CSS sprites. This is because it was simpler to work with the files, as I didn&#8217;t need to rename all the little images and define tons of CSS classes just to apply the specific backgrounds. This also somewhat simplified the JavaScript code applying the styles.</p>
<p>The game defines a set of CSS naming rules which are used in the stylesheets, so the code in the game can easily apply styles without having to use special cases all over the place. Each cell&#8217;s className attribute consists of several classes:</p>
<ul class="biggerMargins">
<li>An &#8220;offset class&#8221;, which is used to place the big image into the small cell: for example, &#8220;o31x1&#8243; is the bottom right corner of a 3&#215;3 tile &#8211; o for offset, 3 for 3&#215;3, 1&#215;1 for the X and Y offset from the center of the tile. The game knows which position of the tile it&#8217;s laying out, so it simply adds the respective offset class into the cell&#8217;s className.</li>
<li>The main &#8220;graphic class&#8221;, such as &#8220;indbuilding&#8221; for an industrial building.</li>
<li>A &#8220;land value/population class&#8221;. This is used to choose which graphic of the building to actually display, such as a small rowhouse, or a big skyscraper. These look like v0p1, where v0 means land value 0 and p1 means population 1</li>
</ul>
<p>There are also some other special classes:</p>
<ul>
<li>nopower class is applied to zone center cells if the zone doesn&#8217;t have power. This shows the little no power indicator</li>
<li>For roads and powerlines, there are classes called up, right, down and left, which are applied in following cases: if you have a road, and there&#8217;s a section of road above it, the class &#8220;up&#8221; is given to the bottom road cell, and the class &#8220;down&#8221; is given to the upper. If there&#8217;s also a road to the left of the upper cell, it gets &#8220;left&#8221;. In the stylesheet, there are combinations of these four classes, which apply the correct road and powerline graphics to the cells.</li>
</ul>
<h3>The scripting side of things</h3>
<p>Of course all this won&#8217;t work without JavaScript. Behind the scenes, the game stores the map as a two dimensional array of objects. The objects in the array contain various data, which is used to determine which classes to apply to each cell when &#8220;rendering&#8221; the map.</p>
<p>The classes are also applied only when something changes &#8211; the game keeps track of what classes are in the cells, as re-applying the class incurs a performance penalty.</p>
<h3>What about canvas?</h3>
<p>Lastly, some words on an alternative to using a table: the HTML5 canvas element.</p>
<p>While it may seem &#8220;wrong&#8221; to use table to do something like this, I think it&#8217;s in certain ways better than canvas. Firstly, you get better performance, and second, you need less code.</p>
<p>Using canvas, you would need to write the code to draw the correct parts of the graphics, and if you wanted animations like the game has now, you would need to write timing code to run the animations. So in addition to the performance penalty of using canvas rendering, you would need additional JavaScript code running the animations and everything else.</p>
<p>The benefits of using canvas would be that you could provide smooth scrolling. With a table it would be very tricky if not completely unfeasible. Canvas would also allow zooming or other effects.</p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>I wrote a Sim City clone in JavaScript</title>
		<link>http://codeutopia.net/blog/2009/04/28/i-wrote-a-sim-city-clone-in-javascript/</link>
		<comments>http://codeutopia.net/blog/2009/04/28/i-wrote-a-sim-city-clone-in-javascript/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 15:23:16 +0000</pubDate>
		<dc:creator>Jani Hartikainen</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Opera]]></category>
		<category><![CDATA[Widgets]]></category>

		<guid isPermaLink="false">http://codeutopia.net/blog/2009/04/28/i-wrote-a-sim-city-clone-in-javascript/</guid>
		<description><![CDATA[This is why I haven&#8217;t been updating lately: I have been working on a Sim City clone, written purely in HTML, CSS and JavaScript! The game is called WidgetCity, and I&#8217;m participating with it in the Betavine Widget Competition 2009. The game was designed to run in Opera Widgets mode, but it also works in [...]]]></description>
			<content:encoded><![CDATA[<p>This is why I haven&#8217;t been updating lately: I have been working on a Sim City clone, written purely in HTML, CSS and JavaScript!</p>
<p>The game is called WidgetCity, and I&#8217;m participating with it in the <a href="http://www.betavine.net/bvportal/competition/view.html?id=ff8080811f1f3dbb011f3721070438d1">Betavine Widget Competition 2009</a>.</p>
<p>The game was designed to run in Opera Widgets mode, but it also works in Firefox &#8211; only downside is that you can&#8217;t save your city. Get <a href="http://codeutopia.net/projects/city/city.wgt">the widget here</a>, or if you don&#8217;t have Opera, you can <a href="http://codeutopia.net/projects/city/">play the game here</a>. There is also <a href="http://codeutopia.net/projects/city/help.html">a help file</a>.</p>
<p>Continue reading to find out more details about the game&#8217;s inner workings and such!</p>
<p><span id="more-227"></span></p>
<h3>The basic stuff</h3>
<p>The game is quite similar to the original Sim City &#8211; it actually uses some graphics from it, thanks to the fact that the original Sim City source code has been released under GPL, which was a good thing because I&#8217;m not the world&#8217;s greatest graphics artist!</p>
<p>As per the requirements of the Betavine competition, the game had to run in a mobile phone. This is why the game is so small: It had the screen size limitations of a Nokia N95, which is something like 260&#215;240 pixels.</p>
<p>The game was originally supposed to be based on the canvas tag, which I&#8217;ve used on my past widget projects like <a href="http://my.opera.com/zomg/blog/2007/01/05/nooo-i-missed">TankWar Online</a>. However, this turned out to be a bit of a problem on the phone, and only one of the problems caused by the phone.</p>
<p>The N95 is actually a quite good device: It has the hardware to run games with 3D graphics, etc. etc., but it&#8217;s completely unable to run JavaScript code at a reasonable pace. Using canvas, the game ran absurdly slow!</p>
<p>In the end, I had to resort to using old-school DHTML style trickery: The game area is simply a table, with some CSS classes applied to each of the cells in JavaScript.</p>
<h3>Under the surface</h3>
<p>Under the relatively simple looking graphics of the game ticks a quite serious simulation engine.</p>
<p>The game engine simulates a lot of things, and it had quite serious performance implications which required a lot of JavaScript optimization. You can read more about the problems and optimizations encountered in development in <a href="http://codeutopia.net/blog/2009/04/30/optimizing-javascript-for-extreme-performance-and-low-memory-consumption/">Optimizing JavaScript for extreme performance and low memory consumption</a>.</p>
<p>The sim engine calculates at least the following: </p>
<p>It keeps a track of what&#8217;s built in each tile in the game. This data is then used to calculate things like how much residential/commercial/industrial demand there is. </p>
<p>For some specific tile types like residential zones, the game calculates desirability and traffic: Is this area of the map &#8220;good enough&#8221; to build a large apartment block, and can the people living here drive to some destination?</p>
<p>The desirability calculations are based on a bunch of other large calculations: Pollution, crime rate, land value, population density. Each of these has to be calculated again and again during the progress of the game to keep the city developing.</p>
<p>Traffic itself uses a quite &#8220;dumb&#8221; algorithm: It just attempts to drive in a random direction along the roads until it reaches a destionation, which works okay for the simple calculations involved.</p>
<p>The large calculations like pollution and land value calculations require going over all the tiles in the map to determine what&#8217;s built where, and then based on those some values are calculated.</p>
<p>You can probably see why the performance wasn&#8217;t so great, as there is <i>a lot</i> of stuff going on in the background!</p>
<h3>Issues during development</h3>
<p>Most of the problems during the game&#8217;s development were caused by the really poor JavaScript performance on the target device.</p>
<p>For example, the original map size in the game was 300&#215;300 tiles. This would cause the phone to immediately run out of memory when attempting to play, so I had to reduce the size to 128&#215;128, which still quite good is nowhere near as large as the original.</p>
<p>Note that the original 300&#215;300 map did run perfectly fine on my desktop and on my HTC Touch Diamond. It would probably have had major performance implications in the future, though&#8230;</p>
<p>Additionally, I originally planned to use canvas. However, I had to scrap that and use a table as the speed of canvas was just way too poor. You may be interested in reading <a href="http://codeutopia.net/blog/2009/06/15/how-widgetcity-does-a-tile-based-map-using-just-css/">how the WidgetCity map is rendered using a table and some CSS</a>.</p>
<p>The JS performance in general seemed quite awful: Just looping over the 128&#215;128 map was slow. If you did nothing else than just iterate over each of the 16 384 tiles, it would already have a small impact, which you wouldn&#8217;t have with most other languages, or even with a bit newer JavaScript engines.</p>
<p>Another memory related problem surfaced closer to finishing the development: The N95 would run out of memory when saving the game.</p>
<p>Saving and loading are a quite vital feature of the game, so this was a critical issue. However, <a href="http://my.opera.com/remcolanting/blog/">Remco Lanting</a> came up with a nice idea to possibly fix it: Save the map in smaller parts. The idea worked flawlessly. Remco also helped with testing the game and with some ideas, so a big thanks to him.</p>
<h3>What&#8217;s missing?</h3>
<p>While the game is quite ready and playable now, there are various things that I would&#8217;ve liked to add to it, but due to lack of time I couldn&#8217;t.</p>
<p>These include being able to lay rail, being able to get nice maps that display things like crime rate in different parts of the map, some user interface improvements, and of course disasters like nuclear plant meltdowns!</p>
<p>One particularily cool thing I would have liked to have was the ability to overlay data like crime rates on top of the city. I wrote a post earlier on <a href="http://codeutopia.net/blog/2008/06/23/simple-photoshop-style-layers-using-javascript/">how you can get Photoshop layer style stuff in JavaScript</a>, which could have been a nice way to do this.</p>
<p>I don&#8217;t know if I will be adding all those, as I have various other things to do now that the game is released, like actually writing blogposts again. <img src='http://codeutopia.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>However, if you&#8217;d like, you are free to modify the game. I&#8217;ve decided to release it under GPL, similar to the graphics from the Micropolis project used in it. If you would like to play with the source code, just <a href="http://codeutopia.net/projects/city/city.wgt">download the widget</a>, rename the file to .zip and unzip it like normal.</p>
]]></content:encoded>
			<wfw:commentRss>http://codeutopia.net/blog/2009/04/28/i-wrote-a-sim-city-clone-in-javascript/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
