Select all the elements in use with JavaScript and store them in variables.
const computerChoiceDisplay = document.getElementById('computer-choice')
const userChoiceDisplay = document.getElementById('user-choice')
const resultDisplay = document.getElementById('result')
const possibleChoices = document.querySelectorAll('button')
Store what user chose and what computer chose with their function + also store what result function output was
let userChoice
let computerChoice
let result
Select buttons in the HTML which were the 3 possible choices and add an event listener so whenever someone clicks on the button:
- The ID of the button is extracted
- ID is inputted to the display by adding it with the .innerHTML method so we know which item we clicked.
Now, add the function that generates the computer’s choice and also the result later, after the computer choice has been found out.
possibleChoices.forEach(possibleChoice => possibleChoice.addEventListener('click', (e) => {
userChoice = e.target.id
userChoiceDisplay.innerHTML = userChoice
generateComputerChoice()
getResult()
}))
Now, run the function which generates the computer’s choice.
Here we
- Pick a random number with the help of Math.random method.
- We have 3 numbers. We set values for each number. Example 1 === rock and so
on. - If the computer randomly picked 1, it’d be assigned to rock so we know the rock
was picked by the computer. - After everything, we assign the value of computerChoice variable to the
innerHTML of the display which is the heading.
function generateComputerChoice() {
const randomNumber = Math.floor(Math.random() * 3) + 1 // or you can use possibleChoices.length
if (randomNumber === 1) {
computerChoice = 'rock'
}
if (randomNumber === 2) {
computerChoice = 'scissors'
}
if (randomNumber === 3) {
computerChoice = 'paper'
}
computerChoiceDisplay.innerHTML = computerChoice
}
We now have value of what user chose and what computer chose and assigned all of it in variable. Now we will have to know what the result was i.e match computer and user’s answer and see who won and who lost and print it out on the screen.
We assign the result to the innerHTML of the display value so it gets displayed on our screen i.e get added in the HTML.
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
}