dimanche 24 février 2019

I'm I nesting these if/else if statements correctly in JavaScript?

I'm working on a rock, paper, scissors game in JavaScript where I have to let the user know if there was a tie and if there was an invalid user choice besides the rock, paper, and scissors, so I thought that nesting if/else statements would be appropriate. I'm pretty new to JS and can't tell if the reason why my code isn't working is due to incorrect nesting or if it's something else. All I'm getting is a parsing error of unexpected token.

var UserChoice = window.prompt("Select rock, paper, or scissors");

var computChoice = Math.random();
if (computChoice <= 0.33) {
    computChoice = "scissors";
} else if (computChoice <= 0.66 && computChoice > 0.33) {
    computChoice = "paper";
} else {
    computChoice = "rock";
}

if (UserChoice === "paper") {
    if (UserChoice === "paper" && computChoice === "rock") {
        window.alert("You chose paper and the computer chose rock! You win! Paper covers rock");  
    } else if (UserChoice === "paper" && computChoice === "paper") {
        window.alert("It's a tie!");
    } else if (UserChoice === "paper" && computChoice === "scissors") {
        window.alert("You lose! You chose paper and computer chose scissors. Scissors cut paper!");
    } 
} else if (UserChoice === "scissors") {
    if (UserChoice === "scissors" && computChoice === "paper") {
        window.alert("You chose scissors and the computer chose paper! You win! Scissors cut paper.");
    } else if (UserChoice === "scissors" && computChoice === "scissors") {
        window.alert("It's a tie! You chose scissors and the computer chose scissors!");
    } else if (UserChoice === "scissors" && computChoice === "rock") {
        window.alert("You lose! You chose scissors and computer chose rock. Rock smashes scissors!");
    }
} else if (UserChoice === "rock") {
    if (UserChoice === "rock" && computChoice === "scissors") {
        window.alert("You chose rock and the computer chose scissors! You win! Rock smashes scissors."); 
    } else if (UserChoice === "rock" && computChoice === "rock") {
        window.alert("It's a tie! You chose rock and the computer chose rock!");
    } else if (UserChoice === "scissors" && computChoice === "rock") {
        window.alert("You lose! You chose rock and computer chose paper. Paper covers rock!");
} else {
    window.prompt("Invalid choice! Choose from rock, paper, or scissors");
}

Aucun commentaire:

Enregistrer un commentaire