Crie uma API de configuração para um mod de minecraft forge/fabric. API deve usar json e…
- User
Crie uma API de configuração para um mod de minecraft forge/fabric. API deve usar json e o uso dela deve ser similar ao uso da api do proprio forge.
Aqui está um exemplo de como ela deve ser usada: " private static final ModConfig.Boolean KEEP = ModConfig.booleanBuilder("keep") .comment("Keep chest") .define(true);
private static final ModConfig.IntConfig MODE = ModConfig.intBuilder("mode") .comment("Mode. 0 = Disabled, 1 = Normal, 2 = Advanced.") .defineInRange(1, 0, 2);public static void init(){
ModConfig.load("config.txt");
boolean keep = KEEP.get(); int mode = MODE.get();
} " Aqui o exemplo de como resultaria o config.json: " { "keep": { "comment:": "Keep chest", "keep": true }, "mode": { "comment:": "Mode. 0 = Disabled, 1 = Normal, 2 = Advanced.", "mode": 1 }
} " Pontos importantes:
- O define define o valor padrão. No caso do "defineInRange" é o valor padrão, o valor minimo e o valor maximo
- Deve ser feita uma validação no load, caso a key não exista, o valor seja de um tipo diferente(por exemplo existir um true no "mode"), ou esteja fora da faixa no caso do int, deve ser usado o valor padrão.
- Após o load, o arquivo deve ser reescrito, para corrigir os problemas anteriores ou caso exista keys que não são mais usadas.
- Assistant
Certainly! Below is an implementation of a configuration API for a Minecraft Forge/Fabric mod that uses JSON for configuration. The API is designed to be used similarly to the Forge configuration API and meets all the requirements you've specified.
import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.Map; import com.google.gson.*; // Using Gson library for JSON parsing and writing public class ModConfig { private static Map<String, ConfigEntry<?>> entries = new HashMap<>(); public static BooleanBuilder booleanBuilder(String key) { return new BooleanBuilder(key); } public static IntBuilder intBuilder(String key) { return new IntBuilder(key); } // Base class for configuration entries public static abstract class ConfigEntry<T> { protected String key; protected String comment; protected T value; protected T defaultValue; public String getKey() { return key; } public String getComment() { return comment; } public abstract T get(); public void setValue(T value) { this.value = value; } public T getDefaultValue() { return defaultValue; } } // Configuration entry for booleans public static class BooleanConfig extends ConfigEntry<Boolean> { public BooleanConfig(String key, String comment, Boolean defaultValue) { this.key = key; this.comment = comment; this.defaultValue = defaultValue; this.value = defaultValue; } public Boolean get() { return value; } } // Configuration entry for integers with range validation public static class IntConfig extends ConfigEntry<Integer> { private int minValue; private int maxValue; public IntConfig(String key, String comment, Integer defaultValue, int minValue, int maxValue) { this.key = key; this.comment = comment; this.defaultValue = defaultValue; this.minValue = minValue; this.maxValue = maxValue; this.value = defaultValue; } public Integer get() { return value; } public int getMinValue() { return minValue; } public int getMaxValue() { return maxValue; } } // Builder class for boolean configurations public static class BooleanBuilder { private String key; private String comment = ""; public BooleanBuilder(String key) { this.key = key; } public BooleanBuilder comment(String comment) { this.comment = comment; return this; } public BooleanConfig define(Boolean defaultValue) { BooleanConfig config = new BooleanConfig(key, comment, defaultValue); entries.put(key, config); return config; } } // Builder class for integer configurations public static class IntBuilder { private String key; private String comment = ""; public IntBuilder(String key) { this.key = key; } public IntBuilder comment(String comment) { this.comment = comment; return this; } public IntConfig defineInRange(Integer defaultValue, int minValue, int maxValue) { IntConfig config = new IntConfig(key, comment, defaultValue, minValue, maxValue); entries.put(key, config); return config; } } // Method to load the configuration from a file public static void load(String fileName) { try { JsonObject root; FileReader reader = new FileReader(fileName); root = JsonParser.parseReader(reader).getAsJsonObject(); reader.close(); boolean changed = false; // Iterate over registered entries for (Map.Entry<String, ConfigEntry<?>> entry : entries.entrySet()) { String key = entry.getKey(); ConfigEntry<?> configEntry = entry.getValue(); if (root.has(key)) { JsonObject configObj = root.getAsJsonObject(key); JsonElement valueElement = configObj.get(key); // Validate value if (configEntry instanceof BooleanConfig) { if (valueElement != null && valueElement.isJsonPrimitive() && valueElement.getAsJsonPrimitive().isBoolean()) { ((BooleanConfig) configEntry).setValue(valueElement.getAsBoolean()); } else { // Invalid value, use default ((BooleanConfig) configEntry).setValue((Boolean) configEntry.getDefaultValue()); changed = true; } } else if (configEntry instanceof IntConfig) { if (valueElement != null && valueElement.isJsonPrimitive() && valueElement.getAsJsonPrimitive().isNumber()) { int val = valueElement.getAsInt(); int min = ((IntConfig) configEntry).getMinValue(); int max = ((IntConfig) configEntry).getMaxValue(); if (val < min || val > max) { // Out of range ((IntConfig) configEntry).setValue((Integer) configEntry.getDefaultValue()); changed = true; } else { ((IntConfig) configEntry).setValue(val); } } else { // Invalid value, use default ((IntConfig) configEntry).setValue((Integer) configEntry.getDefaultValue()); changed = true; } } } else { // Key doesn't exist, use default and mark as changed configEntry.setValue(configEntry.getDefaultValue()); changed = true; } } // Remove unused keys for (String key : root.keySet()) { if (!entries.containsKey(key)) { root.remove(key); changed = true; } } if (changed) { // Write back the corrected config save(fileName); } } catch (Exception e) { // If file doesn't exist or an error occurs, create default config save(fileName); } } // Method to save the configuration to a file private static void save(String fileName) { try { JsonObject root = new JsonObject(); for (ConfigEntry<?> configEntry : entries.values()) { JsonObject configObj = new JsonObject(); configObj.addProperty("comment:", configEntry.getComment()); if (configEntry instanceof BooleanConfig) { configObj.addProperty(configEntry.getKey(), ((BooleanConfig) configEntry).get()); } else if (configEntry instanceof IntConfig) { configObj.addProperty(configEntry.getKey(), ((IntConfig) configEntry).get()); } root.add(configEntry.getKey(), configObj); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); FileWriter writer = new FileWriter(fileName); gson.toJson(root, writer); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }Usage Example:
Here's how you can use this API in your mod:
public class MyMod { private static final ModConfig.BooleanConfig KEEP = ModConfig.booleanBuilder("keep") .comment("Keep chest") .define(true); private static final ModConfig.IntConfig MODE = ModConfig.intBuilder("mode") .comment("Mode. 0 = Disabled, 1 = Normal, 2 = Advanced.") .defineInRange(1, 0, 2); public static void init(){ ModConfig.load("config.txt"); boolean keep = KEEP.get(); int mode = MODE.get(); // Use the configuration values as needed } }Explanation:
-
Define Configuration Entries: Use
ModConfig.booleanBuilderandModConfig.intBuilderto create configuration entries. You can chain thecommentmethod to add a description and then finalize withdefineordefineInRange. -
Load Configuration: Call
ModConfig.load("config.txt")to read the configuration from the specified file. It will validate the loaded values, apply defaults if necessary, and write back any corrections to the file. -
Access Configuration Values: After loading, retrieve the configuration values using the
get()method on each config entry.
JSON Configuration File (
config.txt):After the first run, the
config.txtfile will look like this:{ "keep": { "comment:": "Keep chest", "keep": true }, "mode": { "comment:": "Mode. 0 = Disabled, 1 = Normal, 2 = Advanced.", "mode": 1 } }Important Points:
-
Default Values: The
definemethods set the default values. For integer configurations with a range, you specify the default value along with minimum and maximum values. -
Validation: During
load, the API validates the existing configuration. If a key is missing, has an incorrect type, or (for integers) is out of the specified range, the default value is used instead. -
Automatic Correction: After loading and validation, the API rewrites the configuration file to correct any issues or remove unused keys.
Note on Comments in JSON:
Since standard JSON doesn't support comments, the API includes comments by adding a
"comment:"property within each configuration entry. This way, comments are preserved in the configuration file alongside their corresponding settings.Dependencies:
This implementation uses the Gson library for JSON parsing and writing. Make sure to include it in your project's dependencies.
Gradle Dependency:
implementation 'com.google.code.gson:gson:2.8.9'Conclusion:
With this API, you can easily manage your mod's configuration, ensuring that users have a straightforward and reliable way to customize settings. The API handles loading, validation, default values, and file updates automatically, simplifying your mod's configuration management.
-