Building a Simple JavaScript Interactive Number Guessing Game: A Beginner’s Guide

Written by

in

Ever feel the thrill of a puzzle? The anticipation of a correct guess? The Number Guessing Game is a classic for a reason. It’s simple, engaging, and a fantastic way to sharpen your JavaScript skills. In this guide, we’ll walk you through building your own interactive Number Guessing Game from scratch. This project is perfect for beginners and intermediate learners, offering a hands-on experience that solidifies fundamental JavaScript concepts.

Why Build a Number Guessing Game?

Creating a Number Guessing Game isn’t just about fun; it’s about learning. It allows you to practice essential JavaScript skills, including:

  • Working with variables and data types (numbers).
  • Generating random numbers.
  • User input and output.
  • Conditional statements (if/else).
  • Looping (optional, but can enhance the game).
  • Basic DOM manipulation (updating the game interface).

By building this game, you’ll gain a solid foundation in these core concepts, making more complex projects easier to tackle in the future. Plus, you get a fun game to show off!

Setting Up Your Project

Before we dive into the code, let’s set up the basic structure of our project. You’ll need:

  • A text editor (like VS Code, Sublime Text, or Atom).
  • A web browser (Chrome, Firefox, Safari, etc.).
  • A basic understanding of HTML and CSS (optional, for styling).

Create a new folder for your project. Inside this folder, create three files:

  • index.html: This file will contain the HTML structure of your game.
  • style.css (optional): This file will contain the CSS styles for your game.
  • script.js: This file will contain the JavaScript code for your game.

Building the HTML Structure (index.html)

Open index.html and add the following HTML structure. This provides the basic layout for our game.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Guessing Game</title>
    <link rel="stylesheet" href="style.css"> <!-- Optional: Link to your CSS file -->
</head>
<body>
    <div class="container">
        <h2>Number Guessing Game</h2>
        <p>Guess a number between 1 and 100:</p>
        <input type="number" id="guessField" class="guessField">
        <button class="guessSubmit">Submit guess</button>
        <p class="guesses">Previous guesses: </p>
        <p class="lastResult"></p>
        <p class="lowOrHi"></p>
    </div>
    <script src="script.js"></script>
</body>
</html>

Let’s break down the key elements:

  • <h2>: The game’s title.
  • <p>: Instructions and feedback messages.
  • <input type="number">: The input field where the user enters their guess.
  • <button>: The button to submit the guess.
  • <script src="script.js"></script>: Links the JavaScript file to the HTML.

Styling the Game (style.css) (Optional)

While not essential, adding some CSS can significantly improve the game’s appearance. Here’s a basic example. Feel free to customize it!

.container {
    width: 400px;
    margin: 50px auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    text-align: center;
}

.guessField {
    width: 70%;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.guessSubmit {
    padding: 10px 20px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.lastResult {
    color: red;
    font-weight: bold;
}

Writing the JavaScript Logic (script.js)

This is where the magic happens! Open script.js and add the following code. We’ll explain each part step-by-step.


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

const guesses = document.querySelector('.guesses');
const lastResult = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');
const guessSubmit = document.querySelector('.guessSubmit');
const guessField = document.querySelector('.guessField');

let guessCount = 1;
let resetButton;

function checkGuess() {
  const userGuess = Number(guessField.value);
  if (guessCount === 1) {
    guesses.textContent = 'Previous guesses: ';
  }
  guesses.textContent += userGuess + ' ';

  if (userGuess === randomNumber) {
    lastResult.textContent = 'Congratulations! You got it right!';
    lastResult.style.backgroundColor = 'green';
    lowOrHi.textContent = '';
    setGameOver();
  } else if (guessCount === 10) {
    lastResult.textContent = '!!!GAME OVER!!!';
    lowOrHi.textContent = '';
    setGameOver();
  } else {
    lastResult.textContent = 'Wrong!';
    lastResult.style.backgroundColor = 'red';
    if(userGuess < randomNumber) {
      lowOrHi.textContent = 'Too low!';
    } else if(userGuess > randomNumber) {
      lowOrHi.textContent = 'Too high!';
    }
  }

  guessCount++;
  guessField.value = '';
  guessField.focus();
}

guessSubmit.addEventListener('click', checkGuess);

function setGameOver() {
  guessField.disabled = true;
  guessSubmit.disabled = true;
  resetButton = document.createElement('button');
  resetButton.textContent = 'Start new game';
  document.body.appendChild(resetButton);
  resetButton.addEventListener('click', resetGame);
}

function resetGame() {
  guessCount = 1;

  const resetParas = document.querySelectorAll('.resultParas p');
  for (let i = 0 ; i < resetParas.length ; i++) {
    resetParas[i].textContent = '';
  }

  resetButton.parentNode.removeChild(resetButton);

  guessField.disabled = false;
  guessSubmit.disabled = false;
  guessField.value = '';
  guessField.focus();

  lastResult.style.backgroundColor = 'white';

  randomNumber = Math.floor(Math.random() * 100) + 1;
}

Let’s break down the JavaScript code:

1. Setting up the Game

First, we generate a random number and store it in the randomNumber variable:

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

This line uses the Math.random() function to generate a random number between 0 (inclusive) and 1 (exclusive). We then multiply it by 100 to get a number between 0 and 99.999… The Math.floor() function rounds the number down to the nearest integer, giving us a number between 0 and 99. Finally, we add 1 to get a number between 1 and 100.

Next, we store references to the HTML elements we’ll be manipulating:


const guesses = document.querySelector('.guesses');
const lastResult = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');
const guessSubmit = document.querySelector('.guessSubmit');
const guessField = document.querySelector('.guessField');

We use document.querySelector() to select these elements based on their class names (defined in the HTML). This is an essential part of DOM manipulation.

We also initialize some variables:


let guessCount = 1;
let resetButton;
  • guessCount: Keeps track of the number of guesses the user has made.
  • resetButton: Will hold a reference to the reset button (we’ll create it later).

2. The checkGuess() Function

This function is the core of the game logic. It’s called when the user submits their guess.


function checkGuess() {
  const userGuess = Number(guessField.value);
  if (guessCount === 1) {
    guesses.textContent = 'Previous guesses: ';
  }
  guesses.textContent += userGuess + ' ';

First, it converts the user’s input (which is initially a string) to a number using Number(). It then checks if it’s the first guess and initializes the display of previous guesses. The current guess is appended to the previous guesses display.


  if (userGuess === randomNumber) {
    lastResult.textContent = 'Congratulations! You got it right!';
    lastResult.style.backgroundColor = 'green';
    lowOrHi.textContent = '';
    setGameOver();
  } else if (guessCount === 10) {
    lastResult.textContent = '!!!GAME OVER!!!';
    lowOrHi.textContent = '';
    setGameOver();
  } else {
    lastResult.textContent = 'Wrong!';
    lastResult.style.backgroundColor = 'red';
    if(userGuess < randomNumber) {
      lowOrHi.textContent = 'Too low!';
    } else if(userGuess > randomNumber) {
      lowOrHi.textContent = 'Too high!';
    }
  }

Next, it checks if the user’s guess is correct. If it is, it displays a congratulatory message, changes the background color to green, clears the “Too low/Too high” message, and calls the setGameOver() function. If the user runs out of guesses, a “Game Over” message is displayed and setGameOver() is called. If the guess is incorrect, the “Wrong!” message is displayed, the background color is set to red, and the “Too low/Too high” message is updated accordingly.


  guessCount++;
  guessField.value = '';
  guessField.focus();
}

Finally, it increments the guessCount, clears the input field, and focuses on the input field for the next guess.

3. Event Listener

This line adds an event listener to the submit button. When the button is clicked, the checkGuess() function is executed.

guessSubmit.addEventListener('click', checkGuess);

4. The setGameOver() Function

This function is called when the game is over (either the user wins or runs out of guesses). It disables the input field and the submit button, creates a new reset button, adds a click event listener to the reset button, and appends the reset button to the document body.


function setGameOver() {
  guessField.disabled = true;
  guessSubmit.disabled = true;
  resetButton = document.createElement('button');
  resetButton.textContent = 'Start new game';
  document.body.appendChild(resetButton);
  resetButton.addEventListener('click', resetGame);
}

5. The resetGame() Function

This function is called when the user clicks the reset button. It resets the game to its initial state.


function resetGame() {
  guessCount = 1;

  const resetParas = document.querySelectorAll('.resultParas p');
  for (let i = 0 ; i < resetParas.length ; i++) {
    resetParas[i].textContent = '';
  }

  resetButton.parentNode.removeChild(resetButton);

  guessField.disabled = false;
  guessSubmit.disabled = false;
  guessField.value = '';
  guessField.focus();

  lastResult.style.backgroundColor = 'white';

  randomNumber = Math.floor(Math.random() * 100) + 1;
}

It resets the guessCount, clears the previous guesses, removes the reset button, enables the input field and submit button, clears the input field, sets the background color back to white, and generates a new random number.

Common Mistakes and How to Fix Them

Here are some common mistakes beginners make and how to avoid them:

  • Forgetting to link the JavaScript file: Double-check that you’ve included the <script src="script.js"></script> tag in your HTML file, usually just before the closing </body> tag.
  • Not converting user input to a number: The input from the input field is a string. You need to convert it to a number using Number() before comparing it to the random number.
  • Incorrect use of comparison operators: Make sure you’re using the correct comparison operators (=== for strict equality, < for less than, > for greater than, etc.).
  • Incorrect DOM selection: Ensure the class names in your JavaScript match the class names in your HTML. Use the browser’s developer tools (right-click, Inspect) to verify the elements are being selected correctly.
  • Scope issues: Be mindful of variable scope (let, const). Declare variables within the correct scope to avoid unexpected behavior. For example, the `randomNumber` should be declared outside of any functions so that all functions can access it.

Key Takeaways

  • You’ve learned the fundamentals of building an interactive game with JavaScript.
  • You’ve practiced working with variables, data types, user input, conditional statements, and DOM manipulation.
  • You’ve gained experience with event listeners and functions.
  • You now have a fun, working game to demonstrate your skills!

Optional: FAQ

Here are some frequently asked questions:

  1. Can I add a limit to the number of guesses? Yes! You can add a counter variable and use an if statement to check if the counter exceeds a certain limit. If it does, end the game.
  2. Can I add hints? Yes! You can provide hints (e.g., “Too low!” or “Too high!”) based on the user’s guesses. This is already implemented in the provided code.
  3. Can I add difficulty levels? Yes! You could let the user select a range for the random number (e.g., 1-100, 1-500, etc.) or change the number of allowed guesses.
  4. How can I make the game more visually appealing? Use CSS to style the game! Experiment with different colors, fonts, and layouts. Consider adding animations or images.

This Number Guessing Game is a stepping stone. It’s a project that builds core skills and provides a foundation for more complex JavaScript applications. As you experiment with the code, add features, and customize the design, you’ll deepen your understanding of JavaScript and web development.