Home > Blockchain >  javascript function returns the same value when its supposed to be random
javascript function returns the same value when its supposed to be random

Time:10-29

when i call function game() it keeps returning the same value from computerSelection even when i have it set to return a random value. when i call computerPlay() by itself it will give random value each time its called but not when its used in the game() function under the variable computerSelection.

  function computerPlay() {
  const plays = ["rock", "paper", "scissors"];
  return plays[Math.floor(Math.random() * plays.length)];
};



function playRound(playerSelection, computerSelection) {
  if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
    console.log('paper beat rock')
    return ('paper beats rock')
  } else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'rock') {
    console.log('its a tie, try again!')
    return ('its a tie, try again!')
  } else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
    console.log('rock beats scissors')
    return ('rock beats scissors')
  } else {
    console.log('wut')
  }
};

function game() {
      playRound(playerSelection, computerSelection);
      playRound(playerSelection, computerSelection);
};



const playerSelection = "Rock";
let computerSelection = computerPlay();

CodePudding user response:

You should call computerPlay() once for each playRound(). So try this:

function game() {
      playRound(playerSelection, computerPlay());
      playRound(playerSelection, computerPlay());
};
  • Related