Part 2 of my 256 part series: Useful JavaScript Game Extensions!

/** * Generate uniformly distributed random numbers. * * @param {Number} [n] * @returns A Random integers from [0, n) if n is given, otherwise a random float * between 0 and 1. * @type Number */ function rand(n) { if(n !== undefined) { return Math.floor(Math.random() * n); } else { return Math.random(); } } |

Some games make use of random numbers… a lot. So when choosing the best interface it is important to keep that in mind. Often times uniform distributions are the way to go, such as when selecting from an array, or rolling a six sided die. If one often has need of a variety of random distributions then having different methods live in a `Random`

namespace would probably be best. For simple, everyday use a little `rand(6)`

is very convenient.

Pingback: Useful JavaScript Game Extensions: Array#rand