Class: AStar

Inherits:
Path show all
Defined in:
lib/delve/path/astar.rb

Instance Method Summary collapse

Constructor Details

#initialize(to_x, to_y, free_checker, options = Hash.new) ⇒ AStar

Returns a new instance of AStar.



5
6
7
8
9
10
11
12
# File 'lib/delve/path/astar.rb', line 5

def initialize(to_x, to_y, free_checker, options = Hash.new)
  super to_x, to_y, free_checker, options

  @todo = Array.new
  @done = Hash.new
  @from_x = nil
  @from_y = nil
end

Instance Method Details

#compute(from_x, from_y) ⇒ Object



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
# File 'lib/delve/path/astar.rb', line 14

def compute(from_x, from_y)
  raise 'Cannot compute path without a block' unless block_given?

  @todo = Array.new
  @done = Hash.new
  @from_x = from_x
  @from_y = from_y
  add @to_x, @to_y, nil

  while @todo.length > 0
    item = @todo.shift
    break if item[:x] == from_x and item[:y] == from_y
    neighbours = get_neighbours item[:x], item[:y]

    (0..neighbours.length-1).each do |i|
      neighbour = neighbours[i]
      x = neighbour[0]
      y = neighbour[1]
      id = "#{x},#{y}"
      next if @done.include? id
      add x, y, item
    end
  end

  item = @done["#{from_x},#{from_y}"]
  return nil if item.nil?

  until item.nil?
    yield item[:x], item[:y]
    item = item[:prev]
  end
end