Useful JavaScript Game Extensions: rand

Rand Atlas Shrugged

Rand Atlas Shrugged
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.

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

One thought on “Useful JavaScript Game Extensions: rand”

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s