如题,昨天项目有个需求,要找到A点到B点的间,最靠近B点的一个空位
(前情提要:我们的坐标被组合成了key 既 key = x+y*100)
言归正传 问题其实并不难,但是需要分4个方向判,然后写个广搜,写起来比较啰嗦
就心心念念想写一个简短的,折腾一下就搞了下面这35行版本~✿✿ヽ(°▽°)ノ✿
--- 获得 两key连线的范围中 靠近endKey 的一个空的坐标
function CannonModel:GetLineEmptyPos(beginKey, endKey)
local x1, y1 = MapUtils.Key2XY(beginKey)
local x2, y2 = MapUtils.Key2XY(endKey)
local xStep = (x2 == x1 and 0 or (x2 > x1 and -1 or 1))
local yStep = (y2 == y1 and 0 or (y2 > y1 and -100 or 100))
local index = 0
local maxIndex = 1
local list = {endKey}
local vis = {[beginKey] = true, [endKey] = true} --- @type table<MapItemKey, true>
local emptyKey = nil
local function JudgeNewKey(newKey)
if vis[newKey] then return else vis[newKey] = true end
local xnew, ynew = MapUtils.Key2XY(newKey)
if (xnew - x1) * xStep >= (x2 - x1) * xStep then
if (ynew - y1) * yStep >= (y2 - y1) * yStep then
maxIndex = maxIndex + 1
list[maxIndex] = newKey
if (not GNowScene:GetItemDataByKey(newKey)) then
emptyKey = newKey
end
end
end
end
while index < maxIndex and emptyKey == nil do
index = index + 1
JudgeNewKey(list[index] + xStep)
JudgeNewKey(list[index] + yStep)
end
return emptyKey or beginKey
end