Can't detect why my loop is infinite - javascript

var randomNum = Math.round(Math.random() * 100);
guesses = prompt("guess a number between 1 and 100");
var scores = 0;
while (randomNum < 100) {
if (guesses < randomNum) {
console.log(" too low.. continue")
} else if (guesses > randomNum) {
console.log("too high ... continue ");
score++;
} else if (guesses === randomNum) {
console.log("great ... that is correct!!")
} else {
console.log("game over ... your guess was right " + scores + " times");
}
}
I have been struggling with the while loop concept for some time now and in order to confront my fears I decided to practice with some tiny exercises like the one above.

You're not incrementing randomNum hence it will always stay in an infinite loop.

You initialize randonNum and guesses at the beginning of your code, but then you never change their values again. So, once you go inside the while loop and the condition starts out to be false, then there is nothing inside the while loop to ever change the outcome of the comparison condition. Thus, the condition is always false and you end up with an infinite loop. Your loop structure boils down to this:
while (randomNum < 100) {
// randomNum never changes
// there is no code to ever break or return out of the loop
// so loop is infinite and goes on forever
}
You can fix the problem by either putting a condition in the loop that will break out of the loop with a break or return or you can modify the value of randomNum in the loop such that eventually the loop will terminate on its own.
In addition, guesses === randomNum will never be true because guesses is a string and randomNum is a number so you have to fix that comparison too.
It's not 100% clear what you want to achieve, but if you're trying to have the user repeatedly guess the number until they get it right, then you need to put a prompt() inside the while loop and a break out of the while loop when they get it right or ask to cancel:
var randomNum = Math.round(Math.random() * 100);
var guess;
var score = 0;
while ((guess = prompt("guess a number between 1 and 100")) !== null) {
// convert typed string into a number
guess = +guess;
if (guess < randomNum) {
console.log(" too low.. continue")
} else if (guess > randomNum) {
console.log("too high ... continue ");
score++;
} else if (guess === randomNum) {
console.log("great ... that is correct!!")
console.log("score was: " + score);
// when we match, stop the while loop
break;
}
}

the below line of code of your assign randomNum only one time hence it doesn't change
var randomNum = Math.round(Math.random() * 100);
so when you are trying to create the while loop the randomNum value remains same
try changing the randomNum value in the while loop

I think this is what you tried to achieve. Retry x number of times
var randomNum = Math.round(Math.random() * 100);
var guesses;
var scores = 0;
var tries = 0
while (tries++ < 3) { // Loop if less than 3 tries, and increment
guesses = prompt("guess a number between 1 and 100");
if (guesses < randomNum) {
console.log(" too low.. continue")
} else if (guesses > randomNum) {
console.log("too high ... continue ");
} else {
// It's not to low, not to high. It must be correct
score++;
console.log("great ... that is correct!!");
randomNum = Math.round(Math.random() * 100);
}
}
console.log("game over ... your guess was right " + scores + " times");

Related

Roll dice game if else statement not working

Here is the description of the code i need to write:
Deisgn the logic for a game that simulates rolling two dice by generating two numbers between 1 and 6 inclusive (one number for each die).
The player will choose a number between 2 and 12 (the lowest and highest totals possible for two dice).
The program will then roll the dice three times
-- if the user's guess comes up in one of the rolls the user wins.
-- If the guess does not come up computer wins.
We have not started arrays yet but I am to use a for loop and if else.
It is my if else statement that is not working.
Every roll comes up you lose.
Here is the code:
randNumber = prompt("Please enter a number between 2 and 12");
while (randNumber <= 1 || randNumber >= 13) {
alert("Input was incorrect, try again.");
randNumber = prompt("Please enter a number between 2 and 12");
}
for (var i = 0; i < 3; i++) {
computerRoll = 1 + Math.ceil(Math.random() * 11);
document.write(computerRoll + "<br>");
}
function rollDice() {
var computerRoll = rollDice(2, 12);
}
var computerRoll = rollDice;
if (randNumber == computerRoll) {
document.write("You win.");
} else {
document.write("You lose.");
}
if the computer is trying to roll 2 dice, you need 2 random numbers, both converted to range 0 to 5, and then added, and adding 2. (Try making a function to roll one die, and then calling it twice.)
The rolldice() function does not return a value. And it's computerRoll is independent of the outer computerRoll.
the outer computerRoll is set to a function, which is never equal to a number. This is why you get only losses.
if my translator is correct :
let randNumber, computerRoll
do
{
if (randNumber != undefined) {
alert('Input was incorrect, try again.')
}
randNumber = parseInt(prompt('Please enter a number between 2 and 12')) // bce promt value is string
}
while (!(1<randNumber && randNumber<13)) // to also process NaN values (not a number)
document.write('randNumber -> '+ randNumber + '<br>' )
for (let i=0;i<3;i++)
{
computerRoll = Math.floor(Math.random() *6) +1 // first dice
computerRoll += Math.floor(Math.random() *6) +1 // second dice
document.write('computerRoll -> '+ computerRoll + '<br>' )
if ( computerRoll === randNumber ) break
}
if (randNumber === computerRoll) {
document.write('You win.')
}
else {
document.write('You lose.')
}

How to end program after right answer?

I've made a game with JavaScript where a player can only guess a random number from 1 to 10 three times, each time the program reads a wrong answer it displays what should've been the right answer, and tells the player to try again, if the player gets the right answer the game displays a message saying You got it right. I've managed to make the program work, and apparently, everything seems to be fine, except for one thing, the program won't stop even after the player gets the right answer, it reads through all the statements until it reaches the end. How can I make it stop after the right answer?
var random = Math.floor(Math.random() * 10);
var random1 = Math.floor(Math.random() * 10);
var random2 = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10, you have 3 chances.");
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
} else {
alert("Sorry, the correct answer was " + random);
window.prompt("Make a guess from 1 to 10, you have 2 chances left.");
}
if (answer == random1) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
} else {
alert("Sorry, the correct answer was " + random1);
window.prompt("Make a guess from 1 to 10, you have 1 chance left.");
}
if (answer == random2) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
} else {
alert("Sorry, the correct answer was " + random2);
alert("You've lost");
}
First and forement, the bug
You have a bug in your code. If you win on the first round, it will detect this successfully. On the second and third round, any victory will be purely coincidence.
The reason is because you do not assign the return value from window.prompt to answer every time you call it. So the value of answer never changes from one round to the next.
To fix this, you should replace
window.prompt(...)
with:
answer = window.prompt(...)
The "bad" fix:
Let's start with a very simple (but very bad) solution, and use it as a springboard to teaching better architecture design.
Your current code roughly looks like this:
if (win) {
// say you won
} else {
// say you lost
}
if (win) {
// say you won
} else {
// say you lost
}
if (win) {
// say you won
} else {
// say you lost
}
With all of the extra stuff cleaned up you can clearly see why it's going through all three iterations: the three if/else blocks are entirely unrelated and know nothing about one another. It runs one if/else block, then another, then another -- in order, every time.
The easiest fix is to make sure the later blocks only run if you lose. This is pretty easy to do, because we already know if you lost -- it happens when you didn't win!
if (win) {
// say you won
} else {
// say you lost
if (win) {
// say you won
} else {
// say you lost
if (win) {
// say you won
} else {
// say you lost
}
}
}
Or, using your random, random1, and random2 variables:
var random = Math.floor(Math.random() * 10);
var random1 = Math.floor(Math.random() * 10);
var random2 = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10, you have 3 chances.");
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
}
else {
alert("Sorry, the correct answer was " + random);
answer = window.prompt("Make a guess from 1 to 10, you have 2 chances left.");
if (answer == random1) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
}
else {
alert("Sorry, the correct answer was " + random1);
answer = window.prompt("Make a guess from 1 to 10, you have 1 chance left.");
if (answer == random2) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
}
else {
alert("Sorry, the correct answer was " + random2);
alert("You've lost");
}
}
}
This is ugly, but will work.
Springboarding into better design
As you might imagine, adding 4 or 5 or 6 rounds to this game would get REALLY tedious. You'd have to type out even more if/else blocks, create even more random variables, and type out even more alert statements. To make it more annoying, all of these alert statements contain the same text!
There's a concept in software design called DRY (Don't Repeat Yourself). This means that if you have two identical lines of code, you can probably rewrite it to eliminate the duplication.
In your case, we can do this using a while loop to check if we've won the game or not:
var youHaveWon = false;
while( ! youHaveWon ) {
var random = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10");
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
youHaveWon = true;
}
else {
alert("Sorry, the correct answer was " + random);
}
}
This will allow you to keep making guesses until you get it right, and doesn't repeat any code. Although this doesn't limit you to only 3 guesses. To do that, we should introduce one more variable:
var youHaveWon = false;
var guessesRemaining = 3;
while( ! youHaveWon && guessesRemaining > 0 ) {
var random = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10... you have " + guessesRemaining + " more guesses");
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
youHaveWon = true;
}
else {
alert("Sorry, the correct answer was " + random);
}
guessesRemaining = guessesRemaining - 1;
}
if ( ! youHaveWon ) {
alert("You lost");
}
You can wrap this to a function and return it on right value. Upon return, JS will stop execution and control will move forward
Try below
function findNumber() {
var random = Math.floor(Math.random() * 10);
var random1 = Math.floor(Math.random() * 10);
var random2 = Math.floor(Math.random() * 10);
var answer = window.prompt("Make a guess from 1 to 10, you have 3 chances.");
if (answer === random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
return true;
} else {
alert("Sorry, the correct answer was " + random);
window.prompt("Make a guess from 1 to 10, you have 2 chances left.");
}
if (answer == random1) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
return true;
} else {
alert("Sorry, the correct answer was " + random1);
window.prompt("Make a guess from 1 to 10, you have 1 chance left.");
}
if (answer == random2) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
return true;
} else {
alert("Sorry, the correct answer was " + random2);
alert("You've lost");
}
}
The problem is that you're having three different if-blocks which all will be executed even though the user might have guessed the correct number yet.
I'd recommend setting up a single random number and a global counter which keeps track of the remaining chances.
function validate() {
if (answer == random) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
} else {
if (chances - 1 > 0) {
chances--;
answer = window.prompt("Make a guess from 1 to 10, you have " + chances + " chances.");
validate();
}
}
}
var random = Math.floor(Math.random() * 10);
var chances = 3;
var answer = window.prompt("Make a guess from 1 to 10, you have " + chances + " chances.");
validate();
var randomNumbers = [];
var numberOfTries = 3;
for(var i=0; i<numberOfTries ; i++){
randomNumbers.push(Math.floor(Math.random() * 10));
}
for(var i=numberOfTries-1; i > -1 ; i--){
var answer = window.prompt("Make a guess from 1 to 10, you have "+ parseInt(i + 1) +" chances left.");
if(answer === randomNumbers[i]) {
alert("HORAAYYYY YOU GOT IT RIGHT!!!");
return;
}
else {
alert("Sorry, the correct answer was " + randomNumbers[i]);
}
}

Trying to iterate over if..else but numbers aren't adding up

I'm trying to iterate over this if else statement as many times as someone wants. If the score = counter wins should get +1 each time, same with losses. However every time it goes through this wins and losses will only stay at 1.
var wins1 = 0;
var losses1 = 0;
if(counter == numberToguess)
{
counter = 0
console.log("you win")
randfunction()
randNum();
$(".scoreDiv").text(numberToguess)
losses1 += 1
console.log(wins1)
} else if(counter > numberToguess)
{
counter = 0
console.log("you lose")
randfunction()
randNum()
$(".scoreDiv").text(numberToguess)
losses1 += 1
console.log(losses1)
}
It's hard to tell from the context, but are you declaring win1 and losses1 at the top of your loop? If so then they are going to reset to 0 every time the loop runs, hence the final result of 1.
You have to post what you are using to populate numberToguess so that we can help you finish the script. Ill assume your using a prompt window:
var possibilities = 3;
var wins = 0;
var losses = 0;
var answer = "";
while(answer = prompt("guess a number")) {
var randomNumber = Math.floor(Math.random() * possibilities) + 1;
if(answer == randomNumber) {
wins++;
console.log("You Win");
} else {
losses++;
console.log("You Lose");
}
console.log("wins: " + wins + " - losses: " + losses);
}

Nested else if in javascript

In this random number guessing, after obtaining input from user, if its is wrong (it should go to else) it does not go to the else statement. I can't find where it went wrong.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !");
guessint = parseInt(guess);
var random = Math.floor(Math.random() * 10) + 1;
if (guessint === random) {
document.write("Guessed Correct");
} else if (guessint > random) {
var guessgreat = prompt("Try again with value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
document.write("Guessed Correct great");
}
} else if (guessint < random) {
var guessless = prompt("Try again with value GREATER than " + guessint);
if (parseInt(guessless) === random) {
document.write("Guessed Correct Less");
}
} else {
document.write("Oops Guessed wrong");
}
Assuming that both guessint and random are indeed defined numbers, then your else condition will never be reached, because when comparing one number against another the only three logical outcomes are that the first is equal, less to, or greater than, the second.
You have obscure { in last else if statement, i've hightlighted it with ___^___ in code snippet below, remove it and everything suppose to work as expected:
else if(guessint<random)
{
var guessless = prompt("Try Again With Valur GREATER than "+guessint)
if(parseInt(guessless)===random)
{
document.write("Guessed Correct Less")
}
}
___^___
else
{
document.write("Oops Guessed wrong");
}
Updated code, you need to have the else inside, updated code below.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !");
guessint = parseInt(guess);
console.log(guessint);
var random = 4; //Math.floor(Math.random()*10)+1;
console.log(random);
if (guessint === random) {
document.write("Guessed Correct");
} else if (guessint > random) {
var guessgreat = prompt("Try Again with value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
document.write("Guessed Correct great");
}else {
document.write("Oops Guessed wrong");
}
} else if (guessint < random) {
var guessless = prompt("Try Again With Valur GREATER than " + guessint);
if (parseInt(guessless) === random) {
document.write("Guessed Correct Less");
}else {
document.write("Oops Guessed wrong");
}
}
You could use a while loop for guessing. Stay in the loop while the input value is not equal to the random value.
Inside the loop, you need to check for greater, then and prompt the user. after promting, you need to convert the value to an integer with base 10.
If the value is smaller (the else part) prompt for a new number.
If the loop id leaved, you know the guessed value is found and display the message.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !"),
guessint = parseInt(guess, 10),
random = Math.floor(Math.random() * 10) + 1;
while (guessint !== random) {
if (guessint > random) {
guessint = parseInt(prompt("Try Again with value LESSER than " + guessint), 10);
} else {
guessint = parseInt(prompt("Try Again With Valur GREATER than " + guessint), 10);
}
}
document.write("Guessed Correct");
Let's go through it step by step.
Let's say random is 10 and the user picks 9 (so guessint = 9).
Now let's replace those values on your if / else statements:
if (9 === 10) { // False!
} else if (9 > 10) { // False!
} else if (9 < 10) { // True!
/* Runs this part of the code */
} else { // It will never get to this else!
}
No matter what value the user selects, it will have to be either:
Equal to 10
Greater than 10
Lesser than 10
There is no number that will not match any of those conditions. So it will always enter one of your if statements, and never the last else.
You would need an else on every if, like Thennarasan said, or a control variable, like so:
var guessint = parseInt(prompt("Guess a value between 1 and 10!"));
var random = Math.floor(Math.random() * 10) + 1;
// Control variable
var guessed_correctly = false;
if (guessint === random) {
// Correct on first chance
guessed_correctly = true;
} else if (guessint > random) {
// Second chance
var guessgreat = prompt("Try again with a value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
// Correct on second chance
guessed_correctly = true;
} else {
// Incorrect on second chance
guessed_correctly = false;
}
} else if (guessint < random) {
// Second chance
var guessless = prompt("Try again with a value GREATER than " + guessint);
if (parseInt(guessless) === random) {
// Correct on second chance
guessed_correctly = true;
} else {
// Incorrect on second chance
guessed_correctly = false;
}
}
if (guessed_correctly === true) {
// If the user was correct on any chance
document.write("Congratulations!");
} else {
// If the user was incorrect on both chances
document.write("Oops! Guessed wrong!");
}
Alternatively, there are other methods to implement the game you're making with whiles and such, but the example I've given is based on your format.

Guessing game woes

Hello i am very new to javascript and have been trying to make a random number guessing game. I think i almost got it except there is one thing i cant figure out. Everytime i run it i have to type in my number twice and it also only returns Lower no matter what number i type in.
var randomNumber = Math.floor((Math.random() * 100) + 1);
print("I have thought of a random number in the range of 1 to 100. Guess!");
{
while (randomNumber != readline())
if (readline() < randomNumber)
{
print("Lower");
}
else if (readline() > randomNumber)
{
print("Higher");
}
else if (readline() == randomNumber)
{
print("Good Job");
}
}
Your problem is you are calling readline multiple times per iteration of your while loop. Here I have stored the value of readline into a variable and use that to test:
var randomNumber = Math.floor((Math.random() * 100) + 1);
print("I have thought of a random number in the range of 1 to 100. Guess!");
var hasGuessedCorrectly = false;
while (!hasGuessedCorrectly)
{
var guess = readline();
if (guess < randomNumber)
{
print("Lower");
}
else if (guess > randomNumber)
{
print("Higher");
}
else if (guess == randomNumber)
{
print("Good Job");
hasGuessedCorrectly = true;
}
}

Categories

Resources