Class: Pathfinding::AStarFinder

Inherits:
Object
  • Object
show all
Defined in:
lib/pathfinding/a_star_finder.rb

Overview

An A* Pathfinder to build roads/paths between two coordinates containing different path costs, the heuristic behaviour that can be altered via configuration

Instance Method Summary collapse

Instance Method Details

#find_path(start_node, end_node, grid) ⇒ Object



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
# File 'lib/pathfinding/a_star_finder.rb', line 12

def find_path(start_node, end_node, grid)
  came_from = {}
  g_score = { start_node => 0 }
  f_score = { start_node => manhattan_distance(start_node, end_node) }

  open_set = Pathfinding::PriorityQueue.new
  open_set.push(start_node, f_score[start_node])

  closed_set = Set.new
  until open_set.empty?
    current = open_set.pop

    # Early exit if the current node is in the closed set
    next if closed_set.include?(current)

    # Mark the current node as visited
    closed_set.add(current)

    return reconstruct_path(came_from, current) if current == end_node

    grid.neighbors(current).each do |neighbor|
      tentative_g_score = g_score[current] + 1

      next if closed_set.include?(neighbor) || (g_score[neighbor] && tentative_g_score >= g_score[neighbor])

      came_from[neighbor] = current
      g_score[neighbor] = tentative_g_score
      f_score[neighbor] = g_score[neighbor] + heuristic_cost_estimate(neighbor, end_node)

      open_set.push(neighbor, f_score[neighbor])
    end
  end

  # No path found
  []
end