How to stop execution of a JavaScript program - javascript

So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}

A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();

= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}

Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();

Related

How to set output in a variable from conditional statement in javascript

I make a condition with Else-If to print a line like [You got A+, You got D]. Now I want to store one valid output line in a variable outside the condition.
var gradeMark = Math.round(totalNumber / 6);
//Generate grade mark
if (gradeMark >= 80) {
console.log("You got A+");
} else if (gradeMark >= 70) {
console.log("You got A");
}....
.....
else if (gradeMark >= 0) {
console.log("You got F");
} else {
console.log("It's not valid mark");
}
//Getting grading mark
var validGradeMark =
You can use defining variable instead of console log and it is out of condition now.
let gradeMark = Math.round(totalNumber / 6);
let validGradeMark;
// Generate grade mark
if (gradeMark >= 80) {
validGradeMark = "You got A+";
} else if (gradeMark >= 70) {
validGradeMark = "You got A";
}....
.....
else if (gradeMark >= 0) {
validGradeMark = "You got F";
} else {
validGradeMark = "It's not valid mark";
}
// Getting grading mark
console.log(validGradeMark);

Guess a number game using HTML and javascript

Hello I have a simple script:
var play = true;
var correct = false;
var number = 0;
var guess = 0;
while (play) {
// random number between 1 and 10.
number = Math.floor(Math.random() * 10 - 1);
if (number == 0) number = 1;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}
When I get the number right and prompted to "Do you want another game?" and enter "yes", the program redisplays and stuck at "Do you want another game?".
You need to reset the state of correct on every play loop:
let play = true;
while (play) {
let number = Math.floor(Math.random() * 10 + 1);
let guess = 0;
let correct = false;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}

Do loop keeps on repeating

So my alternative version of this code is in Java, the logic is fairly similar although in JavaScript the userinput is repeated infinitely rather than carrying until the user loses. This is my working Java code for reference:
int stop =0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
do {
int card;
int upcommingcard;
String userinput;
card= rand.nextInt(13)+1;
System.out.println("Card is "+card);
System.out.println("Higher or Lower?");
userinput = scan.next();
upcommingcard = rand.nextInt(13)+1;
if(!userinput.equalsIgnoreCase("H")&&(!userinput.equalsIgnoreCase("L"))){
System.out.println("Invalid Input ");
}
else if((userinput.equalsIgnoreCase("H")) && (upcommingcard > card)){
System.out.println("Correct!");
}
else if(userinput.equalsIgnoreCase("L") && upcommingcard < card){
System.out.println("Correct!l ");
}
else {
System.out.println("You lost it was " + upcommingcard);
stop=1;
}
}while (stop != 1);
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
JavaScript - Not working
var max=13;
var min=1;
var stop=0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is "+card+"... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do{
if((userinput !="H")&&(userinput !="L")){
console.log("Invalid input");
}
else if((userinput ="H")&&(upcommingcard > card)){
console.log("Correct!");
}
else if((userinput ="L")&&(upcommingcard < card)){
console.log("Correct!");
}
else{
console.log("You lost, it was "+ upcommingcard);
stop=1;
}
}
while(stop !=1);
Just to mention also that it registers that the user's input is correct although it fails to continue and just keeps on spitting out the same output until the browser crashes.
EDIT: Thanks for the responses! the loop works perfectly now, my only issue is that the logic is a bit flawed since sometimes I Input 'L' for 8 and upcoming int is 10.. Dispite this I get the Incorrect response.
It's not that your console isn't updating, it's that you never exit your loop if the input is incorrect, and you never offer them the option to try again.
Thus if they are incorrect, the loop will never end, the console won't be updated, and they can't retry.
I would recommend changing the code to the following, to alert the user to try again.
var max = 13;
var min = 1;
var stop = 0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do {
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input!");
userinput = prompt("Card is " + card + "... Higher or lower?");
} else if ((userinput == "H") && (upcommingcard > card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
There are some points I want to make on this:
Your Java and Javascript code logic differs. You had the variables and input reads inside do while in Java but outside in Javascript.
As your prompt right now is outside the loop, it will keep having the same input value everytime and not asking for another one, and will carry on until it's a wrong guess, or forever if it's an invalid input. And the next point worsens your problem:
Your if comparison operators are invalid. What you did, as mentioned in the comments, is a data assignment to userinput and will always return correct
That being said, I corrected it below while adding alert popups instead of console.log only:
var stop = 0;
do {
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input");
stop = 1; //Currently stopping if having invalid input, you can remove this later
} else if ((userinput == "H") && (upcommingcard > card)) {
//Note the '==' above, and also the next one for comparing equal values
console.log("Correct!");
alert("Correct");
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
Now, do compare the JS snippet above with your working Java code you've posted. If you compare again with your JS code, you should be able see what I meant by having different logic.

JavaScript weird issue with else if statement

I'm making a game of Guess the Number, and I want to test if a variable guess is greater than a variable difficulty. difficulty has been taken from my HTML page, and it is not comparing correctly with guess.
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = document.getElementById("difficulty").value;
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = prompt("Enter your guess: ");
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
body {
font-family: sans-serif;
text-align: center;
animation: background 10s infinite;
}
h1 {
margin-top: 48px;
margin-bottom: 48px;
animation: heading 10s infinite;
}
button {
height: 48px;
width: 250px;
font-size: 24px;
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
Read this: key info
This code works, but I want something to happen: When the guess is greater than difficulty, I want to print "Please enter a number between 1-" + difficulty. However, when I change this code:
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
into this:
else if (guess < 1 || guess > difficulty) {...}
(EDIT: the above code is to find out if the guess is greater than difficulty)
then what happens is that EVERY guess except 1, difficulty and anything more than difficulty is alerted by Please enter a number.
How should I fix this?
You're comparing strings not numbers. Convert your strings into numbers.
else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
Better way: Convert it directly after input and...
guess = parseInt(prompt("Enter your guess: "));
...get the difficulty value as number
var difficulty = parseInt(document.getElementById("difficulty").value);
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = parseInt(document.getElementById("difficulty").value);
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = parseInt(prompt("Enter your guess: "));
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1 || guess > difficulty) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
change else if (guess < 1 || guess > parseInt(difficulty))
to else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
or change the type at the input
guess = parseInt(prompt("Enter your guess: "));
You can also use the built-in Number function. See how I fixed your code below:
difficulty = Number(difficulty);
guess = Number(guess);
Try applying this after your variables are declared and it should work!
Change to this should help:
else if (guess < 1 || guess > parseInt(difficulty)) {

for loop getting skipped in javascript

I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
and here is the full code:
//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;
var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?
if (confirmPlay === true) {
console.log("User wants to play");
} else {
window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage
numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number
tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
if (isSkipped === true) {
console.log("Oh no! The for loop has been skipped!");
}
If you need any further details, just ask.
Shouldn't the for be like this?:
for (i = 0; i < tries; i += 1) {
When you write:
for (i = 0; i === tries; i += 0) {
the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.
You should write:
for (i = 0; i < tries; i++) {
Also you need to use parseInt() function on user's input.
var guessedNumber = parseInt(prompt("Guess your number now."), 10);
instead of
var guessedNumber = prompt("Guess your number now.");

Categories