Crkva Kovacica Crkva Kovacica - 3 months ago 7
Javascript Question

What do i need to add, so my JavaScript would work as i want it to?

I started learning JavaScript, and this is my first game i built: Rock, Paper, Scissors.
(Player vs Computer) Now, everything is working, but i couldn't figure out how to make this:

When result is tie, the game starts again asking if i would like to play again, without having to refresh the browser.

Please don't answer with jQuery, I'm trying to learn JavaScript! :)

Here is my snippet:



// declare variables
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();

// prevent the user from choosing a different answer
if (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors") {
userChoice = prompt("Your answer is not acceptable! Please choose again!");
}

// pick a random answer from computer
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
alert("Computer: " + computerChoice);

// check who wins
var compare = function(choice1, choice2) {
if (choice1 === choice2) {
alert("The result is a tie!");
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
alert("rock wins");
} else {
alert("paper wins");
}
} else if (choice1 === "paper") {
if (choice2 === "rock") {
alert("paper wins");
} else {
alert("scissors win");
}
}
}

// call the function
compare(userChoice, computerChoice);




Answer

What you're basically looking to do is wrap the game in a larger contextual loop, which itself just checks for a terminating condition to the game.

Structurally, let's assume the entirety of your game is enclosed in a function:

function playGame() {
    // all the code you have now
}

Then the loop would have a structure like this:

while (true) {
    playGame();

    if (!confirm("Would you like to play again?")) {
        break;
    }
}

You can of course get fancier with the confirmation, or perhaps use a value to control the loop rather than an infinite loop with a break. But the concept is the same. The overall loop will continue to repeat and "play again" until some condition exists which would cause it to stop.

So in your case, you want to check if it's a tie, yes? Structurally something like this:

while (true) {
    playGame();

    if (!gameIsTie()) {
        break;
    }
}

or:

var winner = 0;

while (winner == 0) {
    playGame();
    winner = determineWinner();
}

Wherein you would implement the functions needed to determine if the game is a tie, or if there is a winner, etc.

Comments