Class Options is designed as static class. Typically there is no need to create more that one instance of this class per a game. The usage is straightforward:
function initSFX() {
Options.load(); // load options from a file
if (Options.musics) // access option 'musics'
SFXManager.playBackgroundMusic();
}
// ... or ... function toggleMusics()
{
Options.musics = !Options.musics; // toggle 'musics' option
Options.save(); // save options to a file }
As I mentioned before, Options class is static. All its fields are saved/loaded to/from a file by static function save() and load(). The file is JSON formatted and it is placed under the root application's directory ("data://settings.dat"). To store/load all static fields an iterator is used:
// iterate all object fields for (var prop in obj)
console << prop << "\n";
// iterate all class fields
for (var prop in MyClass)
console << prop << "\n";
The iterator returns all fields including functions, so new "pure" object instance is created. The object instance has only valid fields:
// create pure object without functions (pure object) var options = {};
for (var opt in Options)
if (typeof Options[opt] != #function) // skip functions
options[opt] = Options[opt] // create new attribute with value
Here is full implementation:
// "static" class that provides basic functionality for "Options" used in 2d game development class Options
{
// All these class variables will be serialized var nick = "player01"; var level = 0;
var score = 0; var musics = false;
var sounds = false;
// ... etc, you can add/remove fields according your needs // // Static functions // Static function that saves options to file (json)
function save()
{
// rewrite file
var file = Stream.openFile("data://settings.dat", "w+");
if (!file) {
logE("Unable to create settings file!");
return;
}
// create pure object without functions (pure object)
var options = {};
for (var opt in Options)
if (typeof Options[opt] != #function) // skip functions
options[opt] = Options[opt] // create new attribute with value
file.printf("%V", options); // formatted print to file
file.close(); // close and release
} // Static function that loads options from file (json)
function load()
{
// open file for reading
var file = Stream.openFile("data://settings.dat", "r");
if (!file) {
logW("Unable to load settings file!");
return;
}
var options = parseData(file); // load data to json
file.close(); // close file
for (var opt in options) // iterate all attributes
Options[opt] = options[opt]; // apply to class
} // }