This program is the guessing game. It will input a number between
1 and 100 then it will tell the user if the number the input is too low
or too high.
*/
//holds the high score
var highScore = 0;
//control for the while loop
var notDone = true;
//hold how many attemps to get guess number
var tries = 0;
//will grab random number
var random = getRandom();
//will run until user no longer wants to play
while(notDone){
tries++;
var num = Number(prompt("Enter a number between 1 and 100: ", ""));
num = checkValidNum(num);
var result = HighOrLow(num);
//tell user higher/lower/correct
alert(result);
if(result === "Correct!"){
//tells user the correct answer once correct
alert("The correct number was: " + random);
var score = highScoreFun(tries);
//if its a highscore tell user
if(score == true){
alert("Highscore!!! It took you " + tries + " attempt(s).");
}
//tell user their ammount of attempts.
else{
alert("Amount of attempts is " + tries + ". " + (tries - highScore) + " attempt(s) more than the highscore.");
}
notDone = confirm("Do you want to try again?");
//will reset tries and a new random number if user wants to play again.
if(notDone){
tries = 0;
random = getRandom();
}
}
}
//will tell whether or not it's a high score
function highScoreFun(score){
//if no attempts or attemps is lower then highscore it's a highscore.
if(highScore == 0 || tries < highScore){
highScore = tries;
return true;
}
return false;
}
//checks if its a number between 1 and 100
function checkValidNum(number){
while(isNaN(number) || number < 2 || number >99){
number = Number(prompt("Input is not a number between 1 and 100, please try again: ",""));
}
//will return value once user enters a valid input
return number;
}
//will return whether the input is higher or lower or correct
function HighOrLow(number){
//returns correct if user is right
if(number == random){
return "Correct!";
}
//returns higher if user guessed low
else if(number < random){
return "Higher";
}
//returns lower if user guessed high
else if(number > random){
return "Lower";
}
}
//returns a random integer between 1 and 100
function getRandom(){
return parseInt(Math.random() * (100-2) + 2);
}