Random Numbers, Dice and Games of Chance
Teach your program to roll dice and surprise you
<random> for exactly this. Once you can make random numbers, you can build dice, coins, card shuffles and games.
- say why programs use pseudo-random numbers,
- use the three helpers from
<random>:random_device,mt19937and a distribution, - seed once and roll many times,
- map numbers into a range like
1to6, - build a dice roller and a number-guessing game.
1. Why do we need random numbers?
Think about your favourite games. A board game needs dice. A card game needs a shuffle. A video game drops a surprise enemy or a lucky prize. Even a raffle needs to pick a winner. All of these need a number that nobody can predict in advance.
Randomness is not only for fun. Programmers use random numbers to test their code with lots of different inputs, and scientists use them to simulate things like weather or traffic. So learning to make good random numbers is a real, everyday skill, not just a toy.
2. The old way: rand() and its traps
For a long time C++ programmers used rand(), which lives in the header <cstdlib>. It hands back a whole number somewhere between 0 and a big value called RAND_MAX. It still works, but it has two famous traps.
Trap 1 - forgetting to seed. A seed is the starting point for the number machine. If you never set one, rand() starts from the same place every time, so your program prints the same "random" numbers on every run. To avoid that, older code calls srand(time(0)) once to seed from the clock.
#include <iostream>
#include <cstdlib> // rand, srand
#include <ctime> // time
using namespace std;
int main() {
srand(time(0)); // seed once, using the clock
int roll = rand() % 6 + 1; // squeeze into 1..6
cout << "You rolled: " << roll << endl;
return 0;
}
Trap 2 - the % 6 trick is slightly unfair. Using rand() % 6 to get a small range makes some numbers come up a tiny bit more often than others. For a school project it is usually fine, but there is a better, fairer tool. That tool is the modern <random> library.