summaryrefslogtreecommitdiff
path: root/maze_generator.rb
blob: 951e0d74a4cce8ca92c147c81c20b0e27dc518ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require_relative 'pos'
require_relative 'maze'

class MazeGenerator
  attr_reader :maze

  def initialize(width, height, stack_threshold = nil)
    @maze = Maze.new(width, height)

    @stack_threshold = if stack_threshold
      stack_threshold
    else
      width * height
    end

    @visitedTiles = Array.new(width) { Array.new(height) { false } }
  end

  def generate!()
    start_pos = Pos.new(rand(@maze.width), rand(@maze.height))
    @visitedTiles[start_pos.x][start_pos.y] = true
    @stack = [start_pos]

    if ENV["DEBUG"] == "visual"
      TUI::Screen.save
      TUI::Screen.reset
      puts
      puts "   [ #{TUI::Color.magenta}Generating maze...#{TUI::Color.reset} ]"
      puts
      TUI::Cursor.save
    end

    while !@stack.empty?
      step()

      if ENV["DEBUG"] == "visual"
        TUI::Cursor.restore
        puts @maze.to_s("   ")
        puts
        TUI::Screen.reset_line
        puts "   Stack size: #{@stack.length}"
        if @stack.length < @stack_threshold
          TUI::Screen.reset_line
          puts "   Current algorithm: Depth-first search"
        else
          TUI::Screen.reset_line
          puts "   Current algorithm: Breath-first search"
        end
      end
    end

    if ENV["DEBUG"] == "visual"
      TUI::Screen.restore
    end
  end

  def step()
    current_tile =  if @stack.length < @stack_threshold
      @stack.last
    else
      @stack.first
    end

    neighbors = @maze.neighbors(current_tile)
    neighbors.select! do |neighbor|
      @visitedTiles[neighbor.x][neighbor.y] == false
    end

    if neighbors.empty?
      if @stack.length < @stack_threshold
        @stack.pop()
      else
        @stack.shift()
      end
    else
      randomNeighbor = neighbors.sample
      print "Removing wall between ", current_tile, " and ", randomNeighbor, "\n" if ENV["DEBUG"] == "log"
      @maze.set(current_tile, randomNeighbor.dir_from(current_tile), false)

      @stack.push(randomNeighbor)
      @visitedTiles[randomNeighbor.x][randomNeighbor.y] = true
    end
  end
end