Quite often when developing a game I need “random” numbers, that I can reproduce or that I can steer. Why? – For example when setting up a level or when resetting a level you might want to have it look random, but still the same every time you load it. – So how do we do that? There are tons of ways of achieving a so called “seeded random generated number” – if you want any details on the algorithms you can for example check out this link. But basically they all work the same: You initialize the algorithm with a “seed” (a number, that you choose to steer the algorithm). And every seed will return its own unique set of “random” numbers, so e.g.: Every time I seed the Number 6, I get the same set of generated “random” numbers. Every time I seed the Number 10, I get the same set of “random” number, that is different from the set ‘6’ and so on…
Because of this fact: seeded random numbers are predictable, which is not bad, but just don’t use it for encryption purposes ect… 
The algorithm
So the algorithm I’m using is the following, it’s really very simple:
(this is nothing new and also nothing I invented, but I think this might help quite a few people)
|
// the initial seed Math.seed = 6; // in order to work 'Math.seed' must NOT be undefined, // so in any case, you HAVE to provide a Math.seed Math.seededRandom = function(max, min) { max = max || 1; min = min || 0; Math.seed = (Math.seed * 9301 + 49297) % 233280; var rnd = Math.seed / 233280; return min + rnd * (max - min); } |
Continue reading →