Okay, I am trying to generate a tile map with this code. However, I keep on getting an array index out of bounds. So, how this works is that for the "path" I add in a text file. It holds different numbers each representing its own tile texture. The first 2 numbers of the text file is the width and height of it in which we use. What this for loop is doing is assigning each array of tiles[x][y] to a tile in a position where it belongs. Here is the text file I am using:
15 5
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
(there is not extra spaces between the lines idk why it did that)
if there is anything i need to clear up let me know
String textFile = TextUtility.loadTextAsString(path);
String[] tileValue = textFile.split("\\s+");
width = TextUtility.parseToInt(tileValue[0]);
height = TextUtility.parseToInt(tileValue[1]);
System.out.println(width+" "+height + " " + tileValue.length);
tiles = new int[width][height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
tiles[x][y] = TextUtility.parseToInt(tileValue[(x+y*(width))+2]);
System.out.print(""+ tileValue[(x+ y*(width))+2]);
}
}
The
IndexOutOfBounds
is due to(x+ y*(width))+2
expression. But if you are just trying to hold each tile's value intile[][]
, there is a simpler way in which it can be done!!I'm assuming that your
loadTextAsString(path)
is somewhat like this:This returns the textual representation of your file like shown in below example:
Now, let's start with actual method that will put all these values in a 2-D array.
I hope this is what you were trying to achieve.
Note: I hope your
TextUtility.parseToInt(String val)
method is equivalent toInteger.parseInt(String val)
, hence I've used the later.