Simple HTML Guessing Game: Guess the Number

This is a straightforward HTML game that you can play right in your web browser. It's called 'Guess the Number'.

How to Play

  1. The computer will secretly pick a random number between 1 and 100.
  2. You need to guess the number by typing it into the input field.
  3. After each guess, the computer will let you know if your guess is too high, too low, or if you got it right!
  4. You have a total of 10 guesses to crack the code.

Game Code

<!DOCTYPE html>
<html>
<head>
	<title>Guess the Number</title>
</head>
<body>
	<h1>Guess the Number</h1>
	<p>Guess a number between 1 and 100:</p>
	<input type='number' id='guess'>
	<button onclick='checkGuess()'>Submit</button>
	<p id='message'></p>
	<script>
		// Generate a random number between 1 and 100
		let randomNumber = Math.floor(Math.random() * 100) + 1;
		// Keep track of the number of guesses
		let guessCount = 0;
		// Get the input field and message element
		let guessInput = document.getElementById('guess');
		let message = document.getElementById('message');
		// Define the function to check the guess
		function checkGuess() {
			// Get the value of the input field
			let guess = guessInput.value;
			// Increment the guess count
			guessCount++;
			// Check if the guess is correct
			if (guess == randomNumber) {
				message.innerHTML = 'Congratulations! You guessed the number in ' + guessCount + ' guesses.';
			} else if (guessCount == 10) {
				message.innerHTML = 'Sorry, you ran out of guesses. The number was ' + randomNumber + '.';
			} else if (guess < randomNumber) {
				message.innerHTML = 'Too low. Guess again.';
			} else if (guess > randomNumber) {
				message.innerHTML = 'Too high. Guess again.';
			}
			// Clear the input field
			guessInput.value = '';
		}
	</script>
</body>
</html>

How to Run

  1. Create a new file called 'index.html' on your computer.
  2. Copy and paste the code above into the file.
  3. Save the file.
  4. Open the file in your web browser.

Have fun playing 'Guess the Number'!


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

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