Year: 2011

A Clever Programming Trick...

If you need to swap the values of two variables, this usually requires a third temporary variable (that is, if you're not using a language like Python that supports the a, b = b, a syntax.) It looks something like this:

temp = a;
a = b;
b = temp;

But if these are integer variables, there's a nifty trick to save yourself a little bit of memory. You can use arithmetic instead of a temporary variable:

a = a + b;
b = a - b;
a = a - b;

If the integers on your platform are 32-bits, your new swap will save four bytes of memory.

This is a programming tutorial for beginner and intermediate programmers who want to learn what recursion is. The programming language used for the examples is Python, but you can probably follow along if you know programming in some other language such as PHP or JavaScript. There’s a lot more information about recursion on the Wikipedia article: http://en.wikipedia.org/wiki/Recursion_(computer_science) But this guide is meant to be a more practical guide to show how handy recursion is.

The source code of everything in this article can be downloaded here: floodfill_src.zip

Consider the Lazy Zombie

This is a cat:

This is a normal human:

This is a normal human who has been turned into an ungodly, flesh-eating zombie of the undead:

Zombies are lazy and will only bite things that are next to them. Humans that are bitten will then turn into zombies:

There is an interesting recursive principle here, because the humans that have turned into zombies will start to bite other humans that are next to them, which will make more zombies, who bite more adjacent humans, which will make more zombies, and so on and so on in a chain reaction:

Here's the source code for a Bejeweled clone called Gemgem, written in Python with the Pygame library. You’ll need Python (2 or 3) and Pygame installed to run it. I've tried to keep the source code simple so it's easy to follow and learn programming and Pygame from it. It comes in under 540 lines of code, including whitespace & comments.

To play, click on (or drag over) two adjacent gems to swap their position. You need to swap them so that there are three or more gems of the same type in a row. This causes the gems to disappear and new gems to fall in their place. You get more points for chain reactions or more-than-three matches. The score constantly trickles down, so solve as fast as possible. The game ends when no more moves can be made.

Here's a Sokoban ("box pusher") clone called Star Pusher. I've used the graphics from the Planet Cute collection. You'll need Python (2 or 3) and Pygame installed to run it. Just download and unzip the files to the same directory. It comes with 201 levels from David W. Skinner.