Simple HTML Guessing Game

This tutorial guides you through creating a basic HTML guessing game using JavaScript. The user will need to guess a number from 1 to 10.

HTML

Start by creating an HTML file with a title and a simple form for the user to enter their guess.

<!DOCTYPE html>
<html>
<head>
  <title>Guessing Game</title>
</head>
<body>
  <h1>Guess a Number from 1 to 10</h1>
  <form>
    <label for='guess'>Enter Your Guess:</label>
    <input type='number' id='guess' name='guess'>
    <button type='submit'>Guess</button>
  </form>
  <script src='game.js'></script>
</body>
</html>

JavaScript

Next, create a JavaScript file called 'game.js' and link it to your HTML file. In this file, you'll generate a random number between 1 and 10 and compare it to the user's guess.

// generate random number between 1 and 10
const randomNumber = Math.floor(Math.random() * 10) + 1;

// get user's guess from form
const guessForm = document.querySelector('form');
const guessInput = document.querySelector('input');

guessForm.addEventListener('submit', (event) => {
  event.preventDefault();
  const userGuess = parseInt(guessInput.value);
  
  // compare user's guess to random number
  if (userGuess === randomNumber) {
    alert('You guessed the correct number!');
  } else {
    alert('Sorry, the correct number was ' + randomNumber + '.');
  }
});

Conclusion

That's it! You've now created a simple HTML game. When the user submits their guess, the JavaScript code will generate a random number and compare it to their guess. If they guess correctly, they'll receive an alert message. If they guess incorrectly, they'll receive an alert message with the correct answer.

Feel free to customize this game and make it your own. Good luck and have fun!

Simple HTML Guessing Game Tutorial: Learn to Code a Basic Game with JavaScript

原文地址: https://www.cveoy.top/t/topic/lmlZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录