Number Guessing Game using JavaScript
A Number Guessing Game is a simple game where the player tries to guess a randomly generated number within a specified range. Using JavaScript, you can create this game by generating a random number, taking user input, and providing feedback like too high or too low.
Approach
- Generate Random Number: A random number between 1 and 10 is generated using Math.random().
- User Input Handling: The user inputs a guess through the text field and submits it by clicking the button.
- Compare Guess: The user's guess is compared with the generated number to check if it's correct, higher, or lower.
- Feedback via Alerts: Appropriate feedback is given through alerts based on whether the guess is correct, too high, or too low.
- Increment Guess Counter: The number of guesses is counted and incremented after each incorrect attempt.
Example: Below is the implementation of above explained approach.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Number Guessing Game</title>
<style>
body {
font-family: sans-serif;
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 - 10. See if you can
guess it.
</p>
<div class="form">
<label for="guessField">
Enter a guess:
</label>
<input type="text"
id="guessField"
class="guessField">
<input type="submit"
value="Submit guess"
class="guessSubmit"
id="submitguess">
</div>
<script type="text/javascript">
// Generate a Random Number
let y = Math.floor(Math.random() * 10 + 1);
// Counting the number of guesses
// made for correct Guess
let guess = 1;
document.getElementById("submitguess").onclick = function () {
// Number guessed by user
let x = document.getElementById("guessField").value;
if (x == y) {
alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT IN "
+ guess + " GUESS ");
}
/* If guessed number is greater than actual number*/
else if (x > y) {
guess++;
alert("OOPS SORRY!! TRY A SMALLER NUMBER");
}
else {
guess++;
alert("OOPS SORRY!! TRY A GREATER NUMBER")
}
}
</script>
</body>
</html>
Output: