How games use random numbers (and why they're not really random)
Almost every game uses randomness: shuffling cards, placing mines, choosing the next falling block, deciding where food appears in Snake. But computers follow exact instructions, so how can they do anything random? The answer is that most of the time, they don't, and they don't need to.
Pseudo-random numbers
Most games use a pseudo-random number generator (PRNG). It's a formula that takes a number, scrambles it with some maths, and produces a new number that looks random. Then it uses that number to make the next one, and so on. The results pass lots of tests for randomness, but they're completely predictable if you know the formula and the starting number.
In JavaScript, Math.random() gives a number between 0 and 1. To roll a dice:
const roll = Math.floor(Math.random() * 6) + 1; // 1 to 6
Seeds
The starting number of a PRNG is called the seed. The same seed always produces the same sequence. That sounds like a problem, but games use it on purpose:
- Daily puzzles: use the date as the seed and everyone in the world gets the same puzzle that day.
- Sharing worlds: games that generate whole worlds let players share a seed so friends can explore the same world.
- Replays: recording the seed and the player's inputs is enough to replay a whole game exactly.
Shuffling fairly
Shuffling looks easy, but many simple methods are secretly unfair, making some orders more likely than others. The standard fair method is the Fisher–Yates shuffle: go through the deck from the end, and swap each card with a random card at or before it.
function shuffle(deck) {
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
return deck;
}
Every possible order comes out equally likely. A deck of 52 cards has so many possible orders (a number with 68 digits) that a well-shuffled deck is almost certainly in an order no deck has ever been in before.
Random isn't always fun
Pure randomness can feel unfair. Ten bad results in a row can happen by chance, and players hate it. So many games bend the rules a little:
- Falling-block games often use a "bag": all seven piece shapes are shuffled, dealt out, then reshuffled, so you never wait too long for the piece you need.
- Mine-finding games usually make sure your first click is safe.
- Some games secretly raise your chances after a run of bad luck.
Truly random numbers
When randomness really matters, like for passwords and security, computers collect unpredictability from the real world: tiny timing differences, electrical noise and other physical sources. Browsers provide this through crypto.getRandomValues(). For games, Math.random() is perfectly fine.
Try it
Every new game of Solitaire starts with a shuffle like the one above. If you're learning to code, try writing a dice-rolling program that rolls 6,000 times and counts each number. Each should come up close to 1,000 times.