A点到B点的矩形中,找出最靠近B点的空位(35行精简解决)

博客讲述项目需求,要找到A点到B点间最靠近B点的空位,坐标组合成key。问题解决需分4个方向判断并写广搜,作者最终实现了35行版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如题,昨天项目有个需求,要找到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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值