Random Number Generator

While the built-in Math.random() function provides suitable results for game development purposes, it has its own weaknesses. Most notably, it is not possible to seed the generator in order to reproduce a deterministic sequence of values. This is where ROT.RNG object comes to play.

Note: We use the excellent Alea algorithm, developed by Johannes Baagøe. For more information about the code, please see his article on RNGs in JavaScript. Alea is distributed under the MIT License.

Generating random values

Three main modes of operation are available:

SHOW( ROT.RNG.getUniform(), ROT.RNG.getNormal(0, 10), ROT.RNG.getPercentage() )
var canvas = document.createElement("canvas"); canvas.width = 500; canvas.height = 200; SHOW(canvas); var ctx = canvas.getContext("2d"); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "#f00"; var data = []; for (var i=0;i<40000;i++) { /* generate histogram */ var num = Math.round(ROT.RNG.getNormal(250, 100)); data[num] = (data[num] || 0) + 1; } for (var i=0;i<data.length;i++) { /* plot histogram */ ctx.fillRect(i, canvas.height-data[i], 1, data[i]); }

Working with arrays

SHOW( ROT.RNG.getItem(["apples", "oranges", "zombies"]), ROT.RNG.shuffle(["apples", "oranges", "zombies"]) );

Picking a weighted value

Choosing from a list of values with uneven weights is a common operation in Roguelike development. The getWeightedValue method is useful for this task; just give it a JS object with numeric weight values (arbitrary numbers) and a corresponding key will be picked randomly.

var monsters = { "orc": 3, "ogre": 1, "rat": 5 } for (var i=0; i<20; i++) { SHOW(ROT.RNG.getWeightedValue(monsters)); }

Working with RNG state

RNG's internal state can be retrieved and set to produce identical results.

var state = ROT.RNG.getState(); SHOW(ROT.RNG.getUniform()); ROT.RNG.setState(state); SHOW(ROT.RNG.getUniform());

The RNG can be seeded by a given number. Seeding initializes RNG's internal state. Retrieving the current seed is not very useful, but might come handy if you want to reproduce a behavior resulting from a random seed.

var seed = ROT.RNG.getSeed(); ROT.RNG.setSeed(12345); SHOW( ROT.RNG.getUniform(), ROT.RNG.getUniform() ); ROT.RNG.setSeed(12345); SHOW( ROT.RNG.getUniform(), ROT.RNG.getUniform() );

Cloning a RNG

You can clone a RNG to obtain its copy. The copy is completely independent and pre-set to its parent's state. The copy can be further cloned.

var clone = ROT.RNG.clone(); SHOW(ROT.RNG.getUniform()); SHOW(clone.getUniform()); ROT.RNG.setSeed(123); SHOW(ROT.RNG.getUniform()); SHOW(clone.getUniform());