-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
94 lines (78 loc) · 2.52 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Generates random integer: 0 to max - 1
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
// Generates computer choice
function getComputerChoice() {
let computer = getRandomInt(3);
if (computer == 0) {
return 'ROCK';
} else if (computer == 1) {
return 'PAPER';
} else {
return 'SCISSORS';
}
}
// Initializes a round
function playRound(playerSelection) {
let user = playerSelection;
let ai = getComputerChoice();
ui.textContent = `USER: ${user}`;
content.textContent = `AI: ${ai}`;
if (user == ai) {
tie.play();
score.textContent = `Its a tie! ${humanScore} - ${computerScore}`;
} else if (
(user === 'ROCK' && ai === 'PAPER') ||
(user === 'PAPER' && ai === 'SCISSORS') ||
(user === 'SCISSORS' && ai === 'ROCK')
) {
lose.play();
computerScore += 1;
score.textContent = `AI wins this round! ${humanScore} - ${computerScore}`;
} else {
win.play();
humanScore += 1;
score.textContent = `User wins this round! ${humanScore} - ${computerScore}`;
}
if (humanScore === 5 || computerScore === 5) {
rock.remove();
paper.remove();
scissors.remove();
const gameOver = document.createElement('p');
document.body.appendChild(gameOver);
if (humanScore === 5) {
won.play();
gameOver.textContent = 'YOU WON!';
} else {
lost.play();
gameOver.textContent = 'GAME OVER!';
}
const replay = document.createElement('button');
document.body.appendChild(replay);
replay.textContent = 'PLAY AGAIN';
replay.addEventListener('click', () => location.reload());
}
}
let humanScore = 0;
let computerScore = 0;
const ui = document.querySelector('.description');
const content = document.querySelector('.content');
const score = document.querySelector('.score');
const rock = document.querySelector('#rock');
const paper = document.querySelector('#paper');
const scissors = document.querySelector('#scissors');
const won = document.querySelector('#won');
const lost = document.querySelector('#lost');
const win = document.querySelector('#win');
const lose = document.querySelector('#lose');
const tie = document.querySelector('#tie');
rock.addEventListener('click', () => {
playRound('ROCK');
});
paper.addEventListener('click', () => {
playRound('PAPER');
});
scissors.addEventListener('click', () => {
playRound('SCISSORS');
});