Skip to content

Instantly share code, notes, and snippets.

@levicole
Created July 6, 2011 14:23
Show Gist options
  • Save levicole/1067343 to your computer and use it in GitHub Desktop.
Save levicole/1067343 to your computer and use it in GitHub Desktop.
require 'rubygems'
class Cell
attr_accessor :n, :s, :e, :w, :visited
def initialize(n, s, e, w, visited)
@n, @s, @e, @w, @visited = n, s, e, w, visited
end
def []=(key, value)
self.send("#{key.to_s}=", value)
end
end
srand(rand(0xFFFF_FFFF).to_i)
width = 10
height = 10
DIRECTIONS = [:n, :s, :e, :w]
XDIR={:n => 0, :s => 0, :e => 1, :w => -1}
YDIR={:n => -1, :s => 1, :e => 0, :w => 0}
grid = []
height.times do
row= []
width.times do
row<<Cell.new(1, 1, 1, 1, false)
end
grid << row
end
def opposite(direction)
{:n => :s, :e => :w, :s => :n, :w => :e}[direction]
end
def carve_passage_from(current_x, current_y, grid)
directions = DIRECTIONS.sort_by{rand}
current_cell = grid[current_y][current_x]
current_cell.visited = true
directions.each do |direction|
new_x, new_y = XDIR[direction] + current_x, YDIR[direction] + current_y
if new_x.between?(0,9) && new_y.between?(0,9) && grid[new_y][new_x].visited == false
next_cell = grid[new_y][new_x]
current_cell[direction] = 0
next_cell[opposite(direction)] = 0
carve_passage_from(new_x, new_y, grid)
end
end
end
carve_passage_from(0, 0, grid)
puts " " + "_" * (width * 2 - 1)
height.times do |y|
print "|"
width.times do |x|
cell = grid[y][x]
print((cell.s == 0) ? " " : "_")
if cell.e == 1
print("|")
else
print((cell.s == 0) ? " " : "_")
end
end
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment