Guess The Number Using Random In Js

Posted on February 6, 2025 by Vishesh Namdev
Python C C++ Javascript Java
Array in JS

Guess the Number in JS
Let’s build a cool "Guess the Number" game using pure JavaScript. We'll first create a console-based version, then upgrade it to a web-based version with an interactive UI.

Skills You’ll Learn:

  • Random number generation
  • User input handling
  • Conditional statements
  • DOM manipulation
  • Step 1: Build a Console-Based Game

    Before we will learn about the web version, let’s warm up with a simple console-based "Guess the Number" game. Open your browser's developer console (F12 > Console) and try it out!

      function guessTheNumber() {
        const randomNumber = Math.floor(Math.random() * 100) + 1;
        let guess = null;
        let attempts = 0;
    
        while (guess !== randomNumber) {
            guess = parseInt(prompt("Guess a number between 1 and 100:"));
    
            if (isNaN(guess) || guess < 1 || guess > 100) {
                alert("Please enter a valid number between 1 and 100!");
                continue;
            }
    
            attempts++;
    
            if (guess < randomNumber) {
                alert("Too low! Try again.");
            } else if (guess > randomNumber) {
                alert("Too high! Try again.");
            } else {
                alert(`You got it! The number was ${randomNumber}. Attempts: ${attempts}`);
                break;
            }
        }
    }
    
    // Start the game
    guessTheNumber();

    How It Works:

  • The script generates a random number between 1 and 100.
  • The user guesses until they find the correct number.
  • It provides hints like "Too high" or "Too low".
  • When guessed correctly, it displays the number of attempts.
  • Step 2: Build a Web-Based Guess the Number Game

    Now, let’s move from boring alerts to an interactive web version using HTML, CSS, and JavaScript.

    Create three files:

    (i.) `index.html` - The Game Structure

            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Guess the Number - The Royal Coding</title>
                <link rel="stylesheet" href="style.css">
            </head>
            <body>
                <div class="container">
                    <h1>The Royal Coding </h1>
                    <p class="subtitle">Guess a number between 1 and 100</p>
                    <input type="number" id="guessInput" placeholder="Enter your guess">
                    <button onclick="checkGuess()">Submit Guess</button>
                    <p id="message"></p>
                    <button id="playAgain" onclick="resetGame()">Play Again</button>
                </div>
                <script src="script.js"></script>
            </body>
            </html>

    (ii.) `style.css` - The Game's Styling

            body {
                font-family: Arial, sans-serif;
                background-color: #333;
                color: white;
                text-align: center;
                margin: 0;
                padding: 0;
            }
    
            .container {
                background: #ffa500;
                padding: 20px;
                border-radius: 10px;
                box-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
                width: 50%;
                margin: 50px auto;
            }
    
            h1 {
                color: black;
            }
    
            .subtitle {
                color: black;
                font-size: 1.2em;
                margin-bottom: 15px;
            }
    
            input {
                padding: 10px;
                font-size: 1.2em;
                width: 80%;
                border: 2px solid black;
                border-radius: 5px;
                text-align: center;
            }
    
            button {
                background-color: black;
                color: white;
                border: none;
                padding: 10px 20px;
                margin: 10px;
                font-size: 1.2em;
                cursor: pointer;
                border-radius: 5px;
            }
    
            button:hover {
                background-color: grey;
            }
    
            #message {
                font-size: 1.2em;
                font-weight: bold;
            }
    
            #playAgain {
                display: none;
                background-color: white;
                color: black;
                font-weight: bold;
            }

    (iii.) `script.js` - The Game Logic

            let randomNumber = Math.floor(Math.random() * 100) + 1;
            let attempts = 0;
    
            function checkGuess() {
                let guessInput = document.getElementById("guessInput");
                let message = document.getElementById("message");
                let playAgainBtn = document.getElementById("playAgain");
    
                let guess = parseInt(guessInput.value);
    
                if (isNaN(guess) || guess < 1 || guess > 100) {
                    message.textContent = "Please enter a valid number between 1 and 100!";
                    message.style.color = "black";
                    return;
                }
    
                attempts++;
    
                if (guess < randomNumber) {
                    message.textContent = " Too low! Try again.";
                    message.style.color = "black";
                } else if (guess > randomNumber) {
                    message.textContent = "Too high! Try again.";
                    message.style.color = "black";
                } else {
                    message.textContent = `Correct! You guessed it in ${attempts} attempts.`;
                    message.style.color = "white";
                    document.querySelector("button").disabled = true;
                    playAgainBtn.style.display = "inline-block";
                }
    
                guessInput.value = "";
            }
    
            function resetGame() {
                randomNumber = Math.floor(Math.random() * 100) + 1;
                attempts = 0;
                document.getElementById("message").textContent = "";
                document.getElementById("guessInput").value = "";
                document.querySelector("button").disabled = false;
                document.getElementById("playAgain").style.display = "none";
            }
    Congratulations! Your Game is Ready!

    Open index.html in your browser and start playing!

  • What We Learned?
  • Random Number Generation: Math.floor(Math.random() * 100) + 1
  • User Input Handling: document.getElementById("guessInput").value
  • DOM Manipulation: Updating message & enabling "Play Again"
  • 📢Important Note📢