Skip to content

Instantly share code, notes, and snippets.

@5thWall
Created August 19, 2010 00:50
Show Gist options
  • Save 5thWall/536680 to your computer and use it in GitHub Desktop.
Save 5thWall/536680 to your computer and use it in GitHub Desktop.
Simple recursive maze class
#!/usr/bin/env ruby
# maze.rb
class Integer
def odd?
self % 2 == 1
end
end
class Maze
DIR = {
:N => {:x => 0, :y => -1},
:S => {:x => 0, :y => 1},
:E => {:x => 1, :y => 0},
:W => {:x => -1, :y => 0}
}
WALL = {
"NSEW" => 206.chr,
"NSE" => 204.chr,
"NSW" => 185.chr,
"NS" => 186.chr,
"N" => 186.chr,
"NEW" => 202.chr,
"NE" => 200.chr,
"NW" => 188.chr,
"SEW" => 203.chr,
"SE" => 201.chr,
"SW" => 187.chr,
"S" => 186.chr,
"EW" => 205.chr,
"E" => 205.chr,
"W" => 205.chr
}
def initialize(x = 30, y = 15)
x = x >= 5 ? x : 5
x += 1 unless x.odd?
y = y >= 5 ? y : 5
y += 1 unless y.odd?
fill_in!(x, y)
dig_out!
#purdify_map!
end
def fill_in!(x, y)
puts "Filling in the maze..."
@map = Array.new
y.times { |i| @map[i] = ['#'] * x }
end
def dig_out!
puts "Digging out a new maze..."
visit!(1, 1)
end
def purdify_map!
@map.size.times do |y|
@map[y].size.times do |x|
if is_wall?(x, y)
walls = DIR.keys.inject('') do |walls, dir|
walls += is_wall?(x, y, dir) ? dir.to_s : ''
end
@map[y][x] = WALL[walls]
end
end
end
end
def print_map
@map.each do |line|
puts line.join('')
end
nil
end
def is_wall?(x, y, dir = nil, offset = 1)
if dir
x += (offset * DIR[dir][:x])
y += (offset * DIR[dir][:y])
end
return false if x >= @map[0].length or x < 0
return false if y >= @map.length or y < 0
@map[y][x] != ' '
end
private
def visit!(x, y)
@map[y][x] = ' '
DIR.keys.sort_by { rand }.each do |dir|
punch_through!(x, y, dir) if is_wall?(x, y, dir, 2)
end
end
def punch_through!(x, y, dir)
@map[y + DIR[dir][:y]][x + DIR[dir][:x]] = ' '
visit!(x + (2 * DIR[dir][:x]), y + (2 * DIR[dir][:y]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment