Quick and Dirty Pseudo-Random Generator
Procedural content is big. I’m working on a game based on purely procedurally generated levels. Thus I needed a pseudo-random number generator. I took the formula Adam ‘Atomic’ Saltsman (yeah – the Canabalt guy) presented in the Game Developer magazine and adapted it to work on the iOS platform.
I also thought it’s wise to keep it compatible with 8bit computers
so I truncated the number a great bit. It actually doesn’t matter too much, but I’d not use this code unchecked in production. Myself, I use it for building levels and I just need 999 different ones.
Generate an unsigned int pseudo-random number based on seed “seed”:
#define SONA_PRANDOM(seed) \
((unsigned)((seed * 1103515245 + 12345)/65536) % 32768)
Generate a float16 pseudo-random number based on seed “seed”:
#define SONA_PRANDOM_FLOAT(seed) \
(((float)SONA_PRANDOM(seed)) / (float) (1<<16-1))
Select x, y or z from a set:
#define SONA_PRANDOM_FROM_SET3(seed,x,y,z) \
(SONA_PRANDOM_FLOAT(seed) > 1.f/3.f ? (SONA_PRANDOM_FLOAT(seed) > 1.f/2.f ? x : y) : z)
Generate an int between __MIN__ and __MAX__:
#define SONA_PRANDOM_INT(seed,__MIN__, __MAX__) \
((__MIN__) + SONA_PRANDOM(seed) % ((__MAX__+1) - (__MIN__)))
In order to generate a sequence of random numbers you just reuse the last random number as seed:
unsigned random1 = SONA_PRANDOM(666);
unsigned random2 = SONA_PRANDOM(random1);
unsigned random3 = SONA_PRANDOM(random2);
// and so on
Final advice: Don't use it in production without checking every single value in a test run. If you pick the wrong seed, the random numbers might loop easily. Feel free to use it for prototyping or extend it.






