I am trying to make a Dijkstra algorithm. The way I wanted it to work is to get the surrounding parts for a specific amount of times. Lets say an entity has a range of 3 tiles. The algorithm would get the neighbors of the entity, putting them in a table called “openList”, and removing starting tile from it afterwards. Then, the newly added 4 nodes would go through same process one by one. The processed tiles/nodes would be put into a closed list. This image might show how I want the things to work, the tiles of same number kind of form a ring or a rectangle that gets progressively bigger:
To make this work I made this script:
local Nodes
local openList = {}
local closedList = {}
local range = 3
local Start
local function GetNeighbors()
local neighbors = {}
for i, center in pairs(openList) do
for i, node in pairs(Nodes) do
if node.Position.X / 8 == center.Position.X / 8 and node.Position.Z / 8 + 1 == center.Position.Z / 8 then
table.insert(neighbors, node)
elseif node.Position.X / 8 == center.Position.X / 8 and node.Position.Z / 8 - 1 == center.Position.Z / 8 then
table.insert(neighbors, node)
elseif node.Position.X / 8 + 1 == center.Position.X / 8 and node.Position.Z / 8 == center.Position.Z / 8 then
table.insert(neighbors, node)
elseif node.Position.X / 8 - 1 == center.Position.X / 8 and node.Position.Z / 8 == center.Position.Z / 8 then
table.insert(neighbors, node)
end
end
table.insert(closedList, center)
table.remove(openList, table.find(openList, center))
return neighbors
end
end
local function CheckNeighbors(neighbors)
for i, node in pairs(neighbors) do
if not table.find(openList, node) and not table.find(closedList, node) then
table.insert(openList, node)
end
end
end
local function UpdateColor()
for i, node in pairs(openList) do
node.Color = Color3.fromRGB(0, 170, 255)
end
for i, node in pairs(closedList) do
node.Color = Color3.fromRGB(45, 45, 45)
end
end
script.Parent.MouseClick:Connect(function()
Nodes = workspace:WaitForChild("Nodes"):GetChildren()
Start = workspace:WaitForChild("Nodes").Start
table.insert(openList, Start)
for count = 0, range, 1 do
UpdateColor()
CheckNeighbors(GetNeighbors())
end
print(openList)
end)
It works relatively right, but it seems that “for count = … , … , … do” loop is conflicting with “for i, … in pairs(…)” loop. Instead of repeating the process 3 times, it kind of gets just 3 neighbors, resulting in this:
I was wondering if there is an alternative to my method. May be there is a method for “repeat” that would repeat the function for specific amount of times?