RobloxScripterAI
Discord ↗
Link Copied to Clipboard
×
"make a maze generator using a grid of 3 by 3"
-- Script for Maze Generation local Maze = {} local Cell = {} local Grid = {} local Stack = {} local Size = Vector2.new(3,3) function Cell.new(x, y) local self = {} self.x = x self.y = y self.walls = {true, true, true, true} self.visited = false return self end function Grid.new(size) local self = {} self.size = size self.grid = {} for y=1, size.y do for x=1, size.x do table.insert(self.grid, Cell.new(x, y)) end end return self end function Maze.new(grid) local self = {} self.grid = grid self.current = grid.grid[1] return self end function Maze:generate() self.current.visited = true local next = self:checkNeighbors(self.current) if next then next.visited = true table.insert(Stack, self.current) self:removeWalls(self.current, next) self.current = next elseif #Stack > 0 then self.current = table.remove(Stack) end end function Maze:checkNeighbors(cell) local neighbors = {} local top = self.grid.grid[self:index(cell.x, cell.y - 1)] local right = self.grid.grid[self:index(cell.x + 1, cell.y)] local bottom = self.grid.grid[self:index(cell.x, cell.y + 1)] local left = self.grid.grid[self:index(cell.x - 1, cell.y)] if top and not top.visited then table.insert(neighbors, top) end if right and not right.visited then table.insert(neighbors, right) end if bottom and not bottom.visited then table.insert(neighbors, bottom) end if left and not left.visited then table.insert(neighbors, left) end if #neighbors > 0 then return neighbors[math.random(#neighbors)] else return nil end end function Maze:index(x, y) if x < 1 or y < 1 or x > self.grid.size.x or y > self.grid.size.y then return nil end return x + (y - 1) * self.grid.size.x end function Maze:removeWalls(a, b) local x = a.x - b.x if x == 1 then a.walls[4] = false b.walls[2] = false elseif x == -1 then a.walls[2] = false b.walls[4] = false end local y = a.y - b.y if y == 1 then a.walls[1] = false b.walls[3] = false elseif y == -1 then a.walls[3] = false b.walls[1] = false end end local grid = Grid.new(Size) local maze = Maze.new(grid) while #Stack > 0 or not maze.current.visited do maze:generate() end -- Now maze.grid contains a 3x3 grid where each cell has a table of booleans representing if there is a wall or not. -- You can use this to create your maze in roblox.