Simple HTML Guessing Game: Learn to Code a Fun Web Game
Simple HTML Guessing Game: Learn to Code a Fun Web Game
This is a simple 'Guess the Number' game that you can try out. It's perfect for beginners wanting to learn basic HTML, CSS, and JavaScript.
The Code
<!DOCTYPE html>
<html>
<head>
<title>Guess the Number Game</title>
</head>
<body>
<h1>Guess the Number Game</h1>
<p>Guess a number between 1 and 10:</p>
<input type='number' id='guess'>
<button onclick='checkGuess()'>Check Guess</button>
<p id='result'></p>
<script>
var answer = Math.floor(Math.random() * 10) + 1;
var attempts = 3;
function checkGuess() {
var guess = document.getElementById('guess').value;
if (guess == answer) {
document.getElementById('result').innerHTML = 'Correct! You win!';
} else {
attempts--;
if (attempts == 0) {
document.getElementById('result').innerHTML = 'Sorry, you lose. The answer was ' + answer + '.';
document.getElementById('guess').disabled = true;
} else {
document.getElementById('result').innerHTML = 'Incorrect. You have ' + attempts + ' attempts left.';
}
}
}
</script>
</body>
</html>
How to Play
- Copy and paste the code into a text editor.
- Save the file as an HTML file (e.g., game.html).
- Open the file in your web browser.
- Guess a number between 1 and 10 and click 'Check Guess'.
- You have 3 attempts to guess correctly.
Explanation
- HTML: Defines the structure of the game. This includes elements like the title, input field, button, and result display.
- CSS: Can be used to style the game's appearance, but it's not included in this example. You can add your own CSS to make the game more visually appealing.
- JavaScript: Handles the game logic. It generates a random number, checks the user's guess, and updates the result display based on the outcome.
Learn More
This simple 'Guess the Number' game is a great starting point for learning web development. You can build upon this by adding features like:
- More levels: Increase the number range or add more complex rules.
- Visual feedback: Use CSS to create animations or visual cues when the user guesses correctly or incorrectly.
- Sound effects: Add sounds to enhance the gameplay experience.
Have fun exploring the world of HTML, CSS, and JavaScript!
原文地址: https://www.cveoy.top/t/topic/lmcz 著作权归作者所有。请勿转载和采集!