<?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>O! Mr Speaker! &#187; Nerd</title>
	<atom:link href="http://www.mrspeaker.net/category/nerd/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mrspeaker.net</link>
	<description>Javascript flâneur, internet flibbertygibbert</description>
	<lastBuildDate>Thu, 02 Feb 2012 13:18:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Colourising sprites in Canvas – part 2</title>
		<link>http://www.mrspeaker.net/2012/02/02/colorising-sprites-2/</link>
		<comments>http://www.mrspeaker.net/2012/02/02/colorising-sprites-2/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 10:21:16 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3162</guid>
		<description><![CDATA[And we're back! In part one we looked at setting up a tinted palette for drawing our 8-bit masterpieces to canvas. Here's what we're going for today: rendering colourised sprites and tiles. We'll be loading in our (ok, Notch's) 4-color sprite sheet and rendering tiles from it with our chosen colours. We need the InitPalette [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/minicraft-sprites.png" class="frame-right" alt="colourised sprites" />And we're back! In <a href="http://www.mrspeaker.net/2011/12/30/colorising-sprites-1/">part one</a> we looked at setting up a tinted palette for drawing our 8-bit masterpieces to canvas. Here's what we're going for today: <a href="/dev/spritecol/p5-go.html">rendering colourised sprites and tiles</a>. We'll be loading in our (ok, Notch's) 4-color sprite sheet and rendering tiles from it with our chosen colours.</p>
<p><span id="more-3162"></span>We need the <code>InitPalette</code> and <code>GetColour</code> functions from last time, though the <code>InitPalette</code> function will now store the 216 colours as JavaScript objects (with r, g, and b components) rather than Notch's encoded version:</p>
<p><code>
<pre>
// Before:
colours.push(r1 << 16 | g1 << 8 | b1);

// After:
colours.push({
  r: r1,
  g: g1,
  b: b1
});
</pre>
<p></code></p>
<p>This saves us from having to decode the value before we use it - which is much more practical in JavaScript, because the canvas image data is stored as separate rgba values by default.</p>
<p>On with the new stuff. First up is to make sure we can draw pixels to our canvas element. The process goes like this...</p>
<ol>
<li>Get the canvas's image data with the <code>createImageData</code> function.</li>
<li>Manipulate the bits of the data as we desire</li>
<li>Replace the canvas data using the <code>putImageData</code> function</li>
<li>Repeat from step 2</li>
</ol>
<p class="note">All the JavaScript you see is "inline" for simplicity. All functions are global (and for some reason I uppercased the function names - I sometimes go a bit weird when writing tutorials). A lot of arrays are passed by reference... It's for demonstration purposes only! Namespace things, mix'em in, plaster some classical OOP on them, make them into endo-functing monads... REMEMBER: This isn't production code, it was just me dissecting and porting Notch's Minicraft effort!</p>
<h3>Drawing pixels with canvas</h3>
<p>Right, first we grab the canvas context and keep a reference to the image data. We'll also populate our palette, ready for using.</p>
<p><code>
<pre>&lt;canvas id="board" width="160" height="120"&gt;&lt;/canvas&gt;
...
var ctx = document.getElementById("board").getContext("2d"),
    output = ctx.createImageData(ctx.canvas.width, ctx.canvas.height),
    colours = [];

// Set up our palette
InitPalette(colours);
</pre>
<p></code></p>
<p>Then we run a loop where we pick a random colour index (from the 216 we generated) and put it in each pixel. The canvas data is stored 4 bytes per pixel (rgba) and we put 256 for alpha (opaque).</p>
<p><code>
<pre>
(function run() {
  for (var y = 0; y < ctx.canvas.height; y++) {
    for (var x = 0; x < ctx.canvas.width; x++) {

      // Pick a random palette colour
      var cc = ~~(Math.random() * 216),
          xo = x * 4,
          yo = y * ctx.canvas.width * 4,
          col = colours[cc];

      // Replace the canvas image pixel
      output.data[xo + yo] = col.r;
      output.data[xo + yo + 1] = col.g;
      output.data[xo + yo + 2] = col.b;
      output.data[xo + yo + 3] = 256;
    }
  }

  // Draw it
  ctx.putImageData(output, 0, 0);
  setTimeout(run, 50);
})();</pre>
<p></code>Alright! We have <a href="/dev/spritecol/p1-static.html">some palatte-ized noise</a> on the screen.</p>
<p><img src="/images/pal-static.png" alt="some noise" style="padding-left: 55px"/></p>
<h3>Loading an image</h3>
<p>Next, we need to load in the <a href="/dev/spritecol/sheet.png">grey-scale graphic file</a> (which is the spritesheet from Minicraft). To load an image as canvas data, we'll create a regular ol' JavaScript image then "paint" it onto a canvas element. Then extract the data from the canvas element and discard the JavaScript image and the canvas element. We just want the datas.</p>
<p><code>
<pre>
function LoadSpriteSheet(filename, callback) {
  var img = new Image(),
      pixels = [];
  img.onload = function() {
    var can = document.createElement("canvas"),
        ctx = can.getContext("2d");
    can.setAttribute("width", img.width);
    can.setAttribute("height", img.height);
    ctx.drawImage(img, 0, 0);

    var data = ctx.getImageData(0, 0, img.width, img.height).data;

    // The important bit!
    for(var i = 0; i < data.length; i += 4) {
      pixels.push(~~(data[i] / 64));
    };

    // Send it back
    callback &#038;& callback({
      width: img.width,
      height: img.height,
      pixels: pixels
    });
  }
  img.src = filename;
}
</pre>
<p></code>
<p class="note">If you're playing along at home, remember you need to have a web server running to load the image (you can't run this sample from a <code>file:///</code> url) otherwise you'll get a cross-domain error when trying to manipulate the canvas data.</p>
<p>There's one weird bit in there that is specifically for our colourising code: first, because we only care about greyscale for now - we only look at every 4th byte in the data (because if it's greyscale then r=g=b). And second, every byte that we keep we first <em>divide by 64</em>.</p>
<p>WTF?! Ok, it's a Notch-ism... When he was creating the graphics in his graphics editor, he carefully chose 4 rgb colour values that when divided by 64 (and floored) would return either 0, 1, 2, or 3! That's a handy index for us to work with in code, but at the same time - a decent scale to work in in photoshop.</p>
<p>What we end up with then, is an array sized <code>width * height</code> of integers from 0 to 3. To actually load an image with this function we pass the path and a callback function (because the image load is asynchronous).</p>
<p><code>
<pre>
var spritesheet = null;
LoadSpriteSheet("sheet.png", function(sheet) {
  spritesheet = sheet;
  run();
});
</pre>
<p></code></p>
<p>We then call our <code>run</code> function. For this demo we will blit the spritesheet directly to the output canvas image - this code is almost identical to the "random static" code - except instead of a random colour index, we read the integers from the spritesheet. Because this will only give us a colour from 0 to 3 (which would be from black to very very dark someother colour) we multiply it by, say, 10 - and get the colour from the palette.</p>
<p><code>
<pre>function run() {
  for (var y = 0; y < ctx.canvas.height; y++) {
    for (var x = 0; x < ctx.canvas.width; x++) {
      var cc = spritesheet.pixels[x + (y * spritesheet.width)],
          xo = x * 4,
          yo = y * ctx.canvas.width * 4,
          col = colours[cc * 10]; // make it brighter!

      output.data[xo + yo] = col.r;
      output.data[xo + yo + 1] = col.g;
      output.data[xo + yo + 2] = col.b;
      output.data[xo + yo + 3] = 256;
    }
  }
  ctx.putImageData(output, 0, 0);
  setTimeout(run, 50);
};
</pre>
<p></code><br />
What you see now is <a href="/dev/spritecol/p2-loadsheet.html">a strangely colourised version</a> of part of the spritesheet. We're getting closer!</p>
<h3>A kind of double-buffer</h3>
<p>Right, in the next step we'll create an extra array, the same size as the screen, that will represent... the screen. It will hold screen size, the spritesheet, and the pixels to eventually render. All the sprite rendering we will do to this array, and then at the end copy it to the output canvas element.</p>
<p><code>
<pre>buffer = {
  width: ctx.canvas.width,
  height: ctx.canvas.height,
  sheet: null,
  pixels: []
},</pre>
<p></code></p>
<p>When the spritesheet is loaded, it is stored in the buffer too (instead of the global variable we made last time). To render the buffer to the output canvas we do exactly the same as before - but pass in the arrays to copy from and too.</p>
<p><code>
<pre>function render(buffer, pixels) {
  for (var y = 0; y < buffer.height; y++) {
    for (var x = 0; x < buffer.width; x++) {
      var cc = buffer.pixels[x + (y * buffer.width)],
          xo = x * 4,
          yo = y * buffer.width * 4,
          col = colours[cc];

      if(!col) continue; // Make sure it's defined
      pixels.data[xo + yo] = col.r;
      pixels.data[xo + yo + 1] = col.g;
      pixels.data[xo + yo + 2] = col.b;
      pixels.data[xo + yo + 3] = 256;
    }
  }
}</pre>
<p></code>Now we can re-create our original static - but utilising the buffer:</p>
<p><code>
<pre>for (var y = 0; y < buffer.height; y++) {
  for (var x = 0; x < buffer.width; x++) {
    buffer.pixels[x + y * buffer.width] = ~~(Math.random() * 216);
  }
}

// Transfer screen to output buffer
render(buffer, output);
ctx.putImageData(output, 0, 0);
</pre>
<p></code></p>
<p>A small step backwards - but now we're <a href="http://www.mrspeaker.net/dev/spritecol/p3-buffer.html">rendering noise</a> with our back buffer.</p>
<h3>Plotting some sprites</h3>
<p><img src="/images/minitools.png" alt="minicraft tools" class="frame-left" />With our buffer in hand, we can now do some real work! Anything we put into the buffer will end up on the screen - so now we can copy pieces of the spritesheet data straight into the buffer array. We'll make a <code>renderTile</code> function that copies an 8 by 8 pixel rectangle from spritesheet to a given x and y location. This code is ported pretty much directly from Notch's <code>screen.render</code> function.</p>
<p><code>
<pre>
function renderTile(buffer, xp, yp, tile, colors) {
  var xTile = tile % 32,
      yTile = ~~(tile / 32),
      toffs = xTile * 8 + yTile * 8 * buffer.sheet.width;

  for(var y = 0; y < 8; y++) {
    if (y + yp < 0 || y + yp >= buffer.height) continue; // make sure the pixel is on screen.
    for(var x = 0; x < 8; x++) {
      if (x + xp < 0 || x + xp >= buffer.width) continue; // make sure the pixel is on screen.
      var col = (colors >> (buffer.sheet.pixels[x + y * buffer.sheet.width + toffs] * 8)) &#038; 255;
      if (col < 255) buffer.pixels[(x + xp) + (y + yp) * buffer.width] = col;
    }
  }
}</pre>
<p></code><br />
To render a tile, we pass in the buffer, the position to render, the tile index, and the colour we want to tint the tile with. Most of the code just figures out the correct offset from the spritesheet (notice the magic number "32"? that's because the sheet is 32 x 32 tiles. The magic number 8? Our tiles are 8 x 8 pixels).</p>
<p><strong>But the important line is this whole procedure</strong> is this: <code>var col = (colors >> (buffer.sheet.pixels[x + y * buffer.sheet.width + toffs] * 8)) &#038; 255;</code></p>
<p>This is where the colourising magic happens. The pixel value from 0 to 3 is found from the spritesheet. This is then multiplied by 8 to give either the value: 0, 8, 16, or 24. The colour number is then <em>right shifted</em> by that amount and <em>anded</em> by 255.</p>
<p>Does this sound kind of familiar? It's the inverse of what the ol' <code>GetColour</code> function did - which encoded 4 colour values into 1 integer. This is just doing the opposite: extracting one colour out of the integer and applying it to the correct pixel. The next line then checks that the value is not 255 - which will be our "invisible" colour for transparent areas. </p>
<p>We can call this function for each 8x8 sprite/tile we want to render. The tile number is the integer index into the spritesheet: 0 is the first tile in the first row, 1 is the second tile in the first row, 32 (1 * 32 + 0) is the first tile in the second row, 33 (1 * 32 + 1) is the second tile in the second row... </p>
<p><code>
<pre>renderTile(buffer, 20, 20, (5 * 32) + 0, GetColour(-1, 100, 320, 222));
renderTile(buffer, 30, 20, (5 * 32) + 2, GetColour(-1, 100, 320, 222));
renderTile(buffer, 40, 20, (5 * 32) + 3, GetColour(-1, 100, 320, 222));
</pre>
<p></code></p>
<p>Ah, that's more like it - <a href="/dev/spritecol/p4-render.html">Three colourised Minicraft tools</a>!</p>
<h3>Messing around with it</h3>
<p>With the ability to plot tiles and sprites at a given location - we have all we need to make some games! In each of your entity's render functionality you can call the renderTile as many times as you need. For example, to render a background over the whole screen:</p>
<pre><code>for(var y = 0; y < buffer.height / 8; y++) {
    for(var x = 0; x < buffer.width / 8; x++) {
        renderTile(buffer, x * 8, y * 8, 1, GetColour(0, 130, 120, 0));
    }
}
</code></pre>
<p>You can plot individual tiles to make a font plotter, or stitch a few tiles together for bigger sprites... whatever you want. Here's the code for the weird demo from the beginning of the article. Notice that the Minicraft players are actually 4 tiles in a square:</p>
<p><code>
<pre>var rnd = function(min, max){ if(!max){ max=min; min=0; }; return ~~(Math.random()*(max-min))+min;},
    rndCol = function(){ return parseInt(rnd(5) + "" + rnd(5) + "" + rnd(5), 10); };

// Render peoples
var midX = ~~(Math.sin(new Date().getTime() / 400) * 20) + 70,
    midY = ~~(buffer.height / 2) - 8,
    col1 = GetColour(-1, 1, rndCol(), rndCol()),
    col2 = GetColour(-1, 1, 23, 555);

// Man 1
renderTile(buffer, midX + 16, midY, (14 * 32) + 0, col1);
renderTile(buffer, midX + 24, midY, (14 * 32) + 1, col1);
renderTile(buffer, midX + 16, midY + 8, (15 * 32) + 0, col1);
renderTile(buffer, midX + 24, midY + 8, (15 * 32) + 1, col1);

// Man 2
renderTile(buffer, midX, midY, (16 * 32) + 0, col2);
renderTile(buffer, midX + 8, midY, (16 * 32) + 1, col2);
renderTile(buffer, midX, midY + 8, (17 * 32) + 0, col2);
renderTile(buffer, midX + 8, midY + 8, (17 * 32) + 1, col2);
</code></pre>
<p>Check out the <a href="http://www.ludumdare.com/compo/ludum-dare-22/?action=preview&#038;uid=398">Minicraft source</a> (or <a href="https://github.com/Miserlou/Minicraft">here on GitHub</a>) - especially the <code>render</code> functions of each entity (eg player.java) to see how Notch implements animation and rendering based on the player's direction, if they are attacking, etc.</p>
<p>Anyhow... <a href="/dev/spritecol/p5-go.html">that's it</a>. I'd highly recommend not using any of the code above, but re-implement it yourself from your brain... this code is already ported from Java which was written in a 48 hour game competition, by a mad man - so do yourself a favour and make your own (more idiomatic) version!</p>
<p>It's worth it I think... dynamically colourising sprites like this is a great way to prototype the look and feel of your game, add in old-school colour-cycling effects, and easily add variety to your entities.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/02/02/colorising-sprites-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Navigate the web with your gamepad</title>
		<link>http://www.mrspeaker.net/2012/01/03/gamepad-navigator/</link>
		<comments>http://www.mrspeaker.net/2012/01/03/gamepad-navigator/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 15:30:02 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3121</guid>
		<description><![CDATA[How crap is the mouse, right? Yeah, I know! So I made a greasemonkey script to do my websurfin' using my NES-style USB gamepad. For those of you too excited to read on, take your gamepad-enabled build of Firefox and install Gamepad Navigator now! Up and down to scroll the page up and down. The [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/nes-controller.png" class="frame-right" />How crap is the mouse, right? Yeah, I know! So I made a greasemonkey script to do my websurfin' using my <a href="http://www.thinkgeek.com/electronics/retro-gaming/ba5a/">NES-style USB gamepad</a>. For those of you too excited to read on, take your <a href="http://people.mozilla.com/~tmielczarek/mouselock+gamepad/">gamepad-enabled build of Firefox</a> and install <a href="https://github.com/mrspeaker/Gamepad-Navigator">Gamepad Navigator</a> now!</p>
<p><strong>Up and down</strong> to scroll the page up and down. The top-most visible link on the page will be highlighted for your navigating pleasure. <strong>Left and right</strong> to move between links, <strong>FIRE</strong> to visit. It's just that simple! </p>
<p><span id="more-3121"></span>
<p class="note">The <a href="http://dvcs.w3.org/hg/webevents/raw-file/default/gamepad.html">gamepad API</a> is verrry experimental at the moment - it's only available in special builds of Firefox and Chrome (Chrome Canary)... but it's comin' to a browser near you soon!</p>
<p>I also map the "select" button to back, and "start" button to forward, just for fun. It's only for Firefox at the moment (thanks to some weirdness in the Chrome implementation) and it's hardcoded to the Retrolink controller - you need to tweak the IDs in the script to match yours... but hey, works on my machine!</p>
<p><iframe width="450" height="335" src="http://www.youtube.com/embed/em8lmarM01g" frameborder="0" allowfullscreen></iframe></p>
<p>Konami code not included.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/01/03/gamepad-navigator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Colourising sprites in Canvas &#8211; part 1</title>
		<link>http://www.mrspeaker.net/2011/12/30/colorising-sprites-1/</link>
		<comments>http://www.mrspeaker.net/2011/12/30/colorising-sprites-1/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 10:09:57 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3095</guid>
		<description><![CDATA[First things first: I promise to try to limit the Notch related posts in the future and I apologize to the legions of l337 coders for the continued coverage. Right, now, on to todays topic: "Colour like you're Notch" (Awright, punning on my own blog post titles!). While watching the livestream of Notch coding Minicraft, [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/minicon.png" class="frame-right" />First things first: I promise to try to limit the Notch related posts in the future and I apologize to the legions of l337 coders for the continued coverage.</p>
<p>Right, now, on to todays topic: "Colour like you're Notch" (Awright, punning on <a href="http://www.mrspeaker.net/2011/09/15/code-like-youre-notch/">my own blog post titles</a>!). While watching the livestream of Notch coding <a href="http://www.ludumdare.com/compo/ludum-dare-22/?action=preview&#038;uid=398">Minicraft</a>,  I was intrigued by his dynamic sprite colorising. After a little reverse engineering and experimentation I realised it was dang simple, and we could apply something similar to HTML5 games.</p>
<p><span id="more-3095"></span>The idea is that you create your sprite sheet using only 4 colours. At runtime, you replace the 4 colours with any colours you like - so you can quickly modify the look and feel of the game, or have varied characters that differ only by colour - just like the ol' NES games.</p>
<p>While 95% of Notch's code is extremely straightforward and obvious, the colour system got a bit hairy due to the fact he faffed around with the implementation a few times to get the result he wanted. The end result seems more complex than it really is. The overview of the system goes like so:</p>
<p>1. Set up a limited (256 colour) indexed palette to be used in the game. The colour channels will be divided into 5 "shades".<br />
2. Draw the sprites in 4 colours. When loading the image into the game, reduce the pixels to values from 0 to 3 to represent the colour.<br />
3. When drawing a sprite to the screen, dynamically pass in the 4 colours to use.<br />
4. For each pixel, find the index in the palette and replace the pixel with that colour.<br />
5. Profit!</p>
<p>The trickiest part is realising that Notch just made up a custom colour selecting system. Throughout the Minicraft code you'll see lots of instances of a line like: <code>Color.get(100, 232, -1, 555)</code> - although it kind of looks like some kind of RGBA format, it's really defining 4 separate colours, each made up of 3 channels. The number 100 represents r = 1, g = 0, b = 0 and would be a very dark red. 555 represents r = 5, g = 5, b = 5 and would be white (full red, full green, and full blue). So let's see it in action...</p>
<p>In <code>Game.java</code>, the colour palette is set up. It uses 6 bits per channel to get our 256 colours in 5 shades. Here's the directly ported JavaScript version (well, except that I'm passing in the number of bits to use, so you can play with it):<br />
<code>
<pre>function InitPalette(colours, bits) {
  // Set colours
  for (var r = 0; r < bits; r++) {
    for (var g = 0; g < bits; g++) {
      for (var b = 0; b < bits; b++) {
        var rr = r * 255 / (bits - 1),
            gg = g * 255 / (bits - 1),
	    bb = b * 255 / (bits - 1);

        // Set the mid tone
        var mid = (rr * 30 + gg * 59 + bb * 11) / 100;

        // Tint the palette
        var r1 = ~~(((rr + mid * 1) / 2) * 230 / 255 + 10),
            g1 = ~~(((gg + mid * 1) / 2) * 230 / 255 + 10),
            b1 = ~~(((bb + mid * 1) / 2) * 230 / 255 + 10);

        // Push RGB values into a single integer
        colours.push(r1 << 16 | g1 << 8 | b1);
      }
    }
  }
}</pre>
<p></code></p>
<p>You can have a look at the palette that's generated by this function with <a href="http://jsfiddle.net/Rjcyj/2/">this jsFiddle</a>. One cool thing to notice is the tinting process. Try changing the final line to push the non-tinted values (rr instead of r1, gg instead of g1 etc). Without the tinting the game colours would <a href="http://jsfiddle.net/Rjcyj/1/">look like this</a>. Quite a nice way to give the game a "feel". Here they are side-by-side - the top one is tinted to be more "pastel-ly".</p>
<p><img src="/images/mini-palette.png" alt="comparing tinted and non-tinted palettes" /></p>
<p>The final line <code>colours.push(r1 << 16 | g1 << 8 | b1)</code> converts the RGB values into a single integer (the shift-left operator moves the red bits up the top, the green bits in the middle, and leaves the blue bits at the end). If you want to use this in your HTML5 games, then it'd be better to skip this encoding and store each colour as a simple object - because we just need to decode it later (perhaps the shift version is faster in JavaScript too? Might need a bit of testing!).</p>
<p>Anyway - now we have an indexed palette of colours. To get the colours back at our will we need to use the accessor methods Notch created in <code>Color.java</code>. Here's a JS version:<br />
<code>
<pre>function GetColour(a, b, c, d) {
  function getIndex(d) {
    if (d < 0) return 255;
    var r = ~~(d / 100) % 10; // First digit
    var g = ~~(d / 10) % 10; // Second digit
    var b = d % 10; // Third digit
    return r * 36 + g * 6 + b;
  }

  return (getIndex(d) << 24) + (getIndex(c) << 16) + (getIndex(b) << 8) + (getIndex(a));
}
</pre>
<p></code><br />
Notch's version is the same code, but he uses an overloaded <code>get</code> method for fetching the indexes. The final line returns a single integer like in the palette generation - it pushes the first colour 24 bits up the integer, the second colour 16 bits up etc. The value that it pushes is the index in the palette. This is calculated by the getIndex function by turning the decimal number into 3 channels. The function will accept a number between 0 and 555 (5 x reds, 5 x greens, and 5 x blues). If you put a number higher than 555 into it, it'll die. So don't do that.</p>
<p>Now we can get a single number to represent our 4 colours. <code>GetColour(500, 50, 5, 505) == -1190846796</code> (Be careful, it's tempting to put 500, 050, 005, 505 so it looks nice, but remember - a leading 0 mean the number is octal in JavaScript, so 050 will actually be 40 in decimal).</p>
<h3>Colouring in</h3>
<p>Now that we have a way to encode the colours, we need to be able to decode them. Which is just a matter of reversing the getColour method, really: pop out the values and find the palette index! To show it in action I'll just draw 4 rectangles in the four colours specified by GetColour:<br />
<code>
<pre>function DrawColours(ctx, colourInt, palette) {
    for(var i = 0; i < 4; i++) {
        var colIndx = (colourInt >> i * 8) &#038; 255,
            col = palette[colIndx],
            b1 = col &#038; 255,
            g1 = (col >> 8) &#038; 255,
            r1 = (col >> 16) &#038; 255;
        ctx.fillStyle = "rgb(" + r1 + "," + g1 + "," + b1 + ")";
        ctx.fillRect(i * 10, 0, 10, 10);
    }
}

DrawColours(ctx, GetColour(510, 0, 555, 55), colours);
</pre>
<p></code><br />
<a href="http://jsfiddle.net/Rjcyj/3/">The result</a> is a red-ish rectangle, a black, a "white", and an aqua blue rectangle. The decoding part can be found in the Minicraft source in <code>Screen.java</code> in the render function. The original code looked like this:<br />
<code>int col = (colors >> (sheet.pixels[xs + ys * sheet.width + toffs] * 8)) &#038; 255;</code>. First the pixel colour (for 0 to 3) is found in the sprite sheet that corresponds with the current tile. This is the "i" from our <code>DrawColours</code> function. The number is then multiplied by 8 to get the correct distance to shift by (0, 8, 16, or 24 bits). The result is the number we pushed in with the <code>GetColour</code> call - which was the index of the palette to use. The actual colour components can then be extracted and drawn.</p>
<p>Ok, that's it for this post - it's getting too long. As you can see, the system is very simple - it's just encoding and decoding palette indexes. <a href="http://www.mrspeaker.net/2012/02/02/colorising-sprites-2/">In the next post</a> I'll show you how to load in the sprite sheet, covert it to the correct 0 - 4 format we need, and plot the colourised tiles. Sounds exciting, hey?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/12/30/colorising-sprites-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What I learned from watching people watching Notch</title>
		<link>http://www.mrspeaker.net/2011/12/20/troll-at-notch/</link>
		<comments>http://www.mrspeaker.net/2011/12/20/troll-at-notch/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 10:08:59 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3066</guid>
		<description><![CDATA[Last weekend was the 22nd Ludum Dare 48 hour game comp. Again Notch livestreamed it, again I watched pretty much all of it, and again I learned a lot. But having seen Notch in action before, this time I could afford to take my eyes off the code from time to time, and spend a [...]]]></description>
			<content:encoded><![CDATA[<p>Last weekend was <a href="http://www.ludumdare.com/compo/ludum-dare-22/">the 22nd Ludum Dare</a> 48 hour game comp. Again Notch livestreamed it, again I watched pretty much all of it, and <a href="http://www.mrspeaker.net/2011/09/15/code-like-youre-notch/">again I learned a lot</a>. But having seen Notch in action before, this time I could afford to take my eyes off the code from time to time, and spend a bit more time to perusing the informative "chat" that accompanied the videos.</p>
<p><span id="more-3066"></span>With an average of around 5000 anonymous viewers, that's always going fun. Over the weekend the topics ebbed and flowed over 3 core themes: <strong>"What radio station is this?"</strong> (devolving into music flamewars), <strong>"When is the next Minecraft release?"</strong> (devolving into Minecraft flamewars), and <strong>"What program is he using?"</strong> (Devolving into programming language flamewars). Here were some of my favourite quotes from the informed and poignant programming language discussions:</p>
<ul style="line-height:17pt;padding-left:10px">
<li>java wasnt really made for games</li>
<li>C isn't a very good language, it doesnt have xml or objects</li>
<li>tell me, why the *** would you write a game in an imperative language if you knew c++ just as well?</li>
<li style="list-style-type:none;">
<blockquote>You should start with c++ if you want to learn programming. All other languages are ***, except for the D language.</p></blockquote>
</li>
<li>how do i OOP?</li>
<li>object oriented programming is a sad failed paradigm of the 80s</li>
<li>Object C isn't very flexible ;-;</li>
<li>i hear you need to learn html to get into C#, is this true?</li>
<li>you're a good c++ coder if you don't use any pointers</li>
<li>the part i hated most about notchs code was the bitwise shifting i hate that</li>
<li style="list-style-type:none;">
<blockquote>i learnt c++ from a book, its boring</p></blockquote>
</li>
<li>C++ isnt boring, just as fun as Java, but faster and more flexible</li>
<li>c++ is a mess now</li>
<li>java looks a lot like c++</li>
<li>i just now realized how similar c++ and java really are</li>
<li>C++ can be writtnel like C cause C++ has bacwardcompapility</li>
<li>the C lineage has it's tendrils everywhere in modern programming, maybe not in c++ but certainly in later iterations</li>
<li>c++ is like updated c#</li>
<li>whats easier to learn c++ or java and what is better overall( like quality of programm)</li>
<li style="list-style-type:none;">
<blockquote>java is easiest. c++ is more useful and makes a better program</p></blockquote>
</li>
<li>C# is an improved Java. Java is an improved C++. C++ is far harder, more difficult and complex than java or c#. C# is also a better language than both.</li>
<li style="list-style-type:none;">
<blockquote>C++ is the most efficient programming language to date</p></blockquote>
</li>
<li>java takes too much ressoursses</li>
<li>java is demanding in terms of RAM</li>
<li>Java is similar to C++ with Objects and stuff and antway wasnt java writen in C++</li>
<li>Visual is the standard programming language....doesn't mean its awful << haters</li>
<li>C++ is a giant, ugy, monstrosity of a language. somewhere inside it, there is a much simpler and more elegant language. that language is called java.</li>
<li>Chrome sucks because it has seperate processes for EVERY tab! And they say it's lightweight.. lol</li>
<li>why are you people talking about c++? seriously, learn c# or sth. like that, but not c++... *** c++. so outdated nowadays and just terrible</li>
<li style="list-style-type:none;">
<blockquote>as long as someone is using a old programming language it's worth learning... look @ bank systems they're coded in old langs</p></blockquote>
</li>
</ul>
<p>No one was delving on the irony of spending an hour or so arguing about which language is better for games, without noticing that <a href="https://s3.amazonaws.com/ld48/ld22/index.html">an actual game was unfolding before their eyes</a>. If only games were flamewar powered!</p>
<p>It was obvious that most people liked the idea of making a game, but balked when confronted with the part where you <em>actually had to put in a bit of effort</em>. This attitude was entrenched firmly in what was perhaps my favourite quote for the weekend - directed towards Notch's wife (who at one point was moderating the madness):</p>
<blockquote><p>EZ, any advice for women who want to marry men who are in game development?</p></blockquote>
<p>Now that's just plain lazy.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/12/20/troll-at-notch/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>A Minecraft soundtrack for your daily grind</title>
		<link>http://www.mrspeaker.net/2011/12/07/grindcraft-minecraft/</link>
		<comments>http://www.mrspeaker.net/2011/12/07/grindcraft-minecraft/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 11:23:10 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3053</guid>
		<description><![CDATA[The problem with the real world is it's not enough like Minecraft. The fix is simple: pipe haunting and beautiful C418 tracks at various random times throughout the day, in a Minecraft-y fashion. To keep you on your toes, add in some rare-but-scary cave sounds. And that's exactly what my Grindcraft python script is for. [...]]]></description>
			<content:encoded><![CDATA[<p>The problem with the real world is it's not enough like <a href="minecraft.net">Minecraft</a>. The fix is simple: pipe haunting and beautiful <a href="http://c418.org/">C418</a> tracks at various random times throughout the day, in a Minecraft-y fashion. To keep you on your toes, add in some rare-but-scary cave sounds. And that's exactly what <a href="https://github.com/mrspeaker/grindcraft">my Grindcraft python script</a> is for.</p>
<p>If you're a fan of the game (a fan is someone who has played it) then you'll know that the music in Minecraft is "special". The game proceeds largely in silence... you'll be deep in the process of constructing a summer house out of glass, or building a railroad to your lava pit when it starts... ever-so-slowly drifting in, and filling your body with smiles. Then it washes away without you even noticing.</p>
<p>I decided I needed this for my daily grind, so I whipped up a dodgy python script that plays random ogg files out of the Minecraft resources directory. But first I needed to figure out which songs Minecraft plays, and at what times.<br />
<span id="more-3053"></span><br />
<h2>The algorithm</h2>
<p>According to the <a href="http://www.minecraftwiki.net/wiki/C418">Minecraft wiki on music</a> "In-game music is cued by the time of day, with a random track being played at sunrise, sunset, noon and midnight". Which I thought sounded reasonable - at first. I asked on the IRC channel and received similar stories: Songs play in the early morning, evening and late at night. Not every morning though, and sometimes not at night. And only the twinkly song plays in the morning. And, and, and... Something seemed fishy, so I decided further investigation was necessary.</p>
<p>Minecraft is a standard Java program, and the Mojang team were nice enough not to do any crazy encrypting/obfuscating of the final product: so it can be relatively easily decompiled (and even re-compiled!). I consulted the source to learn the ways of the mystical music-playing algorithm. To my surprise, it goes a little something exactly like so:</p>
<p>When initialised, it does this complex algorithm to determine the optimum time to play the first morning song:<br />
<code>
<pre>rand = new Random();
ticksBeforeMusic = rand.nextInt(12000);</code></pre>
<p>There are 24000 ticks in a Minecraft day, so this just picks a random time between now, and half-a-day away. That's it. I guessed the algorithm for successive tracks would be far more complex than this gimmee. Following the code along I found it calls this function once every game tick:<br />
<code>
<pre>public void playRandomMusicIfReady() {
	if(ticksBeforeMusic > 0) {
	    ticksBeforeMusic--;
	    return;
	}
	SoundPoolEntry soundpoolentry = soundPoolMusic.getRandomSound();
	ticksBeforeMusic = rand.nextInt(12000) + 12000;
	sndSystem.backgroundMusic("BgMusic", soundpoolentry.soundUrl, soundpoolentry.soundName, false);
	sndSystem.play("BgMusic");
}</pre>
<p></code></p>
<p>When the counter is 0 it calls <code>getRandomSound</code> which simply returns a random song from the "music" or "newmusic" folders. It then resets the counter to another random number between half a day, and a full day away! It has absolutely no concept of morning, eventing, night, twinkly song, quiet song... it just plays a random track, at a random time! Damn you <em>human brain</em> for adding meaning where there is none!</p>
<p>Anyway, that's all I wanted to say. If you happen to have Minecraft, python, and <a href="http://pygame.org/news.html">pygame</a> installed, and work with your volume up, but in silence: then <a href="https://github.com/mrspeaker/grindcraft">this script</a> is for you!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/12/07/grindcraft-minecraft/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>My grandmother was immutable</title>
		<link>http://www.mrspeaker.net/2011/11/28/immutable-nanna/</link>
		<comments>http://www.mrspeaker.net/2011/11/28/immutable-nanna/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 13:14:01 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Nerd]]></category>
		<category><![CDATA[The common man]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3021</guid>
		<description><![CDATA[As I move into my twilight years (mid 30s) I start to have flashbacks surrounding various aspects of my youth. This very morn', for example, I was whisked back to an endless summer evening circa the mid 80s... The scene is composed of; a large christmas tree, me, my grandmother, and our TV. Connected to [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/nanna.jpg" class="frame-right" />As I move into my twilight years (mid 30s) I start to have flashbacks surrounding various aspects of my youth. This very morn', for example, I was whisked back to an endless summer evening circa the mid 80s... The scene is composed of; a large christmas tree, me, my grandmother, and our TV. Connected to the TV is my first ever computer: a <a href="http://www.samdal.com/sv318.htm">SpectraVideo 318</a> (sold mostly in Japan and Sweden, apparently - but powered by the famous Zilog Z-80 chip [as seen to this day in my washing machine]).</p>
<p><span id="more-3021"></span>Curious as to the purpose of these wondrous new consumer devices, my grandmother asked for a demonstration of how it worked. She was a teacher, I think (as a kid you don't really probe the lives of those around you) and I felt like this was a mini test, so I was determined to impress. Naturally I fired up BASIC to give her a taste of why she herself might want such a machine, and I wrote a small program to plot a sprite on the screen.</p>
<p><code>RUN...</code></p>
<p>I could tell she hadn't quite grasped the awesomeness of it, so I proceeded to animate it. The animation code went something (but nothing) like this:</p>
<pre><code>...
100 LET X = 0
110 PUT SPRITE 1, X, 100
120 LET X = X + 1
130 GOTO 110</code></pre>
<p>I'd memorised the code from the user manual, or from another game, or something... so I was very unprepared for her sole question regarding the demonstration:</p>
<blockquote><p>How can X possibly be X plus one?</p></blockquote>
<p>I was confused.</p>
<p>Not about her question (I had no idea what she was talking about). I was confused because she wasn't in awe of the HUGE SMILEY FACE that <em>I had just created</em> and then made FLY RIGHT ACROSS THE SCREEN.</p>
<p>But she persisted with her interrogation of the single line of code, buried inside the very first program she had ever seen: how could "X" be "X <em>plus one</em>"? It just didn't make sense to her. If X is 0 then <em>X is 0</em>.</p>
<p>&lt;End flashback&gt; I don't remember much about my grandmother, but this morning I was writing a piece of functional JavaScript and I happend to need the <code><a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7#Block_scope_with_let">let</a></code> keyword. As I typed it, I was transported back in time to that strange moment - I don't even know why it was locked in my head.</p>
<p>At any rate, I'm now a bit miffed that it took me 20-odd years to get up to speed with functional programming, but my grandma - who had never touched a computer in her life - understood immutability instantly and intrinsically.</p>
<p style="font-size: 9pt">
See also <a href="http://www.mrspeaker.net/2011/05/02/conventional-interfaces/">Conventional Interfaces: map/reduce and friends</a>.<br />
See also <a href="http://www.mrspeaker.net/2011/04/27/reducing-map/">Reducing map: jQuery vs jQuery vs JavaScript</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/11/28/immutable-nanna/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>CoffeeScript &amp; Less with Play! 2.0</title>
		<link>http://www.mrspeaker.net/2011/11/14/coffeescript-less-with-play-2-0/</link>
		<comments>http://www.mrspeaker.net/2011/11/14/coffeescript-less-with-play-2-0/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 10:29:47 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3002</guid>
		<description><![CDATA[The Play! framework went and made Java development more fun than Ruby development (*ducks*) - and then Martin Odersky went and made Java more fun than Java (*considers ducking, but doesn't*), and then the Play framework went and mashed those fun things together and now there is the Play! 2.0 framework. Play 2.0 gives a [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.playframework.org/">Play! framework</a> went and made Java development more fun than Ruby development (*ducks*) - and then Martin Odersky went and made <a href="http://www.scala-lang.org/">Java more fun than Java</a> (*considers ducking, but doesn't*), and then the Play framework went and mashed those fun things together and now there is <a href="http://www.playframework.org/2.0">the Play! 2.0 framework</a>.</p>
<p>Play 2.0 gives a big hug to Scala (the core is all Scala now - though there are still Java APIs for everything if you haven't convinced your bosses to switch yet). One small-yet-nice feature of the new version is built-in <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a> and <a href="http://lesscss.org/">Less CSS</a> support. Here's how you use it...</p>
<p><span id="more-3002"></span>After creating a new app, add a <code>app/assets</code> directory to the default structure. Files in here are contenders to be compiled and served as public resources. From here we'll go ahead and add <code>javascripts</code> and <code>stylesheets</code> folders as children.</p>
<h2>Adding some CoffeeScript</h2>
<p>Next, we'll add a new CoffeeScript file. Create a new file <code>app/assets/javascripts/main.coffee</code> and add some coffee magic (here we're alerting after a jQuery document.ready):</p>
<pre><code>$ ->
    alert "Mmmmm... Coffee...."
</code></pre>
<p>To link this from your main template, add a link to <em>where the compiled version should go</em>:</p>
<pre><code>&lt;script type="text/javascript" src="@routes.Assets.at("javascripts/main.js")"&gt;&lt;/script&gt;</code></pre>
<p>Notice the path is <code>javascripts/main.js</code> (not .coffee). We're pretending that the JS file is a normal-ol' JS resource in the <code>/public/javascripts/</code> directory (though, internally it's actually compiled to a separate target directory).</p>
<p>Refresh the page, and alerts abound! Anytime you refresh your browser, any changes will be automagically compiled and served. Neato.</p>
<h2>And some Less</h2>
<p>Adding Less CSS is almost exactly the same: add a file <code>app/assets/stylesheets/main.less</code>:</p>
<pre><code>
body {
    background: green;
    color: yellow;
}
</code></pre>
<p>And link it as a regular resource (and if you're trying this from a default project, don't forget to delete the main.css in the public stylesheets directory, and the @play20.welcome(message) from the index view - which brings it's own CSS to the party!):
<pre><code>&lt;link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")"&gt;</code></pre>
<p>There's one caveat though: if we have an import statement in our Less file - the compile command will merge the files, but it will also find the import and try to compile it standalone. To avoid this, you need to name the import file with a leading underscore.</p>
<p>Here's our import file, <code>apps/assets/stylesheets/_theme.less</code>:</p>
<pre><code>
@mainBackground:        green;
@mainColor:             yellow;
@defaultFont:           13px sans-serif;
</code></pre>
<p>And here's our <code>main.less</code>:</p>
<pre><code>
@import '_theme.less';

body {
    background: @mainBackground;
    color: @mainColor;
    font: @defaultFont;
}
</code></pre>
<p>You can add as many subdirectories as you need to give your project a nice structure (for example, adding all the imports in <code>libs</code> etc.)</p>
<p>And that's it! For the inquisitive of you who are wondering how this works under the hood, check out the code in <code>framework/play/src/main/scala/play/core/coffeescript</code> and <code>less</code>, and Mozilla's <a href="http://www.mozilla.org/rhino/">Rhino</a> project!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/11/14/coffeescript-less-with-play-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notch on film: the livestream videos</title>
		<link>http://www.mrspeaker.net/2011/09/27/notch-on-film/</link>
		<comments>http://www.mrspeaker.net/2011/09/27/notch-on-film/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 10:03:17 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Nerd]]></category>
		<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=2926</guid>
		<description><![CDATA[Since having a chat about what I learned from watchin' Notch, I've received buckets of emails 'n' tweets asking for links to the videos... After an epic google search of 5 minutes I've collected them all and aggregated them in this one happy place. Notch coded Prelude of the Chambered for the Lundum Dare #21 [...]]]></description>
			<content:encoded><![CDATA[<p>Since having a chat about <a href="http://www.mrspeaker.net/2011/09/15/code-like-youre-notch/">what I learned from watchin' Notch</a>, I've received buckets of emails 'n' tweets asking for links to the videos... After an epic google search of 5 minutes I've collected them all and aggregated them in this one happy place. </p>
<p>Notch coded <a href="http://notch.tumblr.com/post/9251960534/prelude-of-the-chambered">Prelude of the Chambered</a> for the <a href="http://ludumdare.com/">Lundum Dare</a> #21 game competition over 48 hours of August 19th-22nd 2011. I think most of it is here - and I've started annotating some of the good bits. Started. I'll fill out this post as I go...</p>
<p>It's well worth a study if you've got a couple of days to spare!<br />
<span id="more-2926"></span><br />
<h3>Part 1: The setup (3h 15m)</h3>
<p>And so the game begins - on Saturday the 20th of August, some time in the afternoon...</p>
<p><a href="http://www.youtube.com/watch?v=QYBUCYUNn3Q">Part 1 direct link</a> (on YouTube - text in fullscreen is readable, but only just!)</p>
<p><iframe width="450" height="253" src="http://www.youtube.com/embed/QYBUCYUNn3Q?hd=1" frameborder="0" allowfullscreen></iframe></p>
<ul>
<li>Sketches out some possible ideas in notepad</li>
<li>Sets up Eclipse and his paint program</li>
<li>Creates blank Java project and Swing component</li>
<li>Creates display frame and boiler plate stuff</li>
<li><strong>(0:27)</strong> Sets up main loop "tick" and game screen</li>
<li>Draws some random pixels with clipping</li>
<li>Pixels with perspective</li>
<li><strong>(1:14)</strong> Maps a roof and floor texture</li>
<li>Adds up-down camera movement</li>
<li>Adds a wall-as-some-pixels</li>
<li>Spends ages getting wall to work properly</li>
<li>Conquers the wall maths!</li>
<li><strong>(2:19)</strong> Adds wall texture</li>
<li>Adds spinning camera</li>
<li>Tweets progress...</li>
<li>Adds input handler</li>
<li>Creates player and binds camera to the keys</li>
<li>Adds "z" movement</li>
<li>Make random cube generation for testing</li>
<li><strong>(3:09)</strong>Adds player/wall collision detection</li>
<li>Fix rendering direction: "Let's flip the Y. Y not?"</li>
<li>Realises the video stream for 3 hours costs $4000. Changes vendors.</li>
</ul>
<h3>Part 2: Adding engine features (2h 00m)</h3>
<p><a href="http://www.twitch.tv/realnotch/b/293076467">Part 2</a> direct link</p>
<p><object type="application/x-shockwave-flash" height="253" width="450" id="clip_embed_player_flash" data="http://www.justin.tv/widgets/archive_embed_player.swf" bgcolor="#000000"><param name="movie" value="http://www.justin.tv/widgets/archive_embed_player.swf" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="auto_play=false&#038;start_volume=25&#038;title=Notch&#038;channel=realnotch&#038;archive_id=293076467" /></object></p>
<ul>
<li>Re-sets up video streaming crap</li>
<li>Adds sprite class</li>
<li>Sprite drawing and clipping</li>
<li>Renders sprite textures</li>
<li><strong>(0:28)</strong> Adds dynamic colouring (greys coloured at render time)</li>
<li>Dynamic colouring for floor and sprites</li>
<li>Switches to 16x16 sprites (double res!)</li>
<li>Messes around with walls and floors designs</li>
<li>Tests screen sizes and scaling</li>
<li><strong>(1:00)</strong> Tests performance and lots-of-sprites</li>
<li>Tweaks the shading a bit</li>
<li>Added dithering</li>
<li>Added a "post-process" step for rendering tweaks</li>
<li>Added per-block colouring</li>
<li>Added per-level floor and roof colouring</li>
<li><strong>(1:35)</strong> Drew a custom font</li>
<li>Created a font renderer</li>
</ul>
<h3>Part 2b: "Getting so tired now" (2h 00)</h3>
<p><a href="http://www.twitch.tv/realnotch/b/293084461">Part 2b direct link</a></p>
<p><object type="application/x-shockwave-flash" height="253" width="450" id="clip_embed_player_flash" data="http://www.justin.tv/widgets/archive_embed_player.swf" bgcolor="#000000"><param name="movie" value="http://www.justin.tv/widgets/archive_embed_player.swf" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="auto_play=false&#038;start_volume=25&#038;title=Notch&#038;channel=realnotch&#038;archive_id=293084461" /></object></p>
<ul>
<li>Snack time!</li>
<li>Created a "level" png file</li>
<li>Added level loader from png</li>
<li>Added cache for loaded levels</li>
<li>Started crashing everything with texture bug</li>
<li><strong>(0:24)</strong> Spawn a player from a colour on png</li>
<li>Fixed rendering directions (things were rendered mirrored)</li>
<li>Tested adding sprites via pixels on png</li>
<li>Started adding game design elements (iron bars)</li>
<li><strong>(0:44)</strong> Made blocking sprites: first room!</li>
<li>Interactable blocks: push-button wall</li>
<li>Fixed artwork manager</li>
<li>Created "switch" block class</li>
<li>Added particle-like smashing to block</li>
<li><strong>(1:20)</strong> Minecraft-esque smash-a-thon</li>
<li>Bit of level design</li>
<li>Add popup message system</li>
<li>"Freedom is temporary and unsatisfying"</li>
<li>Add "Click to focus" when screen unfocused</li>
</ul>
<h3>Part 2c: The end of day one (0h 40m)</h3>
<p><a href="http://www.twitch.tv/realnotch/b/293087310">Part 2c direct link</a><br />
<object type="application/x-shockwave-flash" height="253" width="450" id="clip_embed_player_flash" data="http://www.justin.tv/widgets/archive_embed_player.swf" bgcolor="#000000"><param name="movie" value="http://www.justin.tv/widgets/archive_embed_player.swf" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="auto_play=false&#038;start_volume=25&#038;title=Notch&#038;channel=realnotch&#038;archive_id=293087310" /></object></p>
<ul>
<li>Refactored/cleaned up "blocks with entities" handling</li>
<li>Added boulder entity</li>
<li>Added entity collision detection</li>
<li>Added rolling boulders</li>
<li>Added floor holes</li>
<li>Off to bed</li>
</ul>
<h3>Part 3: Early the next day (1h 13m)</h3>
<p>After a smashing first day of fierce programming, we now rejoin the action on Sunday morning, 8am.<br />
<a href="http://www.twitch.tv/realnotch/b/293125163">Part 3a direct link</a></p>
<p><object type="application/x-shockwave-flash" height="253" width="450" id="clip_embed_player_flash" data="http://www.justin.tv/widgets/archive_embed_player.swf" bgcolor="#000000"><param name="movie" value="http://www.justin.tv/widgets/archive_embed_player.swf" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="auto_play=false&#038;start_volume=25&#038;title=Notch&#038;channel=realnotch&#038;archive_id=293125163" /></object></p>
<ul>
<li>Good morning!</li>
<li>Added chest block</li>
<li>Draw some pick up items</li>
<li>Made game panel GUI (life and pickups)</li>
<li>Rendered currently held item</li>
<li>Added water texture</li>
<li><strong>(1:04)</strong> Added head bobbing when moving</li>
</ul>
<p class="note">{Footage missing: adding using pickup items}</p>
<h3>Part 3b (0h 37m)</h3>
<p><a href="http://www.twitch.tv/realnotch/b/293127222">Part 3b direct link</a><br />
<object type="application/x-shockwave-flash" height="253" width="450" id="clip_embed_player_flash" data="http://www.justin.tv/widgets/archive_embed_player.swf" bgcolor="#000000"><param name="movie" value="http://www.justin.tv/widgets/archive_embed_player.swf" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="auto_play=false&#038;start_volume=25&#038;title=Notch&#038;channel=realnotch&#038;archive_id=293127222" /></object></p>
<h3>Part 4: A plan comes together (2h 00m)</h3>
<p>14 hours: 8 parts.<br />
<a href="http://www.twitch.tv/realnotch/b/293132744">Part 4a direct link</a></p>
<p><object type="application/x-shockwave-flash" height="253" width="450" id="clip_embed_player_flash" data="http://www.justin.tv/widgets/archive_embed_player.swf" bgcolor="#000000"><param name="movie" value="http://www.justin.tv/widgets/archive_embed_player.swf" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="auto_play=false&#038;start_volume=25&#038;title=Notch&#038;channel=realnotch&#038;archive_id=293132744" /></object></p>
<ul>
<li>Adds a torch entity</li>
<li>Creating a dynamic lighting system</li>
<li>Bails on lighting system and removes added code</li>
</ul>
<h3>Part 4: The rest...</h3>
<ul>
<li><a href="http://www.twitch.tv/realnotch/b/293139050">Part 4b</a> (2h 00m)</li>
<li><a href="http://www.twitch.tv/realnotch/b/293146863">Part 4c</a> (2h 00m)</li>
<li><a href="http://www.twitch.tv/realnotch/b/293155149">Part 4d</a> (2h 00m)</li>
<li><a href="http://www.twitch.tv/realnotch/b/293163566">Part 4e</a> (2h 00m)</li>
<li><a href="http://www.twitch.tv/realnotch/b/293171623">Part 4f</a> (2h 00m)</li>
<li><a href="http://www.twitch.tv/realnotch/b/293179154">Part 4g</a> (2h 00m)</li>
</ul>
<h3>Part 4h: I will go to sleep now (0h 43m)</h3>
<p>The final part... <a href="http://www.twitch.tv/realnotch/b/293182081">Part 4h direct link</a></p>
<h3>The End</h3>
<p>Well well well... what a rollercoaster ride that was... highs, lows, chicken, dub step: we had it all, and at the end of the day the game was the real winner. That's all from us here at Lundum Dare #21, until next time - happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/09/27/notch-on-film/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Code like you&#8217;re Notch</title>
		<link>http://www.mrspeaker.net/2011/09/15/code-like-youre-notch/</link>
		<comments>http://www.mrspeaker.net/2011/09/15/code-like-youre-notch/#comments</comments>
		<pubDate>Wed, 14 Sep 2011 16:40:53 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=2889</guid>
		<description><![CDATA[Rich Jones learned stuff from watching Notch code. I learnt some stuff too. Six hundred games: invented, designed, and coded - in 2 days. That was the Lundum Dare game competition #21, held from the 19th to the 22nd of August. Hoards of game makers spent 48 hours creating lil' masterpieces based on the given [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://gun.io/blog/what-i-learned-from-watching-notch-code/">Rich Jones</a> learned stuff from watching Notch code.</p>
<p>I learnt some stuff too.</p>
<p><img src="/images/notch-freedom.jpg" class="frame-left" alt="Freedom is temporary and unsatisfying" /></p>
<p><br style="clear:both"/><br/><strong>Six hundred games</strong>: invented, designed, and coded - in 2 days. That was the <a href="http://ludumdare.com/">Lundum Dare game competition</a> #21, held from the 19th to the 22nd of August. Hoards of game makers spent 48 hours creating lil' masterpieces based on the given theme: "Escape".</p>
<p>One of the superstar contestants was <a href="http://notch.tumblr.com/">Notch</a> of "creator of Minecraft" fame. He took the intrepid step of livestreaming his entire process (which now exists as a <a href="http://www.youtube.com/watch?v=KcfFJ6pNEZk">5 minute timelapse</a> video): every move, every mouse-click, every keypress he made for 2 days - <a href="http://www.mrspeaker.net/2011/09/27/notch-on-film/">streamed live</a> to an average audience of 10,000 viewers.</p>
<p>Over the weekend of the competition I ingested around 30 hours of the action in full screen; surrendering my complete attention to a programmer writing Java. Java! Tens (if not hundreds) of thousands of people watched a guy code Java. It was incredible and inspiring. Here's what I learnt:<span id="more-2889"></span></p>
<h3>Not all programmers are created equal</h3>
<p>Holy crap that guy knows his stuff. After spending 10 minutes talking through some ideas, he settled on making a dungeon crawler. Once decided he started a blank Java project (with no external libraries) and got a screen up displaying random pixels. Then he added some perspective, made a raycaster to render Wolf3D-style walls, implemented camera control, added entities and collision detection, allowed interaction with on-screen elements, created a level system, added pickups and bosses, tweaked all the level designs, added sound and title screens... and was done with a few hours to spare.</p>
<p>For the whole process he consulted the internets exactly 0 times for help. He wrote a raycaster <em>from his brain</em> in one go. He didn't copy-paste old code he'd written, he didn't use any SuperDuper Physics Library (tm)... he just coded to do what he needed - and he knew exactly how to do it.</p>
<p class="note"><strong>What I learnt</strong>: Domain experience is very important. I've done a few of these "code X in a weekend" type things and I've always end up spending 6 hours reading about a subject I'm interested but unfamiliar with. It's still learning, of course, but it doesn't bring immediate results. For a time-based comp it's probably worth scaling back your ideas until you know <em>exactly</em> how you're going to do it.</p>
<h3>The internet is, and distractions are, stupid</h3>
<p><image src="/images/notch-poc-1.png" class="frame-right" />Along with the video stream was a chat session - where the 10,000 viewers could talk about Notch's programming and add their thoughts on game development. Of course, with those kinds of numbers it degenerated pretty quickly into trolls and metatrolls (thankfully the stream was hidden in fullscreen mode). When the trolls weren't shunning Notch for not working on Minecraft updates for them ON THE FUCKING WEEKEND, debate largely centered on the best programming languages for games.</p>
<p>Fights between C++ vs C#, C# vs Flash vs Python, Flash vs GameMaker... every comment explaining in angry details why their preferred language was superior. Notch, however, was never drawn into the fights, because he didn't read one line of the chat logs, because he was too busy creating a complete 2.5D retro dungeon crawler in 48 hours.</p>
<p>In the time it took each flamewar to flare up and subside he'd finished adding a new subsystem to the game. If only games were flamewar powered!</p>
<p>Notch was impervious to all this, and worked eerily distraction-free. He went to Twitter only once (and that was to post an update on his progress). He played Doom for 15 minutes while he ate lunch. He went to sleep for 8 hours on Saturday night. I think he snuck in a toilet break at one stage - I'm not sure. Apart from that, he coded and he drew and he play-tested and THAT'S ALL.</p>
<p class="note"><strong>What I learnt</strong>: Nothing. I already knew I shouldn't be distracted by the intertubes, and that your choice of tool is of <em>absolutely</em> no consequence (and is very boring to read about) - it's only the result that matters. I knew it, but seeing it in practice was awe-inspiring.</p>
<h3>Streamline your process</h3>
<p>Notch used the Eclipse IDE with "hotswap something-something mode" that let him modify code as if he were sitting at a REPL: updating values would instantly and seamlessly update the running game, allowing him to tweak the game mechanics and overall feel very very quickly.</p>
<p>All graphics and level design was done with a simple paint program. At runtime, each game level is extracted from a plain old <code>.png</code> image with each pixel (and it's alpha values) representing the blocks, entities, and triggers in the game. I saw file dialogs maybe, a dozen times throughout the weekend. There was no export phase, no "are your sure?", no "save as interlaced?" - just one keyboard shortcut and the changes were ready to be loaded into the game.</p>
<p class="note"><strong>What I learnt</strong>: Ok, your tools aren't important - but they have to let you work extremely fast. Don't do something with 2 clicks that could be done with 1. Favour simplicity.</p>
<h3>Have a plan</h3>
<p>I can't prove Notch had a plan (perhaps it was just a corollary of his experience), but his impeccable timing leads me to think he did. From the start his pacing was perfect: never rushing but never wasting time. When he finished one aspect of the game he moved straight on to the next. By the time the deadline arrived he was casually adding minor level tweaks.</p>
<p><image src="/images/notch-poc-2.jpg" width="430" class="frame-left" /></p>
<p style="clear:left">It was not all sunshine and lollipops though: at one point Notch decided to add a dynamic lighting system to the game - so torches would cast shadows and some areas would be hidden in darkness. After about 40 minutes he had a basic system functioning - but the effect was not quite right, and there were some graphic glitches. He decided to scrap it.</p>
<p>At the time I was surprised: he seemed pretty close to nailing it... there were only a few issues left to hammer out and it would have been done. But I think he realised he could end up sinking <em>a lot</em> of time perfecting it (there were some parts of the map that were now plunged into total darkness, so more lights would be required) so he decided to scrap it and move on.</p>
<p class="note"><strong>What I learnt</strong>: Timing is everything. Spending time on fancy effects like dynamic lighting reduces time for the truly important aspects of play testing and level design. If you're ahead of schedule you can add some bells and whistles, but the clock is always ticking.</p>
<h3>tl;dr: code like you're Notch</h3>
<p>When I was a kid, a friend and I spent about a million hours learning to ollie on a skateboard. One day after watching an epic skate vid we came up with the genius plan to just "skate like we <em>are</em> one of the guys on the video"... so, cargo-cult style, we just adopted the attitudes and style of the guys we were inspired by: and it worked! Only after truly emulating our heros did we "get it".</p>
<p>The Notch livestream was like an epic skate vid. Only with Java.</p>
<p>As kind of proof that I really did learn something - here's a peek at my cargo-cult-Notch-style game I'm working on: <a href="http://mrspeaker.net/dev/thedarkness/">The Darkness</a>. There's no real game there yet - I'm still experimenting with the mechanics but I'm confident I'll come up with something fun-ish (also, sorry Ross - I borrowed <a href="http://weirdgalaxy.com/">one of your mummies</a>).</p>
<p>It's a HTML5 canvas effort that I plan to complete in under 48 hours (I'm up to about 24.5 so far, averaging 30 minutes to 2 hours a day). If you compare the structure of the app with <a href="https://s3.amazonaws.com/ld48/PoC_source.zip">Notch's source code</a> you'll notice more than a few similarities - but hey, I gotta get my domain knowledge up to scratch somehow!</p>
<p>PS: <a href="http://www.mrspeaker.net/2011/09/27/notch-on-film/">Here's the whole thing</a> for you to watch yourself.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/09/15/code-like-youre-notch/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>What happened to Window Mobile Apps?</title>
		<link>http://www.mrspeaker.net/2011/09/03/what-happened-to-window-mobile-apps/</link>
		<comments>http://www.mrspeaker.net/2011/09/03/what-happened-to-window-mobile-apps/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 14:03:06 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=2883</guid>
		<description><![CDATA[I was messing around with Google's "correlate draw" thingo and found a sad story regarding Windows Mobile Apps mentions... What happened there, hey?!]]></description>
			<content:encoded><![CDATA[<p>I was messing around with <a href="http://www.google.com/trends/correlate/draw">Google's "correlate draw" thingo</a> and found a sad story regarding Windows Mobile Apps mentions...<br />
<img src="/images/winmobapps.png" alt="WinMobApps mentions crash" /></p>
<p>What happened there, hey?!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/09/03/what-happened-to-window-mobile-apps/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

