Part 08 / 09

Functions: Organising the Game

By the end of this part your game will be organised into named pieces, each with one job, and a Play again button will start a new game without refreshing the page.

6 sections 2 interactives
§ 8.1 · interactive

Machines with names

You have been using functions since part 2 without the name. Number() takes text and gives back a number. Math.floor() takes 73.12 and gives back 73. A is a machine with a name: something goes in through a slot, the machine does its one job, and either something comes out, or something changes on the page.

Now you will build your own. Here is a small one:

function showMessage(text) {
document.getElementById("message").textContent = text;
}

The word function says a machine is being defined. Its name, showMessage, says what it does. Between the curly brackets is the job. Defining a function runs nothing: it’s like writing a recipe card and filing it away. The browser reads it, remembers it, and moves on.

To use the machine, you call it, by its name followed by brackets:

showMessage("Too high!");

Now the job runs. The word text in the definition is a : a box that the function fills with whatever you hand it in the brackets when you call it. Call it with “Too high!” and the box text holds “Too high!” while the job runs. Call it again with “Too low!”, and a fresh box text holds that instead. One machine, any message.

Watch the box appear and disappear. Step through a definition and two calls:

Try it

Step through a function call

Press Step. Watch the highlight jump from the call into the function and back, and watch the parameter box text appear for each call and vanish when the job is done.

  1. function showMessage(text) {
  2. document.getElementById("message").textContent = text;
  3. }
  4. showMessage("Too high!");
  5. showMessage("Too low!");
Boxes (variables)

No boxes yet.

Message on the page

9 steps

Press Step to run the first line.

The browser remembers the definition at the start, but the line inside it only runs when the function is called.

§ 8.2

One job each

Look at your script from part 7 with fresh eyes. It’s one long click listener that does everything: reads the guess, checks it, counts it, draws hearts, lists guesses, decides and ends the game. And the starting hearts and “Your guesses:” are typed into the HTML separately, so the same picture is made in two places. Adding a Play again button now would mean resetting all of that from another place again.

Programmers deal with this by giving every job its own function, with a name that says what it does. Your game splits into six:

Function Its one job
newGame() Pick a new secret, reset the counts and draw a fresh page
showMessage(text) Put a message on the page
showLives() Draw one heart per life left
showHistory() List the guesses so far
endGame(text) Show the final message and disable the Guess button
checkGuess() Read the guess, judge it and update everything

Read the names alone and you already know what the game does. That’s the main reason to organise code this way: a function’s name explains a whole chunk of code in a couple of words, so you can read a program like a table of contents and only open the chapter you need.

The other reason is reuse. Once newGame() exists, starting a new game is one line, from anywhere. When the page loads, call newGame(). When the player clicks Play again, call newGame(). The button costs one line of HTML and one line of script. Organising the game first is what makes the new feature almost free.

One more change comes with it. Until now, the click listener was given a function with no name, written right there in the brackets. From now on it gets checkGuess, by name, without brackets:

document.getElementById("guessButton").addEventListener("click", checkGuess);

No brackets, because you’re not calling checkGuess now. You’re handing the machine itself to the button, for the button to call on every click.

§ 8.3

Build it: functions and Play again

This part changes most of the script, so take it one step at a time and keep the full file at the end of this section open beside you.

Step 1. In the HTML, empty the two paragraphs, because newGame() will fill them, and add the Play again button:

game.html
<p id="message"></p>
<p id="lives"></p>
<p id="history"></p>
<button id="newGameButton">Play again</button>

Step 2. At the top of the script, make the boxes without filling them. They start out holding nothing, a value JavaScript calls undefined, until newGame() puts something in them:

game.html
const MAX_ATTEMPTS = 7;
let secret;
let attempts;
let guesses;

Step 3. Below them, add newGame() and the three small functions that draw things. The bodies of showLives() and showHistory() are your loops from part 7, moved inside a name:

game.html
function newGame() {
secret = Math.floor(Math.random() * 100) + 1;
attempts = 0;
guesses = [];
document.getElementById("guessButton").disabled = false;
showMessage("Make your first guess!");
showLives();
showHistory();
}
function showMessage(text) {
document.getElementById("message").textContent = text;
}
function showLives() {
let hearts = "";
for (let i = 0; i < MAX_ATTEMPTS - attempts; i++) {
hearts = hearts + "♥";
}
document.getElementById("lives").textContent = "Lives: " + hearts;
}
function showHistory() {
let text = "Your guesses:";
for (const g of guesses) {
text = text + " " + g;
}
document.getElementById("history").textContent = text;
}
function endGame(text) {
showMessage(text);
document.getElementById("guessButton").disabled = true;
}

Step 4. Turn the old click listener into checkGuess(). Its first line changes, and so does everything that used to draw or end the game, which now calls the functions instead. Because input and guess are filled once per guess and never changed, they become constants:

game.html
function checkGuess() {
const input = document.getElementById("guessInput");
const guess = Number(input.value);
if (input.value === "" || Number.isNaN(guess) || guess < 1 || guess > 100) {
showMessage("Please type a number from 1 to 100.");
return;
}
attempts++;
guesses.push(guess);
showLives();
showHistory();
if (guess === secret) {
endGame("Correct!");
} else if (attempts === MAX_ATTEMPTS) {
endGame("Out of lives! The number was " + secret + ".");
} else if (guess > secret) {
showMessage("Too high!");
} else {
showMessage("Too low!");
}
}

The box message from part 5 is gone: showMessage() finds the paragraph itself.

The functions can come in any order in the file. The browser reads all of them before it reaches the last line, which is the first place any of them is called, so by then it knows every name. This series puts newGame() first because a game starts there, then the small helpers, then checkGuess(), the biggest.

Step 5. At the very end of the script, hand the functions to the two buttons, and start the first game:

game.html
document.getElementById("guessButton").addEventListener("click", checkGuess);
document.getElementById("newGameButton").addEventListener("click", newGame);
newGame();

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"></p>
<p id="history"></p>
<button id="newGameButton">Play again</button>
<script>
const MAX_ATTEMPTS = 7;
let secret;
let attempts;
let guesses;
function newGame() {
secret = Math.floor(Math.random() * 100) + 1;
attempts = 0;
guesses = [];
document.getElementById("guessButton").disabled = false;
showMessage("Make your first guess!");
showLives();
showHistory();
}
function showMessage(text) {
document.getElementById("message").textContent = text;
}
function showLives() {
let hearts = "";
for (let i = 0; i < MAX_ATTEMPTS - attempts; i++) {
hearts = hearts + "♥";
}
document.getElementById("lives").textContent = "Lives: " + hearts;
}
function showHistory() {
let text = "Your guesses:";
for (const g of guesses) {
text = text + " " + g;
}
document.getElementById("history").textContent = text;
}
function endGame(text) {
showMessage(text);
document.getElementById("guessButton").disabled = true;
}
function checkGuess() {
const input = document.getElementById("guessInput");
const guess = Number(input.value);
if (input.value === "" || Number.isNaN(guess) || guess < 1 || guess > 100) {
showMessage("Please type a number from 1 to 100.");
return;
}
attempts++;
guesses.push(guess);
showLives();
showHistory();
if (guess === secret) {
endGame("Correct!");
} else if (attempts === MAX_ATTEMPTS) {
endGame("Out of lives! The number was " + secret + ".");
} else if (guess > secret) {
showMessage("Too high!");
} else {
showMessage("Too low!");
}
}
document.getElementById("guessButton").addEventListener("click", checkGuess);
document.getElementById("newGameButton").addEventListener("click", newGame);
newGame();
</script>
</body>
</html>
§ 8.4 · interactive

Check it works

Save and refresh. A reorganisation like this should change nothing about how the game plays, except the new button, so test the old features as carefully as the new one.

Try it

Your game at the end of part 8

The preview runs the full file above. Win or lose a game, then press Play again and play another without refreshing.

game.html

Guess the Number

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

Make your first guess!

Lives: ♥♥♥♥♥♥♥

Your guesses:

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

Play again calls the same newGame() that runs when the page loads.

Play the same games as in part 7: a win, a win on the last life, a loss, a nonsense guess. Then press Play again in the middle of a game, and after it has ended. If everything that worked before still works, the reorganisation succeeded. Checking that old features still behave after a change is a habit worth keeping for life: it’s how programmers make sure that fixing one thing hasn’t broken another.

What you should see

The page opens with Make your first guess!, seven hearts and “Your guesses:”. Guessing works as in part 7, and the game still ends with Correct! or Out of lives!. Play again, at any moment, brings back seven hearts and an empty list, and a new secret.

§ 8.5

Break it on purpose

Misspell a function’s name where it’s called. In checkGuess(), change showMessage("Too high!"); to showMesage("Too high!");, with one s missing. Save and refresh.

The page loads fine. Make a guess that’s too low: fine again. Now make one that’s too high. The heart disappears and the guess is listed, but the message doesn’t change, and the console says:

Uncaught ReferenceError: showMesage is not defined game.html:80

It’s the same kind of error as part 3’s: a name the browser has never heard of. A function’s name works just like a variable’s, and it has to match exactly.

The interesting part is when it appeared. The browser doesn’t check every name before it starts; it only discovers the broken one when it reaches that line, and that line only runs when a guess is too high. Every line before it in checkGuess() ran normally, which is why the heart and the list updated. A mistake can sit quietly in a line that rarely runs and surprise you much later.

That’s why the Check box of every part asks you to try each path through the game, and not just the one you hope the player takes. Put the missing s back and test a high guess again.

A good editor would have caught this one for you. A code editor, unlike Notepad or TextEdit, knows the names in your file and can underline one it has never seen. If you didn’t install one in part 1, it’s a good next step after this series.

§ 8.6

Your challenge

Add a Give up button. When the player clicks it, the game ends at once and reveals the number: “You gave up. The number was 74.”

You need one new button in the HTML and one listener in the script, but think about which function already does most of the work. Ending a game is a job you’ve already named.

Write the new function first, then hand it to the button, exactly as checkGuess and newGame are handed to theirs. When you test it, try giving up in the middle of a game, then Play again, then give up straight away, before any guess.

Show a solution

Next to Play again:

game.html
<button id="newGameButton">Play again</button>
<button id="giveUpButton">Give up</button>

A tiny function that reuses endGame(), and a listener for it:

game.html
function giveUp() {
endGame("You gave up. The number was " + secret + ".");
}
document.getElementById("guessButton").addEventListener("click", checkGuess);
document.getElementById("newGameButton").addEventListener("click", newGame);
document.getElementById("giveUpButton").addEventListener("click", giveUp);

Three lines of new code, because endGame() already knew how to end a game. Play again starts a fresh one afterwards. Remove the Give up button before part 9 to match the series.

Your game is complete and tidy. In part 9 you make it look and feel finished: colours, the Enter key, the secret behind the number seven, and a file you can send to a friend.

Sources for this part

Functions

Errors

History

Series Guess the Number: Your First Program
Menu

Gears & Signals · Static site · No trackers