-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
36 lines (32 loc) · 1.33 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const choices = ['rock', 'paper', 'scissors'];
const buttons = document.querySelectorAll('.choice');
const userChoiceDisplay = document.getElementById('user-choice').querySelector('span');
const computerChoiceDisplay = document.getElementById('computer-choice').querySelector('span');
const winnerDisplay = document.getElementById('winner').querySelector('span');
buttons.forEach(button => {
button.addEventListener('click', () => {
const userChoice = button.id;
const computerChoice = getComputerChoice();
const winner = getWinner(userChoice, computerChoice);
userChoiceDisplay.textContent = userChoice;
computerChoiceDisplay.textContent = computerChoice;
winnerDisplay.textContent = winner;
});
});
function getComputerChoice() {
const randomIndex = Math.floor(Math.random() * choices.length);
return choices[randomIndex];
}
function getWinner(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return 'It\'s a draw!';
} else if (
(userChoice === 'rock' && computerChoice === 'scissors') ||
(userChoice === 'paper' && computerChoice === 'rock') ||
(userChoice === 'scissors' && computerChoice === 'paper')
) {
return 'You win!';
} else {
return 'Computer wins!';
}
}