NickD
NickD

Reputation: 506

How best to store game config variables in 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.

Upvotes: 5

Views: 3259

Answers (2)

adarshr
adarshr

Reputation: 62593

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
}

Upvotes: 12

biziclop
biziclop

Reputation: 49744

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.

Upvotes: 1

Related Questions