⭐ BONUS EXERCISE

EXERCISE 9: Number Guessing Game

Assignment

Create a number guessing game that:

  1. Generates a random number between 1 and 50 using Math.floor(Math.random() * 50) + 1
  2. Allows the user a maximum of 5 attempts to guess the number
  3. Asks the user to guess the number using prompt()
  4. Provides feedback after each guess:
    • "Too high! Try again." if guess is higher than the random number
    • "Too low! Try again." if guess is lower than the random number
    • "Congratulations! You guessed it!" if correct
  5. Adds a small delay (using setTimeout()) between attempts so feedback is visible before the next prompt appears
  6. Keeps track of the number of attempts
  7. Uses a loop (or recursive function) to continue asking until the user guesses correctly or runs out of attempts
  8. Displays the number of attempts it took to guess correctly, or shows "Game Over" if all 5 attempts are used
  9. Stops the game immediately if the user clicks "Cancel" on the prompt and shows the correct number

Requirements:

  • Use Math.random() and Math.floor() for random number generation
  • Use a loop or recursive function for the game logic
  • Use Number() to convert prompt input to number
  • Use setTimeout() to add delays between attempts
  • Check if the user canceled the prompt (returns null) and handle it appropriately
  • Use if/else statements for comparison and validation
  • Use an external JavaScript file (script.js) linked to your HTML
  • Display results using document.write()

Create an index.html file and a script.js file with your solution.