Class: Knossos::Algorithm::Wilsons

Inherits:
Object
  • Object
show all
Defined in:
lib/knossos/algorithm/wilsons.rb

Instance Method Summary collapse

Constructor Details

#initializeWilsons

Returns a new instance of Wilsons.



4
5
6
# File 'lib/knossos/algorithm/wilsons.rb', line 4

def initialize
  # nothing to do
end

Instance Method Details

#carve(grid:, seed: nil) ⇒ Object



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
# File 'lib/knossos/algorithm/wilsons.rb', line 8

def carve(grid:, seed: nil)
  srand(seed || Kernel.srand)

  unvisited = []
  grid.each_cell { |cell| unvisited << cell }

  unvisited.delete(unvisited.sample)
  while unvisited.any?
    cell = unvisited.sample
    path = [cell]

    while unvisited.include?(cell)
      cell = grid.neighborhood(cell).sample

      position = path.index(cell)
      if position
        path = path[0..position]
      else
        path << cell
      end
    end

    0.upto(path.length - 2) do |index|
      grid.build_passage(path[index], path[index + 1])
      unvisited.delete(path[index])
    end
  end

  grid
end