local maxX = 50
local maxY = 15
local nodes = {}
-- visualization
local f = script.Frame
-- Generate nodes
for x=0, maxX do
for y=0, maxY do
table.insert(nodes, #nodes, {
positionX = x,
positionY = y,
likability = 0,
isStart = false,
isGoal = false,
hasCalculatedAdvance = false
})
end
end
-- choose start and goal in grid
local start = nodes[math.random(0, maxX*maxY)]
local goal = nodes[math.random(0, maxX*maxY)]
local agent = {
currentPositionX = start.positionX,
currentPositionY = start.positionY
}
start.isStart = true
goal.isGoal = true
-- calculate likability
for i,v in ipairs(nodes) do
local currentPos = Vector2.new(v.positionX, v.positionY)
local goalPos = Vector2.new(goal.positionX, goal.positionY)
v.likability = (currentPos - goalPos).Magnitude
end
for i,v in ipairs(nodes) do
local vF = f:Clone()
vF.Position = UDim2.new(0,v.positionX*15, 0, v.positionY*15)
vF.TextLabel.Text = tostring(math.floor(v.likability))
if v.isStart then
vF.BackgroundColor3 = Color3.new(0.666667, 0, 0)
end
if v.isGoal then
vF.BackgroundColor3 = Color3.new(0.666667, 1, 0)
end
vF.Visible = true
vF.Parent = script.Parent.MainFrame.ContentFrame
end
function Step()
end
print(nodes)
local startTime = os.time()
local totalTime = startTime
repeat
wait()
Step()
until agent.currentPositionX == goal.positionX and agent.currentPositionY == goal.positionY
totalTime = os.time() - startTime
print(totalTime)
Lets say I have a point in a 2d grid at (1,1)
The neighbors would be:
(1,0)
(1,2)
(0,1)
(2,1)
Is it possible to create a function that will take any point in a grid and get all neighbors?
An easy way to do it would be to check every direction from a starting point
You need to know the maxX and maxY, and simply add or subtract 1 in each direction.
local maxX = 10
local maxY = 10
--a 10 by 10 grid
local function getAdjacent(pointX, pointY)
local adjacent = []
if not pointX - 1 < 1 then
table.insert(adjacent, (pointX - 1, pointY))
end
if not pointX + 1 > maxX then
table.insert(adjacent, (pointX + 1, pointY))
end
if not pointY - 1 < 1 then
table.insert(adjacent, (pointX, pointY - 1))
end
if not pointY + 1 > maxY then
table.insert(adjacent, (pointX, pointY + 1))
end
end
Now you have a function that can return a list of tuples containing adjacent coordinates to your start location!
say you want to get the adjacent points to (2,2)
just use:
adjacent = getAdjacent(2,2)
Also you can use tuple unpacking to get each points x and y.