Write a simple Java Script Code For a game

1 answer

Sure! Here's a simple JavaScript code for a basic number guessing game. The player has to guess a random number between 1 and 100, and they will receive feedback on whether their guess is too high, too low, or correct.

You can run this code in an HTML file to see it in action. Here’s the complete code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Guessing Game</title>
</head>
<body>
    <h1>Number Guessing Game</h1>
    <p>Guess a number between 1 and 100:</p>
    <input type="number" id="guessInput" />
    <button id="guessButton">Guess</button>
    <p id="result"></p>
    <p id="attempts"></p>

    <script>
        const randomNumber = Math.floor(Math.random() * 100) + 1;
        let attempts = 0;

        document.getElementById('guessButton').addEventListener('click', () => {
            const userGuess = Number(document.getElementById('guessInput').value);
            attempts++;
            
            if (userGuess < 1 || userGuess > 100) {
                document.getElementById('result').innerText = 'Please enter a number between 1 and 100.';
            } else if (userGuess < randomNumber) {
                document.getElementById('result').innerText = 'Too low! Try again.';
            } else if (userGuess > randomNumber) {
                document.getElementById('result').innerText = 'Too high! Try again.';
            } else {
                document.getElementById('result').innerText = `Congratulations! You've guessed the number ${randomNumber} in ${attempts} attempts.`;
                // Optionally, disable the guess button after a correct guess
                document.getElementById('guessButton').disabled = true;
            }
            document.getElementById('attempts').innerText = `Attempts: ${attempts}`;
        });
    </script>
</body>
</html>

How to Run This Game:

  1. Copy the above code.
  2. Open a text editor (like Notepad, VS Code, etc.).
  3. Paste the code into a new file.
  4. Save the file with a .html extension, for example, guessing_game.html.
  5. Open the saved file in a web browser.

How to Play:

  • Enter a number between 1 and 100 in the text input.
  • Click the "Guess" button.
  • The game will tell you if your guess is too high, too low, or correct.
  • The game keeps track of your attempts and shows the total number of attempts once you guess correctly.

Feel free to modify and expand upon this basic game with features like resetting the game, adding difficulty levels, or a scoring system!