i mad a rockpaperscissors program (the code below) that logs user input, cmoputer choice and then compares to get the result. the comparing part doesn't work for some reason it always logs "It's a tie", can someone help.
the code:
let playerSelection = choice();
function choice(){
let input = prompt("pick either rock,paper or scissors");
console.log(input.toLowerCase());
}
let computerChoice = computerPlay();
function computerPlay(){
let picks =["rock","paper","scissors"];
let pick = picks[Math.floor(Math.random(picks)*picks.length)];
console.log (pick);
}
function compare(playerSelection, computerChoice){
if(playerSelection === computerChoice){
console.log("It's a tie!")
}
else if((playerSelection == "rock" && computerChoice == "scissors")||
(playerSelection == "paper" && computerChoice == "rock")||
(playerSelection == "scissors" && computerChoice == "paper")){
console.log("you win! computer lose.");
}
else{
console.log("computer win! you lose.");
}
}
compare();
}
function game(){
console.log(playRound());
}
game();```
You should pass playerSelection
and computerChoice
to the compare
function as parameters when you call the function:
compare(playerSelection, computerChoice);
Also you should return values from the choice()
and computerPlay()
function in order to have values assigned to player and computer. Example for computerPlay:
function computerPlay(){
let picks =["rock","paper","scissors"];
let pick = picks[Math.floor(Math.random(picks)*picks.length)];
return pick;
}
Here is a full snippet:
let playerSelection = choice();
function choice(){
let input = prompt("pick either rock,paper or scissors");
return input;
}
let computerChoice = computerPlay();
function computerPlay(){
let picks =["rock","paper","scissors"];
let pick = picks[Math.floor(Math.random(picks)*picks.length)];
return pick;
}
function compare(playerSelection, computerChoice){
if(playerSelection === computerChoice){
console.log("It's a tie!")
}
else if((playerSelection == "rock" && computerChoice == "scissors")||
(playerSelection == "paper" && computerChoice == "rock")||
(playerSelection == "scissors" && computerChoice == "paper")){
console.log("you win! computer lose.");
}
else{
console.log("computer win! you lose. ");
}
}
compare(playerSelection, computerChoice);