Often while developing projects, you will find yourself looking for ways to generate random numbers. The most common use cases for generating random numbers are games of chance like rolling dice, shuffling playing cards, and spinning roulette wheels. In this guide, you will learn how to generate a random number using the The
A common use of the But the
Often while developing projects, you will find yourself looking for ways to generate random numbers.
The most common use cases for generating random numbers are games of chance like rolling dice, shuffling playing cards, and spinning roulette wheels.
In this guide, you will learn how to generate a random number using the
A common use of the
This is because algorithmic random number generation can never be truly random in nature. This is why we call them pseudo-random number generators (PRNGs).
To learn more about the
Random Number Generator Function
Now let's use the
Let's break down the logic here.
So the intervals would be as follows:
To factor the second interval, subtract min from both ends. So that would give you an interval between 0
So now, to get a random value you would do the following:
Alright, so now the last step remaining is to make sure that
You could use the
So now that you have a fair understanding of how a random generation works, let's use this function to simulate rolling dice.
The Rolling Dice Game
In this section, we will create a really simple mini dice game. Two players enter their name and will roll the dice. The player whose dice has a higher number will win the round.
First, create a function
Inside the function body, call the
Next, create two input fields and a button as shown below:
When the 'Roll Dice' button is
clicked, get the player names from the input fields and call the
You can validate the players' name fields and prettify the markup with some CSS. For the purpose of brevity, I'm keeping it simple for this guide.
That is it. You can check out the demo here.
For most browser-based applications and games, this much randomness is enough and serves its purpose.
That's it for this guide. Stay safe and keep coding like a beast.
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
How random is JS Math random?
It may be pointed out that the number returned by Math. random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets.