Part 06 / 09

Randomness and Counting

By the end of this part your game will pick a different secret number every time it loads, and will count the player's tries out of seven.

7 sections 2 interactives
§ 6.1

A number nobody chose

A guessing game with the same answer every time isn’t much of a game. The secret has to be a number that you, the programmer, didn’t choose, so that even you can play. That means asking the computer for a random number.

JavaScript has one built in:

Math.random()

Each time this runs, it gives back a new number that is at least 0 and less than 1, such as 0.7312… or 0.0465… or 0.9981…, with a long tail of digits after the point. Every value in that range is about equally likely. Two details matter for what comes next. It can give exactly 0. And it can never give exactly 1: it can come very close, 0.99999…, but it always stays below.

Math is a toolbox that comes with JavaScript, full of ready-made calculations; Math.random is one tool in it. The brackets after it, empty here, run the tool. You’ll use a second tool from the same box in a moment.

So you get a decimal between 0 and 1, and you need a whole number between 1 and 100. Getting from one to the other takes three more small steps, and seeing them one at a time is easier than reading them. That’s the machine in the next section.

Did you know?

Math.random() isn’t truly random. It works its numbers out with a formula, starting from a seed the browser picks, which is why they are called pseudo-random. They are fine for games, but MDN’s reference warns never to use them for anything to do with security.

§ 6.2 · interactive

The random number machine

Here is the whole recipe for a secret from 1 to 100:

let secret = Math.floor(Math.random() * 100) + 1;

Read it from the inside out, the way the browser works it out. Each step is a station on a conveyor belt:

Try it

The random number machine

Press New number to send a fresh random value down the belt. Then feed it the smallest and largest values Math.random() can give, and see where they end up.

let secret = Math.floor(Math.random() * 100) + 1;

  1. Station 1 Math.random() a random number from 0 up to, but not including, 1 0.7312…
  2. Station 2 * 100 stretch it to 0 up to, but not including, 100 73.12…
  3. Station 3 Math.floor(…) chop off everything after the point 73
  4. Station 4 + 1 shift 0–99 up to 1–100 74

Press New number. Every number from 1 to 100 is equally likely.

Each station does one small job. Together they turn any number from 0 to just under 1 into a whole number from 1 to 100.

  1. Math.random() gives a decimal from 0 up to, but not including, 1. Say 0.7312…
  2. * 100 multiplies it by 100. (A star is how code writes ×.) Now it’s 73.12…, somewhere from 0 up to, but not including, 100.
  3. Math.floor(…) chops off everything after the point, always rounding down, so 73.12… becomes 73. Floor, like the floor of a room: always down. Now it’s a whole number from 0 to 99.
  4. + 1 shifts the whole range up by one. 73 becomes 74, and 0 to 99 becomes 1 to 100.

The order matters. If you added 1 before rounding down, Math.floor(Math.random() * 100 + 1), you’d get the same range by a different route; but if you rounded down before multiplying, Math.floor(Math.random()) * 100, every secret would be 0, because every value below 1 rounds down to 0. Working from the inside out is how to read any line like this.

The extremes prove it works. The smallest value, 0, goes 0, 0, 0, 1. The largest, just under 1, goes 0.99999…, 99.999…, 99, 100. Nothing can ever come out as 0 or 101. Without the last step, your game could pick 0 and never pick 100, which would be unfair on anyone guessing 100.

§ 6.3

Counting with a box

The second new feature is a counter: how many guesses has the player made? That’s a box holding a number that goes up by one with each guess:

let attempts = 0;

To add one, you write something that looks impossible in maths:

attempts = attempts + 1;

It makes sense once you remember that = means “put into”, and that the browser works out the right-hand side first. Look in the box: 2. Add one: 3. Put the 3 back in the same box. The box now holds 3, and the 2 is gone.

Adding one is so common that JavaScript has a shorter way to write it: attempts++. It does exactly the same thing. You’ll use the short form in your game.

Your game also needs to know how many tries the player gets, and that number should never change while the game runs. For a box like that, use const instead of let:

const MAX_ATTEMPTS = 7;

A box made with const is a : its value is set once and can never be replaced. If any line later tried MAX_ATTEMPTS = 8;, the browser would stop with the error “Assignment to constant variable.” That’s a feature. It protects a fixed rule of the game from an accidental change, and it tells anyone reading the code: this number doesn’t move. Writing it in capitals, with words joined by underscores, is a common style for fixed settings like this, so they stand out.

Why seven? Part 9 reveals the strategy behind it.

§ 6.4

Build it: a real secret

Step 1. Add a paragraph for the counter, under the message:

game.html
<p id="message"></p>
<p id="attempts"></p>

Step 2. At the top of the script, replace let secret = 42; with these three lines:

game.html
const MAX_ATTEMPTS = 7;
let secret = Math.floor(Math.random() * 100) + 1;
let attempts = 0;

Step 3. Count each guess and show the count. These lines go after the guard, so that a guess that makes no sense doesn’t use up a try, and before the decision:

game.html
if (input.value === "" || Number.isNaN(guess) || guess < 1 || guess > 100) {
message.textContent = "Please type a number from 1 to 100.";
return;
}
attempts++;
document.getElementById("attempts").textContent = "Attempts: " + attempts + " of " + MAX_ATTEMPTS;
if (guess === secret) {

Look at the order of the three lines at the top. The constant comes first because it’s a fixed rule of the game, and rules are easiest to find at the top of a file. Then the secret, picked once, when the page loads; it must not be picked again on every click, or the answer would change between guesses. Then the counter, starting at 0, because no guesses have been made yet.

Inside the listener, the order matters just as much, and it’s worth reading the steps in the order the browser will run them. The guard comes first, so nonsense never counts. The count goes up next, and the message comes last. Refreshing the page runs the script again from the top: a new secret, and a counter back at 0. That’s how to start a new game, for now.

The full file so far:

game.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Guess the Number</title>
</head>
<body>
<h1>Guess the Number</h1>
<p>I'm thinking of a number between 1 and 100.</p>
<input id="guessInput" type="number" min="1" max="100">
<button id="guessButton">Guess</button>
<p id="message"></p>
<p id="attempts"></p>
<script>
const MAX_ATTEMPTS = 7;
let secret = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
document.getElementById("guessButton").addEventListener("click", function () {
let input = document.getElementById("guessInput");
let message = document.getElementById("message");
let guess = Number(input.value);
if (input.value === "" || Number.isNaN(guess) || guess < 1 || guess > 100) {
message.textContent = "Please type a number from 1 to 100.";
return;
}
attempts++;
document.getElementById("attempts").textContent = "Attempts: " + attempts + " of " + MAX_ATTEMPTS;
if (guess === secret) {
message.textContent = "Correct!";
} else if (guess > secret) {
message.textContent = "Too high!";
} else {
message.textContent = "Too low!";
}
});
</script>
</body>
</html>
§ 6.5 · interactive

Check it works

Save, refresh, and play a real game at last. You don’t know the secret, so use the hints: start at 50, and let each answer tell you which half to try next.

Try it

Your game at the end of part 6

The preview runs the full file above, with its own random secret. Refresh it for a new number. Peek at the secret if you want to test the Correct! answer quickly.

game.html

Guess the Number

I'm thinking of a number between 1 and 100.

Peeking is not part of your game; it helps you test every message.

Peek is only in the preview. Your own file keeps its secret, as a game should.

What you should see

The counter is empty until your first guess, then shows Attempts: 1 of 7, then 2 of 7, and so on. An empty box or 500 gets Please type a number and doesn’t count. Refreshing the page starts again from nothing, with a different secret.

Peek at the secret in the preview and guess it straight away, to check that Correct! appears and the count still goes up. Then try a nonsense guess between two real ones, and watch the count skip it.

You may notice that nothing stops you at seven. Keep guessing and the counter happily shows Attempts: 8 of 7, and you can keep guessing after Correct! too. The game counts, but it has no rules about counting yet. Ending the game is the job of part 7.

§ 6.6

Break it on purpose

Capital letters matter in names, and this is a good place to see how much. Change Math.random() to Math.Random(), with a capital R. Save and refresh.

The page looks normal. But try a guess: the Guess button does nothing at all. The console explains:

Uncaught TypeError: Math.Random is not a function game.html:19

The toolbox Math has a tool called random, but none called Random. When the browser tried to run Math.Random(), it found nothing there to run, and “is not a function” is how it says “there’s no tool by that name to run”. The error points at line 19, the line that makes the secret.

Notice something else: the error happened as the page loaded, not when you clicked. When an error stops a script, nothing below it runs. The line that attaches the click listener comes after line 19, so it never ran, and the button was never told to listen. One wrong letter at the top silenced the whole game.

That’s worth remembering whenever a button does nothing: look in the console for a red message, and remember that the real mistake may be well above the code you were looking at. Put the lowercase r back, save and refresh, and the game works again.

§ 6.7

Your challenge

Add an easy mode, where the secret is from 1 to 10 instead of 1 to 100.

Changing the recipe is one number. But the game mentions its range in other places too: the invitation, the guard that rejects guesses out of range, its message, and the max on the number box. Find them all, and play a few games to make sure they agree.

Use the random number machine above to check your recipe: what does the last station need to produce for a range of 1 to 10? Then test the edges of your new game, 1 and 10, and one number just outside, 11.

Show a solution

Five changes, all from 100 to 10. In the HTML:

game.html
<h1>Guess the Number</h1>
<p>I'm thinking of a number between 1 and 10.</p>
<input id="guessInput" type="number" min="1" max="10">

At the top of the script:

game.html
let secret = Math.floor(Math.random() * 10) + 1;

And in the guard, inside the click listener:

game.html
if (input.value === "" || Number.isNaN(guess) || guess < 1 || guess > 10) {
message.textContent = "Please type a number from 1 to 10.";

Did you find all five? Having the same number scattered around is how bugs creep in: change four and forget the fifth, and the game breaks its own rules. One of part 9’s extra challenges fixes that properly. Put 100 back before part 7.

Your game keeps count, but it never ends. In part 7, a loop draws the player’s lives as hearts, an array remembers every guess, and the game finally stops when the lives run out.

Sources for this part

Random numbers

Counting and constants

Errors

History

Series Guess the Number: Your First Program
Menu

Gears & Signals · Static site · No trackers