Number Learning Game

by Venkatesh Dematti

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Number Learning Game</title>
</head>
<body>
 <p id="instruction">Click the number:</p>
  <div id="buttons"></div>
  <p id="message"></p>
</body>
</html>

CSS

.button {
      display: inline-block;
      margin: 10px;
      padding: 20px;
      background-color: lightblue;
      border-radius: 8px;
      font-size: 24px;
      cursor: pointer;
    }
    .button:hover {
      background-color: deepskyblue;
    }

JavaScript

const buttonsContainer = document.getElementById('buttons');
    const instruction = document.getElementById('instruction');
    const message = document.getElementById('message');

    // Function to generate a random number
    const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

    // Function to create the game
    const createGame = () => {
      const targetNumber = getRandomNumber(1, 10); // Change range as needed
      instruction.textContent = `Click the number ${targetNumber}:`;
      message.textContent = ''; // Clear the message
      buttonsContainer.innerHTML = ''; // Clear the buttons

      const totalButtons = 5; // Number of buttons to generate
      const correctButtonIndex = getRandomNumber(0, totalButtons - 1); // Index to place the correct number

      for (let i = 0; i < totalButtons; i++) {
        const button = document.createElement('div');

        // Assign the correct number to one button
        if (i === correctButtonIndex) {
          button.textContent = targetNumber;
        } else {
          let randomNumber;
          do {
            randomNumber = getRandomNumber(1, 10);
          } while (randomNumber === targetNumber); // Ensure no duplicate of the target number
          button.textContent = randomNumber;
        }

        button.className = 'button';
        button.onclick = () => {
          if (parseInt(button.textContent) === targetNumber) {
            message.textContent = 'Correct! 🎉 Generating a new number...';
            message.style.color = 'green';
            setTimeout(createGame, 1000); // Start a new game after a short delay
          } else {
            message.textContent = 'Try again!';
            message.style.color = 'red';
          }
        };
        buttonsContainer.appendChild(button);
      }
    };

    // Initialize the game
    createGame();