Solution Files
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bonus Exercise 9 - Number Guessing Game</title>
</head>
<body>
<h1>Bonus Exercise 9: Number Guessing Game</h1>
<script src="script.js"></script>
</body>
</html>
script.js
// Generate random number between 1 and 50
const randomNumber = Math.floor(Math.random() * 50) + 1;
let attempts = 0;
const maxAttempts = 5;
let guessed = false;
document.write("<h2>Number Guessing Game</h2>");
document.write(`<p>I'm thinking of a number between 1 and 50. Try to guess it! You have ${maxAttempts} attempts.</p>`);
// Game function using recursion with timeout
function playGame() {
// Check if already guessed correctly
if (guessed) {
return;
}
// Check if max attempts reached (before getting new guess)
if (attempts >= maxAttempts) {
document.write(`<p><strong>Game Over! You've used all ${maxAttempts} attempts. The number was ${randomNumber}.</strong></p>`);
return;
}
// Get user's guess
const guessInput = prompt(`Enter your guess (1-50) - Attempt ${attempts + 1}/${maxAttempts}:`);
// Check if user canceled
if (guessInput === null) {
document.write(`<p><strong>Game cancelled. The number was ${randomNumber}.</strong></p>`);
return;
}
const guess = Number(guessInput);
// Validate input
if (isNaN(guess) || guess < 1 || guess > 50) {
document.write(`<p>Invalid input. Please enter a number between 1 and 50.</p>`);
// Continue game after timeout (invalid input doesn't count as attempt)
setTimeout(playGame, 1000);
return;
}
attempts++;
// Check the guess
if (guess === randomNumber) {
guessed = true;
document.write(`<p><strong>Congratulations! You guessed the number ${randomNumber} in ${attempts} attempts!</strong></p>`);
} else if (guess > randomNumber) {
document.write(`<p>Attempt ${attempts}: ${guess} - Too high! Try again.</p>`);
// Continue game after timeout
setTimeout(playGame, 1000);
} else {
document.write(`<p>Attempt ${attempts}: ${guess} - Too low! Try again.</p>`);
// Continue game after timeout
setTimeout(playGame, 1000);
}
}
// Start the game
playGame();