I’m trying to create a rock, paper and scissors game using JavaScript, in the game I need to get a user choice (rock, paper or scissors) and a random computer choice (rock, paper or scissors), compare these choices and show a winner. But I can’t get the user choice to compare with the computer choice.
I create a function getUserChoice() with a prompt to get a user choice and use the choice inside the function playRound () but the program don’t show the prompt on the scream.
How can I fix this? and if I fix this the app will work?
<script>
function getUserChoice() {
let userChoice = window.prompt('rock, paper or scissors?')
}
function getComputerChoice() {
let computerChoice = Math.random;
if (computerChoice < 0.34){return 'rock';}
else if (computerChoice <= 0.67){return 'paper';}
else {return 'scissors';}
}
function playRound(userChoice , computerChoice) {
const playerSelection = getUserChoice();
const computerSelection = getComputerChoice();
if (playerSelection === 'rock' && computerSelection === 'scissors') {
console.log('You win! Rock beats Scissors')
}
else if (playerSelection === 'scissors' && computerSelection === 'paper') {
console.log('You win! Scissors beats Paper')
}
else if(playerSelection === 'paper' && computerSelection === 'rock') {
console.log('You win! Paper beats Rock')
}
else if(playerSelection === 'scissors' && computerSelection === 'rock') {
console.log('You lose! Rock beats Scissors')
}
else if(playerSelection === 'paper' && computerSelection === 'scissors') {
console.log('You lose! Scissors beats Paper')
}
else if (playerSelection === 'rock' && computerSelection === 'paper') {
console.log('You lose! Paper beats Rock')
}
else {
console.log('Tie')
}
}
</script>
2
Answers
Functions return
undefined
by default. To return another value, use explicit return statement.Then don’t forget to excute
playRound(getUserChoice(), getComputerChoice())
when a round starts.Ok there are 3 issues here.
first of all
getUserChoice
doesn’t return anything.secondly you haven’t called
Math.random
ingetComputerChoice
but made a reference to thatMath.random
method.and lastly you haven’t called the
playRound()
function.so if we fix these issues, your code should work just fine.