--尋路
local MAX_ROW_NUM = 9 --行數
local MAX_COL_NUM = 9 --列數
local director = cc.Director:getInstance()
local visibleSize = director:getVisibleSize()
--小方塊寬高
local ItemWidth = visibleSize.width / MAX_COL_NUM
local ItemHeight = ItemWidth
--查找方向
local SEARCH_POS = {
cc.p(-1, 0),
--左邊
cc.p(0, 1),
--上
cc.p(1, 0),
--右
cc.p(0, -1),
--下
}
self.m_allItems = {}
for i=1,MAX_ROW_NUM do
self.m_allItems[i] = {}
for j=1,MAX_COL_NUM do
local smallItem = smallItem:create(i, j)
smallItem:setPosition((j - 1) * ItemWidth, (i - 1) * ItemHeight)
self:addChild(smallItem)
self.m_allItems[i][j] = smallItem
end
end
--從(1, 1)找向(7, 7)
self:_AStar(cc.p(1, 1), cc.p(7, 7))
function TestLayer:_AStar(from, to)
local queue = {from}
--記錄行走的路徑
local searchMap = {[from.x*MAX_ROW_NUM + from.y] = {from}}
repeat
local p = table.remove(queue, 1)
if(not p) then break end
--將目前格子的周圍相鄰的格子壓棧
for _,point in ipairs(SEARCH_POS) do
local x = point.x + p.x
local y = point.y + p.y
if x > 0 and x <= MAX_COL_NUM and y > 0 and y <= MAX_ROW_NUM then --格子有效範圍內
local pp = clone(searchMap[p.x*MAX_ROW_NUM + p.y])
table.insert(pp, cc.p(x, y))
if x == to.x and y == to.y then
--找到了
for _,point in pairs(pp) do
-- print("x, y: ", point.x, point.y)
end
return
elseif not self.m_allItems[x][y]:_getIsMask() then --格子未尋過
self.m_allItems[x][y]:_setIsMask(true)
--標記格子尋路過
table.insert(queue, cc.p(x, y))
searchMap[x*MAX_ROW_NUM + y] = pp
end
end
end
until false
end