Please help me make a table generator (RPG)

I have learnt how to generated random numbers within a range, and how to make a table.

How do I say “Roll on this table a number of times equal to the number generated”?

i.e. You have 4 Cookies. For each cookie, choose from this table what type of cookie they are (Chocolate Chip, Snickerdoodle, Christmas Cookie etc.)

You should try JavaScript’s math.random function.

For example, if you wanted a random number between 0 and 10:

var number = Math.floor(Math.random() * 10)
console.log(number) // Should be 1,2,3,4,5,6,7,8,9,10

As for tables, what do you mean by table? Do you mean array like this?

var cookies = ["Snickerdoodle", "Christmas Cookie"]
1 Like

You can also use Math.random to choose a random element from an array:

function randomFromArray(array) {
    return array[Math.floor(Math.random() * array.length)];
}

const cookies = ["Chocolate Chip", "Snickerdoodle", "Shortbread"];

function randomCookie() {
    return randomFromArray(cookies);
}

You can loop and choose multiple cookies:

var myCookies = [];
const numCookies = Math.floor(Math.random() * maxPossibleRoll) + 1;

while (numCookies-- > 0) {
    myCookies.push(randomCookie());
}

This would let you get the same cookie multiple times though.

2 Likes

Okay. So I can do randomFromArray and have a table of cookies to choose from.

I don’t fully understand the multiple cookies loop. That code would allow for the same cookie to be selected more than once?

Yeah, I want to pick from an array a number of times equal to a value.

And I want that value to equal a number output by number generator I already have.

Yes, if you called randomCookie() 10 times it’s possible that you’d get “Chocolate Chip” every time, since it’s just choosing a random element from the cookies array each time, like if you rolled a die 10 times it’s possible to roll a 6 every time.

If the variable “numCookies” is 10 then the loop will run that many times and each time it will add another randomly chosen cookie to the myCookies array.