Create a Simple 'Guess the Number' Game in HTML
Create a Simple 'Guess the Number' Game in HTML
To create a random game in HTML, we'll need to use JavaScript. Here's a simple game you can create:
Game Description:
The game is called 'Guess the Number'. The computer will randomly generate a number between 1 and 10, and the player will have to guess the number. If the player guesses the correct number, they win. If they guess incorrectly, the computer will tell them whether the number is too high or too low, and they can guess again. The game will continue until the player guesses the correct number.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Guess the Number</title>
</head>
<body>
<h1>Guess the Number</h1>
<p>Guess a number between 1 and 10:</p>
<input type='text' id='guess'>
<button onclick='checkGuess()'>Guess</button>
<p id='result'></p>
<script src='script.js'></script>
</body>
</html>
JavaScript Code:
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guessCount = 0;
let guessLimit = 3;
function checkGuess() {
let guess = document.getElementById('guess').value;
let result = document.getElementById('result');
if (guess == randomNumber) {
result.innerHTML = 'Congratulations! You guessed the number in ' + guessCount + ' guesses.';
} else {
if (guessCount < guessLimit) {
if (guess < randomNumber) {
result.innerHTML = 'Too low. Guess again.';
} else {
result.innerHTML = 'Too high. Guess again.';
}
guessCount++;
} else {
result.innerHTML = 'Sorry, you have reached the maximum number of guesses. The number was ' + randomNumber;
}
}
}
How to play:
- Open the HTML file in your web browser.
- Enter a number between 1 and 10 in the input field.
- Click the 'Guess' button.
- The computer will tell you if your guess is too high or too low.
- Guess again until you guess the correct number.
Have fun playing 'Guess the Number'!
原文地址: https://www.cveoy.top/t/topic/lmsi 著作权归作者所有。请勿转载和采集!