Why has HTML5's 〈canvas〉 element has captured people's attention?
For all it's awesomeness, Canvas has drawbacks as well:
Plenty of third-party libraries / frameworks available, but there are tradeoffs
DIY = Do It Yourself
DRY = Don't Repeat Yourself
Push as little code down the wire as possible
DRY-U-DIY-IMA™
Take inspiration from everywhere you can
# --------------------------------------------------------------------
# 2. Set up constants to aid with describing the passage directions
# --------------------------------------------------------------------
N, S, E, W = 1, 2, 4, 8
DX = { E => 1, W => -1, N => 0, S => 0 }
DY = { E => 0, W => 0, N => -1, S => 1 }
OPPOSITE = { E => W, W => E, N => S, S => N }
# --------------------------------------------------------------------
# 3. The recursive-backtracking algorithm itself
# --------------------------------------------------------------------
def carve_passages_from(cx, cy, grid)
directions = [N, S, E, W].sort_by{rand}
directions.each do |direction|
nx, ny = cx + DX[direction], cy + DY[direction]
if ny.between?(0, grid.length-1) && nx.between?(0, grid[ny].length-1) && grid[ny][nx] == 0
grid[cy][cx] |= direction
grid[ny][nx] |= OPPOSITE[direction]
carve_passages_from(nx, ny, grid)
end
end
end
carve_passages_from(0, 0, grid)
// --------------------------------------------------------------------
// 2. Set up constants & helper functions
// --------------------------------------------------------------------
var N = 1, S = 2, E = 4, W = 8,
DIRECTIONS = { N: 1, S: 2, E: 4, W: 8 },
DX = { E: 1, W: -1, N: 0, S: 0 },
DY = { E: 0, W: 0, N: -1, S: 1 },
OPPOSITE = { E: W, W: E, N: S, S: N }
function shuffle(array)
{ // from http://stackoverflow.com/questions/5150665/generate-random-list-of-unique-rows-columns-javascript
for(var j, x, i = array.length; i; j = parseInt(Math.random() * i), x = array[--i], array[i] = array[j], array[j] = x);
return array;
};
// --------------------------------------------------------------------
// 3. The recursive-backtracking algorithm itself
// --------------------------------------------------------------------
function carve_passages_from(cx, cy, grid) {
dir_keys = shuffle("NSEW".split(''));
for (var d=0; d= 0 && ny <= grid.length-1) && (nx >= 0 && nx <= grid[ny].length-1) && (grid[ny][nx].d == 0)) {
grid[cy][cx].d |= DIRECTIONS[dir];
grid[ny][nx].d |= OPPOSITE[dir];
carve_passages_from(nx, ny, grid)
}
}
}
/