So, while I was working on a game I was making, I made myself a little Art class. Here it is:
package com.kirc.drilldescent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.newdawn.slick.AngelCodeFont;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.ResourceLoader;
public class Art
{
// public static Image dirtTile;
private static Map<String,Image> loadedImages;
private static AngelCodeFont font;
/**
* Loads all .png images located in the /res folder.
* @throws SlickException
*/
public static void init() throws SlickException {
// dirtTile = new Image("res/dirtTile.png");
loadedImages = new HashMap<>();
try
{
URI uri = new URI(ResourceLoader.getResource("res").toString());
File[] files = new File(uri).listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String name)
{
if(name.endsWith(".png"))
return true;
return false;
}
});
for(File f:files)
{
FileInputStream fis = new FileInputStream(f);
Image image = new Image(fis, "res/"+f.getName(), false);
loadedImages.put(f.getName(), image);
}
} catch (URISyntaxException | FileNotFoundException e)
{
System.err.println("UNABLE TO LOAD IMAGES FROM RES FOLDER!");
e.printStackTrace();
}
font = new AngelCodeFont("res/bitmapfont.fnt",Art.get("bitmapfont.png"));
}
/**
*
* @param filename The filename of the image in the /res folder
* @return The loaded image of that filename
*/
public static Image get(String filename)
{
return loadedImages.get(filename);
}
public static AngelCodeFont getFont()
{
return font;
}
}
Unfortunately, while this will automatically load all images in my res/ directory (and let me load them once and only once), it won’t work if I decide to pack everything into a .jar. I was wondering if anyone used a nicer pattern to keep all their game art organized and easy to access in their code. I took the lazy way because I didn’t want to add a line for every single one of my images. (Also, if you know how to adapt this to a .jar that’d be nice to share.)