Creating a Random Generator for Dungeons and Dragons

Introduction

As a Dungeon Master, you often find yourself in need of help for random events, discoveries, or encounters. The books provide many tables to roll dice for random elements, but why not automate the process?

Simple JavaScript functions can be created to instantly run the random generations for you, and this guide will show you how!

Setting Up the Function

The function to contain our random number and the generated values must be created. First, declare a variable to contain the value of your random generator.

var randomEncounter = "";

Next, name your function.

function encounterGenerator(value) { }

Creating the Random Number Generator

Inside your function, create a new variable that contains a randomly generated number.

var randomNumber = Math.floor(Math.random()*6+1);

Replace the number 6 in the example below with however many variables the random table is supposed to have. Ie, a d10 table would look like this:

var randomNumber = Math.floor(Math.random()*10+1);

Create a Switch Statement

Now, we're going to create a switch statement that contains each of the possible outcomes of the random table. Pass the randomNumber variable into it.

switch(randomNumber) { case 1: value = "Six kobolds"; break; case 2: value = "Five goblins"; break; case 3: value = "Four bandits"; break; case 4: value = "Three orcs"; break; case 5: value = "Two owlbears"; break; case 6: value = "One Tarrasque"; break; }

Finishing up

Lastly, we'll pack up the randomly generated value we created and prepare to return it from the function.

return value;

Your code should look something like this:

var randomEncounter = ""; function encounterGenerator(value) { var randomNumber = Math.floor(Math.random()*6+1); switch(randomNumber) { case 1: value = "Six kobolds"; break; case 2: value = "Five goblins"; break; case 3: value = "Four bandits"; break; case 4: value = "Three orcs"; break; case 5: value = "Two owlbears"; break; case 6: value = "One Tarrasque"; break; } return value; }

Testing it Out

Open up a JavaScript console and enter the code we just created and hit Enter on your keyboard. After that, type in this code to run the function:

encounterGenerator(randomEncounter);

After hitting Enter again, type in this code to display the random value:

console.log(randomEncounter);

The console will then display your encounter. Hope your random encounter isn't too devastating!