<?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>Jason Mooberry &#187; javascript</title>
	<atom:link href="http://blog.jasonmooberry.com/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jasonmooberry.com</link>
	<description>Stuff I did for you.</description>
	<lastBuildDate>Sat, 29 Oct 2011 23:41:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.2</generator>
		<item>
		<title>The how behind the homepage</title>
		<link>http://blog.jasonmooberry.com/2011/10/the-how-behind-the-homepage/</link>
		<comments>http://blog.jasonmooberry.com/2011/10/the-how-behind-the-homepage/#comments</comments>
		<pubDate>Sat, 29 Oct 2011 23:18:23 +0000</pubDate>
		<dc:creator>Jason Mooberry</dc:creator>
				<category><![CDATA[Fun]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[cellular automata]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.jasonmooberry.com/?p=302</guid>
		<description><![CDATA[I recently built a new homepage to celebrate Fall and kill a few weekends playing with canvas, javascript and CA. A little while back I had an idea to use Cellular Automata rules to generate random groupings of xy coordinates. This worked well as a way to generate a rock pattern for my canvas drawing. [...]]]></description>
			<content:encoded><![CDATA[<p>I recently built a <a href="http://jasonmooberry.com">new homepage</a> to celebrate Fall and kill a few weekends playing with canvas, javascript and CA.</p>
<p>A little while back I had an idea to use <a href="http://en.wikipedia.org/wiki/Cellular_automaton">Cellular Automata</a> rules to generate random groupings of xy coordinates.  This worked well as a way to generate a rock pattern for my <a href="http://blog.jasonmooberry.com/2011/05/death-valley-cellular-automata-and-html5-canvas/">canvas drawing</a>.  I even developed a <a href="http://local.jasonmooberry.com/dev/ca_helper.html">little tool</a> to help me refine the parameters to use that produced the pattern I wanted.</p>
<style>
#tools { margin:10px auto; width:620px; height:300px; }
#tools img { border:1px solid #ccc; }
</style>
<div id="tools">
<a href="http://jasonmooberry.com/dev/ca_fluid_animation.html" style="float:right;"><img src="http://jasonmooberry.com/dev/img/ca_animator.gif" /></a><br />
<a href="http://jasonmooberry.com/dev/ca_helper.html" style="float:left;"><img src="http://jasonmooberry.com/dev/img/ca_helper.gif"  /></a>
</div>
<p>I wanted to expand on that approach to make something more abstract and vizzy.  And animation seemed like the next step.  So I built <a href="http://jasonmooberry.com/dev/ca_fluid_animation.html">another tool</a> that allowed me to play around with animating generated CA sets of cells from one state to the next. </p>
<p>It lets you embed js into the callbacks for the driving parameters and even saves your settings into the hash tag so you can bookmark settings that you like and link to them.</p>
<p>So I&#8217;m publishing them both here for you to play with.  <img src='http://blog.jasonmooberry.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jasonmooberry.com/2011/10/the-how-behind-the-homepage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Drawing with Cellular Automata and HTML5 Canvas</title>
		<link>http://blog.jasonmooberry.com/2011/05/death-valley-cellular-automata-and-html5-canvas/</link>
		<comments>http://blog.jasonmooberry.com/2011/05/death-valley-cellular-automata-and-html5-canvas/#comments</comments>
		<pubDate>Wed, 11 May 2011 03:00:22 +0000</pubDate>
		<dc:creator>Jason Mooberry</dc:creator>
				<category><![CDATA[Fun]]></category>
		<category><![CDATA[Me]]></category>
		<category><![CDATA[cellular automata]]></category>
		<category><![CDATA[game of life]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[PHI]]></category>

		<guid isPermaLink="false">http://blog.jasonmooberry.com/?p=227</guid>
		<description><![CDATA[This weekend I set out to do some canvas drawings. The first one ended up being the centerpiece of my home page. It was inspired by the leaves of a tree on my street. Oh it&#8217;s good to be back in the deciduous loving climate. The second drawing was inspired by a recent campout in [...]]]></description>
			<content:encoded><![CDATA[<p>This weekend I set out to do some canvas drawings.  The first one ended up being the centerpiece of my <a href="http://jasonmooberry.com" target="_blank">home page</a>.  It was inspired by the leaves of a tree on my street.  Oh it&#8217;s good to be back in the deciduous loving climate.</p>
<p>The second drawing was inspired by a recent campout in Death Valley.  The contrast of the blue sky, desert floor, and red coleman tent leave a strong imprint on me every time.</p>
<div style="text-align:center;">
<a href="http://jasonmooberry.com/dev/img/dv.jpg" target="_blank" ><img src="http://jasonmooberry.com/dev/img/dv_sm.jpg" style="margin:10px;" /></a> <a href="http://jasonmooberry.com/dev/dv_drawing.html" target="_blank"><img src="http://jasonmooberry.com/dev/img/dv_drawing.jpg" style="margin:10px;width:300px;height:225px;" /></a>
</div>
<p>The end result should resemble the <a href="http://jasonmooberry.com/dev/dv_drawing.html" target="_blank">picture on the right.</a>  The page load time is a few seconds on my MBP and it looks quite a lot better in Chrome.  The canvas size is determined at load so if you have the horses, full-screen your browser.  </p>
<p>I say resemble because the drawing is generated using canvas and cellular automata, and derived from a random data set every time it is rendered.  </p>
<p>One of the difficulties of drawing a picture of landscape is the seemingly random variations found in it.  Not totally random because each element interacts and affects the others.  The stone pattern on the drawing was the first thing I set out to solve.</p>
<p>Initially I was hoping to hit on some semi-random scatter pattern using PHI and a lot of trial and error.  This produced a fairly uniform random scatter of stones.  What I wanted to draw resembled clumps more than anything.  </p>
<p>While scatter patterning away I happened to over hear a gentlemen at the coffee shop mentioning cellular automata and emergent systems as they explain the state of the universe.  It&#8217;s kindof a hippie coffee shop but this guy is clearly in a league of his own.  At first I dismissed it and then the idea grew on me that I could generate these clumps with CA.  I had used CA for Conway&#8217;s game of life and a few other toy systems to experiment in the past and it was always fun.</p>
<p>So I generated a map of pixels that were randomly turned on.  I weighted the initial data set to be very switched on (baby!).  My reasoning was that I wanted grouping to occur within a few mutations and a seriously overcrowded starting set should do just that.  The size of the canvas element was prohibitively large so I added a resolution factor.  It causes striations in the starting set view but it doesn&#8217;t affect the CA mutations.</p>
<pre>
// set up psuedo random cell set
for (var i=0; i < total; i++) {
  if (Math.random() > .2) {
    cells[i] = 1;
  }
}
</pre>
<div style="text-align:center;"><a href="http://jasonmooberry.com/dev/ca_helper.html" target="_blank"><img src="http://jasonmooberry.com/dev/img/dv_initial_set.gif" /></a><br />
with resolution factor:<br />
<a href="http://jasonmooberry.com/dev/ca_helper.html" target="_blank"><img src="http://jasonmooberry.com/dev/img/dv_initial_set_r.gif" /></a></div>
<p>Let&#8217;s grind this set down with Conway&#8217;s game of life rules and see what comes out:</p>
<pre>
// mutate m number of times
while (m--) {
  var next = {};
  for (p in cells) { next[p] = 1; }

  for (var i=0; i < total; i++) {
    var above = i-w < 0 ? i-w+total : i-w,  // wrap
      below = i+w > total ? i+w-total : i+w, // wrap
      neighbors = [above-1,above,above+1,i-1,i+1,below-1,below,below+1],
      active = 0,
      j = neighbors.length-1;

    while (j--) {
      active += (typeof cells[neighbors[j]] === 'number' &#038;&#038; cells[neighbors[j]] === 1)|0;
    }
    // rule check
    // Any dead cell with exactly three live neighbours becomes a live cell.
    if (active === 3 &#038;&#038; typeof cells[i] === 'undefined') {
      next[i] = 1;
    }
    // Any live cell with two or three live neighbours lives on to the next generation.
    // Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
    // Any live cell with more than three live neighbours dies, as if by overcrowding.
    else if (active < 2 || active > 3) {
      delete next[i];
    }
  }
  var cells = {};
  for (p in next) { cells[p] = 1; }
}
</pre>
<div style="text-align:center;"><a href="http://jasonmooberry.com/dev/ca_helper.html" target="_blank"><img src="http://jasonmooberry.com/dev/img/dv_pass_1.gif" /></p>
<p><img src="http://jasonmooberry.com/dev/img/dv_pass_3.gif" /></p>
<p><img src="http://jasonmooberry.com/dev/img/dv_pass_8.gif" /></a></div>
<p>As you can see the first pass cleared out a bunch of em.  The resolution factor has spaced the pixels apart but you can see the basics of game of life players emerging.  By pass 3 it&#8217;s in a much more spare state but still larger groups than I want.  By pass 8 the groups have moved away from each other a bit more and formed a decent pattern. Since this pattern is generated fresh from a random data set every time, we just need something that&#8217;s right most of the time.  </p>
<p>What I like about this approach is that it gives some credence to the hippie coffee shop guy&#8217;s words.  I don&#8217;t think the world runs on CA rules, but iterative, interactive rules seem to give rise to interesting &#8220;random&#8221; patterns.</p>
<p>The dataset produced from these mutations can now be used to render a rock pattern with a little magic for the coloring/size.  </p>
<pre>
for (var i in cells) {
  c.beginPath();
  var x = (i*r)%w,
    y = (i*r)/w|0;
  c.strokeStyle = (['rgba(116,116,108,.7);','rgba(87,93,55,.9);'])[i%15===0|0];
  c.lineWidth = Math.max(30,50*(y/h));
  c.arc(x,y,3,0,360,false);
  c.stroke();
}
</pre>
<div style="text-align:center;"><a href="http://jasonmooberry.com/dev/ca_helper.html" target="_blank"><img src="http://jasonmooberry.com/dev/img/dv_render.gif" /></a></div>
<h3>tl dr;</h3>
<p>Using Cellular Automata rules to mutate random datasets can produce interesting and unique landscape patterns.  This approach was super useful for me in drawing an impressionist picture of my favorite camping spot.</p>
<p>I wrote a <a href="http://jasonmooberry.com/dev/ca_helper.html" target="_blank">simple tool</a> to experiment with different factors for generating these patterns.</p>
<p>And <a href="http://jasonmooberry.com/dev/dv_drawing.html" target="_blank">here&#8217;s the picture</a> that is generated from random CA patterns.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jasonmooberry.com/2011/05/death-valley-cellular-automata-and-html5-canvas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ecsmas and Tron</title>
		<link>http://blog.jasonmooberry.com/2010/12/ecsmas-and-tron/</link>
		<comments>http://blog.jasonmooberry.com/2010/12/ecsmas-and-tron/#comments</comments>
		<pubDate>Mon, 27 Dec 2010 08:09:19 +0000</pubDate>
		<dc:creator>Jason Mooberry</dc:creator>
				<category><![CDATA[Fun]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[ecsmas]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[tron]]></category>

		<guid isPermaLink="false">http://blog.jasonmooberry.com/?p=212</guid>
		<description><![CDATA[Well I really had a blast working with @darkgoyle on the Merry Ecsmas project on Christmas Eve. It was my first attempt at a canvas creation and it came together great. I am still finding myself creating snowflakes there! All this canvas exposure and seeing how @darkgoyle does his maths got me in a mood [...]]]></description>
			<content:encoded><![CDATA[<p>Well I really had a blast working with <a href="http://twitter.com/@darkgoyle">@darkgoyle</a> on the <a href="http://ecsmas.com">Merry Ecsmas</a> project on Christmas Eve.  It was my first attempt at a canvas creation and it came together great.  I am still finding myself creating snowflakes there!  <img src='http://blog.jasonmooberry.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>All this canvas exposure and seeing how <a href="http://twitter.com/@darkgoyle">@darkgoyle</a> does his maths got me in a mood to experiment!  So I played around with implementing variations on a Fibonacci graph and many other different oddities involving timestamps and Phi.  The one I liked the most was pretty simple.  It is a rotation at 160 degrees with a 10px increment on the line length at each iteration.  Here&#8217;s what it produces:</p>
<div style="text-align:center"><a href="http://jasonmooberry.com/img/160d.png"><img src="http://jasonmooberry.com/img/160d_sm.png" /></a></div>
<p>I think it&#8217;s rad in a simple Trony sortof way.  Here&#8217;s the code to generate it:</p>
<pre>
// get the canvas
var canvas = document.getElementsByTagName('canvas')[0],
  c = canvas.getContext('2d'),
  center = { x: canvas.width/2, y: canvas.height/2 };

// setup starting state
c.translate(center.x,center.y);

// base styles
c.lineCap = 'round';
c.lineWidth = 2;
c.strokeStyle = 'rgba(0,0,255,.7)';

var f = 1;
while (f < 500) {
  c.beginPath();
  c.moveTo(0,0);
  c.rotate(160*(Math.PI/180)); // convert degrees to radians
  c.lineTo(f,f);
  c.translate(f,f);
  c.stroke();
  f += 10;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jasonmooberry.com/2010/12/ecsmas-and-tron/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The long dark tea-time of the node</title>
		<link>http://blog.jasonmooberry.com/2010/11/the-long-dark-tea-time-of-the-node/</link>
		<comments>http://blog.jasonmooberry.com/2010/11/the-long-dark-tea-time-of-the-node/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 04:52:13 +0000</pubDate>
		<dc:creator>Jason Mooberry</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[express]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[ndistro]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[OAuth]]></category>
		<category><![CDATA[Twitter]]></category>

		<guid isPermaLink="false">http://blog.jasonmooberry.com/?p=91</guid>
		<description><![CDATA[Looking back I would&#8217;ve never guessed this project would have had so many twists and turns. I set out to build a game that was about synchronizing with computer generated rhythms. Ie. Make the box move at the same rhythm as a sine wave. I really liked the idea of something so simple requiring intense [...]]]></description>
			<content:encoded><![CDATA[<p>Looking back I would&#8217;ve never guessed this project would have had so many twists and turns.  I set out to build a game that was about synchronizing with computer generated rhythms.  Ie. Make the box move at the same rhythm as a sine wave.  I really liked the idea of something so simple requiring intense concentration.  It&#8217;s immersive but really really simple.  Anyways, I set out to craft this thing with some jQuery, plain js, and recursive timeouts.  At some point I thought it might be fun to track the score and even make an easy way to share your score on Twitter or Facebook.  I figured I&#8217;d make some type of nodejs app to handle the sharing and the rest could be static html pages.</p>
<p>What followed was a journey through two different types of oauth implementations, several nodejs modules and many greps through codebases to figure out how and why this worked or didn&#8217;t.  Since much of this will be useful to some other poor sap building with the same tools, I&#8217;ll outline here what I did and how it all works together.</p>
<h3>Javascript, front to back</h3>
<p><strong>Animation</strong><br />
Building the game itself took some time but was pretty straight-forward.  jQuery is extremely useful for binding events and such, but I tried to use bare js inside the loops for efficiency.  Since I&#8217;m not using canvas here, just manipulating positions of dom objects, it&#8217;s fairly processor intensive.  With that said Chrome and Safari handle it with ease.  Firefox will make your processor fan spin up.</p>
<p>The core of the animation stuff is variations on this simple recursive timeout:</p>
<pre class="brush:js">
block = $('#block');
move_timeout = null;
(function send_it_down() {
  move_timeout = setTimeout(function() {
    block.css('top',block.css('top')+1);
    send_it_down();
  },30);
})();
// to stop animation
// clearTimeout(move_timeout);
</pre>
<p>jQuery has some nice animation functionality but it&#8217;s all based on a fixed time of execution in which each step&#8217;s timeout is based on the amount of steps to execute and the total time for the animation to run.  Rolling my own animation code allowed me to control an infinitely executing constant speed animation.</p>
<p>The <a href="http://api.jquery.com/">jQuery api docs</a> and <a href="http://www.w3schools.com/jsref/default.asp">w3schools js ref</a> got me through anything tricky and <a href="http://mathworld.wolfram.com/Nephroid.html">Wolframs Mathworld</a> was the key to the color game (intially it was a spirograph pattern, then a simpler nephroid, finally a circle).</p>
<p><strong>OAuth</strong><br />
First thing&#8217;s first.  What is <a href="http://oauth.net/">OAuth</a> and how do I use it?  In order to make sharing your score easy I had to write an app that interfaced with both <a href="http://dev.twitter.com/doc">Twitter</a> and <a href="http://developers.facebook.com/docs/">Facebook&#8217;s</a> apis.  I heard Twitter was simpler and their docs were better so I started there.  A link in the twitter docs to this <a href="http://hueniverse.com/oauth/">Oauth Guide</a> made for an easy introduction.  Twitter is currently using an OAuth 1.0 implementation that is pretty true to what you would expect after reading the guide.  The only difference was that Twitter seems to store your callback url for you on your request token call so you don&#8217;t need to supply it on your auth token call.  Facebook has an OAuth 2.0 implementation that requires ssl and has fewer steps.  The only catch on Facebook is they&#8217;re sticklers for your callback url.  It must be present in both your authorize call as well as your auth token call and it must match exactly.  </p>
<p>Now that I know what OAuth is and have a basic understanding of how to interface with Twitter and Facebook&#8217;s apis, I searched out an OAuth module for nodejs.  </p>
<p><strong>Nodejs</strong><br />
I found some buzz around <a href="http://github.com/ciaranj/node-oauth">Ciaranj&#8217;s node-oauth</a> and found it to a pretty good wrapper for the functionality I would need.  It&#8217;s lacking a way to make POST requrests in the OAuth2 code, but writing my own wasn&#8217;t too tough.  I had my eye on <a href="http://expressjs.com/">Expressjs</a> as a framework for building http handlers for this app.  It&#8217;s a sweet little implementation with a very simple premise and good docs.  For my datastore I decided to take another crack at <a href="http://www.mongodb.org/">MongoDB</a>.  I&#8217;ve built PHP apps that interfaced with Mongo but nothing with nodejs yet.  </p>
<p>So far Nodejs has been a great tool for ad hoc api clients and prototypes.  This is the first server app I&#8217;ve written with nodejs.  A few things I noticed that were unexpected.  One, nesting callbacks can become tedious.  This was especially true with the MongoDB module.  I don&#8217;t see any way to get around it, but it&#8217;s ugly.  The other thing was that error handling with callbacks is much different than exception handling within a single thread of execution.  Wrap anything with a callback in a try/catch and you&#8217;ll see it&#8217;s useless.  So becoming expectant on an onError() method for all of the connections is the norm.  </p>
<p>Other challenges with nodejs included: since my nodejs app is listening on a different port than my html pages are being served from, I had to do some extra redirection at the end of my OAuth process so that my final landing page of my popup would be able to call back to the main window and trigger a success event.  And any exception that I didn&#8217;t catch takes down my app completely.  </p>
<p>With that aside I was able to craft a sweet little app in less than a couple hundred lines that is fast and easy.  I can manage the sharing process with a couple ajax calls and a bind to my custom success event.</p>
<p><strong>nDistro</strong><br />
Installing nodejs modules can be done a few different ways.  Initially I was using <a href="http://npmjs.org/">npm</a>.  It worked ok but since it installs to a central npm repository, and nodejs and it&#8217;s modules version so quickly, it made more sense to use <a href="http://github.com/visionmedia/ndistro">nDistro</a>.  It allows you to manage your nodejs versions as well as your module versions from a simple config file.  This is super useful since I can literally break my app with the wrong version.  </p>
<p>I found one oddity using nDistro to install <a href="http://github.com/christkv/node-mongodb-native">MongoDB&#8217;s node module</a>.  If you compile the C version of the BSON parser and intend to use it with your code, it will not be available.  The reason for this is that nDistro symlinks each module to a common lib/node directory.  There is a relative path that is broken in one of mongodb&#8217;s require statements for including the compiled BSON parser.  I was able to fix this by setting up a symlink in the lib directory.  Another issue with the MongoDB module is that in order to compile the native BSON parser you need to have a full nodejs install with the node-waf binary in an available path.  The node binary installed by nDistro is not sufficient.  After all of this I had errors compiling BSON on my vps that were not on my mac..  The js parser will work fine given the size of my records.</p>
<p><strong>MongoDB</strong><br />
<a href="http://www.mongodb.org/">MongoDB</a> showed up on my radar over a year ago and since then it&#8217;s gotten easier to use and more reliable.  The 10gen developers have put a lot of effort into building good libraries in many languages to interface with MongoDB.  With the <a href="http://groups.google.com/group/mongodb-user/browse_thread/thread/528a94f287e9d77e">postmortem</a> after <a href="http://blog.foursquare.com/2010/10/05/so-that-was-a-bummer/">FourSquare&#8217;s recent outage</a>, I got a little window into the scale that mongo seems to be handling well.  FTA the outage was due to overactivity in one of the shards that was running too close to memory capacity.  Given that FourSquare is running multiple 66GB RAM EC2 mongodbs and they just hit their <a href="http://blog.foursquare.com/2010/10/06/quite-the-way-to-celebrate-our-200-millionth-check-in/">200 millionth checkin</a> I am confident that my 2 dozen friend&#8217;s tweet/post counts will be handled with grace and speed.  <img src='http://blog.jasonmooberry.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Installing MongoDB is pretty much a matter of unzipping a tgz and running mongod from the command line.  </p>
<h3>Putting it all together</h3>
<p>This post has been short on code snippets cus I&#8217;m hosting the entire codebase at the <a href="https://github.com/jasonmoo/tunr">Github</a>.  This is my first run at a nodejs app with mongo running live and I am curious to see how stable everything is.  My new linode server is purring like a kitten with anything I throw at it.  Hopefully the tunr app continues the trend.  </p>
<p>Oh and you can <a href="http://tunr.jasonmooberry.com">play tunr here</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jasonmooberry.com/2010/11/the-long-dark-tea-time-of-the-node/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Geoff &#8211; Game Life!</title>
		<link>http://blog.jasonmooberry.com/2010/06/geoff-game-life/</link>
		<comments>http://blog.jasonmooberry.com/2010/06/geoff-game-life/#comments</comments>
		<pubDate>Sun, 27 Jun 2010 00:31:05 +0000</pubDate>
		<dc:creator>Jason Mooberry</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[game of life]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.jasonmooberry.com/?p=61</guid>
		<description><![CDATA[I've been fascinated with Conway's Game of Life for years now.  I love how there is an apparent order to things that is reproducible as well as simple in it's requirements.  Recently there was a discovery that made the tech news about a new pattern that replicated itself.  I'll be honest, the demo of the replicating code wasn't as sexy as I had hoped.  But it did remind me how much I want to make this game.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been fascinated with <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life" target="_blank">Conway&#8217;s Game of Life</a> for years now.  I love how there is an apparent order to things that is reproducible as well as simple in it&#8217;s requirements.  Recently there was a discovery that made the tech news about a <a href="http://www.newscientist.com/article/mg20627653.800-first-replicating-creature-spawned-in-life-simulator.html" target="_blank">new pattern that replicated itself</a>.  I&#8217;ll be honest, the demo of the replicating code wasn&#8217;t as sexy as I had hoped.  But it did remind me how much I want to make this game.</p>
<p>I&#8217;ve been on a recent tear through javascript, browser and server side (node.js is just fun).  So I set out to build a little game of life with js and html.  jQuery aided with some of the lifting too.  :)</p>
<p>After a couple afternoons Geoff was born.  He&#8217;s a simple lad.  Just gives you the basics, but still fun to play with non-the-less.  I have only tested him on Chrome, FF, and Safari.  Interestingly this is a great way to see how fast your js engine is.  Chrome handles it the best on my laptop.  FF the worst.</p>
<p><strong>A little bit about the code:</strong></p>
<p>jQuery&#8217;s <a href="http://api.jquery.com/live/" target="_blank">live()</a> event handling is perfect for this situation.  Since I opted to turn a crap-ton of b tags into large pixels of my game grid, I needed to bind some mouseover/mouseout and click events to each item.  There is no need to do this to each of the ~2k tags.  Instead, using live(), jQuery will bind to the document and as events bubble up, check to see if they&#8217;re relevant to my event handlers.  This cuts memory usage as well as bind time.</p>
<p>Recursion with setTimeout().  Initially when I built this I was using setInterval() to fire my life function and advance Geoff another step.  On Chrome it was fast enough that I didn&#8217;t notice any problems.  But when I tested in Safari and FF, I found that I was &#8220;dropping frames&#8221; when I cranked up the speed.  This had weird effects.  So I used a recursive function that pauses at the end of it&#8217;s execution.  This will ensure that I don&#8217;t lose an iteration, while giving reasonable control over the speed of execution.</p>
<p>Pseudo-casting as integer.  This is a hack that I picked up from <a href="http://james.padolsey.com/javascript/double-bitwise-not/">James Padolsey&#8217;s blog</a>.  For my purposes it&#8217;s a nice way to take a boolean expression and convert it into a 0 or 1.</p>
<pre class="brush: js">
// sum up the active neighbors
active += ~~(typeof current[neighbors[j]] === 'number' &amp;&amp; current[neighbors[j]] === 1);
</pre>
<p>Best practices.  I&#8217;ve violated them .. a bit.  :)</p>
<p>Well I hope you have fun playing.  I tried drawing moo and it lived a healthy and rich life.  ;)</p>
<p><strong><a href="http://jasonmooberry.com/dev/geoff.html" target="_blank">Enjoy Geoff!</a></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jasonmooberry.com/2010/06/geoff-game-life/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.125 seconds -->

