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, such as a program 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, which will eventually run the game (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 die, you can get a number from 1 to 6, because a die has six faces. And if you roll two dice, you can get a number from 2 to 12.
So we pass arguments 2 and 12 to the function? No, we’ll do it in a better way! Let’s make the arguments depend on the number of dice: with one die, the arguments will be 1 and 6; with three dice, they will be 3 and 18.
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 muffin.throwDice 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