Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
val antonini committed Apr 28, 2024
1 parent 7ac71d5 commit a2e4e63
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions astar.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,16 @@ func NewPathfinder(weights Grid[int]) Pathfinder {
}

// Find returns a path from start to end. If no path is found, an empty slice.
func (p Pathfinder) Find(start, end Vec2) []Vec2 {
open := newMinHeap(p.weights.Width, p.weights.Height)
searchSpace := newSearchSpace(p.weights) // tracks the open, closed and f values of each node
func (p Pathfinder) Find(startPos, endPos Vec2) []Vec2 {
searchSpace := newSearchSpace(p.weights) // tracks the open, closed and f values of each node
open := newMinHeap(searchSpace.Width, searchSpace.Height) // prioritised queue of f

origin := searchSpace.Get(start)
origin.f = 0
start := searchSpace.Get(startPos)
start.f = 0
start.open = true

open.push(heapNode{pos: start})
searchSpace.Set(start, origin)
open.push(heapNode{pos: startPos, f: start.f})
searchSpace.Set(startPos, start)

for open.len() > 0 {
qPos := open.pop().pos
Expand All @@ -43,12 +44,12 @@ func (p Pathfinder) Find(start, end Vec2) []Vec2 {

successor.parent = &q
successor.g = q.g + manhattan(qPos, succPos)
successor.h = manhattan(succPos, end)
successor.h = manhattan(succPos, endPos)
successor.f = successor.g + successor.h
successor.open = true

// found
if succPos == end {
if succPos == endPos {
path := []Vec2{}
var curr *node = &successor
for curr != nil {
Expand All @@ -59,22 +60,24 @@ func (p Pathfinder) Find(start, end Vec2) []Vec2 {
return path
}

// check if more optimal path to successor was already encountered
existingSuccessor := searchSpace.Get(succPos)

if existingSuccessor.open && existingSuccessor.f < successor.f {
continue
}

if existingSuccessor.closed && existingSuccessor.f < successor.f {
continue
}

searchSpace.Set(succPos, successor)
open.push(heapNode{pos: succPos, f: successor.f})
}

q.closed = true
searchSpace.Set(qPos, q)
}

// not found
return []Vec2{}
}

Expand Down

0 comments on commit a2e4e63

Please sign in to comment.