1

I am a beginner and have not been able to find a solution on Google for days. That is why I have come to Stack Overflow today and ask for support. Once again, please excuse if the code or my question isn't on a high level yet, I'm trying to get there.

The following code tells me that the variable playerSelection cannot be found. To see whether this value is generated at all, I built in console.log(playerSelection) and see that it is generated within this function.

I suspect that the variable playerSelection is only available within this function and cannot be found outside of this function. That's how I came up with this question: How can I make this variable accessible to the other function playRound?

var buttons = document.getElementsByClassName("button");

for (i of buttons) {
  i.addEventListener("click", function(e) {
    let playerSelection = e.srcElement.value;
    console.log(playerSelection);
    playRound();
  })
};

function computerPlay() {
  const shapes = ['rock', 'paper', 'scissors'];
  const random = Math.floor(Math.random() * shapes.length);
  console.log(shapes[random]);
};

let computerSelection = computerPlay();

function playRound() {
  if (playerSelection === computerSelection) {
    console.log("Tie! Repeat to break the tie");
  } else if (playerSelection === 'rock' && computerSelection === 'paper') {
    console.log("You Lose! Paper beats Rock");
  } else if (playerSelection === 'rock' && computerSelection === 'scissors') {
    console.log("You Win! Rock beats Scissors");
  } else if (playerSelection === 'paper' && computerSelection === 'rock') {
    console.log("You Win! Paper beats Rock");
  } else if (playerSelection === 'paper' && computerSelection === 'scissors') {
    console.log("You Lose! Scissors beats Paper");
  } else if (playerSelection === 'scissors' && computerSelection === 'rock') {
    console.log("You Lose! Rock beats Scissors");
  } else if (playerSelection === 'scissors' && computerSelection === 'paper') {
    console.log("You Win! Scissors beats Paper");
  } else {
    console.log("Invalid input! Please try again");
  }
};
<div class="buttons">
  <button class="button" value="rock">Rock</button>
  <button class="button" value="paper">Paper</button>
  <button class="button" value="scissors">Scissor</button>
</div>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

0
for (i of buttons) {
  i.addEventListener("click", function(e) {
    let playerSelection = e.srcElement.value;
    // playerSelection is in this function's scope.
    // To use it in another function, you need to
    // pass it as a parameter of the other function.
    // In this case: 
    playRound(playerSelection);
  })
};

function playRound(playerSelection) {
  // Your codes...
}
Bulent
  • 3,307
  • 1
  • 14
  • 22