This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

Hi all! Carrying over some code from a Columns puzzle clone. I'm trying to produce the gdscript equivalent of:

typedef struct TILE
{ 
int x,y,type;
} TILE;
TILE grid[16][16];

//example
grid[0][0].type = 3

//example
int x = 0;
int y = 0;
for(a = 0; a < 16; a++)
    {
    for(b = 0; b < 16; b++)
        {
        grid[a][b].x = x;
        grid[a][b].y = y;
        y += 16;
        }
    x += 16;
    y = 0;
    }

So just a struct to a 2D array, giving the tiles as many properties as desired. Would anyone know how all this might be written in gdscript? Been stumbling on it for a while! Thanks!!

in Engine by (20 points)

1 Answer

+1 vote
Best answer

You can use Dictionary:

var grid = null

func get_default_tile(): -> Dictionary
     var tile = {}
     tile.x = 0
     tile.y = 0
     tile.type = 0
     return tile

func get_tile_grid(width, height): -> Array
    grid = []
    for x in range(width):
        grid [x]=[]
        for y in range(height):
            grid [x][y]= get_default_tile()
    return grid


func _ready():
    grid = get_tile_grid(16, 16)
    # change tile 0, 1:
    grid[0][1].x = 100
    grid[0][1].y = 200
    grid[0][1].type = 10
by (197 points)
selected by

Thanks! Got it working borrowing a couple changes from a similar Q&A on here for 2D arrays, only now with the dictionary. Going to roll with this and see how it goes!

var grid = null

func get_default_tile() -> Dictionary:
        var tile = {}
        tile.x = 0
        tile.y = 0
        tile.type = 0
        return tile

func get_tile_grid(width, height) -> Array:
        grid = []
        for x in range(width):
            grid.append([]) #changed from grid [x]=[]
            for y in range(height):
                grid[x].append(0) #added this
                grid[x][y]= get_default_tile()
        return grid

func _ready():
        grid = get_tile_grid(16, 16)

Dictionary is a reference type, so it is not a replacement for struct

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.