vendredi 19 février 2021

Why is my rock/paper/scissors game getting the same random number for multiple function calls?

I have made a functioning (if possibly extremely verbose) game of rock/paper/scissors.

If I run the game by calling the function once over and over the 'computer's' choice is properly randomised and therefore the outcome of the game is as intended. However if I call the function thrice at once, with "rock", "paper" and "scissors" as my guesses, the computer's choice is randomised, but the same choice is applied to all three calls to the function.

Thank you in advance. Here's the problemo...

JS:

const choices = ["rock", "paper", "scissors"];

const randChoice = Math.floor(Math.random() * choices.length);

const compChoice = choices[randChoice];

const playGame = (you, comp) => {
  if (you === "paper" && comp === "rock") {
    console.log(you + " beats " + comp + ". YOU WIN!")
  } else if (you === "rock" && comp === "paper") {
    console.log(comp + " beats " + you + ". YOU LOSE!")
  } else if (you === "rock" && comp === "scissors") {
    console.log(you + " beats " + comp + ". YOU WIN!")
  } else if (you === "scissors" && comp === "rock") {
    console.log(comp + " beats " + you + ". YOU LOSE!")
  } else if (you === "scissors" && comp === "paper") {
    console.log(you + " beats " + comp + ". YOU WIN!")
  } else if (you === "paper" && comp === "scissors") {
    console.log(comp + " beats " + you + ". YOU LOSE!")
  } else if (you === comp) {
    console.log("You both chose " + you + ". That's a draw.")
  }
};

If I call the function once, the game works...

playGame("rock", compChoice);

If I call the function thrice, the computer's choice is the same for all three matches, therefore I will win, lose and draw every time, albeit in a random order...

playGame("rock", compChoice);
playGame("paper", compChoice);
playGame("scissors", compChoice);



Aucun commentaire:

Enregistrer un commentaire