Number Guessing Game in JavaScript & HTML

In this article I will tell you how to make Number Guessing Game using HTML, CSS and JavaScript. You can make this JavaScript Number Guessing Game even if you are a beginner.

In the world of web development, creating interactive and engaging games is a fantastic way to apply your programming skills. One popular beginner-friendly project is the Number Guessing Game in JavaScript.

Number Guessing Game in HTML, CSS, JavaScript

A Number Guessing Game in JavaScript is a simple interactive game where the user is prompted to guess a randomly generated number within a specified range. 

The game typically provides feedback to the user after each guess, indicating whether their guess was too low, too high, or correct. The user continues to make guesses until they correctly identify the target number.

See the Pen Untitled by Growthpanda (@Growthpanda) on CodePen.

This JavaScript Number Guessing Game is made in a very simple way. First I created a placeholder, a button and a display within a box. Finally I activated this project(Number Guessing Game using JavaScript) by JavaScript.

Number Guessing Game HTML Code

Let’s start by creating the basic structure of our game using HTML. Open your favorite text editor and create a new HTML file. Add the following code.

This simple HTML structure includes the game’s title, instructions, input field for the user’s guess, a button to submit the guess, and a message area to display the game’s feedback.

   <div class="container">
       <h3>I am thinking of a number between 1-100.</h3>
       <h3>Can you guess it?</h3>

       <input type="text" placeholder="Num" id="guess"><br>
       <button onclick="play()" id="my_btn">GUESS</button>

       <p id="message1">No. Of Guesses: 0</p>
       <p id="message2">Guessed Numbers are: None</p>
       <p id="message3"></p>
   </div>

CSS for Guess a Number Game

Create a new file named styles.css and add some basic styles to enhance the visual appeal of your game. Here’s a sample.

*,
*:before,
*:after{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
body{
    height: 100vh;
    background: linear-gradient(
        to right,
        #7f53ac,
        #657ced
    );
}
.container{
    position: absolute;
    width: 50%;
    min-width: 580px;
    transform: translate(-50%,-50%);
    top: 50%;
    left: 50%;
    background-color: #ffffff;
    padding: 50px 10px;
    border-radius: 5px;
    display: grid;
    justify-items: center;
    font-family: 'Poppins',sans-serif;
}
h3{
    font-size: 16px;
    font-weight: 600;
}
input[type="text"]{
    width: 90px;
    font-weight: 600;
    color: #663399;
    padding: 20px 0;
    text-align: center;
    margin-top: 30px;
    border-radius: 5px;
    border: 2px solid #202020;
    font-size: 28px;
}
button{
    width: 160px;
    padding: 15px 0;
    border-radius: 5px;
    background-color: #663399;
    color: #ffffff;
    border: none;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 30px;
    outline: none;
}
p{
    font-weight: 400;
}

Number Guessing Game JavaScript Code

Now, create a new file named script.js and implement the game’s logic using JavaScript.

This JavaScript code defines functions to generate a random number, check the user’s guess, and display messages accordingly.

// Get references to HTML elements with IDs "message1", "message2", "message3"
var msg1 = document.getElementById("message1");
var msg2 = document.getElementById("message2");
var msg3 = document.getElementById("message3");

// Generate a random number between 1 and 100
var answer = Math.floor(Math.random() * 100) + 1;

// Initialize variables to track the number of guesses and guessed numbers
var no_of_guesses = 0;
var guessed_nums = [];

// Function to play the guessing game
function play() {
    // Get the user's guess from the input element with ID "guess"
    var user_guess = document.getElementById("guess").value;

    // Check if the user's guess is outside the valid range (1 to 100)
    if (user_guess < 1 || user_guess > 100) {
        alert("Please enter a number between 1 and 100.");
    } else {
        // Add the user's guess to the array of guessed numbers
        guessed_nums.push(user_guess);
        // Increment the number of guesses
        no_of_guesses += 1;

        // Check if the user's guess is too low, too high, or correct
        if (user_guess < answer) {
            msg1.textContent = "Your guess is too low.";
            msg2.textContent = "No. of guesses: " + no_of_guesses;
            msg3.textContent = "Guessed numbers are: " + guessed_nums;
        } else if (user_guess > answer) {
            msg1.textContent = "Your guess is too high.";
            msg2.textContent = "No. of guesses: " + no_of_guesses;
            msg3.textContent = "Guessed numbers are: " + guessed_nums;
        } else if (user_guess == answer) {
            msg1.textContent = "Yippie You Win!!";
            msg2.textContent = "The number was: " + answer;
            msg3.textContent = "You guessed it in " + no_of_guesses + " guesses";
            
            // Disable the button with ID "my_btn" to prevent further guesses
            document.getElementById("my_btn").disabled = true;
        }
    }
}

Congratulations! You’ve successfully created a simple Number Guessing Game using JavaScript and HTML. This project(Create Number Guessing Game Using JavaScript) serves as an excellent starting point for honing your web development skills and exploring more advanced game development concepts.

You will get all these codes of this Number Guessing Game below. Comment how you like this simple javascript project.

Below is a simple implementation of a “Guess the Number” game in JavaScript. This game generates a random number between 1 and 100, and the player needs to guess the correct number.


<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}

input, button {
margin-top: 10px;
padding: 5px;
font-size: 16px;
}
</style>
 

<h1>Guess The Number Game</h1>
<p>Guess a number between 1 and 100:</p>

<input type=”number” id=”userGuess” min=”1″ max=”100″>
<button onclick=”checkGuess()”>Submit Guess</button>

<p id=”message”></p>

<script>
// Generate a random number between 1 and 100
const secretNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;

function checkGuess() {
// Get user’s guess from input
const userGuess = parseInt(document.getElementById(“userGuess”).value);

// Check if the guess is correct
if (!isNaN(userGuess) && userGuess >= 1 && userGuess <= 100) {
attempts++;

if (userGuess === secretNumber) {
displayMessage(`Congratulations! You guessed the number ${secretNumber} in ${attempts} attempts.`);
} else if (userGuess < secretNumber) {
displayMessage(“Too low. Try again!”);
} else {
displayMessage(“Too high. Try again!”);
}
} else {
displayMessage(“Please enter a valid number between 1 and 100.”);
}
}

function displayMessage(message) {
document.getElementById(“message”).textContent = message;
}
</script>

// Function to generate a random number between min (inclusive) and max (inclusive)
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max – min + 1)) + min;
}

// Function to play the guess the number game
function guessTheNumberGame() {
const minNumber = 1;
const maxNumber = 100;
const secretNumber = generateRandomNumber(minNumber, maxNumber);
let attempts = 0;

while (true) {
// Prompt user for input
let userGuess = prompt(`Guess a number between ${minNumber} and ${maxNumber}:`);

// Check if the user clicked cancel or entered an invalid input
if (userGuess === null || isNaN(userGuess)) {
alert(“Invalid input. Please enter a number.”);
continue;
}

// Convert user input to a number
userGuess = parseInt(userGuess);

// Check if the guess is correct
if (userGuess === secretNumber) {
attempts++;
alert(`Congratulations! You guessed the number ${secretNumber} in ${attempts} attempts.`);
break;
} else if (userGuess < secretNumber) {
attempts++;
alert(“Too low. Try again!”);
} else {
attempts++;
alert(“Too high. Try again!”);
}
}
}

// Start the game
guessTheNumberGame();

You can run this script in a browser’s developer console or integrate it into an HTML file. It uses the prompt function to get input from the user and the alert function to display messages.

 

Leave a Comment

Home
Menu
Instagram
Search