Cat_in_the_hat

Maze pathfinding

Nov 24th, 2025 (edited)
843
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.98 KB | None | 0 0
  1. local start = Vector3.new(342, 72, 342)
  2. local goal  = Vector3.new(309, 72, 372)
  3.  
  4. local step = 3
  5. local size = Vector3.new(3, 3, 3)
  6.  
  7. local function free(p)
  8.     return BlockService.getBlockAt(p) == nil
  9. end
  10.  
  11. local function place(p)
  12.     local part = PartService.createPart(ItemType.CLAY_WHITE, p)
  13.     part:setSize(size)
  14.     part:setAnchored(true)
  15.     part:setCollidable(false)
  16. end
  17.  
  18. local function equal(a, b)
  19.     return a.X == b.X and a.Y == b.Y and a.Z == b.Z
  20. end
  21.  
  22. local function getNeighbors(p)
  23.     local n = {}
  24.  
  25.     local p1 = Vector3.new(p.X + step, p.Y, p.Z)
  26.     local p2 = Vector3.new(p.X - step, p.Y, p.Z)
  27.     local p3 = Vector3.new(p.X, p.Y, p.Z + step)
  28.     local p4 = Vector3.new(p.X, p.Y, p.Z - step)
  29.  
  30.     if free(p1) then table.insert(n, p1) end
  31.     if free(p2) then table.insert(n, p2) end
  32.     if free(p3) then table.insert(n, p3) end
  33.     if free(p4) then table.insert(n, p4) end
  34.  
  35.     return n
  36. end
  37.  
  38. local function buildPath(s, g)
  39.     if free(g) == false then
  40.         error("unable reach goal")
  41.         return
  42.     end
  43.  
  44.     local queue = {s}
  45.     local came = {}
  46.     came[s.X .. "," .. s.Z] = s
  47.  
  48.     local found = false
  49.  
  50.     while #queue > 0 do
  51.         local p = table.remove(queue, 1)
  52.  
  53.         if equal(p, g) then
  54.             found = true
  55.             break
  56.         end
  57.  
  58.         local neighbors = getNeighbors(p)
  59.         for _, np in ipairs(neighbors) do
  60.             local key = np.X .. "," .. np.Z
  61.             if came[key] == nil then
  62.                 came[key] = p
  63.                 table.insert(queue, np)
  64.             end
  65.         end
  66.     end
  67.  
  68.     if found == false then
  69.         error("unable reach goal")
  70.         return
  71.     end
  72.  
  73.     local path = {}
  74.     local cur = g
  75.  
  76.     while true do
  77.         table.insert(path, cur)
  78.         if equal(cur, s) then
  79.             break
  80.         end
  81.         local key = cur.X .. "," .. cur.Z
  82.         cur = came[key]
  83.     end
  84.  
  85.     for i = #path, 1, -1 do
  86.         place(path[i])
  87.     end
  88. end
  89.  
  90. buildPath(start, goal)
Advertisement
Add Comment
Please, Sign In to add comment