To be fair, BGT's dictionaries are kinda cumbersome. Python, Javascript, Java, all have much more intuitive implementations of the same concept. Bonus: Python stores just about everything in the current session in a dictionary, making it easy for something like Dill to save/load.
I almost always write a function or method to make retrieving dictionary entries simpler, in BGT. I think I uploaded a zip with quickdict.bgt, where it's reduced to a handful of get functions for primitives. And there's a global dictionary (just called a), so anything that needs to be serialized can be set easily from anywhere.
There's a serialization tutorial in the manual, but this example should work if you have quickdict:
#include "quickdict.bgt"
void save_settings() {
string data = serialize (a);
// I'd encrypt it, just to be safe:
text = string_encrypt(text, "I don\'t remember if this is the right order.");
file fout;
fout.open ("data.dat", "wb");
fout.write (text);
}
bool load_settings () {
// Returns true on success, false on failure.
if(!file_exists("data.dat") return false;
file fin;
fin.open ("data.dat", "rb");
string text = fin.read();
fin.close();
text = string_decrypt (text, same_key_as_before); // What possessed me to use such a long key while typing on my phone?
a = deserialize (text);
return true;
}
void initialize () {
if (load_settings()) return; // If we already have a file saved, just do that.
else { // Set some defaults:
a.set ("bgm volume", -10);
// etc.
}
}
void change_bgm_volume (float amount) {
bgm.volume = bgm.volume + amount;
// I'm making it more complicated, here, because I sometimes temporarily adjust volume for cut scenes, or let music fade in/out during gameplay, so we actually want to set these separately:
float vol = getf ("bgm volume");
vol += amount;
if (vol>0) vol=0;
else if (vol<-100) vol=-100;
a.set ("bgm volume", vol);
}
// now we let the player change volume:
void system_keys () {
if (key_pressed(KEY_PRIOR)) change_bgm_volume (5);
else if (key_pressed (KEY_NEXT)) change_bgm_volume (-5);
}
Generally speaking, it would be better to teach than to give usable examples, but judging by where you are in the process, an example to take apart and put back together would probably be useful.
After all, I haven't tested the above, and the bit with the encryption key has a problem as written.
看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
George... Don't do that.