Search code examples
javascriptloopsvariablesdo-whileprompt

Heads or tails game javascript do/while loop


I am trying to make a basic heads or tails game using a do/while loop. My problem is that my prompts don't seem to influence my variables whatsoever as whatever I type it simply proceeds to the next section and then doesn't loop at all. Am I missing something? What am I doing wrong?

var userChoice;
var playAgain;

do {
    playAgain = prompt("Do you want to play Heads or tails?");
}
while (playAgain === "Yes") {
    userChoice = prompt("Choose Heads or Tails.");
    if (userChoice === "Heads") {
        coin = Math.random();
        if (coin <= 0.5) {
            console.log("You Win!");
        }
        else {
            console.log ("You lose");
        }
    }
    if (userChoice === "Tails") {
        coin = Math.random();
        if (coin > 0.5) {
            console.log("You Win!");
        }
        else {
            console.log("You lose");
        }
    }
    playAgain = prompt("Would you like to play again?");
};

Solution

  • You should try like this instead:

    var userChoice;
    var playAgain;
    
    playAgain = prompt("Do you want to play Heads or tails?");
    
    while (playAgain === "Yes") {
        userChoice = prompt("Choose Heads or Tails.");
        if (userChoice === "Heads") {
            coin = Math.random();
            if (coin <= 0.5) {
                alert("You Win!");
            }
            else {
                alert ("You lose");
            }
        } else if (userChoice === "Tails") {
            coin = Math.random();
            if (coin > 0.5) {
                alert("You Win!");
            }
            else {
                alert("You lose");
            }
        }
        playAgain = prompt("Would you like to play again?");
    }

    The do/while loop does the action under the do statement while the while condition is not met. Usually, you tend to avoid the do/while loop unless you REALLY need it, which is pretty rare.

    Also, I replaced console.log to window.alert for the coherence and to avoid going to look at the console.