Number Guessing Game in JavaScript

Introduction:

The number guessing game serves as an excellent and interactive coding challenge that helps developers enhance their logical reasoning and critical thinking skills. In this tutorial, we will explore the theoretical aspects of creating a number guessing game using JavaScript. This well-known game involves a player trying to guess a randomly selected number within a set range, providing a great opportunity to delve into various programming principles.

Approach:

  • Characterize Core Rules: Lay out the game's major boundaries, including number range and permitted attempts.
  • Random Number Generation: Utilize JavaScript's Math.random to produce random numbers inside the predefined range.
  • User Input Taking care of: Catch and approve user surmises through DOM connections and occasion audience members.
  • Conditional Statements: Carry out game logic utilizing if statements to consider user assumptions and direct the stream appropriately.
  • User Feedback: Use dynamic DOM manipulation to give continuous feedback on the accuracy of surmises.
  • Improvements: Consider adding difficulty levels and score tracking for a more flexible and serious gaming experience.
  • Clean Code: Focus on code clearness and construction to work with simpler investigating and future adjustments.
  • User-Driven Plan: Spotlight on making a drawing-in and charming user interface for an improved gaming experience.
  • Core Concepts:

    a. Random Number Generation:

A crucial aspect of a number guessing game involves creating a random number within a specified range. JavaScript provides developers with the Math.random method, which produces a pseudo-random decimal number ranging from 0 (inclusive) to 1 (exclusive). By incorporating this method into mathematical operations, developers can generate a random number within a desired range.

Example

// Generate a random integer within a specified range
function generateRandomNumber( min, max ) {
    return Math.floor( Math.random( ) * ( max - min + 1 )) + min;
}

b. User Input:

Capturing user input plays a crucial role in game development. In JavaScript, this task is typically achieved by interacting with the Document Object Model (DOM). Developers can employ event listeners to detect when a user submits a guess and retrieve the inputted value. Validating and processing user input is essential for ensuring the game operates smoothly and accurately.

Example

// Capture user input using event listeners
const guessInput = document.getElementById(' userGuessInput ');
const submitButton = document.getElementById(' submitButton ');

submitButton.addEventListener( ' click ', function() {
    const userGuess = parseInt(guessInput.value);
    // Validate and process user input
    // (Logic for handling user input goes here)
});

Game Logic:

a. Laying out the Game Rules:

Defining the game's rules is a fundamental step in the enhancement process. This involves establishing the possible number range, the allowed number of guesses, and any additional regulations, such as providing hints or imposing time constraints for each conjecture.

b. Conditional Statements:

The use of conditional statements is essential in implementing game logic. Developers can employ constructs such as if statements to compare the user's guess with the randomly generated number. These statements control the flow of the game, enabling the system to respond appropriately based on whether the guess is correct, too high, or too low.

Example

// Define game rules
const minNumber = 1;
const maxNumber = 100;
const maxAttempts = 10;

// Compare the user's guess with the randomly generated number
function checkGuess(userGuess, randomNumber) {
    if ( userGuess === randomNumber ) {
        // Handle correct guess
    } else if ( userGuess < randomNumber ) {
        // Handle guess too low
    } else {
        // Handle guess too high
    }
}

User Feedback:

a. Showing Messages:

Providing precise and cohesive feedback to the player enhances the overall gaming experience. Developers have the option to employ JavaScript for dynamically updating the HTML content on the webpage, informing the user about the accuracy of their guess or providing hints for the next attempt. This interactive feedback is instrumental in keeping players engaged and motivated to solve challenges.

Example

// Update HTML content to display messages
function displayMessage(message) {
    const messageElement = document.getElementById(' message ');
    messageElement.textContent = message;
}

b. DOM Manipulation:

Comprehending the manipulation of the Document Object Model (DOM) is essential for updating the user interface while a game is in progress. JavaScript provides developers the ability to interact with and modify HTML elements, enabling real-time modifications. Through adjusting the content, appearance, or visibility of elements, programmers can craft a lively and interactive user interface.

Example

// Update HTML content dynamically
function updateUI() {
    // (Logic for updating the UI goes here)
}

Improvements and Features:

a. Adding Difficulty Levels:

Engineers have the option to adjust various levels of complexity to enhance the game's flexibility. This could involve altering the range of possible numbers, adjusting the allowed number of attempts, or introducing additional challenges. This feature adds variety and caters to players with varying skill levels.

b. Executing Score Tracking:

Integrating a scoring system enhances the competitive aspect of the game. Engineers can create a leaderboard or provide users with a performance metric by monitoring the number of tries or time spent guessing the correct number. This feature motivates players to enhance their skills and compete with others.

Example

// Track user score
let attempts = 0;
let score = 0;

// Update score based on user performance
function updateScore() {
    // ( Logic for updating score goes here )
}

Implementation

The following code demonstrates the basic setup for a number-guessing game. It generates a random target number ranging from 1 to 100, allows the user to input their guess, provides feedback on whether the guess is too high, too low, or correct, and keeps count of the remaining attempts.

HTML:

Example

<!DOCTYPE html>
<html lang = " en " >
<head>
    <meta charset = " UTF-8 ">
    <meta name = " viewport " content = " width = device-width, initial-scale = 1.0">
    <link rel = " stylesheet " href = " styles.css ">
    <title> Number Guessing Game </title>
</head>
<body>
    <div class = " container ">
        <h1> Number Guessing Game </h1>
        <p id = " message "> Can you guess the number? </p>
        <input type = " number " id = " userGuessInput " placeholder = " Enter your guess ">
        <button id = " submitButton "> Submit Guess </button>
    </div>

    <script src = "https://placehold.co/300x300/3498db/ffffff?text=Sample+Image"></script>
</body>
</html>
Example

body {
    font-family: ' Arial ', sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}

.container {
    text-align: center;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba( 0, 0, 0, 0.1 );
}

button {
    background-color: #4caf50;
    color: #fff;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
    border: none;
    border-radius: 4px;
}

button:hover {
    background-color: #45a049;
}

input {
    padding: 10px;
    font-size: 16px;
}

h1 {
    color: #333;
}

JavaScript:

Example

document.addEventListener(' DOMContentLoaded ', function () {
    const guessInput = document.getElementById(' userGuessInput ');
    const submitButton = document.getElementById(' submitButton ');
    const messageElement = document.getElementById(' message ');

    const minNumber = 1;
    const maxNumber = 100;
    const maxAttempts = 10;
    let secretNumber;
    let attempts = 0;

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

    // Function to start a new game
    function newGame() {
        secretNumber = generateRandomNumber(minNumber, maxNumber);
        attempts = 0;
        messageElement.textContent = ' Can you guess the number? ';
    }

    // Function to check the user's guess
    function checkGuess() {
        const userGuess = parseInt(guessInput.value);

        if ( isNaN(userGuess) || userGuess < minNumber || userGuess > maxNumber ) {
            messageElement.textContent = ' Please enter a valid number between 1 and 100. ';
            return;
        }

        attempts++;

        if (userGuess === secretNumber) {
            messageElement.textContent = ` Congratulations! You guessed the number in ${attempts} attempts. `;
        } else if ( userGuess < secretNumber ) {
            messageElement.textContent = ' Too low. Try again! ';
        } else {
            messageElement.textContent = ' Too high. Try again! ';
        }

        if (attempts === maxAttempts) {
            messageElement.textContent = ` Sorry, you've reached the maximum number of attempts. The correct number was ${secretNumber}. `;
        }
    }

    // Event listener for the submit button
    submitButton.addEventListener(' click ', function () {
        checkGuess();
    });

    // Start a new game on page load
    newGame();
});

Output:

Conclusion:

Mastering the number prediction game in JavaScript involves a blend of fundamental programming principles, critical thinking, and a well-thought-out user interface strategy. By incorporating elements such as generating random numbers, handling user input, managing game logic, and providing feedback to the user, developers can leverage various JavaScript functionalities to create an engaging and user-friendly gaming experience.

When embarking on creating your own number guessing game, keep in mind these theoretical ideas, and soon enough, you will develop an engaging game for users to enjoy.

Input Required

This code uses input(). Please provide values below: