<?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>disruption.ca &#187; Programing</title>
	<atom:link href="http://disruption.ca/archives/category/programing/feed/" rel="self" type="application/rss+xml" />
	<link>http://disruption.ca</link>
	<description></description>
	<lastBuildDate>Thu, 15 Apr 2010 04:18:09 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>God Does Not Play Dice With The Universe</title>
		<link>http://disruption.ca/archives/dice/</link>
		<comments>http://disruption.ca/archives/dice/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 22:31:21 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/?p=84</guid>
		<description><![CDATA[
My dice portrait of Albert Einstein is finally finished and hanging on my wall.
A little over a year ago, I read a blog post about creating an amazing portrait of The Madonna using dice.  I loved the idea, and after some minor hesitation, decided to blatantly steal the concept.  Einstein would be my [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://disruption.ca/wordpress/wp-content/uploads/2009/11/IMG_0321.JPG"><img src="http://disruption.ca/wordpress/wp-content/uploads/2009/11/IMG_0321-225x300.jpg" alt="Finished" title="Finished" width="225" height="300" class="alignnone size-medium wp-image-94" /></a></p>
<p>My dice portrait of Albert Einstein is finally finished and hanging on my wall.</p>
<p>A little over a year ago, I read a blog post about creating an <a href="http://www.flight404.com/blog/?p=131">amazing portrait of The Madonna using dice</a>.  I loved the idea, and after some minor hesitation, decided to blatantly steal the concept.  Einstein would be my subject, almost purely so that I could use this title, though it is <a href="http://en.wikiquote.org/wiki/Albert_Einstein">a bit of a mis-quote</a>.  I immediately started writing code to visualize different dice images, and playing with different algorithms for picking the dice.  In an effort to differentiate my project I tried using a mixture of black and white dice to give 12 colour choices.</p>
<p><a href="http://disruption.ca/wordpress/wp-content/uploads/2009/11/AlbertEinsteinKate5.jpg_5000_light_whiteAndBlackDice_normalized_error.jpg"><img src="http://disruption.ca/wordpress/wp-content/uploads/2009/11/AlbertEinsteinKate5.jpg_5000_light_whiteAndBlackDice_normalized_error-263x300.jpg" alt="Black and White" title="Black and White" width="263" height="300" class="alignnone size-medium wp-image-92" /></a></p>
<p>Ultimately  I decided that the resulting image looked too blocky and pixelated.  I was able to generate some interesting images by adding grey dice and working with 18 shades.  But that seemed to sacrifice some of the purity, fun and craziness of making an image in dice.  As one of my friends said, I might as well be working in a medium that is appropriate for a portrait if I am going to throw grey dice into the mix.</p>
<p>An idea from the <a href="http://www.reddit.com/r/programming/comments/79tkd/how_i_took_2925_dice_and_formed_them_into_a/">reddit discussion</a> of The Dice Madonna was rotating the 2s, 3s and 6s to create more detail.  I experimented with generating images that rotated these dice and used an error calculation to look for an improvement.  I was never able to generate a result that I was happy with using this technique.  I find the white space created by rotating adjacent 2s and 3s creates weird interference patterns without contributing to the image.  Here is an <a href="http://disruption.ca/wordpress/wp-content/uploads/2009/11/AlbertEinsteinKate5.jpg_new_5000_light_gamma2.2_specialR_normalized_population.jpg">image showing the problem</a>.</p>
<p>I ultimately decided on a 4950 dice image generated with a population algorithm for dice distribution.  My final image uses some rotation of 2s 3s and 6s in very limited situations.  I also experimented with dithering, but decided against it.</p>
<p><a href="http://disruption.ca/wordpress/wp-content/uploads/2009/11/AlbertEinsteinKate5.jpg_new_5000_light_gamma2.2_whiteDice_normalized_population.jpg"><img src="http://disruption.ca/wordpress/wp-content/uploads/2009/11/AlbertEinsteinKate5.jpg_new_5000_light_gamma2.2_whiteDice_normalized_population-263x300.jpg" alt="Final" title="Final" width="263" height="300" class="alignnone size-medium wp-image-89" /></a></p>
<p>Once I had an image, I ordered 5000 dice from <a href="http://www.koplowgames.com">Koplow Games</a>.  I chose the 12mm dice, as they are smaller, lighter and cheaper than the more common 16mm dice.  However they are still large enough to qualify as what most people consider normal dice.</p>
<p><a href="http://disruption.ca/wordpress/wp-content/uploads/2009/11/IMG_1121.JPG"><img src="http://disruption.ca/wordpress/wp-content/uploads/2009/11/IMG_1121-225x300.jpg" alt="5000 dice" title="5000 dice" width="225" height="300" class="alignnone size-medium wp-image-91" /></a></p>
<p>The next step was to build <a href="http://disruption.ca/dl/dice/dice.html">a flash program to help me place the dice</a>.  Follow the link to try it out.  Click to give the program focus, and use the arrow keys to move around the image.</p>
<p><a href="http://disruption.ca/wordpress/wp-content/uploads/2009/11/IMG_0120.JPG"><img src="http://disruption.ca/wordpress/wp-content/uploads/2009/11/IMG_0120-225x300.jpg" alt="Progress" title="Progress" width="225" height="300" class="alignnone size-medium wp-image-90" /></a></p>
<p>Actually placing the dice took about 12 hours, spread out over a week.  A friend built a case from plywood and lexan, which was a huge help.  Carpentry is not one of my strengths.  Interestingly the assembled dice were not very square.  There is enough variation in the dice that I needed to use foam tape around the inside of the frame to even the edges out.  The final package weighs 53lbs, and I was concerned about hanging it from the wall.  But a trip to a local framing store provided all of the needed hardware.</p>
<p>I took me over a year of off and on work to go from idea to art on my wall, but it was very fun.  Incredibly, about a month ago I saw this link to <a href="http://www.knowltonmosaics.com/imagepages/o-1.htm">a 10 year old web page that demonstrates just how rare new ideas are</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/dice/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Links from my FitC Edmonton talk</title>
		<link>http://disruption.ca/archives/links-from-my-fitc-edmonton-talk/</link>
		<comments>http://disruption.ca/archives/links-from-my-fitc-edmonton-talk/#comments</comments>
		<pubDate>Mon, 19 Oct 2009 01:10:23 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/?p=61</guid>
		<description><![CDATA[I&#8217;d like to start with a disclaimer for anyone coming to my blog for the first time.  I swear I didn&#8217;t just install worpress and leave it on the default theme.  I actually chose this template before it became the wordpress default.  I&#8217;m really going to have to change it soon. (Edit: [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;d like to start with a disclaimer for anyone coming to my blog for the first time.  I swear I didn&#8217;t just install worpress and leave it on the default theme.  I actually chose this template before it became the wordpress default.  I&#8217;m really going to have to change it soon. (Edit: Ok, I&#8217;ve updated the template.)</p>
<p>On with the links.</p>
<p>First, <a href="http://randomnine.wootfu.com/project.php?p=5">Commies</a>, the game that introduced me to the LD48.</p>
<p>The web site for the LD48 competitions:<br />
<a href="http://www.ludumdare.com/compo/">ludumdare.com</a></p>
<p>The <a href="http://www.ludumdare.com/compo/ludum-dare-15/?action=top">top ranked games</a> from the last competition.</p>
<p>Some recent LD48 games your really should check out:<br />
<a href="http://properundead.com/2009/08/new-game-beacon.html">Beacon</a><br />
<a href="http://www.codedojo.com/?p=104">Mind Wall</a><br />
<a href="http://www.increpare.com/2008/12/rara-racer/">Rara Racer</a></p>
<p>These are just a few highlights.  There are so many great games.</p>
<p>Here is an updated version of my entry in the last competition.  <a href="http://disruption.ca/cave/cavePC.html">Caves and Bombs</a>.  I&#8217;ll be writing a post about this game some time soon.</p>
<p>Next, some tools:<br />
<a href="http://flixel.org/">Flixel</a>. An open source AS3 framework for rapid game development.<br />
<a href="http://www.drpetter.se/project_sfxr.html">SFXR</a>. A small utility for generating retro style sound effects.<br />
<a href="http://opensword.org/Pixen/">Pixen</a>.  An image editor that specifically targets creating pixel art.</p>
<p>Here is a link to a blog post that covers a lot of similar concepts that my talk covered.  It seems I basically stole their title for my talk.  Oops.  <a href="http://headrush.typepad.com/creating_passionate_users/2005/08/build_something.html">Build something cool in 24 hours</a></p>
<p>Finally, a couple of unrelated links that would be relevant had I stuck with my original talk topic of Runtime Actionscript.<br />
<a href="http://metal.hurlant.com/blog/2008/05/17/web/as3-eval-updated/">As3 Eval</a>.<br />
<a href="http://wonderfl.net/">wonderfl</a></p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/links-from-my-fitc-edmonton-talk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Edmonton Game Jam</title>
		<link>http://disruption.ca/archives/edmonton-game-jam/</link>
		<comments>http://disruption.ca/archives/edmonton-game-jam/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 04:12:55 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/archives/edmonton-game-jam/</guid>
		<description><![CDATA[tigsource.com is a community dedicated to independent games.  Some form members are organizing a Western Canada TIGjam in Edmonton, and I&#8217;d really like to see this happen.
The concept is pretty simple.  It&#8217;s about getting a group of people who are interested in game development together for a couple of intense days of game [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://tigsource.com">tigsource.com</a> is a community dedicated to independent games.  Some form members are organizing a Western Canada TIGjam in Edmonton, and I&#8217;d really like to see this happen.</p>
<p>The concept is pretty simple.  It&#8217;s about getting a group of people who are interested in game development together for a couple of intense days of game creation.  I&#8217;ve only ever done this sort of thing online, but I&#8217;m excited about trying something like this with a local group.</p>
<p>More information is available from this <a href="http://mattmakesgames.com/blog/2009/03/tigjam-canada.html">organizer&#8217;s blog entry</a>.</p>
<p>No date has been set yet, but if you are interested you should <a href="http://doodle.com/cggpde5p7qyyy3h5">register your availability</a>.</p>
<p>Finally, if you&#8217;d like to read more, there is some <a href="http://forums.tigsource.com/index.php?board=15.0">discussion on the TIGsource forms</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/edmonton-game-jam/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tweetcoding</title>
		<link>http://disruption.ca/archives/tweetcoding/</link>
		<comments>http://disruption.ca/archives/tweetcoding/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 23:15:43 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/archives/tweetcoding/</guid>
		<description><![CDATA[Grant Skinner recently came up with a fun challenge.  Try to write an interesting program in a tweet (140 chars) worth of actionscript.  Take a look at the rules for the competition, and the #tweetcoding aggregation page that includes the results.
There are some amazing visual effects and impressive programs amongst the entries.  [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://gskinner.com/blog/">Grant Skinner</a> recently came up with a fun challenge.  Try to write an interesting program in a tweet (140 chars) worth of actionscript.  Take a look at the <a href="http://gskinner.com/playpen/tweetcoding.html">rules for the competition</a>, and the <a href="http://tweetcoding.machine501.com/">#tweetcoding aggregation page</a> that includes the results.</p>
<p>There are some amazing visual effects and impressive programs amongst the entries.  My favorites include:</p>
<ul>
<li><a href="http://tweetcoding.machine501.com/tc_1267109791.swf">diagonal snake</a> by <a href="http://twitter.com/tomee6">tomee6</a>, it&#8217;s a minimalist game that is actually kind of fun.</li>
<li><a href="http://tweetcoding.machine501.com/tc_1262902747.swf">eye</a> by <a href="http://twitter.com/mesanges">messages</a>.  Very cool visuals depending on where you position the mouse.</li>
</ul>
<p> You can see the code for my entry on <a href="http://twitter.com/erikejohnson">my twitter page</a>, and here is the resulting SWF: <a href="http://tweetcoding.machine501.com/tc_1267915343.swf">Langton&#8217;s Ant</a>.  Langton&#8217;s Ant is a cellular automaton algorithm with very simple rules.  If the current grid cell is black, paint it white, turn to the left and take a step forward.  If the current cell is white, paint it black, turn to the right and take a step forward.  According to the <a href="http://en.wikipedia.org/wiki/Langton%27s_ant">Wikipedia Langton&#8217;s Ant article</a>, given an infinite grid, Langton&#8217;s Ant is a universal Turing machine, capable of performing any computation.  I don&#8217;t expect to win any prizes, but I&#8217;m happy with the geek factor of my entry.</p>
<p>Taking an algorithm and trying to implement it in 140 characters of source code is, like many optimization activities, quite fun and addictive.  But what surprised me was how much I learned from the experience.</p>
<p>Langton&#8217;s Ant does interesting things after about 10,000 iterations.  At 60 frames per second, it would take almost 3 minutes to reach that point.  So an extra I had to build into my implementation was a loop that ran the simulation 15 times for every frame.  After doing this, I discovered that the framerate would start to seriously drop after 15k ~ 20k iterations of the algorithm.  With some very rough profiling I discovered that it was the graphics render step that was taking so much time, which was surprising seeing as I was only plotting 15 pixels per frame.  It seems that whenever you draw to a graphics object in flash, it re-renders every drawing operation to recreate the image from scratch.  So after 15k iterations, the flash player is performing 15k drawing operations per frame.  Yuck.</p>
<p>I wasn&#8217;t able to find much information online about working around this.  Here is a <a href="http://www.dannyburbol.com/2008/05/flash-as3-graphicsdrawrect-memory-leak/">blog entry that incorrectly characterizes the problem as a memory leak</a>.  I tried using cacheAsBitmap, but it didn&#8217;t help.  Switching from drawLine, which the tweetcoding framework provides shortcuts for, to drawRect improved things by about 30%.  Setting the render quality to low had similar results, but using drawRect cost me less characters.</p>
<p>Using bitmap graphics, with setPixel calls avoids this problem and allows the algorithm to run at full speed even after 10&#8217;s of thousands of iterations.  Unfortunately, the minimum code required to get a bitmap graphics object onto the stage is something like this:</p>
<blockquote><p><code>addChild(new Bitmap(m=new BitmapData(w,h)));</code></p></blockquote>
<p>With only 140 characters to work with, I couldn&#8217;t find a way to fit this technique into my entry.  So I went with the drawRect method, and you will see a serious performance degradation problem as my entry runs.</p>
<p>There are many ways to compress source code.  Some techniques can be used methodically: using single character variable names, removing  comments and unneeded white space, chaining assignments, using the result of an assignment statement as a parameter and using the ? : operators instead of if() statements.</p>
<p>But what I found to be interesting was finding ways to express the algorithm more succinctly.  My biggest revelation came from compressing the code that handles the direction the ant is moving.  The ant needs to make 90 degree turns to the left or to the right.  Here is an uncompressed version of my first implementation of this logic:</p>
<blockquote><p><code>v = [ [1,0], [0,1], [-1,0], [0,-1] ]; // a list of the direction options.</p>
<p>d = (d + 1) % 4;  // rotate the ant's heading 90 degrees to the right.<br />
x = x + v[d][0];  // Change the ant's x position based on it's heading.<br />
y = y + v[d][1];  // Change the ant's y position based on it's heading.<br />
</code></p></blockquote>
<p>In my efforts to optimize this, I first looked at the list of direction vectors.  The X components of the list being 1, 0, -1, 0 and the Y components being 0, 1, 0, -1 stood out.  The Y list is the same as the X list, rotated by one position.  This lead to the following code:</p>
<blockquote><p><code>v = [1, 0, -1, 0];  // a list of vectors.</p>
<p>d = (d + 1) % 4;  // rotate the ant's heading 90 degrees to the right.<br />
x = x + v[d];  // Change the ant's x position based on it's heading.<br />
y = y + v[(d + 1) % 4];  // Change the ant's y position based on it's heading.<br />
</code></p></blockquote>
<p>With this revision, the 1,0,-1,0 list is specified once instead of twice and the X and Y components of the heading are derived from the same value.  I thought that this was as compact as I could make the logic.  Then I was struck by the idea of using the sine function.  A sine wave varies from 0 to 1 to 0 to -1 based on multiples of pi divided by two.  Cosine does the same thing one step out of phase.  With this insight the code becomes:</p>
<blockquote><p><code>d = (d + 1) % 4;  // rotate the ant's heading 90 degrees to the right.<br />
x = x + sin(d * PI/2); // Change the ant's x position based on it's heading.<br />
y = y + cos(d * PI/2);  // Change the ant's y position based on it's heading.</code></p></blockquote>
<p>I&#8217;m sure that to some people the relationship between the cardinal directions and the sine function is obvious, but for me it was a very cool discovery.</p>
<p>I had a lot of fun with this, and I&#8217;m looking forward to seeing which entries get picked to win by the judges, as well as seeing that future competitions hold.</p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/tweetcoding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Game: Roads to Nowhere</title>
		<link>http://disruption.ca/archives/new-game-roads-to-nowhere/</link>
		<comments>http://disruption.ca/archives/new-game-roads-to-nowhere/#comments</comments>
		<pubDate>Mon, 29 Dec 2008 00:36:25 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/archives/new-game-roads-to-nowhere/</guid>
		<description><![CDATA[On December 5th took part in the 13th Ludum Dare 48 hour game programming competition.  The theme was roads and I created a small puzzle sort of game in flash.
You can play the game online.  Roads to Nowhere Competition Version
There is also the Roads to Nowere ld48 page.
What went right:

Motivation.  For some [...]]]></description>
			<content:encoded><![CDATA[<p>On December 5th took part in the 13th Ludum Dare 48 hour game programming competition.  The theme was roads and I created a small puzzle sort of game in flash.</p>
<p>You can play the game online.  <a href="http://disruption.ca/roads/roads.html">Roads to Nowhere Competition Version</a></p>
<p>There is also the <a href="http://www.ludumdare.com/compo/?category_name=ld13&#038;author_name=erik">Roads to Nowere ld48 page</a>.</p>
<p><strong>What went right:</strong></p>
<ol>
<li><em>Motivation</em>.  For some reason the combination of theme, timing, my idea and my mood had me very motivated.  I think I spent about 22 hours in front of the computer during the compo, and that time was almost 100% productive.  The distractions of the internet sucked up very little of my time.  It was a really great feeling to get so much productive time in.  Unfortunately I couldn&#8217;t tell you exactly what the driving factor was that made my motivation level higher this time than it was last time.</li>
<li><em>Tools</em>.  I decided to work in Actionscript 3 so that my game would run in flash.  I recently wrote a tutorial on using Adobe&#8217;s freely provided mxmlc, and I found that I had no trouble building a game from what I had learned.  I even learned to use the included debugger, fdb.  It&#8217;s pretty limited, but it&#8217;s helpful in a pinch.  Though I&#8217;m still more productive with Python&#8217;s tools and libraries, I&#8217;m happy with my choice to work in AS3.  The biggest thing I miss from Python is an equivalent to iPython.  I really wish there as an interactive Actionscript 3 shell. Ultimately, being able to play the resulting game in the browser is enough of a win for me to be willing to tolerate a lot of down sides.</li>
<li><em>Idea</em>.  The Roads theme immediately had me thinking about cities collecting resources from around them by building roads to them.  Something like the resource mechanic in the early Civilization games.  With this in mind, I thought it would be interesting to try to make some sort of resource gathering puzzle game, similar to what <a href="http://www.ludumdare.com/compo/author/jolle/">Jolle</a> had done with some of his ld48 games.  I think this worked out well for me.  Interestingly, two of the reviewers of my game noticed the Jolle influence and commented on it.</li>
<li><em>Crunch Time</em>.  I fond myself at a point where I had about eight hours left in the competition, and I had zero gameplay.  I had to scale back my original idea, cut some features, stop implementing new things and start creating a game from what I had.  The final game concept, the rule system, the user interface and the levels all came together in the last hours of the weekend.  In fact, I put the levels together so quickly that I had no idea whether or not they would be interesting or fun.  Fortunately, people enjoyed the game.  There were even people that were impressed by the intricacy and design of the levels.</li>
</ol>
<p><strong>What went wrong</strong></p>
<ol>
<li><em>Pathfinding</em>.  My initial gameplay idea involved having workers transporting resources along the roads from the land into the cites.  In order for this to work, I would need path finding from each of road tiles to the cites via the road grid the player built.  I considered implementing A*, but I didn&#8217;t have an AS3 priority queue library and implementing one or finding one and learning in the short time frame didn&#8217;t appeal to me.  So instead I decided that I would do a brute force depth first search from each road tile to each city.  For performance reasons, I cached the paths that I found on intermediate tiles.  Unfortunately, this scheme can cache bad paths when a road ends in a loop.  I spent most of my programming time on Saturday, and a good part of Sunday fighting with this.  I tried working around the problem, but the performance quickly hit unacceptable levels.  I decided to start from scratch on the pathfinding, instead implementing a breadth first search starting from each city.  As the search spread out, it found all of the connected road tiles, and stored the shortest path that was used to find that tile.  I had my new algorithm up are running perfectly in about an hour.  Of course I wouldn&#8217;t have been able to implement the new scheme so quickly if I hadn&#8217;t spent so much time with the old scheme.  The most frustrating part of it was that with so much time wasted on pathfinding, I had to change my game idea to a simpler one that didn&#8217;t really need the pathfinding at all.</li>
<li><em>Graphics</em>.  I had hoped to make nice pixel art land tiles, resource gathering animations and rippling water effects.  All of these ideas got cut in my last minute scramble to put something playable together.  Instead I ended up with some crude last minute pixel art with big ugly blocks for land tiles.  While graphics have never been a big focus for my games, I think that the visual impact counts for a lot.  In this case, I think the visuals were so bad that some people might have been discouraged from giving the game a try.</li>
<li><em>Time management</em>. Spending over a quarter of my time on a pathfinding feature than was never used certainly seems like a waste of time. But I have trouble categorizing my use of time as something that really went wrong.  I had to give up on my original gameplay idea, but I ended up with gameplay that people like.  I didn&#8217;t have any time to play test the levels I made, but on the other hand I didn&#8217;t over think the levels, and people were happy with the result.  Plus there was something satisfying about grinding through the pathfinding problem and getting it working correctly in the end.
</li>
</ol>
<p><strong>Results</strong></p>
<p>My game did quite well in the competition ratings:</p>
<p><a href="http://www.ludumdare.com/compo/category/ld13/?compo_limit=59">LD48 #13 full ratings</a>.</p>
<p>6th Overall, tied for 6th in Fun, 3rd in Innovation, 7th in Use of Theme.  The scores were very close in the Fun category.  Second place had a score of 3.90, tenth place had a score of 3.80.  I received a lot of great feedback in the comments, and these are the highest scores I&#8217;ve received for a ld48 entry.  Pretty good for a game that I thought was too rushed for anyone to be interested in.</p>
<p>I&#8217;m really glad I made the last minute decision to enter this competition.  It was a lot of fun, and I made a game that a lot of people seemed to like.</p>
<p>Finally, I suggest you take a look at <a href="http://www.ludumdare.com/compo/2008/12/07/all-roads-lead-from-home/">all roads lead from home by dessgeega</a>, and <a href="http://www.ludumdare.com/compo/2008/12/07/rara-racer-finished/">Rara Racer by increpare</a>.  These two entries really made me say wow.</p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/new-game-roads-to-nowhere/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Actionscript and mxmlc</title>
		<link>http://disruption.ca/archives/actionscript-and-mxmlc/</link>
		<comments>http://disruption.ca/archives/actionscript-and-mxmlc/#comments</comments>
		<pubDate>Sat, 20 Sep 2008 03:25:32 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/archives/actionscript-and-mxmlc/</guid>
		<description><![CDATA[I think that flash is a fantastic platform for games, but the tools are expensive.  I have been curious about alternatives to Flash Studio for a while, and I decided to investigate.  The flash development environment that I was looking for:

Would be free.
Would work on OS X, Windows, and if I was lucky, [...]]]></description>
			<content:encoded><![CDATA[<p>I think that flash is a fantastic platform for games, but the tools are expensive.  I have been curious about alternatives to Flash Studio for a while, and I decided to investigate.  The flash development environment that I was looking for:</p>
<ul>
<li>Would be free.</li>
<li>Would work on OS X, Windows, and if I was lucky, Linux.</li>
<li>Would not involve working in Flex with MXML.</li>
<li>Would produce bytecode for the faster actionscript virtual machine 2 (AVM2).</li>
<li>Would allow embedding assets such as images and sound directly into the SWF file.</li>
<li>Would allow the use of existing flash libraries such as PaperVision3d and Box2dFlash.</li>
</ul>
<p><span id="more-53"></span></p>
<p>I was able to meet all of my requirements with mxmlc, the compiler that is the core of the Flex Builder SDK.  I was initially uncertain about this, as I wanted to avoid developing with the Flex framework.  Happily, I discovered that you can use mxmlc without needing a single line of XML.  Gamedev.net has a good article on <a href="http://www.gamedev.net/reference/programming/features/flex/">building flash games with mxmlc</a>, but it uses XML files to set up the build.  I&#8217;m going to discuss doing similar things while sticking to just actionscript.  I&#8217;m not really saying anything new or unknown here, I just wanted to document what I figured out, and I hope that this might be useful to someone else.</p>
<h2>Getting Started</h2>
<p>Mxmlc is a command line tool, and I assume that the reader is comfortable with the dos or unix shell.  If you using Windows, you might want to investigate FlashDevelop.  Here is nice <a href="http://www.gamepoetry.com/wpress/2008/03/26/make-flash-games-for-free/">introduction to using FlashDevelop</a>.</p>
<p>The first step is to get mxmlc.   It&#8217;s part of the <a href="http://www.adobe.com/products/flex/">Flex SDK</a>, which Adobe provides for free.  Download it and unpack it somewhere reasonable.  You might want to add the bin directory to your execution path so that you can use mxmlc without having include the full location of the command.</p>
<p>That&#8217;s all you need.  Here is an example Actionscript file that you can now build.</p>
<pre><code>
package
{
  import flash.display.Sprite;
  import flash.text.TextField;
  import flash.text.TextFormat;
  import flash.text.TextFieldAutoSize;

  [SWF(backgroundColor="#ffffff", frameRate="24", width="400", height="224")]
  public class HelloFlash extends Sprite
  {
    public function HelloFlash():void
    {
      var textfield : TextField = new TextField();

      textfield.text = "Hello Flash!!";
      textfield.autoSize = TextFieldAutoSize.LEFT;
      textfield.setTextFormat(new TextFormat(null,48));
      textfield.x = stage.stageWidth / 2 - textfield.width / 2;
      textfield.y = stage.stageHeight / 2 - textfield.height / 2;

      addChild( textfield );
    }
  }
}

</code></pre>
<p>To compile it, we use a command like the following:</p>
<p><code>~/flex_sdk_3/bin/mxmlc HelloFlash.as</code></p>
<p>And here is the resulting swf:<br />

<object	type="application/x-shockwave-flash"
			data="/files/mxmlcintro/HelloFlash.swf"
			width="400"
			height="224">
	<param name="movie" value="/files/mxmlcintro/HelloFlash.swf" />
</object>
<p>The <a href="http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&#038;file=compilers_123_04.html">command line options for mxmlc</a> are documented online.  There is also detailed information available from the compiler itself, with the mxmlc &#8211;help command.</p>
<p>The key to being able build this program with mxmlc is the [SWF] compiler meta-data tag.  It&#8217;s not properly documented on the Adobe site, but the oversight is corrected in the comments of the <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=metadata_3.html">meta-data documentation</a> page.</p>
<p>Here is an example of using an additional metadata tag to embed an image in the SWF.</p>
<pre>
<code>
package
{
  import flash.display.Sprite;
  import flash.display.Bitmap;
  import flash.display.StageQuality;

  [SWF(backgroundColor="#ffffff", frameRate="24", width="400", height="224")]
  public class HelloImage extends Sprite
  {   

    [Embed(source="cow.png")]
    private var Picture:Class;

    public function HelloImage():void
    {
      var pic:Bitmap = new Picture();

      pic.width *= 4;
      pic.height *= 4;

      pic.x = stage.stageWidth / 2 - pic.width / 2;
      pic.y = stage.stageHeight / 2 - pic.height / 2;

      addChild( pic );
    }
  }
}
</code></pre>

<object	type="application/x-shockwave-flash"
			data="/files/mxmlcintro/HelloImage.swf"
			width="400"
			height="224">
	<param name="movie" value="/files/mxmlcintro/HelloImage.swf" />
</object>
<p>If you&#8217;d like to read more, here is a blog entry detailing the use of the <a href="http://www.bit-101.com/blog/?p=853">embed tag</a>.  Here is another blog entry, describing more <a href="http://dispatchevent.org/roger/embed-almost-anything-in-your-swf/">advanced embed techniques</a>.</p>
<p>Finally here is an example of using an external library.  I&#8217;ve added a simple animation using the <a href="http://blog.greensock.com/tweenliteas3/">TweenLite</a> library.</p>
<pre>
<code>
package
{
  import flash.display.Sprite;
  import flash.display.Bitmap;

  import flash.events.Event;
  import flash.events.MouseEvent;

  import gs.TweenLite;
  import gs.easing.*;

  [SWF(backgroundColor="#ffffff", frameRate="30", width="400", height="224")]
  public class HelloTween extends Sprite
  {   

    [Embed(source="cow.png")]
    private var Picture:Class;

    public function HelloTween():void
    {
      var pic:Bitmap = new Picture();
      var running:Boolean = false;

      pic.width *= 4;
      pic.height *= 4;

      pic.x = 10;
      pic.y = 10;

      var myTween:TweenLite;

      function tween1():void {
        myTween = TweenLite.to(pic, 2, {x:stage.stageWidth-10-pic.width,
                                        y:stage.stageHeight-10-pic.height,
                                        ease:Bounce.easeOut,
                                        onComplete:tween2});
      }

      function tween2():void {
        myTween = TweenLite.to(pic, 2, {x:10,
                                        y:10,
                                        ease:Bounce.easeOut,
                                        onComplete:
                                           function ():void {
                                             running = false;
                                           }});
      }

      function clickHandler(e:Event):void {
        if(! running) {
          tween1();
          running = true;
        }
      }

      stage.addEventListener(MouseEvent.CLICK, clickHandler);

      addChild( pic );
    }
  }
}

</code>
</pre>
<p>In order to compile this, you need to specify the location of the library as part of the source path.<br />
<code>mxmlc -compiler.source-path+=~/code/flash/TweenLiteAS3/ HelloTween.as</code></p>
<p>Click the cow to see the animation in action:<br />

<object	type="application/x-shockwave-flash"
			data="/files/mxmlcintro/HelloTween.swf"
			width="400"
			height="224">
	<param name="movie" value="/files/mxmlcintro/HelloTween.swf" />
</object>
<p>That&#8217;s all I have to show for now.  I think once you know how to use it, mxmlc provides all the building blocks you need for full featured flash projects.</p>
<p>Here is a zip file bundling all of the code and files.  <a href="/files/mxmlcintro/mxmlcintro.zip">mxmlcintro.zip</a>  Everything is public domain, except for the cow image, which belongs to <a href="http://www.wardtek.ca/">Jay</a>.  You would have to ask his permission if you would like to use it.</p>
<h2>Alternatives</h2>
<p>Command line mxmlc might not be right for you.  <a href="http://www.flashdevelop.org/community/">FlashDevelop</a>, which I mentioned earlier, can serve as an IDE and GUI for mxmlc, making it a nice option for Windows users.   Other compiler alternatives Include <a href="http://www.mtasc.org/">MTASC</a>, which compiles Actionsscript 2 for the original Actionscript virtual machine, and <a href="http://haxe.org/">HaXe</a> which is a language with tools that will build for multiple targets, including AVM2 SWFs.</p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/actionscript-and-mxmlc/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Imageboard</title>
		<link>http://disruption.ca/archives/imageboard/</link>
		<comments>http://disruption.ca/archives/imageboard/#comments</comments>
		<pubDate>Sat, 10 Mar 2007 21:12:40 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/archives/imageboard/</guid>
		<description><![CDATA[
Last month there was an informal weekend long game development competition that   Jay and I were planning on participating in.  One of the themes chosen was &#8220;anti-text&#8221;.  The voting was happening in IRC, and Jay suggested that we create a textless IRC. The idea of making something like a web based [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/misc/mouse.png" /></p>
<p>Last month there was an informal weekend long game development competition that   Jay and I were planning on participating in.  One of the themes chosen was &#8220;anti-text&#8221;.  The voting was happening in IRC, and Jay suggested that we create a textless IRC. The idea of making something like a web based pictochat was kicked around, and after spending the weekend working on it we ended up with <a href="http://imageboard.net">imageboard.net</a>.</p>
<p>We built a site that is like a web based discussion form, except that you draw low resolution pixel art instead of typing text.  I made the pixel art application in Flash, and Jay did the backend in Python, as well as the HTML/CSS/Javascript.  Our icons on the web interface were contributed by users.</p>
<p>The site has resulted in some awesome pixel art, as well as some really clever image threads.  For example, <a href="http://www.imageboard.net/298/">chickenz</a> is one of my favorites.</p>
<p>Here are the <a href="http://www.imageboard.net/top/">top voted images, animations, and threads</a>.</p>
<p>Here are the <a href="http://www.imageboard.net/user/12/">images that I have signed</a>.</p>
<p>Now that you are done reading this, go draw something.  The site is more interesting when more people are playing with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/imageboard/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adventures In Actionscript</title>
		<link>http://disruption.ca/archives/adventures-in-actionscript/</link>
		<comments>http://disruption.ca/archives/adventures-in-actionscript/#comments</comments>
		<pubDate>Thu, 21 Sep 2006 23:17:33 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/?p=48</guid>
		<description><![CDATA[I&#8217;ve been interested in porting Bee Commander to flash for a while, but I haven&#8217;t devoted much time to it.  I did get the basic bee swarming working though.  Let me tell you about my adventure.
When I wrote the main update loop I discovered that Actionscript lacks a foreach construct.  Boo. I [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been interested in porting <a href="/games/bee-commander/">Bee Commander</a> to flash for a while, but I haven&#8217;t devoted much time to it.  I did get the basic bee swarming working though.  Let me tell you about my adventure.</p>
<p>When I wrote the main update loop I discovered that Actionscript lacks a foreach construct.  Boo. I guess it&#8217;s back to C style for loops.  So I came up with the following:</p>
<blockquote><p><code></p>
<pre>
for(i = 0; i < length(bees); i++) {
	bees[i].update()
}
</pre>
</pre>
<p></code></p></blockquote>
<p>Looks reasonable, doesn&#8217;t it?  It&#8217;s brutally slow.  On my desktop the Python code can make 200 bees look good using hardware rendering, but in flash with this code it struggled to draw 25 bees at 30fps.  I had to really fight to figure out where the problem was.  It turns out that length(array) in Actionscript isn&#8217;t the same thing as len(array) in Python.  The length function returns the number of characters in a string, not the length of an array.  So why does the above work at all?  And why does it run so slowly?</p>
<p>When I call length(bees), actionscript casts the array of bee objects into a single string containing the names of all the objects in the array, giving something like: &#8220;_level0.bee0,_level0.bee1,_level0.bee2&#8230;&#8221;  It then walks the length of this string to count the characters, and returns that value.  So what happens with the bees[i].update() when the index passes the end of the array?  Nothing.  The array access fails silently, and the loop continues.  So the code calls update on every bee in the array, and the bees move correctly.  It just happens very, very slowly.  How slow?  Well, if n is the number of elements in the array,  length() walks a string of length 13n, and it does this 13n times before i < length(bees).  So it's doing O(n^2) work to solve a problem that should be O(1).  Throw in the overhead of the string conversion, and the extra length that it adds to the array, and it becomes easy to see why it is so painfully slow.</p>
<p>It seems that the correct way to loop across an array in Actionscript is like this:</p>
<p>
<blockquote><code>
<pre>
for (i in bees) {
	bees[i].update()
}
</pre>
<p></code></p></blockquote>
<p>After years of Perl and Python, this just seems weird.  It&#8217;s like a foreach operator, but it returns the index instead of the value.  Also, the magic &#8220;in&#8221; only seems to work in the context of the for loop.  I guess it has something to do with the way arrays relate to objects in Actionscript.  Take a look at this example:</p>
<blockquote><p><code>
<pre>
a = [1,2,3]
a.myName = 'bob'
for (i in a) {
	trace(i)
}
</pre>
<p></code></p></blockquote>
<p>The output is:</p>
<blockquote><p><code>
<pre>
myName
2
1
0
</pre>
<p></code></p></blockquote>
<p>Weird weird weird.  You might think that this implies that array indexes can be accessed in the same manner as an object&#8217;s instance variables, and that a.1 is the same as a[1], but no that doesn&#8217;t work.</p>
<p>I don&#8217;t quite grok Actionscript yet, but I have bees swarming in flash reasonably well with the for(&#8230; in &#8230;) loop.  If you have at least flash 7, you can check out <a href="/files/flash/beedemo/beedemo.html">my bad actionscript demo</a>.</p>
<p>In other news I&#8217;ve been reading up on continuations.  I&#8217;m fascinated by the way that <a href="http://www.seaside.st/">Seaside </a>takes tracking state in web based applications, and turns it into a list of imperative function calls.  I wonder if I could do something similar for the structure of my games.  Every time I work on handling levels and menus, animated clips, or any other number of tasks that require tracking state I feel like I&#8217;m writing bad hackish code and that there must be an elegant way to do it.</p>
<p>One last thing, Todd, Jay and I recently participated in the <a href="http://pyweek.org/3/">third PyWeek</a> game programming competition.  <a href="http://pyweek.org/e/DoR/">Shadow Runner</a> is the name of our game, and it turned out to be kind of neat.</p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/adventures-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Live Coding, Continued</title>
		<link>http://disruption.ca/archives/live-coding-continued/</link>
		<comments>http://disruption.ca/archives/live-coding-continued/#comments</comments>
		<pubDate>Tue, 29 Aug 2006 23:25:34 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/?p=47</guid>
		<description><![CDATA[I have spent some time on further experiments with live coding and it seems to get tricky when you start using state.  If you are loading and executing all of your code every frame, how do you handle tasks like animation?  How do you load an image and cache it so you don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>I have spent some time on further experiments with <a href="/archives/live-coding-games-in-python/">live coding</a> and it seems to get tricky when you start using state.  If you are loading and executing all of your code every frame, how do you handle tasks like animation?  How do you load an image and cache it so you don&#8217;t have to reload every frame?</p>
<p>One approach I played with, just for fun, was animation without maintaining any state information.  I have slightly expanded on my previous controller script.  The major differences are that my new version will now print a stack trace if the current exception is different from the last exception.  With the old script, if you eliminated one exception from your code, but a second exception prevented execution, no stack trace would be displayed.  Also, this controller passes the livegame script the frame count when it calls play.  You can view the updated script here: <a href="/files/livepython/controller_stateless.py">controller_stateless.py</a>.</p>
<p>Here is my <a href="/files/livepython/livegame_stateless.py">livegame_stateless.py</a>:</p>
<blockquote><p><code>
<pre>
fps = 30
screenWidth = 640
screenHeight = 480

# check to see if the pygame module is in the namespace
try:
    pygame
except NameError:
    # pygame doesn't exsist, so import it.
    # this only happens once.
    import pygame
    from pygame.locals import *

    # initialize the pygame display
    pygame.init()
    pygame.display.set_mode((screenWidth,screenHeight),0,32)
    display = pygame.display.get_surface()

    # initialize the pygame clock
    clk = pygame.time.Clock()

def getMotion(framecount, shapeSize, screenSize, velocity):
    """
        Calculates a linear position using a step number, a
        velocity, and a derived range of motion.

        Returns the position.
    """

    # calculate the range of motion:
    workingSize = (screenSize - shapeSize) / velocity

    # use mod to find position in the range of motion.
    # *2 is used to bounce back and forth inside the range
    pos = framecount % (workingSize * 2)   

    # if we are greater than the initial size, we are moving
    # in the opposite direction.
    if pos > workingSize:
        pos = 2*workingSize - pos

    return pos * velocity

def play(framecount):
    """ Main game logic, called once per frame."""

    # fill the display with black.  Clears the screen.
    pygame.draw.rect(display, (0,0,0,255),(0,0,screenWidth,screenHeight))

    shapeColor = (10,80,10,255)
    shapeWidth = 30
    shapeHeight = 30

    xVel = 10.0 # velocity in pixels per frame
    yVel = 10.0

    x = getMotion(framecount, shapeWidth, screenWidth, xVel)
    y = getMotion(framecount, shapeHeight, screenHeight, yVel)

    # draw a shape.
    pygame.draw.ellipse(display, shapeColor,(x,y,shapeWidth,shapeHeight))

    # update the display.
    pygame.display.flip()

    # check for events, and return true if we get an exit signal.
    events = pygame.event.get()
    for event in events:
        if event.type == QUIT or (event.type == KEYDOWN
                                    and event.key == K_ESCAPE):
            return True

    # try to maintain a set frame rate.
    clk.tick(fps)

    # No exit signal was recived, so return false.
    return False
</pre>
<p></code></p></blockquote>
<p>This code isn&#8217;t truly stateless.  I use the Pygame module loading to do some Pygame initialization and window setup.  Even this could be removed, but you would need a very fast machine to be able to recreate the pygame window every frame at a decent framerate.  I&#8217;ve tried it though, and it is pretty cool to be able to change your window size mid run by tweaking your initialization parameters.</p>
<p>The animation produced by this code is stateless.  And the code was surprisingly easy to write.  It would be interesting to see how far you could push this approach.   I think that it would rapidly become impossible to work with, as any sort of complex program would need to be passed all of the previous user input as a parameter to the play function.  While it would be interesting to try to write a game that constantly derived it&#8217;s state from a time coded array of past user input, I doubt it would be fruitful.  I suppose games like chess could read a board state and return a new board state every frame.  Its great, from a mental exercise point of view, but I expect a dead end productivity wise.</p>
<h3>Caching</h3>
<p>So, onward to the next approach.  Caching.  This essentially boils down to having some code that isn&#8217;t run every frame.  For example, if I wanted to move a box across the screen, I could use some special code to initialize it&#8217;s x position to 0, and then the live code that runs every frame increments the position by 1.  You rapidly run into problems with this approach though.  For some interesting reading on the topic of state and live coding, take a look at <a href="http://programming.reddit.com/info/c5lk/comments/cc6wf">this reddit comment</a>.</p>
<p>When I started working on this approach, I immediately ran into problems where my initialized state wasn&#8217;t in sync with my live code.  To expand on the box moving example, lets suppose that I want to add a second moving box.  So I add a line of code to the initialization section that sets x2 to 0, and I add my code to the live section to increment x2 by 1 every frame.  Should work, right?  Nope.  If you do this while the code is live, you get an exception because x2 was never initialized, because the init code hasn&#8217;t been re-run since you added x2.  I don&#8217;t have a solution for this that I am really happy with, but I have a couple of hacks that go a long way towards eliminating this problem.  One is having &#8216;r&#8217; keypresses call the init function.  This helps a little.  You could add x2 to the init, save, press &#8216;r&#8217;, add x2 to the live segment, and save again.  But that sucks.  The other hack I added was to the controller.  I put the controller in charge of the initialization function at start up.  Also, if the controller encounters an exception when calling play() on the livegame, it attempts to call the init function, to see if resetting the system will resolve the exception.  I&#8217;m not really happy with my implementation, but you can take a look at it here: <a href="/files/livepython/controller_hackish.py">controller_hackish.py</a>.</p>
<p>Here is the corresponding <a href="/files/livepython/livegame_hackish.py">livegame_hackish.py</a>.    To run this, you will need an image.  I use my pixel art alien:</p>
<p><img src="/files/livepython/eyealien.png" alt="Eye Alien" /></p>
<blockquote><p><code>
<pre>
fps = 30
width = 640
height = 480

import random

class Alien:
    """
       Effectivly a very simple sprite class, with it's properties
       defined in it's init code.
    """

    def __init__(self):
        self.alienImage = pygame.image.load('eyealien.png')
        self.alienImage.convert_alpha()

        self.pos = [50,50]
        self.direction = [1,1]

        self.velocity = [2.5, 2.5]

    def draw(self, display):
        display.blit(self.alienImage, self.pos)

    def update(self):
        """
            Update is called every frame.
            Adjust the alien's position based on it's
            velocity.
        """

        if self.pos[0] > ( width - self.alienImage.get_width() ) \
                or self.pos[0] < 0:
            self.direction[0] *= -1

        if self.pos[1] > ( height - self.alienImage.get_width() ) \
                or self.pos[1] < 0:
            self.direction[1] *= -1

        self.pos[0] += self.velocity[0] * self.direction[0]
        self.pos[1] += self.velocity[1] * self.direction[1]  

# Ugh, has to be global because it is initialized in a function
# and used in a different scope.
global alien

def initState():
    """
        Called by the controller, used to initialize variables
        and objects that maintain state.
    """
    global alien

    alien = Alien()

# check to see if the pygame module is in the namespace
try:
    pygame
except NameError:
    # pygame doesn't exsist, so import it.
    # this only happens once.
    import pygame
    from pygame.locals import *

    # initialize the pygame display
    pygame.init()
    pygame.display.set_mode((width,height),0,32)
    display = pygame.display.get_surface()

    # initialize the pygame clock
    clk = pygame.time.Clock()

    initState()

def play():
    """ Main game logic, called once per frame."""
    global alien

    # fill the display with black.  Clears the screen.
    pygame.draw.rect(display, (0,0,0,255),(0,0,width,height))

    # draw a shape.
    pygame.draw.ellipse(display, (180,40,200,255),(200,160,100,50))

    # move the alien
    alien.update()

    # draw the alien
    alien.draw(display)

    # update the display.
    pygame.display.flip()

    # check for events, and return true if we get an exit signal.
    events = pygame.event.get()
    for event in events:
        if event.type == KEYDOWN and event.key == K_r:
            # reinitialize the program state.
            initState()
        if event.type == QUIT or (event.type == KEYDOWN
                                    and event.key == K_ESCAPE):
            return True

    # try to maintain a set frame rate.
    clk.tick(fps)

    # No exit signal was recived, so return false.
    return False
</pre>
</pre>
<p></code></p></blockquote>
<p>The above code loads an image, and uses an object in a way that maintains state across frames.  There are a few things that I don&#8217;t like about it though.  One is the globals.  I had to make my alien object global, because I initialize it in a function and then use it outside of that function&#8217;s scope.  It&#8217;s ugly, and I don&#8217;t know if python offers a better way to do it.  The other problem is related to the contents of the reddit comment I linked to above.  When my alien object is initialized, it captures the code of it&#8217;s methods.  Which means that the method code is not live.  If you change the Alien.draw() method for example, the change doesn&#8217;t take effect when you save the file.  You must reinitialize the system to get an alien object that uses the new code.  It&#8217;s possible to work with this, but it doesn&#8217;t fit with the spirit of keeping everything ultra-dynamic for live coding.</p>
<p>It would be really nice if a Python guru could just hand me a framework that addressed all of the problems, and made live coding a completely painless process.  I really think this sort of thing could make for an amazing game development environment.  I just wish I had more free time to work through the quirks.</p>
<p>Not on the topic of live coding, but still along the lines of game development and python dynamism, I recently discovered a Python project called Bruce the Presentation Tool.  I don&#8217;t know much about it, buy one feature caught my eye.  It has an interactive Python shell running inside a Pygame window.  I imagine that this could be very useful for introspection when working with Pygame.  In the past I&#8217;ve had a lot of success with using a keystroke to spawn an iPython shell in the console window I&#8217;ve launched my game from.  It&#8217;s extremely useful for debugging and experimentation.  I imagine that a deeper embedding of the shell might be even better.</p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/live-coding-continued/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Live Coding Games in Python</title>
		<link>http://disruption.ca/archives/live-coding-games-in-python/</link>
		<comments>http://disruption.ca/archives/live-coding-games-in-python/#comments</comments>
		<pubDate>Wed, 02 Aug 2006 23:14:18 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Programing]]></category>

		<guid isPermaLink="false">http://disruption.ca/?p=46</guid>
		<description><![CDATA[Reddit recently lead me to Logan Koester&#8217;s blog post about live coding with Python, and I found it fascinating.  Live Coding is the practice of editing code for a running program in an environment that loads in the changes as they are made.  Apparently people do this as a performance art, writing programs [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://reddit.com">Reddit</a> recently lead me to <a href="http://www.logankoester.com/mt/2006/07/live_coding_with_python_1.html">Logan Koester&#8217;s blog post about live coding with Python</a>, and I found it fascinating.  Live Coding is the practice of editing code for a running program in an environment that loads in the changes as they are made.  Apparently people do this as a performance art, writing programs on the fly to play music.  There is even a <a href="http://en.wikipedia.org/wiki/Live_coding">Wikipedia article on live coding</a>.</p>
<p>I tried out the examples on Logan&#8217;s page, generated some weird drum loops, and had some fun with it all.  The experience was a reminder that I want to learn how to make music.  But it also opened my eyes to what seems like a new approach to programming.</p>
<p>After 30 seconds of looking I have failed to find a good reference on this, but I have read that a major factor in programmer productivity is the turnaround time between editing code and testing the results.  If you are working on big project with a slow build process making changes takes a long time.  Because changing too many things at once is a bad idea, you have to spend a lot of time waiting to test your code. If you are working on a small project in a scripting language, then it&#8217;s just save and run with little waiting to see the results of your edits.</p>
<p>What if we take this a step further?  Are there productivity gains to be found through live coding, where you see the results of your changes when you save the code?  I&#8217;ve decided it&#8217;s a neat idea, and I want to explore it.  Since most of my programming focuses on game development, I tried out live coding with PyGame.  What can I say?  Recompiling your game&#8217;s codebase every frame strikes me as a wonderful way to trade cpu cycles for increased programmer productivity.</p>
<p>The first step is building the controlling script that does the live coding magic.  I started with Logan&#8217;s example, but I wanted to do a couple of things differently.  The first is I wanted to see a message and a backtrace for both syntax and runtime errors.  The second is that I wanted the host and the client to be largely independent.  Here is my controller.</p>
<p><a href="/files/livepython/controller.py">controller.py</a>:</p>
<blockquote><p><code>
<pre>
import traceback
import StringIO

from time import sleep

done = False
imported = False
loadBroken = False
runBroken = False

def genTraceback(ErrString):
    """ Takes an error message as an arguemnt.
        Generates a traceback of the most recent
        exception, and prints it with the error
        message.  Sleeps for 2 seconds before
        returning.
    """
    fp = StringIO.StringIO()
    traceback.print_exc(file=fp)
    message = fp.getvalue()

    print ErrString,"\n", message
    print "\nFix livegame.py to continue.\n"

    sleep(2) 

# loop until we sucessfully import livegame.py
while not imported:
    try:
        import livegame
    except:
        if not loadBroken:
            genTraceback("Failed to import livegame.py.")
            # set a flag so that the traceback is only printed
            # once
            loadBroken = True
    else:
        imported = True

# loop until livegame.play() returns True
while not done:

    # attempt to reload the code
    try:
        reload (livegame)
    except:
        # if the reload fails, print the traceback once.
        if not loadBroken:
            genTraceback("livegame.py is broken.")
            loadBroken = True

    else:
        loadBroken = False

        # if the reload is succesful, try to run livegame.play()
        try:
            done = livegame.play()
        except:
            if not runBroken:
                genTraceback("play() in livegame.py is broken.")
                runBroken = True

        else:
            runBroken = False
</pre>
<p></code></p></blockquote>
<p>Sorry for the <code>&#92;"</code> silliness in the above code.  It seems to be a wordpress bug.  Anyway, what the above code does is load livegame.py and then reload it in a loop, calling livegame&#8217;s play function every time.  Thanks to the traceback and StringIO modules, it outputs both syntax and runtime error tracebacks to the console seamlessly.</p>
<p>Here is a very basic <a href="/files/livepython/livegame.py">livegame.py</a>:</p>
<blockquote><p><code>
<pre>
fps = 10
width = 640
height = 480

# check to see if the pygame module is in the namespace
try:
    pygame
except NameError:
    # pygame doesn't exsist, so import it.
    # this only happens once.
    import pygame
    from pygame.locals import *

    # initialize the pygame display
    pygame.init()
    pygame.display.set_mode((width,height),0,32)
    display = pygame.display.get_surface()

    # initialize the pygame clock
    clk = pygame.time.Clock()

def play():
    """ Main game logic, called once per frame."""

    # fill the display with black.  Clears the screen.
    pygame.draw.rect(display, (0,0,0,255),(0,0,width,height))

    # draw a shape.
    pygame.draw.ellipse(display, (0,40,200,255),(200,200,100,50))

    # update the display.
    pygame.display.flip()

    # check for events, and return true if we get an exit signal.
    events = pygame.event.get()
    for event in events:
        if event.type == QUIT or (event.type == KEYDOWN
                                    and event.key == K_ESCAPE):
            return True

    # try to maintain a set frame rate.
    clk.tick(fps)

    # No exit signal was recived, so return false.
    return False
</pre>
<p></code></p></blockquote>
<p>The first time this code is run, it initializes PyGame and creates a window.  Every time play is called, it clears the window, draws a blue ellipse, checks for events, and then sleeps long enough to try to maintain a set framerate.  If you press the escape key livegame signals the controller script, and the controller exits.  To see where things get interesting, change this line:</p>
<pre><code>
<blockquote>pygame.draw.ellipse(display, (0,0,255,255),(200,200,100,50))</blockquote>

</code></pre>
<p>to something like this:</p>
<pre><code>
<blockquote>pygame.draw.rect(display, (255,0,0,255),(200,200,200,100))</blockquote>

</code></pre>
<p>Save the change with the PyGame window open beside your text editor, and watch the small blue ellipse instantly turn into a larger red rectangle.  A basic example, I admit.  But it hints at very deep potential.</p>
<p>The next step is taking this live environment, and building a full game using it.  I intend to give it a try, hopefully soon.  It will take some cleverness to keep things both dynamic and running fast enough.  I might have to set up some sort of caching system so that expensive operations, such as loading an image or level from disk, don&#8217;t happen every frame.  I could perhaps bind a key so that the expensive stuff is only done on request, but I think the experiment will be most interesting if I keep that sort of thing to a minimum.</p>
<p>There are obvious improvements to the above code that could be made, but I wanted to keep things as simple as possible.  Though I do want to add more features before I make an attempt at building something significant using the live environment.  I hope to modify the controller so that it takes the name of its client as a command line argument.  I would like it if the controller gave some sort of audible notification if the client code caused an exception and produced a new traceback.  I will see if I can use Ipython&#8217;s handy syntax highlighting for the controller&#8217;s tracebacks.  It would also be neat to modify the client code to use the python <code>if name == '__main__'</code> trick. Then the client could optionally run as an independent program without the controller.  This would also allow changing settings such as the target frames per second based on the environment the code is running in.</p>
<p>If I haven&#8217;t stated it enough already this post: this approach opens up lots of interesting possibilities.  The only downside is that some day I&#8217;m going to start writing flash games that run directly in the browser.  When I do that, I&#8217;m really going to miss all this dynamic language magic that I&#8217;m learning to use with Python.</p>
<p><strong>Edit:</strong> I&#8217;ve posted an update, <a href="/archives/live-coding-continued/">Live Coding, Continued</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://disruption.ca/archives/live-coding-games-in-python/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
