Earlier today I asked a question on how to place images in sequence as part of a whole picture, so that I could generate 2D maps like you see in the old Pokemon games. Everything is tile-based.
I’ve come to the point where I generate the map itself, but it comes out a little funny.
I’ve tracked the problem to when I fill a HashMap with Tile Objects. A Tile Object holds a Name and a BufferedImage. What seems to be the problem is how the program reads the files from the folder filled with tiles (png files) and place them in the HashMap.
Here is the code for when I place the Tile Objects in the HashMap:
private static HashMap<Integer, Tile> getTiles(String path) throws IOException {
HashMap<Integer, Tile> temp = new HashMap<>();
File folder = new File(path);
Tile tile;
int counter = 0;
for(File file : folder.listFiles()) {
if(file.isFile()) {
try {
if(file.getCanonicalPath().endsWith(".png")) {
tile = new Tile(file.getName(),ImageIO.read(file));
temp.put(counter, tile);
counter++;
}
} catch(IOException ioe) {
System.out.println("Picture number " + counter + " could "
+ "not be saved in the hashmap: \n"
+ ioe.getMessage());
continue;
}
}
}
return temp;
}
And here is the Output when I do a toString() on the HashMap:
Tiles: (0,0.png)(1,1.png)(2,10.png)(3,100.png)....
Notice how after tile 1.png it starts counting 10, then 100, then 101, then 102…then when it reaches 112 it starts counting like this:
(112,2.png)(113,20.png)(114,200.png)(115,201.png)...
There is a total of 220 Tiles in this folder, (counting tile 0.png).
I clearly see what the problem is, but not how I fix it.
I would guess that
folder.listFiles()doesn’t return the files in order. You could put these into aListand then sort it, but this isn’t a great approach. If image50.pngwere removed and someone added100000.pngthen all the images after 49 would be shifted over by one. This could easily go undetected.The better approach is to split the filename by the period and parse it to an int.
Here is how to split the filename:
With this approach you no longer have to increment the counter. It also won’t improperly number a tile if the image is missing.