2
\$\begingroup\$

For the code in my game, I want a 2D array which represents the map.

I created an actual map with Tiled but it produces a 1D array. Is there any way to convert it into my desired format wothout manually adding brackets and commas after each line?

\$\endgroup\$
1
  • \$\begingroup\$ Are you sure you really need a 2D array? You can do the same with a 1D array. For example array[currentLine * nbElemByLine + elemAtLine], something like that. \$\endgroup\$
    – nathan
    Commented Jan 28, 2014 at 16:31

1 Answer 1

3
\$\begingroup\$

You can always index a 1D array with 2D semantics. Given the x and y you'd like to look up, if you know the width of the "2D" interpretation of the array, use the following indexing math:

var tile = array[y * width + x]

This will save you the hassle of converting.

If you must convert, and Tiled does not offer an option to export in the format you want, your best bet is to write a function to do it. This would look roughly like (in pseudo-code):

var result = new array[width][height];
for (var row = 0; row < height; ++row) {
  for (var column = 0; column < width; ++column) {
    result[column][row] = tiledLevelArray[row * width + column]
  }
}

Run your level through a function like this at initialization time; this way you do not have to manually fix up the Tiled-generated array every time you'd like to change it.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .