Parham
Parham

Reputation: 224

Rock, Paper, Scissors game: the loop in my code keeps giving me the same random result

I am creating a rock, paper, scissors games and just testing out my unfinished code. The game is between the user and the computer.

As you can see, computerSelection will generate a random "rock", "paper", or "scissors". The issue is that without refreshing the page, every time I type "rock" in the prompt and hit OK, I get the same console.log message in a loop: "Good job! Rock Beats Scissors" or "Sorry! paper beats Rock". In other words, the game has become one-sided; every time I type in "rock" and hit OK, either I always win or the computer always wins.

UPDATE: I have revised my code, but another issue I have is that sometimes the code repeats in console.log, not adding any score. If you look at the screenshot, it has repeated the code 2 times, but did not add a score.

enter image description here

const playerSelection = ''
const computerSelection = computerPlay()
let computerScore = 0;
let playerScore = 0;
console.log(playRound(playerSelection, computerSelection))

function computerPlay(){
  let values = ['rock', 'paper', 'scissors'],
  valueToUse = values [Math.floor(Math.random()* values.length)];
  return valueToUse;
};

function playRound(playerSelection, computerSelection) {
  while(true){
    playerSelection = prompt ('Pick your poison');

    if (playerSelection.toLowerCase() === 'rock' && computerPlay() === 'paper'){
      computerScore += 1
      console.log('Sorry! Paper beats Rock')
    } 
    else if (playerSelection.toLowerCase() === 'rock'.toLowerCase() && computerPlay() === 'scissors'){
      playerScore += 1
      console.log('Good job! Rock beats Scissors');
    }
    else 
    {
      console.log('Please type Rock, Paper, or Scissors')
    }

  console.log (`User Selection: ${playerSelection.toUpperCase()} | Player Score: ${playerScore} 
Computer Selection: ${computerSelection.toUpperCase()} | Computer Score: ${computerScore}`);
  }
}

Upvotes: 0

Views: 630

Answers (1)

colourCoder
colourCoder

Reputation: 1452

The following changes to the code will make it work:

  1. Declaring computerSelection the same way as playerSelection.

New version:

const playerSelection = ''
const computerSelection = ''

Original version:

const playerSelection = ''
const computerSelection = computerPlay()
  1. Calling the function computerPlay() within the playRound(playerSelection, computerSelection) function, hence assigning a value to the computerSelection variable each time the player makes their pick, as well.

New version:

playerSelection= prompt ('Pick your...');
computerSelection = computerPlay();

Original version:

 playerSelection= prompt ('Pick your...');

(Disclaimer: I've tried to stay as close to the original code as possible.)

Upvotes: 2

Related Questions