ActionScript3 Dice Class
In game development randomness is often necessary for certain tasks, be it the random distribution of graphic tiles, a random factor in NPC AI or random stats in a roleplaying game. Especially for the latter purpose the static Dice class provides a set of methods to roll dice as it is common in a Role-playing game, to be exact four-, six-, eight-, ten-, twelve-, twenty-sided and percentile dice.
The Dice class (and it’s supporting classes) are rather elaborated, using for example the Linear Congruential algorithm in the process of generating ‘true’ random numbers so it might not be the most speed-optimized method for calculating random numbers. For absolute performance the LCA and rounding routines can be removed to speed up calculations.
Using the Dice class is very simple! For example rolling two ten-sided dice can be done with the following call …
var result:int = Dice.tenSided(2);
… rolling the percentile die is even simpler as it does not need any arguments. It always returns a value between 1 and 100 …
var result:int = Dice.percentile();
… the class also provides the roll method with that any x-sided die could be rolled, 3 sixteen-sided dice for instance …
var result:int = Dice.roll(16, 3);
The following small Flex application uses the Dice class and can be used to test dice throw probability according to the bell curve (the more dice are used the lower the probability to roll boundary results).
Update: The Dice class is now part of the hexagonLib and can be found here.