save game settings and parse them

This commit is contained in:
2025-12-12 11:34:01 +01:00
parent d294578a74
commit 099f52278c
6 changed files with 91 additions and 18 deletions

View File

@@ -0,0 +1,65 @@
package de.miaurizius.jgame2d.core;
import java.io.*;
import java.util.HashMap;
import java.util.List;
public class Config {
private final GamePanel panel;
private final HashMap<String, String> settings = new HashMap<>();
private final String[] options = new String[]{
"fullscreen", //0
"music-vol", //1
"sfx-vol" //2
};
public Config(GamePanel panel) {
this.panel = panel;
for (String option : options) settings.put(option, null);
}
//
public final void save() {
try {
insertToHash();
BufferedWriter writer = new BufferedWriter(new FileWriter("gamedata/config"));
settings.forEach((invoke, value) -> {
try {
writer.write(invoke + ": " + value);
writer.newLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public final void load() {
try {
BufferedReader reader = new BufferedReader(new FileReader("gamedata/config"));
List<String> lines = reader.lines().toList();
if(lines.isEmpty()) return; //No config found, use default values
for (int i = 0; i < options.length; i++) {
String value = lines.get(i).split(": ")[1];
switch (options[i]) {
case "fullscreen" -> panel.fullscreen = Boolean.parseBoolean(value);
case "music-vol" -> panel.music.volumeScale = Integer.parseInt(value);
case "sfx-vol" -> panel.sfx.volumeScale = Integer.parseInt(value);
}
}
insertToHash();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// HELP FUNCTIONS
private void insertToHash() {
settings.put(options[0], String.valueOf(panel.fullscreen));
settings.put(options[1], String.valueOf(panel.music.volumeScale));
settings.put(options[2], String.valueOf(panel.sfx.volumeScale));
}
}