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 a602449
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
28 changes: 16 additions & 12 deletions astar.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,18 @@ 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
// Find returns a path from start to end. If no path is found, an empty slice
// is returned.
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 +45,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 +61,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
4 changes: 2 additions & 2 deletions grid.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ func NewGrid[T any](width, height int) Grid[T] {

// NewGridFromSlice creates a new grid with the given width and height and
// fills it with the given slice.
func NewGridFromSlice[T any](width, height int, weights []T) Grid[T] {
func NewGridFromSlice[T any](width, height int, values []T) Grid[T] {
inner := make([]T, width*height)
copy(inner, weights)
copy(inner, values)

grid := Grid[T]{
Width: width,
Expand Down

0 comments on commit a602449

Please sign in to comment.