Java creating new Sprites coding problem

by pangaea   Last Updated January 13, 2018 06:13 AM

So I'm trying to load various different types of grass Sprites from the same spritesheet. However, the code looks really ugly. The thing is I have

public static Sprite grassi = new Sprite(16,i-1,0,SpriteSheet.tiles);

Now I was wondering is there a way to put this into a for loop. As I currently, have this mess below

public static Sprite grass1 = new Sprite(16,0,0,SpriteSheet.tiles);
public static Sprite grass2 = new Sprite(16,1,0,SpriteSheet.tiles);
public static Sprite grass3 = new Sprite(16,2,0,SpriteSheet.tiles);
public static Sprite grass4 = new Sprite(16,3,0,SpriteSheet.tiles);
public static Sprite grass5 = new Sprite(16,4,0,SpriteSheet.tiles);
public static Sprite grass6 = new Sprite(16,5,0,SpriteSheet.tiles);
public static Sprite grass7 = new Sprite(16,6,0,SpriteSheet.tiles);
public static Sprite grass8 = new Sprite(16,7,0,SpriteSheet.tiles);
public static Sprite grass9 = new Sprite(16,8,0,SpriteSheet.tiles);
public static Sprite grass10 = new Sprite(16,9,0,SpriteSheet.tiles);
public static Sprite grass11 = new Sprite(16,10,0,SpriteSheet.tiles);
public static Sprite grass12= new Sprite(16,11,0,SpriteSheet.tiles);
public static Sprite grass13 = new Sprite(16,12,0,SpriteSheet.tiles);
public static Sprite grass14 = new Sprite(16,13,0,SpriteSheet.tiles);
public static Sprite grass15 = new Sprite(16,14,0,SpriteSheet.tiles);
public static Sprite grass16 = new Sprite(16,15,0,SpriteSheet.tiles);

This works, but it destroys the code as it's a big mess. I also have 16x16 SpriteSheet and don't want to do this for every sprite.

Tags : java


Answers 1


A decent option for sprite lookup is the combination of a HashMap with enums. You have an enum to define the type and the HashMap holds the lists of different types. For example:

public enum SpriteType {
    Grass,
    Dirt,
    Rock;
}

HashMap<SpriteType, ArrayList<Sprite>> spritesByType = 
    new HashMap<SpriteType, ArrayList<Sprite>>();

Then for adding all your sprites you can do something like this:

for(SpriteType st : SpriteType.Values()) {
    int spriteCount = getSpriteCountForType(st);
    int spriteColumn = getSpriteColumnForType(st);
    spritesByType.put(st, new ArrayList<Sprite>());
    for(int i = 0; i < spriteCount; i++) {
        spritesByType.get(st).add(new Sprite(spriteColumn,i,0,SpriteSheet.tiles));
    }
}

Then accessing is easy too:

randomGrassSprite = 
   spritesByType.get(Grass).get(RandomInt(getSpriteCountForType(Grass)));
MichaelHouse
MichaelHouse
December 26, 2012 16:10 PM

Related Questions


Java Game How to find the x and y for a tile?

Updated March 26, 2015 14:04 PM


Java game check if any of the booleans are true?

Updated March 27, 2015 13:04 PM

New to game programming

Updated April 07, 2015 20:05 PM

How to build an AIManager class

Updated April 10, 2015 19:05 PM