In: Computer Science
(HTML) Write a script that plays a “guess the number” game as follows: Your program chooses the number to be guessed by selecting a random integer in the range 1 to 1000. The script displays the prompt Guess a number between 1 and 1000 next to a text field. The player types a first guess into the text field and clicks a button to submit the guess to the script. If the player's guess is incorrect, your program should display either Too high, try again or Too low, try again to help the player “zero in” on the correct answer and should clear the text field so the user can enter the next guess. When the user enters the correct answer, display Congratulations! You guessed the number! and clear the text field so the user can play again.
HTML & JS CODE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Number Guessing Game</title>
<style>
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>Guess The Number</h1>
<p>We have selected a random number between 1 - 1000.
See if you can guess it.</p>
<div class="form">
<label for="guessField">Enter a guess: </label>
<input type = "number" id = "guessField" class = "guessField" min="1" max="1000">
<input type = "submit" value = "Submit guess"
class = "guessSubmit" id = "submitguess">
</div>
<script type = "text/javascript">
// random value generated
var y = Math.floor(Math.random() * 10 + 1);
// counting the number of guesses
// made for correct Guess
var guess = 1;
document.getElementById("submitguess").onclick = function(){
// number guessed by user
var x = document.getElementById("guessField").value;
if(x == y)
{
alert("Congratulations! You guessed the number! "
+ guess + " GUESS ");
}
else if(x > y) /* if guessed number is greater
than actual number*/
{
guess++;
alert("Too high, try again");
}
else
{
guess++;
alert("Too low, try again");
}
document.getElementById("guessField").value='';
}
</script>
</body>
</html>