--[[
A*寻路算法,目前只适用于 01图, 0可通行, 1不可通行
--]]
-- 行走的4个方向
local four_dir = {
{1, 0},
{0, 1},
{0, -1},
{-1, 0},
}
-- 行走的8个方向
local eight_dir = {
{1, 1},
{1, 0},
{1, -1},
{0, 1},
{0, -1},
{-1, 1},
{-1, 0},
{-1, -1}
}
local AStar = {}
-- 地图、起始点、终点
AStar.init = function(self, map, startPoint, endPoint, four_dir)
self.startPoint = startPoint
self.endPoint = endPoint
self.map = map
self.cost = 10 -- 单位花费
self.diag = 1.4 -- 对角线长, 根号2 一位小数
self.open_list = {}
self.close_list = {}
self.mapRows = #map
self.mapCols = #map[1]
self.four_dir = four_dir -- 使用4方向的寻路还是八方向的寻路
end
-- 搜索路径 ,核心代码
AStar.searchPath = function(self)
-- 验证终点是否为阻挡,如果为阻挡,则直接返回空路径
if self.map[self.endPoint.row][self.endPoint.col] ~= 0 then
Logger.info("(", self.endPoint.row, ",", self.endPoint.col, ") 是阻挡!!!无法寻路")
return nil
end
-- 把第一节点加入 open_list中
local startNode = {}
startNode.row = self.startPoint.row
startNode.col = self.startPoint.col
startNode.g = 0
startNode.h = 0
startNode.f = 0
table.insert(self.open_list, startNode)
-- 检查边界、障碍点
local check = function(row, col)
if 1 <= row and row <= self.mapRows and 1 <= col and col <= self.mapCols then
&

该博客介绍了如何使用Lua实现A*寻路算法,适用于01图,提供了4个和8个方向的行走选择。文章详细讲解了算法的核心部分,包括节点的开放列表和关闭列表管理,以及路径构建和估价函数。
最低0.47元/天 解锁文章
6407

被折叠的 条评论
为什么被折叠?



