Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
Trouble with computer's selection in rock paper scissors game

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())

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!