(Slick2D) Managing Resources in game

I am having a mental battle trying to decide the right course of action for managing resources in my game. In building my game, I’ve only used the most abstract parts of Slick2D to do the rendering and left the rest of the game’s design to myself.

Here was my first idea. For each level that is loaded, image and sound resources would be read and buffered. While this is a convenient way of handling the process, I realize that it is terribly inefficient when considering that many levels reuse the exact same resources, background music in particular. I figure that I can make a class that will handle the management of resources. The manager will load resources on request and then cache them for later use.

Consider this:

Image lolCat = myGame.getResources().getImage(“res/lolcat.png”);

The next time I call getImage from the resource manager, the cached image will be returned rather than a new copy of the image. While this is fine and dandy, I have my grievances with this method… Each time that a resource is requested, the manager has to compare possibly hundreds of Strings to the one provided until a possible match is found. If a match IS found, then we know, of course, that the resource is within the cache and can be reused. If not, then the resource must be read from the file, cached, and returned. The search could take a long time especially if the resource has not been loaded.

I also considered accessing particular resources through multiple getters within the manager.

For instance:

Image moonBackground = myGame.getResources().getBackground(Resources.BG_MOONWORLD);

would load a background specified by the manager itself. This would prevent the manager from having to perform a time consuming search, as each time this particular method is called, it will only need to check the one resource for potential reuse. This has the consequence of restricting my programming speed as each time I need to add a new element to the game, I must add it to the manager in order for it to be used efficiently.

Does anyone know of a more effective way to load images without having to create a large amount of String data and without restricting my programming speed? Are either of these two methods I’ve suggested good programming practices? I know there are tradeoffs, but I need to know the lesser of the two evils, or preferably, a third solution less evil than the first two…

I generally go:


public class Resources {
      public static Image MOON_BACKGROUND;

      public static void init() throws IOException { 
             MOON_BACKGROUND = new Image("moon_background.png");
      }
}

then just use Resources.MOON_BACKGROUND anywhere you feel like. No lookup no nothing. You can auto-generate the Resources class if you want to based on the contents of your res directory.

Cheers,

Kev

Say, thanks! Seems that my second idea wasn’t blasphemous after all. The war is over…