local RoadPoint = {}
function RoadPoint:CreateNode(p)
-- body
local t = {}
t.g = -1;
t.h = -1;
t.f = 0;
t.point = p;
t.parent = nil;
return t;
end
-- 判斷p是否在open表中
function RoadPoint:exists(p)
for i =1,#self.open do
if self.open[i].point.x == p.x and self.open[i].point.y == p.y then
return true;
return false;
function RoadPoint:FindPath(startp,endp,maskparent)
release_print(string.format("開始點:x--%d,y--%d",startp.x,startp.y));
release_print(string.format("結束點:x--%d,y--%d",endp.x,endp.y));
self.step = 40;
self.open = {};
self.close = {};
self.childs = maskparent:getChildren();
self.childCount = maskparent:getChildrenCount();
local point = self:CreateNode(startp);
table.insert(self.open,point);
while(#self.open ~= 0)
do
table.sort(self.open,function (a,b)
return a.f < b.f;
end)
local tempStart = self.open[1];
table.remove(self.open,1);
table.insert(self.close,tempStart);
local sur = self:GetSurPoints(tempStart.point);
for i=1,#sur do
if self:exists(sur[i].point) then
local pg = 0;
if sur[i].parent ~= nil then
pg = sur[i].parent.g;
local g = sur[i].g + pg;
if g < sur[i].g then
sur[i].g = g;
sur[i].f = sur[i].g + sur[i].h;
sur[i].parent = tempStart;
else
sur[i].h = math.abs(endp.x - sur[i].point.x) + math.abs(endp.y,- sur[i].point.y);
table.insert(self.open,sur[i]);
for i = 1, #self.close do
local tempP = self.close[i].point;
local x = math.abs(tempP.x - endp.x);
local y = math.abs(tempP.y - endp.y);
if math.abs(tempP.x - endp.x) < self.step and math.abs(tempP.y - endp.y) < self.step then
return self.close[i];
return nil;
function RoadPoint:GetSurPoints( p )
local t = {};
local up = cc.p(p.x,p.y - self.step);
if self:judge(up) == true then
local point = self:CreateNode(up);
point.g = 10;
table.insert(t,point)
local down = cc.p(p.x,p.y+ self.step);
if self:judge(down) == true then
local point = self:CreateNode(down);
local left = cc.p(p.x - self.step,p.y);
if self:judge(left) == true then
local point = self:CreateNode(left);
local right = cc.p(p.x + self.step, p.y);
if self:judge(right) == true then
local point = self:CreateNode(right);
table.insert(t, point)
local leftup = cc.p(p.x - self.step,p.y - self.step);
if self:judge(leftup) == true then
local point = self:CreateNode(leftup);
point.g = 14;
table.insert(t,point);
local leftdown = cc.p(p.x - self.step,p.y + self.step);
if self:judge(leftdown) ==true then
local point = self:CreateNode(leftdown);
local rightup = cc.p(p.x + self.step,p.y - self.step);
if self:judge(rightup) == true then
local point = self:CreateNode(rightup);
local rightdown = cc.p(p.x + self.step,p.y + self.step);
if self:judge(rightdown) == true then
local point = self:CreateNode(rightdown);
function RoadPoint:judge(p)
for i = 1,#self.close do
if self.close[i].point.x == p.x and self.close[i].point.y == p.y then
for i=1,self.childCount do
if cc.rectContainsPoint(self.childs[i]:boundingBox(),p) then
return RoadPoint;