Looping through grid to find spaces compatible with tile?

Hi,

I am working on a custom grid script for a frame that I have. The grid script takes all of the GuiObjects (tiles) that are parented to the frame and spaces them accordingly.

Inside of the script I have some functions that create a 2D array, each space in the array holding a default ID of 0. The ID of each space changes to the ID of the tile that is in the space.

In theory this would work well and is how most standard grids would work, however, I am having issues with looping through all of the available spaces and then determining which spaces combined would fit a tile.

For example, let’s say I have a 4x4 grid for my tiles. I have 4 tiles that are 2x1 and a tile that is 2x4, how would I go about fitting those in accordingly?

Here is what I have so far that manages the 2D array and object tiles:

local GRID_X = 4
local GRID_Y = 4

local frame = script.Parent
local grid = {}

-- Initialize grid
for i = 1, GRID_X do
	grid[i] = {}
	for j = 1, GRID_Y do
		grid[i][j] = 0
	end
end

-- Convert to tile size
local function ConvertToGrid(object: GuiObject): Vector2
	return Vector2.new(
		math.ceil(object.Size.X.Scale*GRID_X),
		math.ceil(object.Size.Y.Scale*GRID_Y)
	)
end

-- Auto position object upon being added
local function AutoPosition(object: GuiObject, tileSize: Vector2)
	-- Loop through every column in the grid
	for i, column in pairs(grid) do
		-- Loop through every space in the column
		for j, space in pairs(column) do
			-- Do something with the space??
		end
	end
end

If you have any ideas, it would be greatly appreciated. I don’t really need scripts or code as much as I need it explained. If I can understand what I am meant to do, I can figure it out. I just have no idea how I would find out what spaces go together to form different tiles.

I hope this made at least a little bit of sense lol :slightly_smiling_face:

1 Like