I'm making a game using java. I'm wondering what would be the best way to store games options (like screen height and width, full screen boolean and many other similar options the user can select) at run time?
Currently, I read the options from a text file so everything that comes out of the reader is a string. I would like to add the value of the string to the appropriate variable in as few steps as possible. I would also avoid having to code getters and setters for all variables there is and have a general getter and setter that takes the name of the option as a parameter. ex:
public void set(String name, Object value){
options[name] = value;
}
public Object get(String name){
return (Object options[name]);
}
I was thinking about a hashmap of variable names and values but the problem is: not all variables are of the same type, I'll have ints and doubles and booleans. so what would be the best way to store all those different variable types and access them with general calls? Should I leave them as Object and cast them as I need to use them? Or do i really have to set them all manually in my code (which would be quite the hassle should i decide to add more options down the line)?
UPDATE: So, here's the code i got so far for serialization but still not working:
Options.java:
public class Options implements java.io.Serializable{
//Final variables declaration
static transient final String SAVE_DIR = System.getProperty("user.dir") + "\\res\\saves\\";
static transient final String OPTION_FILE = "options.ser";
//Static variables declaration
public int s_width;
public int s_height;
public float fov;
private static transient Options instance;
private Options()
{
this.s_width = (this.s_width == 0)? 800 : this.s_width;
this.s_height = (this.s_height == 0)? 600 : this.s_height;
this.fov = (this.fov == 0)? 60 : this.fov;
}
public static Options GetInstance()
{
if(instance == null)
instance = new Options();
return instance;
}
Serializer.java:
public class Serializer {
private static Options o = Options.GetInstance();
public static void loadOptions()
{
File dir = new File(Options.SAVE_DIR);
if(dir.exists())
{
File file = new File(dir + "\\" + Options.OPTION_FILE);
if(!file.exists())
{
saveOptions();
}
try {
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
o = (Options) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
else
{
dir.mkdir();
saveOptions();
}
}
public static void saveOptions()
{
File dir = new File(Options.SAVE_DIR + "\\" + Options.OPTION_FILE);
try {
if(!dir.exists())
{
dir.createNewFile();
o = Options.GetInstance();
System.out.println("otpion.ser created and initialised succesfully!");
}
FileOutputStream f = new FileOutputStream(dir);
ObjectOutputStream out = new ObjectOutputStream(f);
out.writeObject(o);
out.close();
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}