Reputation: 3
I need a bit of help with a basic JavaScript version of Rock-Paper-Scissors I'm working on. I just started learning today and would like to keep the code as intact as possible, if possible.
The main problem I'm having is with the loop. It continues despite me setting 'again' to 'no' (through the prompt). Also, the computer always seems to choose Rock... I have a feeling that I'm just missing something simple:
<html>
<script type="text/javascript">
var myChoice = "";
var compChoice = "";
var again;
while (again = "yes")
{
myChoice = prompt("Do you choose rock, paper or scissors?");
compChoice = Math.random();
if (compChoice < 0.33)
{
compChoice = "rock";
}
else if(compChoice < 0.67)
{
compChoice = "paper";
}
else
{
compChoice = "scissors";
}
if (compChoice = myChoice)
{
alert("It's a tie!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (compChoice = "rock")
{
if(myChoice = "scissors")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "paper")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
}
else if (compChoice = "paper")
{
if (myChoice = "rock")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "scissors")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
}
else if (compChoice = "scissors")
{
if (myChoice = "rock")
{
alert("You win!");
again = prompt("Would you like to play again?(yes/no)");
}
else if (myChoice = "paper")
{
alert("You lose!");
again = prompt("Would you like to play again?(yes/no)");
}
}
};
</script>
</html>
Upvotes: 0
Views: 468
Reputation: 388316
You are using =
instead of ==
in the while statement and same in all the if statements also
=
is the assignment operator, while ==
is the comparison operator
var myChoice = "";
var compChoice = "";
var again;
do
{
myChoice = prompt("Do you choose rock, paper or scissors?");
compChoice = Math.random();
if (compChoice < 0.33)
{
compChoice == "rock";
}
else if(compChoice < 0.67)
{
compChoice = "paper";
}
else
{
compChoice == "scissors";
}
if (compChoice == myChoice)
{
alert("It's a tie!");
}
else if (compChoice == "rock")
{
if(myChoice == "scissors")
{
alert("You lose!");
}
else if (myChoice == "paper")
{
alert("You win!");
}
}
else if (compChoice == "paper")
{
if (myChoice == "rock")
{
alert("You lose!");
}
else if (myChoice == "scissors")
{
alert("You win!");
}
}
else if (compChoice == "scissors")
{
if (myChoice == "rock")
{
alert("You win!");
}
else if (myChoice == "paper")
{
alert("You lose!");
}
}
again = prompt("Would you like to play again?(yes/no)");
}while (again == "yes");
Demo: Fiddle
Upvotes: 2
Reputation: 10718
One major issue is that you are assigning values instead of comparing values in multiple places.
a = 2 // assigns a to value 2, and evaluates to true
a == 2 // compares a to 2, only evaluates to true if a has value 2
Upvotes: 1