davidbau / seedrandom

seeded random number generator for Javascript
2.06k stars 160 forks source link

Persisting a seedrandom instance #11

Closed pkmnfrk closed 9 years ago

pkmnfrk commented 9 years ago

Hi,

Is it possible to serialize a seedrandom instance, and then restore it later?

My use case is that I'm using it to procedurally generate levels in a game, and allowing the user to pick the seed. It works great, except that if the user saves and quits, I can't find a way to save and restore the state, so the random numbers will be wrong, as compared to having retained the same instance.

For example, I want this:

var rng = seedrandom("Foobar");
console.log(rng()); //0.12345

var state = rng.serialize();

console.log(rng()); //0.23456
console.log(rng()); //0.34567

rng = seedrandom.unserialize(state); // or, seedrandom(state) or whatever

console.log(rng()); //0.23456
console.log(rng()); //0.34567
davidbau commented 9 years ago

Hey there!

I can add this. What do you think of the proposed API described here:

https://github.com/davidbau/seedrandom/blob/savestate/README.md#saving-and-restoring-prng-state

pkmnfrk commented 9 years ago

So, it needs to be explicitly marked as saveable, or restored from a serialized version that itself must have been marked as saveable. Yeah, that seems like it should work fine.

Thanks for the quick reply, incidentally! I tried yesterday to look in to implementing this myself, but I now realize that this is a lot more complicated under the hood than something like http://indiegamr.com/generate-repeatable-random-numbers-in-js/ .

davidbau commented 9 years ago

OK! It's not that complicated - it's just RC4, which has an internal state of an array and two indexes. Now you can save them away and restore them.

Version 2.3.11 is adds this feature, and it's released now.

pkmnfrk commented 9 years ago

Awesome, thanks! Works like a charm!

carcinocron commented 2 years ago

So, it needs to be explicitly marked as saveable, or restored from a serialized version that itself must have been marked as saveable. Yeah, that seems like it should work fine.

Thanks for the quick reply, incidentally! I tried yesterday to look in to implementing this myself, but I now realize that this is a lot more complicated under the hood than something like http://indiegamr.com/generate-repeatable-random-numbers-in-js/ .

thanks for sharing this, being able to store RNG state as a single number is going to be a game changer for me.