Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to store game config variables in java

Tags:

java

I'm writing a small java game and am storing global game settings in a class structure like the one below:

public class Globals {
    public static int tileSize = 16;
    public static String screenshotDir = "..\\somepath\\..";
    public static String screenshotNameFormat = "gameNamexxx.png";
    public static int maxParticles = 300;
    public static float gravity = 980f;
    // etc
}

While this is very convenient to work with I'd like to know if this is the accepted pattern.

like image 865
NickD Avatar asked Apr 13 '12 12:04

NickD


2 Answers

Store it in a .properties file.

config.properties

tile.size=16
screenshot.dir=..\\somepath\\..

Reading it

// Make sure this happens only the first time you start your application
Properties properties = new Properties();
// You can use FileInputStream, ClassLoader.getResourceAsStream or a reader too
properties.load(...)

Using it

int tileSize = Integer.valueOf(properties.getProperty("tile.size"));
String screenshotDir = properties.getProperty("screenshot.dir");

To simplify things, and to keep your changes minimal, you can also do something like this:

public class Globals {
    private static final Properties properties = new Properties();

    static {
        // do the loading here
    }

    public static final int TILE_SIZE = 
        Integer.valueOf(properties.getProperty("tile.size"));
    public static final String SCREENSHOT_DIR = 
        properties.getProperty("screenshot.dir");
    // etc
}
like image 85
adarshr Avatar answered Sep 27 '22 18:09

adarshr


If it really is a small application, it will do. It's not ideal but there's no point bringing in too much sophistication on a small scale.

But read those values from a properties file.

like image 44
biziclop Avatar answered Sep 27 '22 18:09

biziclop