我正在尝试实现一个适用于打开和关闭列表的简单寻路系统。我在关闭清单时遇到问题。如何检查已关闭的列表是否已包含坐标?
closed[current] = true
local neighbors = getNeighbors(current[1], current[2]) -- get neighbors for the current node
for k, v in ipairs(neighbors) do -- iterate through each neighbor
if not closed[v] then
table.insert(open, v)
end
end
getNeighbours以坐标(x,y)的形式返回tile(x,y)的每个邻居tile。如何检查已关闭的表是否已包含这些坐标?
答案 0 :(得分:0)
使用Lua,表的关键(哈希)几乎可以是所有内容, EVEN 一个包含2个值的表。
假设current[1]
和current[2]
分别代表坐标x
和y
,您只需检查closed[current]
即可。请参阅以下示例:
local coordinates = {
{1.3,5},
{2.2,3.4},
{3,6.8}
}
local closed = {} --Empty closed list
local current = coordinates[1] --{1.3,5}
print(closed[current]) --Not visited = nil
closed[current] = true --Marking as visited
print(closed[current]) --visited = true
print(coordinates[2]) --Not visited = nil
当您检查if closed[current] then ...
时,不存在的条目等同于nil
,相当于false
。如果您明确需要false
值而非nil
,则可以按如下方式初始化已关闭的列表:
closed = {}
for i=1,#coordinates do
closed[coordinates[i]] = false
end
如果您在代码中的某处复制坐标值而不是引用表{x,y}
,则会出现唯一的问题。在这种情况下,您将拥有不同的表,因此即使2个表的值相等,哈希也会为您提供false
。
如果可能发生这种情况,您需要使用 VALUES 而不是表格进行哈希处理。您可以像Egor所建议的那样,使用单个哈希,使用双哈希,如下所示:
local function listAddPoint(list,point) --Adds point (a {x,y} table) to the list
if not list[point[1]] then
list[point[1]] = {}
end
list[point[1]][point[2]] = true
end
local function listHasPoint(list,point) --Checks if the point (a {x,y} table) is on the list
if list[point[1]] and list[point[1]][point[2]] then
return true
end
return false
end
local coordinates = {
{1.3,5},
{2.2,3.4},
{3,6.8}
}
local closed = {} --Empty closed list
local current = coordinates[1] --{1.3,5}
print(listHasPoint(closed,current)) --Not visited = false
listAddPoint(closed,current)--Marking as visited
print(listHasPoint(closed,current)) --visited = true
print(listHasPoint(closed,coordinates[2])) --Not visited = false