Simple Number Guessing Game in HTML: Code and Tutorial
HTML Number Guessing Game
This tutorial shows you how to build a simple number guessing game in HTML using JavaScript. The game will involve the user guessing a random number between 1 and 10.
Game Structure
We'll start by creating the basic HTML structure for the game:
<form>
<label for='guess'>Guess a number between 1 and 10:</label>
<input type='number' id='guess' name='guess' min='1' max='10'>
<button type='button' onclick='checkGuess()'>Submit</button>
</form>
This code creates a form with:
- A label to instruct the user to enter their guess.
- An input field (
type='number') that allows the user to enter a number between 1 and 10. - A submit button that calls the
checkGuess()function when clicked.
JavaScript Logic
Now, let's write the JavaScript function checkGuess() to handle the game logic:
function checkGuess() {
// Generate random number between 1 and 10
const randomNumber = Math.floor(Math.random() * 10) + 1;
// Get user's guess from input field
const userGuess = document.getElementById('guess').value;
// Compare user's guess to random number
if (userGuess == randomNumber) {
alert('You win!');
} else {
const playAgain = confirm(`You lost. The number was ${randomNumber}. Do you want to play again?`);
if (playAgain) {
location.reload();
}
}
}
Here's a breakdown of the code:
- Generate a random number:
const randomNumber = Math.floor(Math.random() * 10) + 1;generates a random number between 1 and 10. - Get user's guess:
const userGuess = document.getElementById('guess').value;retrieves the value entered by the user in the input field. - Compare guesses: The
ifstatement compares the user's guess to the random number. If they match, the user wins. Otherwise, they lose. - Play again option: If the user loses, a confirmation prompt asks if they want to play again. If they choose 'yes', the page reloads using
location.reload().
CSS Styling
Finally, we'll add some basic CSS to style the form and button:
form {
display: flex;
flex-direction: column;
align-items: center;
}
input[type='number'] {
margin-bottom: 10px;
padding: 5px;
border-radius: 5px;
border: none;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
}
This CSS styles the form to be vertically aligned and centers the elements. It also adds some basic styling to the input field and button.
Conclusion
Now you have a simple number guessing game that you can play in the browser. You can enhance it by adding more features like keeping track of the number of guesses, providing hints, or adding more difficulty levels. This tutorial provides a starting point for your game development journey using HTML, JavaScript, and CSS.
原文地址: https://www.cveoy.top/t/topic/lmr4 著作权归作者所有。请勿转载和采集!