Skip to main content Jump to list of all articles

Easy JavaScript Guessing Game – Part 1

The JavaScript guessing game tutorial is a simple beginners project. It features modern JavaScript syntax and runs without a Framework. In this part, we will build the basic functionality and in further parts, we will customise it further. If you want to how this guessing game advances check out part 2.

Screenshot

Background

When I was learning web dev in the 2000’s JavaScript usage was dwindling.  jQuery was huge so I chose to use that instead of learning JavaScript. Often people chose to switch JavaScript off in the browser.  As a result, websites needed to be functional without JavaScript.

Since the creation of Node, JavaScript has had a revival and the latest updates make it cool again.  I chose to learn a little bit more this year and thought I would create some beginners tutorials.

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

All versions are available in a single zip file. The latest version has been updated on the 2nd November 2021.

Also available on GitHub

The Concept

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

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 and eventually 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 as Session storage data temporary remains 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 value is compared to the generated number
    1. If the value is correct
    2. Display you won message and refresh the page
    3. else see if you need to guess higher or lower
    4. Display message
    5. Add to session
  5. Display guesses
  6. Repeat
Guessing Game
Functions and Event Handlers

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);
		userGuess.value = "";
	}
});

We have assigned the variable userGuess to the value of the input. This 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);
    //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];
    if (sessionStorage.getItem(store) !== null) {
        let data = sessionStorage.getItem(store);
        return JSON.parse(data);
    } else {
        return null;
    }
}

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];
    data.push(saveData);
    // If the session return nothing
    if (session === null) {
        //create for the first time
        sessionStorage.setItem(store, JSON.stringify(data.flat()));
    } else { //grab data and merge
        session.push(data);
        sessionStorage.setItem(store, JSON.stringify(session.flat()));
    }
}

Once the submit button is clicked. The user guess is passed through the checkGuess function to compare both guesses for a match. It will set a message on the message element.

Add the guess to the session and display the guesses in tags.

/**
 * Checks the user submitted number against the generated one
 *
 * @param {array}
 * 
 */
let checkGuess = guess => {
    // Get user generated number
    let generatedNumber = getSession(['computer-guess', null]),
        message = document.getElementById('message');

    if (parseInt(guess[1]) === generatedNumber[0]) {
        message.innerText = "Jackpot, you won";
        setTimeout(() => {
            sessionStorage.clear();
            location.reload();
        }, 5000);
    } else {
        if (parseInt(guess[1]) > generatedNumber[0]) {
            message.innerText = "You need to go lower";
        } else {
            message.innerText = "You need to go higher";
        }
        addToSession(guess);
    }
    displayGuesses();
}

Finally the displayGuesses displays the guesses that you have made.

/**
 * Displays the amount of user guesses
 */
let displayGuesses = () => {
    let userGuess = getSession(['user-guess', null]);

    if (userGuess !== null) {
        let guess = userGuess;
        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. In the meantime please feel free to request other tutorials. Check out part 2 for new features that make our guessing game a little harder.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.