+ 1

HELP, I'm trying to create a rockpaper scissors game out of only if-else statements

It only displays "you lose" no matter what. How can i fix that? <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> var rock; var paper; var scissors; var compVal; var choose = prompt("Enter 'r', 'p' or 's' to choose rock, paper or scissors respectively."); if (choose == "r" || choose == "p" || choose == "s") { compVal =(Math.random()*3 + 1); if (choose == "p" && compVal == 1) { alert("You win"); } else if (choose == "s" && compVal == 2) { alert("You win"); } else if (choose == "r" && compVal == 3) { alert("You win"); } else if (choose == "r" && compVal == 1) { alert("You tie"); } else if (choose == "p" && compVal == 2) { alert("You tie"); } else if (choose == "s" && compVal == 3) { alert("You tie"); } else { alert("You lose"); } } </script> </body> </html>

2nd Feb 2018, 3:31 PM
Tyrell Reid
Tyrell Reid - avatar
3 Respuestas
+ 1
Codecademy has the same challenge. Creating rock paper scissors. This is how it looks in a different way. Try to compare it and make your code work. var userChoice = prompt("Do you choose rock, paper or scissors?"); var computerChoice = Math.random(); if (computerChoice <0.34){ computerChoice = "rock"; }else if(computerChoice <=0.67){ computerChoice = "paper"; } else{ computerChoice = "scissors"; } var compare = function(choice1,choice2){ if(choice1===choice2){ return "The result is a tie!"; } if(choice1==="rock"){ if(choice2==="scissors"){ return "rock wins"; } else{ return "paper wins"; } } if(choice1==="paper"){ if(choice2==="rock"){ return "paper wins"; } else{ return "scissors wins"; } } if(choice1==="scissors"){ if(choice2==="rock"){ return "rock wins"; } else{ return "scissors wins"; } } }; compare(userChoice,computerChoice);
2nd Feb 2018, 3:38 PM
Christian Cuppers
Christian Cuppers - avatar
+ 1
(Why are you using Math.random like that?.. Math.random takes a number between 0 and 1....) You need to do this: 1:3. So you have 3 parts of 0.34. 0,34 for each type (rock, paper or scissor). You lose because : your code is not == 2 or ==1 or ==3. THE ERROR LIES IN DEFINING math.Random
2nd Feb 2018, 3:47 PM
Christian Cuppers
Christian Cuppers - avatar
0
I haven't learned functions yet unfortunately so I don't know exactly what they do
4th Feb 2018, 5:32 AM
Tyrell Reid
Tyrell Reid - avatar