HTML Guessing Game: How to Code a Simple Number Game
<!DOCTYPE html>
<html>
<head>
<title>Guess the Number Game</title>
</head>
<body>
<h1>Guess the Number Game</h1>
<script>
<p>//generate a random number between 1 and 10
var number = Math.floor(Math.random() * 10) + 1;</p>
<p>//counter of the number of guesses
var counter = 0;</p>
<p>//ask the user to guess the number
var guess = prompt('Guess a number between 1 and 10');</p>
<p>//while loop to check if the guess is correct
while (parseInt(guess) !== number) {</p>
<p>//if the guess is not correct, add 1 to the counter
counter +=1;</p>
<p>//if the guess is higher than the number
if (parseInt(guess) > number) {</p>
<p>//tell the user it's too high
alert('Your guess is too high! Try again');</p>
<p>//if the guess is lower than the number
} else {</p>
<p>//tell the user it's too low
alert('Your guess is too low! Try again');</p>
<p>}</p>
<p>//ask the user for another guess
guess = prompt('Guess a number between 1 and 10');</p>
<p>}</p>
<p>//if the guess is correct
alert('You guessed the number in ' + counter + ' tries');</p>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmca 著作权归作者所有。请勿转载和采集!