Part 07 / 09

Loops: Lives and History

By the end of this part your game will show the player's lives as hearts, list every guess so far, and end the game when the lives run out.

6 sections 2 interactives
§ 7.1 · interactive

Doing something again and again

Your game is about to show the player’s lives as hearts: seven at the start, one fewer after each guess. You could write out seven different lines for seven different cases, but there’s a better way. Tell the computer to add one heart, and to keep doing that until there are enough.

Doing the same thing again and again is what a is for. Loops are everywhere in programs: going through every message in an inbox, every pixel of a photo, every item in a shopping basket to add up the total. Whenever you catch yourself about to write almost the same line several times, a loop is usually the better answer. Here is the one that builds the hearts:

let hearts = "";
for (let i = 0; i < MAX_ATTEMPTS - attempts; i++) {
hearts = hearts + "♥";
}

Without a loop you’d need a separate line for every possible number of hearts, from seven down to none, and you’d have to change them all if the game ever had ten lives. With a loop, one line does the work and the gate decides how often.

Picture a runner on a circular track. The brackets after for hold three instructions, separated by semicolons, and each one is part of the track:

  • let i = 0 is the start line. Before the first lap, make a box called i to count laps, and set it to 0. Loop counters are often called i, as in MDN’s own examples, but any name would work.
  • i < MAX_ATTEMPTS - attempts is a gate the runner passes before every lap. It’s a condition, a question, like the ones in part 5. If the answer is true, run another lap. If it’s false, leave the track.
  • i++ happens at the end of every lap: add one to the counter.

Notice that the gate’s question uses a sum, MAX_ATTEMPTS - attempts, which is the number of lives left. The browser works it out afresh on every visit to the gate, so the same loop draws seven hearts at the start of a game and none at the end.

The lap itself is the code between the curly brackets: add one heart to the string. With 7 lives and 4 attempts used, the gate asks “is i less than 3?” three times with the answer yes, so there are three laps and three hearts. On the fourth visit i is 3, “is 3 less than 3?” is false, and the loop is over.

Step through it to see every visit to the gate. Try 7 attempts, and notice that the loop can run zero times: if the first answer is false, the runner never starts.

Try it

Step through the hearts loop

Choose how many attempts have been used, then press Step. The highlighted part of the line is the part that runs.

Attempts so far
  1. let hearts = "";
  2. for (let i = 0; i < MAX_ATTEMPTS - attempts; i++) {
  3. hearts = hearts + "♥";
  4. }
  5. document.getElementById("lives").textContent = "Lives: " + hearts;
Boxes (variables)

No boxes yet.

Lives on the page

13 steps

Press Step to run the first line.

MAX_ATTEMPTS is 7, so the number of laps is 7 minus the attempts used.

§ 7.2

A list of guesses

The second feature is a list of every guess so far: “Your guesses: 50 25 37”. A variable holds one value, but you don’t know in advance how many guesses there will be. You need a box that holds a whole list.

That’s an : a row of numbered boxes under one name. Arrays hold most of the lists you meet on screens: the messages in an inbox, the songs in a playlist, the scores in a table of winners. You write one with square brackets:

let guesses = [];

Those empty brackets make an empty list. To add a value to the end, use push:

guesses.push(37);

After three guesses, the array holds [50, 25, 37]. Each value has its own numbered box, and the numbering starts at 0, not 1. You don’t need the numbers in this series, but they explain why programmers so often start counting at zero.

To show the list, you need to visit every box in turn, which is another loop. For lists there is a simpler kind, for…of:

let text = "Your guesses:";
for (const g of guesses) {
text = text + " " + g;
}

Read it as: for each value in guesses, call it g and run the lap. There’s no counter and no gate to write: the loop takes one value per lap and stops after the last one. The box g is made fresh for each lap and never changed during it, which is why it’s a const. Each lap glues a space and the next guess onto the text.

§ 7.3

Build it: lives, history, game over

Step 1. Replace the attempts paragraph with two new ones. They start with the text a new game should show:

game.html
<p id="message"></p>
<p id="lives">Lives: ♥♥♥♥♥♥♥</p>
<p id="history">Your guesses:</p>

The heart is a single character. The easiest way to get it into your file is to copy it from this page, with the copy button on the code. Part 1’s <meta charset="utf-8"> line is what lets the browser show it.

Step 2. At the top of the script, add an empty array for the guesses:

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

Step 3. In the click listener, replace the line that showed the attempts with these lines, which remember the guess, draw the hearts and list the guesses:

game.html
attempts++;
guesses.push(guess);
let hearts = "";
for (let i = 0; i < MAX_ATTEMPTS - attempts; i++) {
hearts = hearts + "♥";
}
document.getElementById("lives").textContent = "Lives: " + hearts;
let text = "Your guesses:";
for (const g of guesses) {
text = text + " " + g;
}
document.getElementById("history").textContent = text;

Step 4. Make the game end. A correct guess ends it, and so does using the last life. A new road in the decision catches that, and both endings disable the Guess button, so it can’t be clicked any more:

game.html
if (guess === secret) {
message.textContent = "Correct!";
document.getElementById("guessButton").disabled = true;
} else if (attempts === MAX_ATTEMPTS) {
message.textContent = "Out of lives! The number was " + secret + ".";
document.getElementById("guessButton").disabled = true;
} else if (guess > secret) {

The order matters again. Correct comes first, so a right answer on the very last life still wins.

Step 3’s lines go after guesses.push(guess) and before the decision, so the hearts and the list are up to date before the game decides what to say, including on the final guess. And notice that the starting text in step 1, seven hearts and “Your guesses:”, is typed into the HTML, while the loops draw the same things in the script. The same picture is now made in two places. It works, but if you ever changed MAX_ATTEMPTS to 5, the page would still start with seven hearts. Part 8 fixes that properly.

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="lives">Lives: ♥♥♥♥♥♥♥</p>
<p id="history">Your guesses:</p>
<script>
const MAX_ATTEMPTS = 7;
let secret = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
let guesses = [];
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++;
guesses.push(guess);
let hearts = "";
for (let i = 0; i < MAX_ATTEMPTS - attempts; i++) {
hearts = hearts + "♥";
}
document.getElementById("lives").textContent = "Lives: " + hearts;
let text = "Your guesses:";
for (const g of guesses) {
text = text + " " + g;
}
document.getElementById("history").textContent = text;
if (guess === secret) {
message.textContent = "Correct!";
document.getElementById("guessButton").disabled = true;
} else if (attempts === MAX_ATTEMPTS) {
message.textContent = "Out of lives! The number was " + secret + ".";
document.getElementById("guessButton").disabled = true;
} else if (guess > secret) {
message.textContent = "Too high!";
} else {
message.textContent = "Too low!";
}
});
</script>
</body>
</html>
§ 7.4 · interactive

Check it works

Save and refresh, then play two games: one where you win, and one where you lose on purpose. To start the second game, refresh the page.

Try it

Your game at the end of part 7

The preview runs the full file above. Win a game, then refresh and lose one: guess the same wrong number seven times.

game.html

Guess the Number

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

Lives: ♥♥♥♥♥♥♥

Your guesses:

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

Refresh starts a new game, with a new secret, here as in your own file.

Test the endings carefully, because they’re the newest roads. Peek at the secret in the preview, then make six wrong guesses and the right one on the seventh: the game should say Correct!, not Out of lives!, because the right answer is checked first. Then refresh and make seven wrong guesses. Try the same two games in your own file, without peeking, by guessing the same number seven times.

What you should see

The game starts with seven hearts and “Your guesses:”. Each real guess removes a heart and adds the number to the list. A correct guess, or the seventh wrong one, ends the game: the Guess button goes pale and stops working. After seven wrong guesses there are no hearts left and the page says Out of lives! The number was, followed by the secret.

§ 7.5

The loop that never ends

This part’s mistake is one to look at, not to try, so it appears here only as a picture. The loop at the top of the figure below looks almost like a safe one. The difference is in the last instruction: i-- instead of i++. Two minus signs take one away. So the counter goes 0, −1, −2, −3…, and the gate’s question, “is i less than 7?”, gets the answer yes every single time. The runner never leaves the track.

A computer is very fast, so this loop runs millions of laps, and it doesn’t stop to let anything else happen. The browser runs a page’s JavaScript and redraws the page on the same track of work, called the main thread, and while your loop holds it, nothing else on the page can move. Buttons stop answering, the page stops drawing, and the tab freezes. Nothing on your computer is damaged, but the only cure is to close that tab, fix the file, and open it again.

That’s why this is the one mistake in the series you should only look at. Every loop you write needs a way out: a condition that becomes false at some point. Check that the counter moves towards the finish, not away from it. MDN’s guide to loops puts it in one line: make sure the condition eventually becomes false, otherwise the loop will never end.

Your hearts loop is safe for exactly that reason: i starts at 0 and counts up, and the finish is a fixed number of lives, so the gate always says no in the end.

§ 7.6

Your challenge

Make the list of guesses more helpful. Next to each wrong guess, show an arrow pointing the way to go next: down after a guess that was too high, up after one that was too low. With a secret of 37, the list should look like this: “Your guesses: 50↓ 25↑ 37”.

The loop already visits every guess. Inside it, you can use an if, just as in part 5, to decide what to glue on. To type the arrows, copy them from this page.

Think about what the loop knows on each lap: the guess, in g, and the secret, which is still in its box. That’s everything you need to choose the arrow.

Show a solution

Replace the history loop with this one:

game.html
let text = "Your guesses:";
for (const g of guesses) {
if (g > secret) {
text = text + " " + g + "↓";
} else if (g < secret) {
text = text + " " + g + "↑";
} else {
text = text + " " + g;
}
}

A loop can hold an if, and an if can hold anything, even another loop. Building programs is mostly putting small pieces like these inside each other. Change the loop back before part 8.

The game works, but the only way to play again is to refresh, and the code that draws the hearts lives in two places. In part 8 you organise the whole game into functions, and a Play again button turns out to be almost free.

Sources for this part

Loops

Arrays and buttons

History

Series Guess the Number: Your First Program
Menu

Gears & Signals · Static site · No trackers