Skip to Content
Course content

27: Practice Exercise: Building a Number Guessing Game

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about the last time you played a game of "Higher or Lower" with a deck of cards. Someone flips a card over but keeps it hidden from you. You guess a number, and they tell you, "Higher!" or "Lower!" You keep refining your guess based on that feedback until you eventually nail it. It's a simple loop of guess $\rightarrow$ feedback $\rightarrow$ adjustment.

Building a number guessing game in JavaScript is exactly the same process, just translated into logic the browser can understand. Here is how that card game maps directly to your code:

  • The hidden card: This is a variable storing a random number generated when the game starts.
  • Your guess: This is the user input, usually captured via a prompt or an input field.
  • "Higher" or "Lower": These are your if/else statements comparing the guess to the secret number.
  • Winning the game: The specific condition where the guess equals the secret number.

Picking the Secret Number

You can't just hardcode let secret = 7; because the game would be boring after one round. I usually use Math.random() combined with Math.floor() to get a whole number. If you want a number between 1 and 100, you'll multiply the random decimal by 100 and add 1 to avoid getting a zero. It's a little quirk of how the math library works, but it's the standard way we handle ranges in JS.

const secretNumber = Math.floor(Math.random() * 100) + 1;

The Feedback Loop

The heart of this project is the comparison logic. You aren't just checking if the user is right; you're guiding them toward the answer. I like to think of this as a funnel. You start with a wide range of possibilities and use if blocks to narrow them down.

You'll need a way to keep the game running until the user wins. While a while loop is the "textbook" answer, in a real web app, you're more likely to wrap this logic in a function that gets called every time a "Submit" button is clicked. This prevents the browser from freezing while it waits for the user to think.

function checkGuess(userGuess) {
    if (userGuess === secretNumber) {
        return "You got it! You're a mind reader.";
    } else if (userGuess > secretNumber) {
        return "Too high! Try something smaller.";
    } else {
        return "Too low! Aim higher.";
    }
}

Tracking the Effort

A game isn't really a game without a score or a challenge. To make this feel professional, you should track how many attempts the user has made. I recommend declaring a let attempts = 0; variable outside your check function. Every time the function runs, you increment that counter. It gives the user a sense of achievement (or frustration) when they finally hit the number.

One thing to watch out for: users will try to break your game. They'll enter text, leave the box empty, or enter a number like 1,000,000. I've spent way too many hours of my career fixing bugs caused by "garbage" input. Always validate that the input is actually a number before you start comparing it to your secret value.




📋 Practical Task

Build the "Limited-Life Guessing Challenge"

Your task is to create a fully functional Number Guessing Game. However, to make it challenging, you must implement a "Life" system.

Requirements:

  • Generate a random number between 1 and 100.
  • Give the user exactly 10 attempts to guess the number.
  • After each guess, tell the user if they are "Too High" or "Too Low".
  • If the user guesses correctly, display a victory message and the number of attempts it took them.
  • If the user runs out of lives, reveal the secret number and tell them "Game Over".
  • Ensure the game handles non-numeric input gracefully (e.g., tell the user "Please enter a valid number") without counting it as a lost life.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.