I'm trying to write a simple game of rock paper scissors and I'm stuck at trying to get the game to run for 5 rounds. The computer chooses a value from an array at random but then it doesn't choose a new one on the reiteration of the loop. i.e. the computer chooses rock for round 1 then it remains rock for all 5 rounds. Can someone please explain what I'm doing wrong?
let myArray = ['rock', 'paper', 'scissors']
let randomValue = myArray[Math.floor(Math.random() * myArray.length)]
function computerPlay() {
return randomValue;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == computerSelection) {
console.log('It\'s a tie!')
return
} else if ((playerSelection == 'rock' && computerSelection == 'scissors') ||
(playerSelection == 'paper' && computerSelection == 'rock') ||
(playerSelection == 'scissors' && computerSelection == 'paper')) {
console.log('The human wins!');
console.log(playerScore += 1);
return
} else {
console.log('The computer wins!');
console.log(computerScore += 1);
return
}
}
let playerScore = parseInt(0);
let computerScore = parseInt(0);
function game() {
for (i = 0; i < 5; i++) {
let playerSelection = prompt('Choose your weapon');
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
console.log('Your score = ' + playerScore);
console.log('Computer\'s score = ' + computerScore);
}
}
console.log(game())
You need to move randomValue's definition to inside the computerPlay() function because every time computerPlay() is called, it is not generating a new value, but returning the pre-defined value calculated at the beginning of the program for randomValue. If you move it, then randomValue will be calculated and defined every time computerPlay() is called.
I recommend doing this instead:
let myArray = ['rock', 'paper', 'scissors']
function computerPlay() {
let randomValue = myArray[Math.floor(Math.random() * myArray.length)]
return randomValue;
}
{insert rest of code}