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 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() );