如何最好地在java中存储游戏配置变量

Nic*_*ckD 5 java

我正在编写一个小型java游戏,并将全局游戏设置存储在类结构中,如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

虽然这很方便,但我想知道这是否是可接受的模式.

ada*_*shr 12

将其存储在一个.properties文件中.

config.properties

tile.size=16
screenshot.dir=..\\somepath\\..
Run Code Online (Sandbox Code Playgroud)

阅读它

// 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(...)
Run Code Online (Sandbox Code Playgroud)

使用它

int tileSize = Integer.valueOf(properties.getProperty("tile.size"));
String screenshotDir = properties.getProperty("screenshot.dir");
Run Code Online (Sandbox Code Playgroud)

为了简化操作并保持最小化,您还可以执行以下操作:

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
}
Run Code Online (Sandbox Code Playgroud)

  • 就个人而言,我宁愿将它们存储在POJO中,并使用一些XStream库将其反序列化为XML文件。比读取属性要方便得多。懒得写单独的答案。 (2认同)