Skip to content

Instantly share code, notes, and snippets.

@itarato
Created February 1, 2017 19: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 itarato/40db27091721facc4e009199728af043 to your computer and use it in GitHub Desktop.
Save itarato/40db27091721facc4e009199728af043 to your computer and use it in GitHub Desktop.
Maze generator
EMPTY = 0x0
UP = 0x1
RIGHT = 0x2
DOWN = 0x4
LEFT = 0x8
# Maze generator class.
class Generator
def initialize(w, h)
@w = w
@h = h
@maze = (0...@h).map { [EMPTY] * @w }
end
def out
@maze.each do |row|
row.each { |cell| print ' ║═╚║║╔╠═╝═╩╗╣╦╬'[cell] }
puts
end
end
def opposite(dir)
return UP if dir == DOWN
return DOWN if dir == UP
return RIGHT if dir == LEFT
return LEFT if dir == RIGHT
EMPTY
end
def make
queue = [[0, 0]]
@maze[0][0] = UP
until queue.empty?
cell = queue.shift
available_neighbors = get_available_neighbors cell
had_one = false
unless available_neighbors.empty?
available_neighbors.map { |k, v| [k, v] }.shuffle.each do |k, v|
break if had_one and rand(10) < 9
@maze[cell[0]][cell[1]] |= k
@maze[v[0]][v[1]] = opposite(k)
queue << v
had_one = true
end
end
end
end
def get_available_neighbors(cell)
available = {}
{ UP => [-1, 0], DOWN => [1, 0], LEFT => [0, -1], RIGHT => [0, 1] }.each do |dir, coord|
y = cell[0] + coord[0]
x = cell[1] + coord[1]
available[dir] = [y, x] if y.between?(0, @h - 1) && x.between?(0, @w - 1) && @maze[y][x] == EMPTY
end
available
end
end
# mg = Generator.new(96, 24)
# mg = Generator.new(356, 96)
mg = Generator.new(128, 46)
mg.make
mg.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment