Guess the Number: Create a game where the user tries to guess a randomly generated number within a certain range. The game provides feedback on whether the guess is too high or too low.
Certainly! Here's a simple implementation of the "Guess the Number" game in HTML, CSS, and JavaScript:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Guess the Number</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Guess the Number</h1>
<p>Guess a number between 1 and 100:</p>
<input type="number" id="guessInput">
<button onclick="checkGuess()">Guess</button>
<p id="message"></p>
<script src="script.js"></script>
</body>
</html>
---------------------------------------------------------------------------------------------------------------
CSS (style.css):
body {
text-align: center;
font-family: Arial, sans-serif;
}
h1 {
color: navy;
}
input[type="number"] {
width: 50px;
text-align: center;
}
button {
margin-top: 10px;
}
p#message {
font-weight: bold;
}
-------------------------------------------------------------------------------------------------------
JavaScript (script.js):
// Generate a random number between 1 and 100
const targetNumber = Math.floor(Math.random() * 100) + 1;
// Function to check the user's guess
function checkGuess() {
// Get the user's guess from the input field
const guess = parseInt(document.getElementById("guessInput").value);
// Check if the guess is correct, too high, or too low
if (guess === targetNumber) {
showMessage("Congratulations! You guessed the correct number!");
} else if (guess > targetNumber) {
showMessage("Too high! Try again.");
} else {
showMessage("Too low! Try again.");
}
}
// Function to display a message
function showMessage(message) {
document.getElementById("message").textContent = message;
}
------------------------------------------------------------------------------------
Save the HTML code in a file named index.html, the CSS code in a file named style.css, and the JavaScript code in a file named script.js. Place all three files in the same directory. Open the index.html file in a web browser, and you should see the "Guess the Number" game interface.
The game generates a random number between 1 and 100. When the user enters a guess and clicks the "Guess" button, the game checks if the guess is correct, too high, or too low and displays an appropriate message.
Note: This is a basic implementation without input validation or error handling. You can enhance the game further by adding features like a limited number of guesses, tracking the number of attempts, or providing a reset option.
Comments
Post a Comment