Beautiful Algorithms 2: Tunnels (Part 2)
This is Part 2 of the Tunnels tutorial, Part 1 can be found here: Beautiful Algorithms 2: Tunnels.
Note: The code examples in this article might not appear in your feed reader.
Lookup Tables
Lookup tables are basically arrays of values. Referring to elements in an array is faster than calculating them. Doing this in Ruby is almost as simple as:
100.times.collect { |i| Math.sin i * (Math::PI / 180) }
The tunnels code calculates sin and cos for values that would evenly plot a circle for a given table size. The table length is calculated based on precision:
@precision = 0.2
@inverse = 1.0 / @precision
@table_length = (360.0 * @inverse).to_i
I’ve also used the lookup class to store the current X and Y direction of the tunnels. I’m using the lookup class a little bit like a global variable so other classes can coordinate with commonly referenced values.
Movement
Recall that rings are deleted when they get too large. At this point the global direction is changed. There’s a method called Lookup.change_direction which is used to do this. Each time a ring is initialized the current direction in Lookup is referenced.
Change direction is random, but constrained. This causes the tunnel to gently move around the screen as new rings are added.
Palette
A palette is created just like in the Fire algorithm, except this time it’s shades of blue rather than red to yellow. As the rings get larger they get brighter too.
Putting it Together
The final example can be downloaded here: tunnel-p5r. For instructions on how to run it, see the Fire tutorial.

