I want to create a guessing game where you pick a maximum number in the prompt and you type the number that the program randomly generates.
However, I want it so that when you press "q", the game quits automatically.
Here's my code
let maximum = parseInt(prompt("Enter the maximum number"));
while (!maximum) {
maximum = parseInt(prompt("Please Enter a valid number!"));
}
let targetNum = Math.floor(Math.random() * maximum + 1);
console.log(targetNum)
let guess = parseInt(prompt("Enter your first guess!"));
let attempts = 1;
while(parseInt(guess) !== targetNum || guess.toString !== "q") {
if (guess > targetNum) {
guess = prompt("too high! Enter a new guess")
}
else {
guess = prompt("too low! Enter a new guess")
attempts++;
}
}
console.log(`You got it! It took you ${attempts} guesses`)
Whenever I press q, it doesn't work. Can someone please explain to me why :) ?
I put your variables on top to make it more clean. I also added an else if that breaks the loop when i type "q".
let maximum = parseInt(prompt("Enter the maximum number"));
let guess = parseInt(prompt("Enter your first guess!"));
let attempts = 1;
let targetNum = Math.floor(Math.random() * maximum + 1);
while (!maximum) {
maximum = parseInt(prompt("Please Enter a valid number!"));
}
while(parseInt(guess) !== targetNum) {
if (guess > targetNum) {
guess = prompt("too high! Enter a new guess")
attempts++;
}
else if(guess < targetNum){
guess = prompt("too low! Enter a new guess")
attempts++;
}else if(guess == "q"){
break;
}
}
console.log(targetNum)
console.log(`You got it! It took you ${attempts} guesses`)
const guessNumberGame = {
start_ : function(){
let n = prompt( 'Enter the secret number:' );
if( n ){
if ( !isNaN( n ) ){
this.guess_(n);
}else{
alert( 'That is not a valid number!' );
this.start_();
}
}else{
alert( 'Cancel the game!' );
}
},
guess_ : function(n){
const g = prompt( 'guess the number!' );
if( g ){
if ( !isNaN( g ) ){
if( g > n ){
alert( 'Too high!' );
this.guess_(n);
}
else if( g < n ){
alert( 'Too low!' );
this.guess_(n);
}
else{
alert( 'Correct!' );
this.start_();
}
}else{
alert( 'That is not a valid number!' );
this.guess_(n);
}
}else{
this.start_();
}
}
};
guessNumberGame.start_();