标签:
---------AStar.lua文件
local Point = require("Point")
local Map = --Map 地图信息 1不可以走 0可以走
{
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,0,0,1},
{1,0,0,0,0,0,1,0,0,1},
{1,0,0,0,0,0,1,0,0,1},
{1,0,1,1,0,1,1,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,1,1,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1},
}
local Direcion = {--走的放向 8个方向可以走
{1,1},
{1,0},
{1,-1},
{0,-1},
{-1,-1},
{-1,0},
{-1,1},
{0,1},
}
local OpenList = {} --open list 开放列表
local CloseList = {} --clost list 闭合列表
function existsPoint(list,point)
for i, p in pairs(list) do
if (p.x == point.x) and (p.y == point.y) then
return true
end
end
return false
end
local findPath = function(s,e)
s.g = 0;
s.h = math.abs(e.x-s.x) + math.abs(e.y - s.y);
s.f = s.g + s.h;
s.parent = nil
table.insert(OpenList,s);
while #OpenList ~=0 do
table.sort(OpenList, function(p1,p2) return p1.f<p2.f end)
local temp = OpenList[1];
print("----------OpenList--------------")
temp:print()
print("------------------------")
table.remove(OpenList,1);
table.insert(CloseList,temp);
for i=1,8 do --遍历8个方向
local p = temp:add(Point:new(Direcion[i][1],Direcion[i][2]));
p:print()
if (not existsPoint(CloseList,p)) and
Map[p.x][p.y] ~=1 then
local tempg = temp.g + 1;
local temph = math.abs(e.x-p.x) + math.abs(e.y - p.y);
local tempf = tempg + temph
if p.f == 0 or p.f > tempf then
p.g = tempg;
p.h = temph;
p.f = tempf;
p.parent = temp
table.insert(CloseList, p);
table.insert(OpenList, p);
end
if p.x == e.x and p.y == e.y then
return p;
end
end
end
end
end
local p = findPath(Point:new(4,4),Point:new(2,9))
print("---------path-----------")
while p do
p:print();
p = p.parent;
end
print("--------------------")
---------------------------Point.lua文件
local Point = {}
Point.__index = Point
function Point:new(x,y)
local t = {}
setmetatable(t,self)
t.x = x;
t.y = y;
t.g = 0;
t.h = 0;
t.f = 0;
return t;
end
function Point:print()
print(self.x .. " " .. self.y .. " " .. self.f);
end
function Point:add(p1)
local x = self.x + p1.x;
local y = self.y + p1.y;
return Point:new(x,y);
end
return Point;
标签:
原文地址:http://www.cnblogs.com/chuyunfei/p/5793912.html