How to end program after right answer? - javascript

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]);
}
}

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.')
}

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);
}

Can't detect why my loop is infinite

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");

Javascript if/else statements not working

I am pretty new to Javascript, and it seems like i didnt understand the if else statements correctly.
I have a script which will make the visitor go to 1 of 4 websites, but the 2 last sites in my code does not work.
<script>
setTimeout(function() {
var r = Math.random();
if(r > 0.49) {
window.location.replace("1.html");
}
else if(r < 0.48) {
window.location.replace("2.html");
}
if (r == 0.48){
window.location.replace("maybe.html");
}
else if (r == 0.49){
window.location.replace("4.html");
}
}, 1);
</script>
Is how my code looks like right now. How would it need to look to make it work?
Update
I originally said this looked fine, but I just noticed a problem. There is no branch for r > 0.48 && r < 0.49. Values in this range, such as 0.48342... are more likely than hitting 0.48 or 0.49 exactly, and these are completely unaccounted for, which I assume was not your intention. A simple else branch is always a good idea, or you should account for these cases explicitly.
Original
Your logic looks fine to me. Reduce your problem:
function randomizeText() {
var r = Math.random();
var result = '';
if (r > 0.49) {
result = 'A';
}
else if (r < 0.48) {
result = 'B';
}
else if (r == 0.48){
result = 'C';
}
else if (r == 0.49){
result = 'D';
}
document.getElementById('output').innerText = result;
document.getElementById('random-number').innerText = 'Number was: ' + r;
}
randomizeText();
<button type="button" onclick="randomizeText();">Randomize!</button><br>
<div id="output"></div>
<div id="random-number"></div>
Note that it's going to be very very unlikely that you'll hit either of the last 2 conditions.
You can replace your entire code block with these 2 lines, and they will do what you want:
var r = Math.floor(Math.random() * 4) + 1;
window.location.replace(r+".html");
Explanation:
Your code is actually working. The problem is that the number returned by Math.random() is a random number between 0 and 1 (it might be 0.5544718541204929 ), and will almost NEVER be exactly 0.48 or 0.49, but will almost always be between those two numbers.
A better solution would be:
var r = Math.floor(Math.random() * 4) + 1;
and then test if number is 1, 2, 3 or 4.
Example:
jsFiddle Demo //jsFiddle temporarily not saving fiddles
var r = Math.floor(Math.random() * 4) + 1;
if(r ==1) {
alert("1.html");
}else if(r==2){
alert("2.html");
}else if(r==3){
alert("3.html");
}else{
alert("4.html");
}
BUT there is no need for the entire IF block. Just do this:
var r = Math.floor(Math.random() * 4) + 1;
window.location.replace(r+".html");
//alert( r + ".html" );
In response to the this question, submitted as a comment: I want it to be page 1 and page 2 has is almost 50/50, and the last 2 is pretty rare
This would give odds of 1% for cases 3 and 4.
var r = Math.floor(Math.random() * 100) + 1; //return number between 1 and 100
if(r <=48) {
alert("1.html");
}else if(r<=98){
alert("2.html");
}else if(r==99){
alert("3.html");
}else{ //r==100
alert("4.html");
}
If you desire slightly larger odds:
if(r <=40) { //40% chance
alert("1.html");
}else if(r<=80){ //40% chance
alert("2.html");
}else if(r<=90){ //10% chance
alert("3.html");
}else{ //r is between 91 and 100, 10% chance
alert("4.html");
}

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