0

I'm working through the OdinProject but I'm stuck on the rock paper scissors assignment. The game looks fine on the browser but the instructions from the JS file don't seem to make it over.

I have tried moving the files to a different directory, renaming the JS file, and putting the source code in multiple parts of the file. I have also used the debugger in the development tools. The debugger says "redelaration of userChoice" and a google search of this error suggests renaming the variable, but I am not sure why that is necessary if this is the first declaration.

Here is the code HTML

<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js'></script>
<script type='text/javascript' src="script.js"></script>
<title>Rock Paper Scissors</title>
</head>
<body>
    
<h2>Computer Choice: <span id="computer-choice"></span></h2>
<h2>Your Choice: <span id="user-choice"></span></h2>
<h2>Result: <span id="result"></span></h2>

<button id="rock">rock</button>
<button id="paper">paper</button>
<button id="scissors">scissors</button>

   

        
</body>
</html>

And the JS file

const userChoiceDisplay = document.getElementById('user-choice')
const resultDisplay = document.getElementById('result')
const possibleChoices = document.querySelectorAll('button')

let userChoice
let computerChoice
let result

possibleChoices.forEach(possibleChoice => possibleChoice.addEventListener('click', (e) => {
  userChoice = e.target.id
  userChoiceDisplay.innerHTML = userChoice
  generateComputerChoice()
  getResult()
}))

function getResult() {
    if (computerChoice === userChoice) {
      result = 'its a draw!'
    }
    if (computerChoice === 'rock' && userChoice === "paper") {
      result = 'you win!'
    }
    if (computerChoice === 'rock' && userChoice === "scissors") {
      result = 'you lost!'
    }
    if (computerChoice === 'paper' && userChoice === "scissors") {
      result = 'you win!'
    }
    if (computerChoice === 'paper' && userChoice === "rock") {
      result = 'you lose!'
    }
    if (computerChoice === 'scissors' && userChoice === "rock") {
      result = 'you win!'
    }
    if (computerChoice === 'scissors' && userChoice === "paper") {
      result = 'you lose!'
    }
    resultDisplay.innerHTML = result
}

Thank you for your help!

1 Answers1

1

The function generateComputerChoice() is undefined.

You can try this function:

function generateComputerChoice() {
  const choices = ["rock", "paper", "scissors"];
  const selection = Math.round(Math.random() * 2);
  computerChoice = choices[selection];
}

codepen link: https://codepen.io/Labnan/pen/NWaEzQW

Labnan
  • 76
  • 4