pathfind

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

Package pathfind 提供网格地图上的 A* 寻路,纯计算、纯标准库、零依赖。

适用:塔防 / SLG / MMO 小地图的自动寻路、怪物追击、点击移动。把地图抽象成 二维网格(Grid),每格可通行或阻挡、可带移动代价(如沼泽更慢);FindPath 返回 从起点到终点的最短路径(格子序列)。

算法:A*(带启发式的最短路),启发函数按是否允许对角移动自动选择—— 四方向用曼哈顿距离,八方向用对角(Chebyshev/octile)距离,保证 admissible (不高估),从而路径最优。开集用最小堆,闭集用 visited 标记。

网格坐标:X 为列、Y 为行,原点 (0,0) 在左上。对角移动默认关闭;开启后默认 禁止"穿墙角"(两侧都是障碍时不允许斜穿),可配置放开。

Grid 构建后若地图不变则并发安全(只读);FindPath 无共享可变状态,可并发调用 同一 Grid。动态改格子(SetBlocked/SetCost)需调用方自行同步。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Grid

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

Grid 二维网格地图。每格有通行性与移动代价(>=1)。零值不可用,用 NewGrid 构造。

func NewGrid

func NewGrid(width, height int) *Grid

NewGrid 创建 width×height 的网格,初始全部可通行、代价 1。

func (*Grid) FindPath

func (g *Grid) FindPath(from, to Point, opts ...Option) []Point

FindPath 求 from 到 to 的最短路径,返回从 from 到 to(含两端)的格子序列。 无路可达返回 nil。from/to 越界或本身阻挡则返回 nil。

func (*Grid) Height

func (g *Grid) Height() int

Height 返回网格高(行数)。

func (*Grid) InBounds

func (g *Grid) InBounds(p Point) bool

InBounds 判断坐标是否在网格内。

func (*Grid) IsBlocked

func (g *Grid) IsBlocked(p Point) bool

IsBlocked 返回格子是否阻挡(越界视为阻挡)。

func (*Grid) SetBlocked

func (g *Grid) SetBlocked(p Point, blocked bool)

SetBlocked 设置格子是否阻挡(越界忽略)。

func (*Grid) SetCost

func (g *Grid) SetCost(p Point, cost int)

SetCost 设置进入某格的移动代价(<1 会被夹到 1;越界忽略)。 代价越高越"难走",A* 会倾向绕开(如沼泽=5、平地=1)。

func (*Grid) Width

func (g *Grid) Width() int

Width 返回网格宽(列数)。

type Option

type Option func(*config)

Option 配置寻路行为。

func WithCutCorner

func WithCutCorner(allow bool) Option

WithCutCorner 允许"贴墙角斜穿"(默认禁止:对角移动时两侧格子任一阻挡即不可斜穿)。 仅在开启对角移动时有意义。

func WithDiagonal

func WithDiagonal(allow bool) Option

WithDiagonal 允许八方向(含对角)移动(默认仅四方向)。

type Point

type Point struct {
	X, Y int
}

Point 网格坐标(X=列, Y=行)。

Jump to

Keyboard shortcuts

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