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

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

Related

Hangman game same letter validation javascript only

I need help with my hangman game, how do I stop lives going down if players guess repeated letter before, as for now if I run it and player guesses the same letter, it will output that he have already made this guess but the lives is dropping too. Also if players keep input the same correct letter, it will output that he have already made this guesses but it will say he won after inputting the same letter 4-5 times.
1st error: lives dropping even if players use letter that is guessed before
2nd error: players input the same correct letter guessed and game will say he won after inputting 4-5 times
Code
guesses = [];
// Show player their progress | .join returned answer as a string
while (remainingLetters > 0 && lives > 0) {
(answerArray.join(""));
guess = readline.question(name+"'s guess (Enter 9 for lifelines or 0 to pass): ");
guess = guess.toUpperCase();
//if guess is more than 1 letter or no letter, alert player to guess 1 letter only
if (guess.length !== 1) {
console.log("Please enter 1 letter only.");
}
//if valid guess
else {
correctGuess = 0;
for (var j = 0; j < Word.length; j++) {
if (Word[j] == guess) {
answerArray[j] = guess;
remainingLetters--;
correctGuess = 1;
}
}
if (correctGuess == 1) {
console.log("\nGood job! "+guess+" is one of the letters!\n");
console.log(JSON.stringify(answerArray)+"\n");
console.log(JSON.stringify(alphabets)+"\n");
} else {
lives -= 1;
console.log("\nSorry. "+guess+" is not a part of the word.\n");
console.log(JSON.stringify(answerArray)+"\n");
console.log(JSON.stringify(alphabets)+"\n");
console.log("You have "+lives+" lives remaining.\n");
}
if (guesses.includes(guess)) {
console.log("You have already made this guess, please try another letter!\n");
} else {
guesses.push(guess)
}
}
if (remainingLetters == 0) {
console.log("Congratulation! You managed to guess the word!\n");
break;
}
if (lives == 0) {
console.log("Game Over... You failed to guess the word. The word is "+Word+".\n")
}
}
Inside else for valid guess move your entire code inside else of if (guesses.includes(guess)) {. It will solve both of your issues.
// Show player their progress | .join returned answer as a string
while (remainingLetters > 0 && lives > 0) {
(answerArray.join(""));
guess = readline.question(name + "'s guess (Enter 9 for lifelines or 0 to pass): ");
guess = guess.toUpperCase();
//if guess is more than 1 letter or no letter, alert player to guess 1 letter only
if (guess.length !== 1) {
console.log("Please enter 1 letter only.");
}
//if valid guess
else {
if (guesses.includes(guess)) {
console.log("You have already made this guess, please try another letter!\n");
} else {
guesses.push(guess);
correctGuess = 0;
for (var j = 0; j < Word.length; j++) {
if (Word[j] == guess) {
answerArray[j] = guess;
remainingLetters--;
correctGuess = 1;
}
}
if (correctGuess == 1) {
console.log("\nGood job! " + guess + " is one of the letters!\n");
console.log(JSON.stringify(answerArray) + "\n");
console.log(JSON.stringify(alphabets) + "\n");
} else {
lives -= 1;
console.log("\nSorry. " + guess + " is not a part of the word.\n");
console.log(JSON.stringify(answerArray) + "\n");
console.log(JSON.stringify(alphabets) + "\n");
console.log("You have " + lives + " lives remaining.\n");
}
}
}
if (remainingLetters == 0) {
console.log("Congratulation! You managed to guess the word!\n");
break;
}
if (lives == 0) {
console.log("Game Over... You failed to guess the word. The word is " + Word + ".\n")
}
}

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

Checking for two consecutive values match of a variable's value in JavaScript

I built a function called roll() which handles a roll of a dice. I'm trying to read the value of the roll and check if the roll hit 6 twice in a row so that I can interrupt the player's turn and turn it to the next player.
I can read the dice value alright, I'm having trouble trying to figure out how to check for a 6 twice in a row.
This is my function:
roll = function(){
if (gamePlaying){
// 1. Get a random number
//var dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
var dice = 6;
//2. Display the result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'images/' + 'dice-' + dice + '.png';
//3. Update the roundScore IF the rolled number is not 1
// for type coersion, we need to use !== and not !=
if(dice !== 1) {
//add score
roundScore += dice; // same as roundScore = roundScore + dice
//it outputs to a div of ID = #myId
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
alert('Next Player')
nextPlayer();
}
// Is this right?
for(var i = 1; i >= 2; i++){
if (dice == 6){
console.log('sixes');
}
}
}
}
Being triggered by a button like this:
document.querySelector('.btn-roll').addEventListener('click', function(){
roll();
});
I loaded the game to this CODEPEN
P.S. I put a dice = 6; under the random function so you don't have to play the game until you get two sixes. Just uncomment it and comment out the dice = math function and you'll get nothing but sixes.
I also put a "Is this right?" comment on top of a for loop. What I mean by that is, " is this the right approach?" Should I keep experimenting with a loop or am I way off already?
And by the way, if 2 sixes do come up, the entire score is deleted which is being passed to the score[] But I can do that... I think lol
Many thanks.
You can try something like this, where you make roll() a self invoking function. That way you can store how many times they have rolled a six.
roll = (function(){
var count = 0;
var lastRoll = 0;
return function() {
if (gamePlaying){
// 1. Get a random number
var dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
var thisRoll = dice;
if(dice === 6) {
lastRoll = 6;
count += 1;
} else {
lastRoll = 0;
count = 0;
}
if(thisRoll === 6 && lastRoll === 6 && count === 2) {
alert('You rolled a six twice!');
lastRoll = 0;
count = 0;
// do your stuff for 2 sixes in a row here!
return;
}
//2. Display the result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'http://sitedev.online/repo/' + 'dice-' + dice + '.png';
//3. Update the roundScore IF the rolled number is not 1
// for type coersion, we need to use !== and not !=
if(dice !== 1) {
//add score
roundScore += dice; // same as roundScore = roundScore + dice
//it outputs to a div of ID = #myId
document.querySelector('#current-' + activePlayer).textContent = roundScore;
console.log(dice);
} else {
alert('Next Player')
nextPlayer();
}
}
}
})();
Just for the heck of it, you don't need any global or outside vars to do this. The trick is, remember that functions are objects. You can read and write properties to them; you can even entirely change a function from within the function (which is the trick to an old JS singleton pattern).
Here's an example. If you say feed it "true", it will update the "last" reference values and return two random dice rolls. If you feed it "false", it will NOT update the previous reference values until you pass in true again (but it still returns a fresh roll). That way, you can keep rolling, hold the initial value, and compare it to a new second value all you want.
<html>
<head>
</head>
<body>
<script>
var rollfunc = function ( updateLast ) {
var d1 = Math.floor((Math.random() * 6) + 1);
var d2 = Math.floor((Math.random() * 6) + 1);
if ( updateLast ) {
rollfunc.d1 = d1;
rollfunc.d2 = d2;
}
return {
dice1 : d1,
dice2 : d2,
bothsixes : ( ( d1 + d2 === 6 ) && ( rollfunc.d1 + rollfunc.d2 === 6 ) )
};
}
var result = rollfunc ( true );
// If you pass in true then d1, d2, and rollfunc.d1, rollfunc.d2 will always be the same
console.log ( "Reference updated: ", result, "d1 = " + rollfunc.d1, ", d2 = " + rollfunc.d2 );
var result = rollfunc ( false );
// If you pass in false, the reference won't change, but the new roll will, you can compare the two
console.log ( "Reference left alone: ", result, "d1 = " + rollfunc.d1, ", d2 = " + rollfunc.d2 );
</script>
</body>
</html>
I get this might be overly academic, but it's useful to know JS can do this.
A little late to this game. But I'm new to JavaScript, and currently on a similar project from udemy.com.
Here's a solution I found that apparently works. I verified it on your CodePen, too.
document.querySelector('.btn-roll').addEventListener('click', function() {
if (gamePlaying) {
// 1. Get a random number
dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
thisRoll = dice;
if (dice === 6) {
lastRoll = 6;
count += 1;
} else {
lastRoll = 0;
count = 0;
}
if (thisRoll === 6 && lastRoll === 6 && count === 2) {
alert('You rolled a six twice!');
lastRoll = 0;
count = 0;
nextPlayer();
// do your stuff for 2 sixes in a row here!
return;
}
//2. Display result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'http://sitedev.online/repo/' + 'dice-' + dice + '.png';
//3. Update round score if the rollled number was not a 1
if (dice !== 1) {
//Add score
roundScore += dice;
//roundScore = roundScore + dice
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
nextPlayer();
}
}
});
Working on the same problem. Found another solution on udemy. Hope it helps...
var lastRoll;
document.querySelector('.btn-roll').addEventListener('click', function() {
// Generating a random variable
var dice = Math.floor(Math.random() * 6) + 1;
// Check for two consecutive 6's'
if ( dice === 6 && lastDice === 6) {
//If consecutive 6's code goes here
}
lastRoll = dice;
});

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

Categories

Resources