In this article, we will create a Number guessing game using JavaScript. The game is to guess a random number generated by a computer in the range 1 – 10 in a minimum number of Guesses.
Prerequisites
Approach
-
HTML Structure:
- Simple structure with a title, introductory text, input form, and a submit button.
-
CSS Styling:
- Minimal styling for a clean and responsive layout.
-
JavaScript Logic:
-
Generates a random number between 1 and 10 using
Math.random()
andMath.floor()
. -
Initializes a counter (
guess
) to track the number of user guesses.
-
Generates a random number between 1 and 10 using
-
User Interaction:
- On button click, retrieves the user’s guessed number and compares it with the random number.
- Displays appropriate alerts based on the comparison (correct guess, too high, or too low).
- Increments the guess counter accordingly.
Example: Below is the implementation of above explained approach.
HTML
<!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: