标签:io os ar for on art cti ad bs
local AStar={}
function AStar:create(s_node,e_node,map_list)
local openlist={}
local closelist={}
local maplist=map_list
local startnode={x=s_node.x,y=s_node.y,g=0,h=0,f=0,prenode=nil}
local endnode={x=e_node.x,y=e_node.y}
if startnode.x==endnode.x and startnode.y==endnode.y then
return {}
end
if maplist[endnode.x][endnode.y] > 0 then
return {}
end
local isendnode=nil
local function setH(node)
node[‘h‘]=math.abs(node[‘x‘]-endnode[‘x‘])+math.abs(node[‘y‘]-endnode[‘y‘])
end
local function setG(node)
node[‘g‘]=node[‘prenode‘][‘g‘]+1
end
local function setF(node)
node[‘f‘]=node[‘g‘]+node[‘h‘]
end
local function GetNodeByPoint(node,x,y)
--这里超出的范围--可以根据自己的要求来改
if x<1 or y<1 or x>7 or y>7 then
return
end
if maplist[x][y]>0 then
return
end
for key, var in ipairs(closelist) do
if var.x==x and var.y==y then
return
end
end
local snode={}
snode[‘x‘]=x
snode[‘y‘]=y
snode[‘prenode‘]=node
setH(snode)
setG(snode)
setF(snode)
for key, var in ipairs(openlist) do
if var.x==x and var.y==y then
if snode[‘f‘]>var[‘f‘] then
return
end
var[‘prenode‘]=node
--setH(var)
setG(var)
setF(var)
return
end
end
openlist[#openlist+1]=snode
if (snode[‘x‘] == endnode[‘x‘]) and (snode[‘y‘]==endnode[‘y‘]) then
isendnode=snode
end
end
local function addfengopen(node)
GetNodeByPoint(node, node[‘x‘], node[‘y‘]+1)
GetNodeByPoint(node, node[‘x‘], node[‘y‘]-1)
GetNodeByPoint(node, node[‘x‘]+1, node[‘y‘])
GetNodeByPoint(node, node[‘x‘]-1, node[‘y‘])
end
local function findmin()
local fmin=9999
local node=nil
local index=nil
for key, var in ipairs(openlist) do
if fmin>var[‘f‘] then
fmin=var[‘f‘]
node=var
index=key
end
end
if node then
table.remove(openlist,index)
return node
end
end
local function search()
local currentnode=startnode
currentnode[‘g‘]=1
setH(currentnode)
setF(currentnode)
closelist[#closelist+1]=currentnode
local xunluan=0
while true do
addfengopen(currentnode)
currentnode=findmin()
if not currentnode then
return {}
end
closelist[#closelist+1]=currentnode
-- print(‘open list ...‘)
-- showtable1:printtable(openlist)
-- print(‘close list ...‘)
-- showtable1:printtable(closelist)
if isendnode then
print(‘tui chu‘,isendnode,xunluan)
break
end
xunluan=xunluan+1
end
--找到了路径
local apath={}
while isendnode[‘prenode‘] do
apath[#apath+1]={x=isendnode[‘x‘],y=isendnode[‘y‘]}
isendnode=isendnode[‘prenode‘]
end
return apath
end
return search()
end
return AStar
标签:io os ar for on art cti ad bs
原文地址:http://www.cnblogs.com/wpcf/p/4049866.html