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

标签 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
}

虽然使用起来非常方便,但我想知道这是否是可接受的模式。

最佳答案

将其存储在 .properties 文件中。

config.properties

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

正在阅读

// 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(...)

使用它

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

为了简化事情并尽量减少更改,您还可以这样做:

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
}

关于java - 如何最好地在 Java 中存储游戏配置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10140630/

相关文章:

java - 访问相机时崩溃?

java - 如何使用 jersey 和 java 在客户端和 web 服务 rest 之间传输对象

Java多线程

java - 如何在枚举中注入(inject)记录器

java - 使用 XML Schema、DTD、RelaxNG 和 Schematron 验证 DocBook 文档

java - 如何在j2me应用程序中启动浏览器而不确认

java - 正方形之间的 2D 碰撞检测,简单但比 boolean 值更具体 + 不受大空间跳跃的影响

java - 为什么在Java中打印0100会打印64?

java - 将文件夹中的文件列出到 JOptionPane

Java:按住鼠标时基于二维数组填充图形