Web Development

Easy JavaScript Guessing Game – Part 2

The JavaScript guessing game tutorial is a simple beginners project. It features modern JavaScript syntax and runs without a Framework. We have already built a foundation for our game in Part 1. In this part, we make it a little bit harder to guess the number.

Prerequisites

A modern browser and a text editor.  I recommend VS Code. Some knowledge of HTML and JavaScript would be beneficial but not required.  For the sake of this guessing game tutorial, I am using a pre-compiled version of the Bulma Framework.

Download

The latest JavaScript Guessing Game update has been released on 2nd November 2021.

Also available on GitHub

The Concept

To build a JavaScript guessing game that generates a random number for the computer. Your job is to guess what that number is within 5 guesses.

If you are incorrect it will tell you if you need to go higher or lower. If you are correct it will confirm that you have won the jackpot. It will display how many guesses you had and refresh the page.

To start off I had a rough plan of what I was going to use. I decided to use session storage to record the random number and user guesses. Session storage data will remain temporary until exiting the browser.
Here is our rough pseudocode:

  1. Page loads and generates a random number
  2. Number added to sessionStorage
  3. User inputs number value and presses submit
  4. The number is added to the session
  5. The value is compared to the generated number
    1. If the value is correct
      1. Display you won message and refresh the page
    2. else check how if you have had 5 guesses
      1. Display you lose message and refresh the page
    3. else guess higher or lower
      1. Display message
  6. Display all the guesses
  7. Repeat

Let’s Get Coding

HTML Source

It’s a very simple HTML page with an input field, button and a few placeholder divs.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>JavaScript Guessing Game</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
    <script src="js/guessing-game.js" defer></script>
  </head>
  <body>
    <section class="hero is-success is-bold is-fullheight">
      <div class="hero-body">
        <div class="container">
          <h2 class="title" id="message">Pick a number</h2>
          <form class="form" id="guess-container">
            <div class="field has-addons">
              <div class="control is-expanded">
                <input class="input is-large" 
                       type="number" 
                       min="1" 
                       max="100" 
                       id="guess" 
                       placeholder="Number">
              </div>
              <div class="control">
                <button id="btn" class="is-large button is-link">Submit</button>
              </div>
            </div>
          </form>
          <div class="tags" id="tags">Your guesses will display here</div>
        </div>
      </div>
    </section>
  </body>
</html>

Guessing Game Code

First, we will need to grab the user input by attaching an event listener to the submit button.

/*
 *  Adds event listener to the submit button
 */document.getElementById("btn").addEventListener("click", (e) => {
 e.preventDefault();

 let userGuess = document.getElementById("guess"),
  usrArr = [];

 if (userGuess.value === "") {
  alert("Please enter a number");
 } else {
  usrArr = ["user-guess", userGuess.value];
  checkGuess(usrArr);
  displayGuesses();
  userGuess.value = "";
 }
});

We have assigned the variable, userGuess to the value of the input. If the guess is not empty the value gets stored in an array and passed to the checkGuess function.
The computer guess needs to be set when the browser first loads. It is also required to stay the same if the page is refreshed.

/**
 * Executes on browser load. Saves computer guess to browser session if not set.
 */window.onload = () => {
    let genGuess = randomNumber(1, 100),
        arr = ["computer-guess", genGuess],
        //Check to see if a session has been set
        session = getSession(arr);
    displayGuesses();
    //If it hasn't generate a random number and store it
    if (session === null) {
        addToSession(arr);
    }
};

The randomNumber function.

let randomNumber = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min);
}

Now we need to handle the session storage. Notes to remember: Session Storage can only accept strings!  We will use the JSON.stringify() method to convert the object to a string.

We will also use JSON.parse() to convert it back when we grab the data. The getSession grabs all the information and is the most used function throughout.

/**
 * Get data out of session storage
 *
 * @param {array}
 *
 * @return {object || null}
 */let getSession = (item) => {
    let store = item[0],
        data =
            sessionStorage.getItem(store) !== null
                ? JSON.parse(sessionStorage.getItem(store))
                : null;
    return data;
};

To add to the session and merge any existing data.

/**
 * Stores data in sessionStorage. Merges data if already exists
 *
 * @param {array}
 */let addToSession = (item) => {
    //Check if a session is set
    let session = getSession(item),
        data = [],
        store = item[0],
        saveData = item[1],
        sessionData = [];
    data.push(saveData);
    // If the session return nothing
    if (session === null) {
        //create for the first time
        sessionData = data;
    } else {
        //grab data and merge
        session.push(data);
        sessionData = session;
    }
    sessionStorage.setItem(store, JSON.stringify(sessionData.flat()));
};

Once the submit button is clicked. The user guess is passed through the checkGuess function to compare both guesses for a match.  If the guesses match a message is displayed. New to v1.1 – If you don’t guess it within 5 tries a message is displayed. Failing that a message will be displayed to guess higher or lower.

/**
 * Checks the user submitted number against the generated one
 *
 * @param {array}
 *
 */let checkGuess = (guess) => {
    addToSession(guess);
    // Get user generated number
    let generatedNumber = getSession(["computer-guess", null]),
        message = document.getElementById("message"),
        total_guesses = countGuesses();
    if (parseInt(guess[1]) === generatedNumber[0]) {
        message.innerText =
            "Jackpot, you won. You guessed it within " + total_guesses + " tries";
        clearSession();
    } else if (total_guesses === 5) {
        message.innerText = "You lose, you have reached the maximum guesses.";
        clearSession();
    } else {
        higherOrLower(message, guess[1], generatedNumber[0]);
    }
};

The following 3 functions are new to Version 1.1. They are pretty self-explanatory.
higherOrLower
countGuesses
clearSession

/**
 * Checks to see if your number matches the computer one
 *
 * @param   {string}  num   user guess
 * @param   {int}  num2  computer guess
 *
 * @return  {object}     Insert message into parent container
 */let higherOrLower = (message, num, num2) => {
    if (parseInt(num) > num2) {
        message.innerText = "You need to go lower";
    } else {
        message.innerText = "You need to go higher";
    }
};
/**
 * Counts the user guesses
 *
 * @return  {int}
 */let countGuesses = () => {
    let userGuess = getSession(["user-guess", null]),
        guesses = userGuess !== null ? userGuess.length : 0;
    return guesses;
};
/**
 * Starts a new game by clearing a session and reloading the page
 *
 */let clearSession = () => {
    setTimeout(() => {
        sessionStorage.clear();
        location.reload();
    }, 10000);
};

Finally the displayGuesses displays the guesses that you have made.

/**
 * Displays the user guesses in a tag format
 *
 */let displayGuesses = () => {
    let guess = getSession(["user-guess", null]);
    if (guess !== null) {
        document.getElementById("tags").textContent = "";
        guess.forEach((item) => {
            let span = document.createElement("span"),
                text = document.createTextNode(item);
            span.classList.add("tag");
            span.appendChild(text);
            document.getElementById("tags").appendChild(span);
        });
    }
};

The JavaScript Guessing Game Demo

Choose a number between 1 and 100.

Conclusion

Like I stated this was a very simple tutorial. Please feel free to fork the code and tweak it further. I will continue to add features to it. Please feel free to request other tutorials.

Share
Published by
Tracy Ridge

Recent Posts

Hot New Web Dev – October 2024

Welcome to Hot Web Dev October 2024, featuring the latest technology and web development news.… Read More

3 weeks ago

New Svelte 5 Guessing Game 2024

In this tutorial, you’ll build a fun and interactive guessing game using Svelte 5, the… Read More

2 months ago

Hot New Web Dev – September 2024

Welcome to Hot Web Dev September 2024, featuring the latest technology and web development news.… Read More

2 months ago

New JavaScript Guessing Game 2024

The JavaScript guessing game tutorial is a simple beginner's project. It features modern JavaScript syntax… Read More

2 months ago

Hot Web Dev – 12 Useful Top Tools of 2023

If you have been following the monthly Hot Web Dev magazine you will find the… Read More

2 months ago

Hot New Web Dev – August 2024

Welcome to Hot Web Dev August 2024, featuring the latest technology and web development news.… Read More

3 months ago