A Random Note


I know of very few games that don’t have a randomized element of some sort, be it randomized levels, items, AI behavior, and timing, among others. There are a lot of great articles online about random numbers in computing, including this one with a fantastic discussion of using random numbers in procedural generation. For Startup Freak I also have quite a few random elements, so I have formalized it a little with an interface:

IRandom Interface

Putting an interface in front of the random number generator has a couple of advantages. It’s not dissimilar to using an IClock interface instead of directly calling DateTime.Now. For one it allows much easier testing. It also lets me quickly change the underlying implementation (for example I’m currently using System.Random but could easily change to a hash algorithm across the game). Lastly because I inject this interface as a dependency into all classes that require it, I have more control over which components share a random seed. At the moment I use a fixed seed across the whole app when running in the editor so that I can get some repeatability as I play test certain features.

Here is what the interface currently looks like:

public interface IRandom
  double Double();
  int Integer(int minVal = int.MinValue, int maxVal = int.MaxValue);
  T From<T>(ICollection<T>; collection);
  T FromEnum<T>() where T : struct, IConvertible;

You’ll also note that I have encapsulated some commonly performed tasks with random numbers here, namely selecting a random element from a collection, and selecting a random value from an enum.


You can check out the implementation here

Important Note: System.Random is not thread safe, nor is this implementation. That’s fine in my case as I’m not doing any threading for this game (at least not yet), but keep it in mind.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s