package org.newdawn.spaceinvaders.java2d;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;
import org.newdawn.spaceinvaders.Sprite;
/**
* A resource manager for sprites in the game. Its often quite important
* how and where you get your game resources from. In most cases
* it makes sense to have a central resource loader that goes away, gets
* your resources and caches them for future use.
* <p>
* [singleton]
* <p>
* @author Kevin Glass
*/
public class Java2DSpriteStore {
/** The single instance of this class */
private static Java2DSpriteStore single = new Java2DSpriteStore();
/**
* Get the single instance of this class
*
* @return The single instance of this class
*/
public static Java2DSpriteStore get() {
return single;
}
/** The cached sprite map, from reference to sprite instance */
private HashMap sprites = new HashMap();
/**
* Retrieve a sprite from the store
*
* @param window The window to which the sprite will be drawn
* @param ref The reference to the image to use for the sprite
* @return A sprite instance containing an accelerate image of the request reference
*/
public Sprite getSprite(Java2DGameWindow window,String ref) {
if (sprites.get(ref) != null) {
return (Sprite) sprites.get(ref);
}
BufferedImage sourceImage = null;
try {
URL url = this.getClass().getClassLoader().getResource(ref);
if (url == null) {
fail("Can't find ref: "+ref);
}
sourceImage = ImageIO.read(url);
} catch (IOException e) {
fail("Failed to load: "+ref);
}
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK);
image.getGraphics().drawImage(sourceImage,0,0,null);
Sprite sprite = new Java2DSprite(window,image);
sprites.put(ref,sprite);
return sprite;
}
/**
* Utility method to handle resource loading failure
*
* @param message The message to display on failure
*/
private void fail(String message) {
// we'n't available
System.err.println(message);
System.exit(0);
}
}
Total 103 Lines of Code.
|
Source code formatted using showsrc by William Denniss
|