HTML:
<!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>
<style>
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: #333;
}
.game-container {
background: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
input[type="number"] {
padding: 10px;
margin: 10px 0;
font-size: 16px;
}
button {
padding: 10px 20px;
font-size: 16px;
color: #fff;
background-color: #007bff;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.message {
margin-top: 10px;
font-size: 18px;
color: #555;
}
</style>
</head>
<body>
<div class="game-container">
<h1>Number Guessing Game</h1>
<p>Guess the number between 1 and 100</p>
<input type="number" id="guessInput" min="1" max="100" placeholder="Enter your guess">
<button onclick="checkGuess()">Submit Guess</button>
<p class="message" id="message"></p>
</div>
<script>
// Generate a random number between 1 and 100
const randomNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
// Function to check the user's guess
function checkGuess() {
const userGuess = parseInt(document.getElementById('guessInput').value);
const message = document.getElementById('message');
attempts++;
if (!userGuess || userGuess < 1 || userGuess > 100) {
message.textContent = 'Please enter a valid number between 1 and 100.';
} else if (userGuess === randomNumber) {
message.textContent = `Congratulations! You guessed the correct number ${randomNumber} in ${attempts} attempts.`;
message.style.color = 'green';
} else if (userGuess < randomNumber) {
message.textContent = 'Too low! Try again.';
message.style.color = 'orange';
} else {
message.textContent = 'Too high! Try again.';
message.style.color = 'orange';
}
}
</script>
</body>
</html>