Skip to content

Instantly share code, notes, and snippets.

@yous
Created April 19, 2015 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yous/bd45694ee0c04cf36ca5 to your computer and use it in GitHub Desktop.
Save yous/bd45694ee0c04cf36ca5 to your computer and use it in GitHub Desktop.
def print_maze(width, height, hori_walls, vert_walls)
puts ' ' + '-' * (width * 2 - 1)
(height - 1).times do |y|
print '|'
(width - 1).times do |x|
print ' '
print hori_walls[y][x] ? '|' : ' '
end
puts ' |'
width.times do |x|
print ' '
print vert_walls[y][x] ? '-' : ' '
end
puts
end
print '|'
(width - 1).times do |x|
print ' '
print hori_walls[height - 1][x] ? '|' : ' '
end
puts ' |'
puts ' ' + '-' * (width * 2 - 1)
end
def generate_maze(width, height)
# Walls between horizontally adjacent cells
hori_walls = []
height.times { hori_walls << Array.new(width - 1).map { true } }
# Walls between vertically adjacent cells
vert_walls = []
(height - 1).times { vert_walls << Array.new(width).map { true } }
visited = []
(width * height).times { visited << false }
x, y = [0, 0]
stack = []
while visited.include?(false)
neighbors = []
neighbors << [x - 1, y] if x > 0 && !visited[y * width + x - 1]
neighbors << [x + 1, y] if x < width - 1 && !visited[y * width + x + 1]
neighbors << [x, y - 1] if y > 0 && !visited[(y - 1) * width + x]
neighbors << [x, y + 1] if y < height - 1 && !visited[(y + 1) * width + x]
if neighbors.empty?
if stack.empty?
index = visited.map.with_index.select { |v, i| !v }.sample[1]
x, y = index % width, index / width
visited[y * width + x] = true
else
x, y = stack.pop
end
else
neighbor = neighbors.sample
stack << [x, y]
if neighbor[0] == x
vert_walls[[neighbor[1], y].min][x] = false
else
hori_walls[y][[neighbor[0], x].min] = false
end
x, y = neighbor
visited[y * width + x] = true
end
end
print_maze(width, height, hori_walls, vert_walls)
end
# generate_maze(10, 10)
# -------------------
# | | | |
# - - -
# | | | | | | | |
# - - - -
# | | | | | | |
# - - -
# | | | | | | | | |
# - -
# | | | | | | |
# - - - - -
# | | | | | | |
# - - - -
# | | | | | | |
# - - -
# | | | | | | |
# - - - - -
# | | | | | |
# - - - - - -
# | | |
# -------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment