Adventures in Random Land

Posted on February 12, 2010, under Tanglet

Up until now I’ve used each platform’s random number generator in my games. Obviously they’re not good enough for statistical analysis, but in my experience they are okay for my simple programs. However, they’re not the same on Windows, Linux, and the Mac. Which means that a game seed on one platform won’t start the same game on another. And, if the platform makers change them at all, the saved games will break.

I decided to implement my own generator to solve those issues. It was a little tricky to wade through all of the discussions of random number generators, though, because it seems like everybody who talks about them is obsessed with the intricacies of the math. I know, it’s a complex field with complex solutions, but I don’t need something that is cryptographically secure!

In the end I decided to use a basic xorshift generator. Obviously, the algorithm isn’t strong enough for anything beyond my simple games, but I’m surprised at how easy it is to create random numbers. Repeatedly shift and XOR a seed number with a few “magic” numbers, and you’re all set.

Using a different generator will of course break saved games, so I’m thinking about wrapping up the platform generator in the same API (probably as a sub-class). I would simply need to add a field to the saved games specifying which generator to use, and if the game can’t find the field it will fall back to using the platform’s generator.

The first game to get the xorshift generator is Tanglet, because that is the one I am actively working on. Tanglet is also one of the easiest games to add it to, because it doesn’t save games across runs.

Categories