Class: Amaze::Algorithm::HuntAndKill

Inherits:
Amaze::Algorithm show all
Defined in:
lib/amaze/algorithm/hunt_and_kill.rb

Instance Attribute Summary

Attributes inherited from Amaze::Algorithm

#duration

Instance Method Summary collapse

Methods inherited from Amaze::Algorithm

#on, #speed

Instance Method Details

#statusObject



50
51
52
# File 'lib/amaze/algorithm/hunt_and_kill.rb', line 50

def status
  "Hunt and Kill algorithm: #{duration}s"
end

#work(grid) ⇒ Object



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
# File 'lib/amaze/algorithm/hunt_and_kill.rb', line 4

def work grid
  
  current = grid.random_cell
  path = [] # visualize
  
  while current
    unvisited_neighbors = current.neighbors.select {|c| c.links.empty? }

    path << current                               # visualize
    yield Stat.new(                               #
      current: path,                              #
      pause: unvisited_neighbors.empty?,          #
      info: "Path: #{path.size}") if block_given? #

    # kill
    if unvisited_neighbors.any?
      neighbor = unvisited_neighbors.sample
      current.link neighbor
      current = neighbor
      
    # hunt
    else
      current = nil

      path = [] # visualize
      hunt = 0  #

      grid.each_cell do |cell|
        visited_neighbors = cell.neighbors.select {|c| c.links.any? }

        yield Stat.new(                                       # visualize
          current: [cell],                                    #
          pause: cell.links.empty? && visited_neighbors.any?, #
          info: "Hunt: #{hunt += 1}") if block_given?         #

        if cell.links.empty? && visited_neighbors.any?
          current = cell
          neighbor = visited_neighbors.sample
          current.link neighbor
          break
        end
      end
    end
  end
end