Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Shall we play?
You have some free time to spare between running endless errands for the Boss. Why not write something for yourself, like for rolling dice?
The principle is that players take turns rolling two dice. The result of the roll is the participant’s points. The winner is the one who scored the most points. To create excitement, each player will have three attempts.
We will write the program step-by-step and start with creating the runGame
function where in the future the game will be launched from (rolling dice and accumulating points).
To roll dice, use the function muffin.throwDice(min, max)
, which generates random numbers in a given interval, including the minimum and maximum values. This function exists only in the course. In JavaScript, there is no such function, but there are others that perform similar actions. We’ll talk about them later in other courses. In the meantime, we will use muffin.throwDice(min, max)
. What are the minimum and maximum values?
If you roll one dice, you can get a number from 1
to 6
, because a dice has six faces. And if you roll two dice, you can get a number from 2
to 12
.
So we transfer arguments 2
and 12
to the function? No, we’ll do it in a better way! Let’s attach the arguments to the number of dice: if we have one dice, then the values of the arguments will be the same, if there are three dice, then we will have different values.
The worst result in the game is obtained when all dice get a one and the best: if all dice get a six. Therefore, the minimum value is equal to the number of dice, and the maximum value is 6 * number of dice
.
All we have left to do is declare a variable that will store the number of dice and use it to calculate the arguments of the runGame
function.
Let’s roll the dice and make sure that the function works.
Let the game begin!
- script.js
Thanks! We’ll fix everything at once!
The code has changed, click “Run” or turn autorun on.
Comments