mardi 17 mai 2016

Pseudorandom, repeatable data in javascript

Example: Imagine the following situation: You want to build an rpg / roguelike with a randomly generated world. As an input to the generation of the world, you'd use a randomly generated number ('seed'). If the player dies but wants to play in the same world again, he would simply have to provide the seed of the world when starting a game.

Question: Accordingly, the code should look something like this:

const generator = createGenerator( "SOME_SEED" )

/* ... Some lines later ... */

const heightOfWaterInTemple = generator( "HEIGHT_OF_WATER" )

The 'generator' function should take a string ('purpose') as an input and return a 'deterministic', yet 'random' number between 0 and 1.

  • 'Deterministic' in the sense that every time the code runs with the same seed, it generates the same output.
  • 'Random' in the sense that is distributed 'niceley' over the interval between 0 and 1 when varrying seed and purpose.

Cryptographic safety is not a concern. How would I implement this in JS?

Caveat: If I understand the linked module correctly, this is not a solution: The output depends on the order of function calls and thus on the ordering of the code. As I most likely want to refactor or change the code later on, this makes this approach invalid as it might change the output after an update to the program. ( In the example the user would after a patch to the game find his beloved worlds in a completely changed state. )




Aucun commentaire:

Enregistrer un commentaire