[Solved] Guess The Number Game

  

3
Topic starter

I need to create JavaScript game which will run on the browser for guessing the number;

Requirements:

1. If the user types the right number it should say: "YOU HAVE IT RIGHT!"

2. If the user types higher number it should alert: "Too high! Guess again!"

and the third case:

3. If the user types too low number (less then my secret number) it should alert: "Too low! Guess again!"

1 Answer
2

First you need to create your HTML file and then follow the logic in the java script file - and then connect them and check in Google Chrome with alert (use prompt to take user's result):

Here is the HTML file (connected to script.js - see lower):

<!DOCTYPE html>
<html lang="en">
<head>
 
    <meta charset="UTF-8">
    <title>JavaScript Guess Game</title>
 
    <script src="script.js"></script>
 
 </head>
 
<body>
 
<h1>Guess The Number Game With JavaScript</h1>
 
</body>
</html>

Here is the JavaScript file -script.js (read the comments to understand the code better):

//create secret number
var secretNumber = 4;
 
//ask user for a number
var StringGuess = prompt("Guess the number!");
var guess = Number(StringGuess);
 
//check if guess is right
if (guess === secretNumber) {
    alert("YOU HAVE IT RIGHT!");
}
 
//otherwise, check if higher
else if (
    guess > secretNumber) {
    alert("Too high! Guess again!")
}
 
//otherwise, check if lower
else {
    alert("Too low! Guess again!")
}
Share: