I created cpuPlay to call either rock, paper, or scissors, whenever a random number between 0-2 is called. This function works properly, but rps() is the function that I can't seem to build properly after 3 days of doing this. No matter how I build this, it seems I keep on getting one of four answers when I call rps(). The answers I get are either 'rock','paper','scissors','undefined'.
Before I thought it was because I used .toLowerCase() on playerChoice, but either way, this function has been giving the same results. If you keep on running rps('paper'), it eventually shows. I'm not sure how I should go any further with this problem, or maybe I'm not supposed to be able to compare. I don't even know anymore.
function cpuPlay(){
let numberGen = Math.floor(Math.random() * 3)
if (numberGen === 0){
return 'rock'
}
if (numberGen === 1){
return 'paper'
}
if (numberGen === 2){
return 'scissors'
}
}
// cpuPlay()
function rps(playersChoice){
if(playersChoice == 'paper' && cpuPlay() == 'rock'){
console.log('rock')
} else if (playersChoice == 'paper' && cpuPlay() == 'paper'){
console.log('paper')
} else if (playersChoice == 'paper' && cpuPlay() == 'scissors'){
console.log('scissors');
}
}
rps('paper')
You are calling cpuPlay() in each expression so it is possible that every conditional fails, because cpuPlay() value is changing, you can try this:
function cpuPlay(){
let numberGen = Math.floor(Math.random() * 3)
if (numberGen === 0){
return 'rock'
}
if (numberGen === 1){
return 'paper'
}
if (numberGen === 2){
return 'scissors'
}
}
function rps(playersChoice){
let currentCpuPlay = cpuPlay()
if(playersChoice == 'paper' && currentCpuPlay == 'rock'){
console.log('rock')
} else if (playersChoice == 'paper' && currentCpuPlay == 'paper'){
console.log('paper')
} else if (playersChoice == 'paper' && currentCpuPlay == 'scissors'){
console.log('scissors');
}
}
rps('paper')
cpuPlay() generates a random value every time you call it.
You are generating a random value and comparing it to rock. Then you generate a new random value and compare it to paper. Then you generate a third random value and compare it to scissors.
You should generate the CPU player's response once, at the top of the comparison function and then compare that value each time.
function rps(playersChoice){
const cpuChoice = cpuPlay();
if(playersChoice == 'paper' && cpuChoice == 'rock'){
the cpuPlay() is returning random results at every if statement
so when in the first if and the result is not rock, it will jump to next statement again, then but at the second if, the cpuPlay() is returning different results, so end up your function has a chance to have no results.
function rps(playersChoice){
let cpuRoll = cpuPlay(); // only random once per game
if(playersChoice == 'paper' && cpuRoll == 'rock'){
console.log('rock')
} else if (playersChoice == 'paper' && cpuRoll == 'paper'){
console.log('paper')
} else if (playersChoice == 'paper' && cpuRoll == 'scissors'){
console.log('scissors');
}
}