Your game works. Now it should look as if it means it. How a page looks is the job of a third language, . HTML says what’s on the page, JavaScript says what it does, and CSS says how it looks: colours, sizes, spacing, alignment.
CSS goes in a <style> element inside the head, and it’s written as rules. Each rule names which elements it’s for, then lists changes in curly brackets:
The part before the curly brackets, the selector, can pick elements in three ways, and your game uses all three:
bodypicks every element of that kind, here the one body.#messagepicks one element by its id. The#means id..winpicks every element that carries a called win. The dot means class. A class is a label, like an id, except that many elements can share it, and your script can add or remove it.
That last one is how the game will colour the result. When the player wins, the script gives the message the class win, and the rule .win { color: green; } turns it green. A loss gets the class lose, and turns it red. The words still say what happened, so the game makes sense to someone who can’t tell red from green; the colour only adds to it.
rem is a unit of size: 1.4rem is 1.4 times the page’s normal text size. Colours can be written by name, such as green or firebrick, or as a code like #f6f4ee, a warm off-white. Note that CSS spells it color, the American way.
Step 1. Add a style element to the head, under the title:
<title>Guess the Number</title><style> body { font-family: sans-serif; text-align: center; padding: 2rem; background: #f6f4ee; color: #222; } input, button { font-size: 1.2rem; padding: 0.4rem 0.8rem; } #message { font-size: 1.4rem; min-height: 2em; } .win { color: green; } .lose { color: firebrick; }</style>Step 2. Give endGame() a second parameter, the class for the message, and tell each ending which one to use. The winning message now counts the tries:
function endGame(text, className) { showMessage(text); document.getElementById("message").className = className; document.getElementById("guessButton").disabled = true;}if (guess === secret) { endGame("Correct! You found it in " + attempts + " tries.", "win");} else if (attempts === MAX_ATTEMPTS) { endGame("Out of lives! The number was " + secret + ".", "lose");A function can have as many parameters as it needs, separated by commas, and the values in a call fill them in order. className is the element’s list of classes, so setting it to “win” gives the message that class.
Step 3. In newGame(), take the class away again, so a new game starts uncoloured:
guesses = []; document.getElementById("guessButton").disabled = false; document.getElementById("message").className = ""; showMessage("Make your first guess!");Step 4. At the very end of checkGuess(), clear the box and put the cursor back in it, ready for the next guess:
showMessage("Too low!"); } input.value = ""; input.focus();}Step 5. Let the Enter key guess too. Pressing a key is an event, called keydown, and the listener gets a note about which key it was:
document.getElementById("guessButton").addEventListener("click", checkGuess);document.getElementById("newGameButton").addEventListener("click", newGame);document.getElementById("guessInput").addEventListener("keydown", function (event) { if (event.key === "Enter") { checkGuess(); }});The parameter event holds that note, and event.key is the name of the key: “Enter”, “a”, “7” and so on. Only Enter calls checkGuess().
Step 6. Save, refresh, and play a game. Win it. Then type another number into the box and press Enter. The game carries on as if nothing had ended: a heart vanishes, the guess is listed, and the green “Correct!” turns into “Too high!” or “Too low!”.
The button is disabled, but the keyboard was never told. Enter calls checkGuess() directly, without going through the button. The fix is to disable the box too when the game ends, and enable it again for a new one:
function endGame(text, className) { showMessage(text); document.getElementById("message").className = className; document.getElementById("guessButton").disabled = true; document.getElementById("guessInput").disabled = true;} document.getElementById("guessButton").disabled = false; document.getElementById("guessInput").disabled = false; document.getElementById("message").className = "";The second pair of lines goes in newGame(), next to the line that enables the button. Finding a hole like this, by trying something no one planned, is a big part of real programming.
The finished file:
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>Guess the Number</title> <style> body { font-family: sans-serif; text-align: center; padding: 2rem; background: #f6f4ee; color: #222; } input, button { font-size: 1.2rem; padding: 0.4rem 0.8rem; } #message { font-size: 1.4rem; min-height: 2em; } .win { color: green; } .lose { color: firebrick; } </style></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; document.getElementById("guessInput").disabled = false; document.getElementById("message").className = ""; 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, className) { showMessage(text); document.getElementById("message").className = className; document.getElementById("guessButton").disabled = true; document.getElementById("guessInput").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! You found it in " + attempts + " tries.", "win"); } else if (attempts === MAX_ATTEMPTS) { endGame("Out of lives! The number was " + secret + ".", "lose"); } else if (guess > secret) { showMessage("Too high!"); } else { showMessage("Too low!"); }
input.value = ""; input.focus(); }
document.getElementById("guessButton").addEventListener("click", checkGuess); document.getElementById("newGameButton").addEventListener("click", newGame); document.getElementById("guessInput").addEventListener("keydown", function (event) { if (event.key === "Enter") { checkGuess(); } });
newGame(); </script></body></html>Save, refresh, and play with the keyboard only: type, Enter, type, Enter. You shouldn’t need the mouse at all until you want to play again.
The finished game
The preview runs the finished file. Play with the Enter key. Win a game and try pressing Enter again; then lose one and see the colour change.
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.
The preview draws the game in this site's colours, so it matches your light or dark setting; your own file uses the warm off-white from its style rules.
Then test everything once more, the way you did after the reorganisation in part 8: a win, a loss, a nonsense guess, Play again in the middle of a game. Adding style and keys shouldn’t change how the game judges guesses, and checking that it didn’t is part of finishing.
The page is centred, in a sans-serif font, on a warm off-white background. Enter makes a guess, and after each guess the box is empty with the cursor in it. A win shows Correct! You found it in, followed by the number of tries, in green; a loss shows Out of lives! in red. After either, the box and the Guess button are disabled until you press Play again.
One last mistake to make on purpose, because CSS fails differently. Change .win { color: green; } to .win { colour: green; }, the British way, and win a game. The message stays dark, and the console is empty. When CSS meets a setting it doesn’t know, it quietly skips it. JavaScript complains loudly; CSS just doesn’t do it. If a style has no effect, check the spelling first. Then put color back.
Why seven lives? Because seven is exactly enough for a player who knows the trick.
The trick is to always guess the middle of what’s left. Start with 50. If that’s too high, the secret is somewhere from 1 to 49, so guess the middle of that, 25. Each answer throws away at least half of the numbers still possible:
100 → 50 → 25 → 12 → 6 → 3 → 1
After six wrong guesses, at most one number can be left, and the seventh guess must be it. With six lives, an unlucky player could be left with two possibilities and one guess. Computer scientists call this strategy binary search, and the US National Institute of Standards and Technology defines it as searching “by repeatedly dividing the search interval in half”. It’s how a program finds a word in a sorted list of a million in about twenty steps.
The halving strategy
Hide a number, then press Guess the middle and watch the range shrink. Try 100, one of the numbers that needs all seven.
A number is hidden. Press Guess the middle.
Each guess is the middle of the numbers still possible, rounded down. No number from 1 to 100 ever needs more than seven.
Try the hard number, 100, and count: 50, 75, 88, 94, 97, 99, 100. Seven guesses, the last one landing on the only number left. Most numbers take fewer.
So the game is fair, but only just. A player who guesses at random will often run out of lives; a player who halves never will.
Your game is one file. Everything is in it: the page, the style and the program. There’s nothing to install, no server and no account. That makes it easy to share.
Send game.html the way you’d send any file: attach it to an email or a message, or copy it onto a USB stick. Your friend saves it, double-clicks it, and the game opens in their browser, just as yours does, even without an internet connection. If a mail service won’t send it, put it in a zip file or a shared folder first. Tell your friend about the seven lives, but not about the halving trick: let them discover it.
Nothing about it depends on your computer. Any up-to-date browser on Windows, a Mac or Linux opens it the same way, because they all follow the same web standards. Your friend can’t break their computer with it either, for the same reason you couldn’t break yours: it runs inside a browser tab.
They can also open it in a text editor and read every line you wrote. Code you share is code other people can learn from, the same way you’ve been learning from examples in this series.
That isn’t flattery. You wrote a program that takes input, makes decisions, picks random numbers, repeats work, remembers a list, is organised into functions and answers the keyboard. Those are the ideas inside every program, in every language. Here is where each one lives in your game:
- The page: elements, the page’s furniture (part 1).
- The Guess button: an that starts your code (part 2).
- The secret: a holding a random number (parts 3 and 6).
- The number box: input that arrives as text and becomes a number (part 4).
- The message: a and if, else if, else (part 5).
- The hearts: a that adds one per life (part 7).
- The list: an that grows with every guess (part 7).
- Play again: a you can call from anywhere (part 8).
- The look and the Enter key: and a keydown event (part 9).
You also learned the habits that matter more than any single idea: change one thing at a time, save and refresh, read the error message, and test every path, not just the one you hope for.
You’ve finished the series, and the game is yours. Change it, break it, add to it: every idea you’d like to add can be built from the pieces you now have.
This is the first series in the Programming section, and more are planned. They will appear on the Programming page. Until then, the other sections of the site tell the stories behind the machine you’ve been programming: how computers came to be, in Technology; the science of electricity and light, in Science; and how switches and chips actually work, in Electronics.
Three bigger tasks, if you want to keep going. Each uses only what you know, plus one or two new pieces explained in its solution.
1. Choose the difficulty. Add a menu with three ranges: 1 to 10, 1 to 100 and 1 to 1000. Changing it starts a new game in that range. You’ll need a <select> element, a drop-down list, and the change event it sends when the choice changes.
Show a solution
Give the invitation an id, and add the menu under it. <label> names the menu for anyone using a screen reader:
<p id="intro">I'm thinking of a number between 1 and 100.</p>
<label for="difficulty">Numbers up to</label><select id="difficulty"> <option value="10">10</option> <option value="100" selected>100</option> <option value="1000">1000</option></select>Add let maxNumber; under let guesses;. Then, in newGame(), read the menu and use the range everywhere it’s needed:
function newGame() { maxNumber = Number(document.getElementById("difficulty").value); secret = Math.floor(Math.random() * maxNumber) + 1; document.getElementById("intro").textContent = "I'm thinking of a number between 1 and " + maxNumber + "."; document.getElementById("guessInput").max = maxNumber;In checkGuess(), the guard checks guess > maxNumber and says "Please type a number from 1 to " + maxNumber + ".". Finally, start a new game whenever the menu changes:
document.getElementById("difficulty").addEventListener("change", newGame);The range now lives in one box, maxNumber, instead of five places. With numbers up to 1000, seven lives make a real challenge: halving needs ten guesses.
2. Remember the best score. After a win, keep the lowest number of tries in the browser, so it’s still there tomorrow, and show “Best: 4 tries” under the list. Browsers keep small notes like this in localStorage. But a browser may refuse, for example for files opened from your own computer or when the person has blocked storage, and then it reports an error. Your game must keep working anyway.
Show a solution
Add <p id="best"></p> under the history paragraph, and these two functions:
function showBest() { try { const best = Number(localStorage.getItem("best")); if (best > 0) { document.getElementById("best").textContent = "Best: " + best + " tries"; } } catch (error) { // This browser won't store anything for this page. The game still works. }}
function saveBest() { try { const best = Number(localStorage.getItem("best")); if (best === 0 || attempts < best) { localStorage.setItem("best", attempts); } } catch (error) { // No storage, so no best score. Nothing else changes. } showBest();}Call showBest(); at the end of newGame(), and saveBest(); on the line after the winning endGame(). try runs the code in its curly brackets; if anything in it causes an error, the browser jumps to catch instead of stopping the whole script. The lines starting with // are : notes for people, which the browser ignores. localStorage.getItem gives back nothing at all before the first win, and Number() turns that into 0, which is why best === 0 means “no best score yet”.
3. Hot or cold. Add a hint to every wrong guess: within 5 of the secret is “You’re hot!”, within 15 is “You’re warm.”, and anything further is “You’re cold.”.
Show a solution
A function that gives back the hint for a guess:
function hint(guess) { const distance = Math.abs(guess - secret); if (distance <= 5) { return " You're hot!"; } else if (distance <= 15) { return " You're warm."; } else { return " You're cold."; }}And glue it onto the two hints in checkGuess():
} else if (guess > secret) { showMessage("Too high!" + hint(guess));} else { showMessage("Too low!" + hint(guess));}Math.abs gives the distance without a minus sign, so 30 from 37 and 44 from 37 are both 7. This time return doesn’t just stop the function: it sends a value back out, like the machine in part 8 that gives back a number.
You started with an empty text file and finished with a game. Whatever you build next, start the same way: one small step, save, refresh.
Sources for this part
CSS
- CSS: Cascading Style Sheets, MDN Web Docs. Checked 16 October 2026.
<style>: The Style Information element, MDN Web Docs. Checked 16 October 2026.- class, MDN Web Docs. Checked 16 October 2026.
<length>, MDN Web Docs. Checked 16 October 2026.<named-color>, MDN Web Docs. Checked 16 October 2026.- Use of color, Understanding WCAG 2.2, W3C Web Accessibility Initiative. Checked 16 October 2026.
- Cascading Style Sheets, level 1, W3C Recommendation, 17 December 1996. Checked 16 October 2026.
The finishing touches
- Element: className property, MDN Web Docs. Checked 16 October 2026.
- Element: keydown event, MDN Web Docs. Checked 16 October 2026.
- KeyboardEvent: key property, MDN Web Docs. Checked 16 October 2026.
- HTMLElement: focus() method, MDN Web Docs. Checked 16 October 2026.
- HTMLInputElement: disabled property, MDN Web Docs. Checked 16 October 2026.
Halving
- binary search, Dictionary of Algorithms and Data Structures, NIST. Checked 16 October 2026.
Extra challenges
<select>: The HTML Select element, MDN Web Docs. Checked 16 October 2026.<label>: The Label element, MDN Web Docs. Checked 16 October 2026.- HTMLElement: change event, MDN Web Docs. Checked 16 October 2026.
- Window: localStorage property, MDN Web Docs. Checked 16 October 2026.
- try…catch, MDN Web Docs. Checked 16 October 2026.
- Lexical grammar: comments, MDN Web Docs. Checked 16 October 2026.
- Math.abs(), MDN Web Docs. Checked 16 October 2026.
- return, MDN Web Docs. Checked 16 October 2026.