0

I'm making some kind of game with JS. And I want to have an ability to restore game board from previous games. I think I will be able to achieve this behavior if I will have an ability to reproduce sequence of pseudo random numbers. This pseudocode should illustrate my idea:

var seed = 1; // for example
var random1 = initRandom(seed); // I'm looking for this function initRandom
var random2 = initRandom(seed);
console.assert(random1() === random2()); // both random1 and random2 generates pseudo random numbers
console.assert(random1() === random2());
console.assert(random1() === random2());
console.assert(random1() === random2());
console.assert(random1() === random2()); // I will use those number for board generation

Can somebody propose a way to achieve this behavior?
N.B.: random1 and random2 must be time-independent.

kharandziuk
  • 12,020
  • 17
  • 63
  • 121
  • possible duplicate of [Javascript Random Seeds](http://stackoverflow.com/questions/521295/javascript-random-seeds) – Evan Knowles Aug 07 '14 at 08:30
  • I think you should generate such random numbers on server side, not in JS – hindmost Aug 07 '14 at 08:31
  • @hindmost what is the reason to do that? – kharandziuk Aug 07 '14 at 08:32
  • @kharandziuk On server side you can have ready-to-use (or even built-in) facilities to generate desired random numbers. Whereas in JS you have to implement it yourself. Furthermore, imho server-side implementation is better from the security point – hindmost Aug 07 '14 at 08:39
  • @hindmost I think it make sense. Provide it as an answer and I will accept it – kharandziuk Aug 07 '14 at 09:24

1 Answers1

1

The standard psuedo-random generator in JavaScript is not seedable, but you can implement some standard algorithm or use a library such as https://github.com/skeeto/rng-js by Christopher Wellons.