API:RNG::state

From Spherical
Jump to: navigation, search


RNG::state is an accessor property which allows you to get or set the current state of the random number generator instance.

Usage

current_state = rng_object.state;
rng_object.state = new_state;

API Information

Description

RNG::state is a 32-byte hexadecimal string that encodes the exact state of the RNG instance. If you save the value of this property to a file and load it in a later session, you can resume a random number sequence from where you left off. This is distinct from seeding (see RNG.fromSeed()), which starts a sequence from the beginning.

One use of this is to combat "save scumming", where a player saves a game before a randomly-determined event and reloads until they get a result they like (in Pokémon, for instance). If you save the state of the random number generator along with the other game data, the RNG becomes much harder to exploit since the same sequence of numbers will be generated again after the reload. This is also why Sphere allows you to construct multiple RNG instances: by having separate instances for different events and persisting their states across saves, you can combat RNG manipulation.

Examples

Saving

let save = {
    name:     heroGuy.name,
    level:    heroGuy.level,
    rngState: myRNG.state,
    // etc...
};
let saveData = JSON.stringify(save);  // JSON encode
FS.writeFile('~/saveGame.json', saveData);

Loading

let saveData = FS.readFile('~/saveGame.json');
let save = JSON.parse(saveData);  // JSON decode
heroGuy.name = save.name;
heroGuy.level = save.level;
myRNG = RNG.fromState(save.state);  // or: myRNG.state = save.state;
// etc...

See Also