astar

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 1, 2024 License: MIT Imports: 3 Imported by: 0

README

go-astar

Build and test

A 2d AStar implementation in Go.

// will traverse the 1
weights := []int{
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 1, 0, 1, 1, 1, 0, 0,
    0, 1, 1, 1, 0, 1, 1, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
}
grid := astar.NewGridFromSlice(8, 4, weights)

pathfinder := astar.NewPathfinder(grid)
got := pathfinder.Find(astar.Vec2{1, 1}, astar.Vec2{6, 2})

want := []astar.Vec2{
    {1, 1},
    {1, 2},
    {2, 2},
    {3, 2},
    {3, 1},
    {4, 1},
    {5, 1},
    {5, 2},
    {6, 2},
}

fmt.Println(slices.Equal(got, want)) // true

see my c# implementation

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Grid

type Grid[T any] struct {
	Width  int
	Height int
	// contains filtered or unexported fields
}

Grid is a 2D grid of any type.

func NewGrid

func NewGrid[T any](width, height int) Grid[T]

NewGrid creates a new grid with the given width and height.

func NewGridFromSlice

func NewGridFromSlice[T any](width, height int, values []T) Grid[T]

NewGridFromSlice creates a new grid with the given width and height and fills it with the given slice.

func (*Grid[T]) Get

func (b *Grid[T]) Get(v Vec2) T

Get returns the value at the given position.

func (*Grid[T]) Set

func (b *Grid[T]) Set(v Vec2, val T)

Set sets the value at the given position.

type Option

type Option func(o *option)

Option is a functional option for the pathfinder.

func EuclideanDistance added in v0.0.2

func EuclideanDistance() Option

EuclideanDistance sets the heuristic to Euclidean distance.

func PunishChangeDirection

func PunishChangeDirection() Option

PunishChangeDirection punishes changing direction when calculating G.

func WithDiagonals

func WithDiagonals() Option

WithDiagonals enables diagonal movement in the search space.

type Pathfinder

type Pathfinder struct {
	// contains filtered or unexported fields
}

Pathfinder is a simple A* pathfinding algorithm implementation.

func NewPathfinder

func NewPathfinder(weights Grid[int], opts ...Option) Pathfinder

NewPathfinder creates a new Pathfinder with the given weights and options. The weights are used to determine the cost of traversing a cell. A weight of 0 means the cell is not traversable. A weight of 1 or higher means the cell is traversable.

func (Pathfinder) Find

func (p Pathfinder) Find(startPos, endPos Vec2) []Vec2

Find returns a path from start to end. If no path is found, an empty slice is returned.

type Vec2

type Vec2 struct {
	X int // X denotes the horizontal position.
	Y int // Y denotes the vertical position.
}

Vec2 defines a 2D vector.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL