-
Notifications
You must be signed in to change notification settings - Fork 0
/
javascript.js
99 lines (78 loc) · 2.55 KB
/
javascript.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
function getComputerChoice() {
let a = Math.random() * 3;
switch (true) {
case a >= 2:
return 'rock';
break;
case a >= 1:
return 'paper';
break;
case a >= 0:
return 'scissors';
break;
}
}
function playRound(playerSelection, computerSelection) {
let win_array = [[0, 1, 2],
[2, 0, 1],
[1, 2, 0]];
let p, c;
if (playerSelection === 'rock') {
p = 0;
} else if (playerSelection === 'paper') {
p = 1;
} else if (playerSelection === 'scissors') {
p = 2;
}
if (computerSelection === 'rock') {
c = 0;
} else if (computerSelection === 'paper') {
c = 1;
} else if (computerSelection === 'scissors') {
c = 2;
}
if (win_array[p][c] === 0) {
return 'tie';
} else if (win_array[p][c] === 1) {
return 'lose';
} else {
return 'win';
}
}
const pScore = document.querySelector('#player-score');
const cScore = document.querySelector('#computer-score');
const msg = document.querySelector('#msg')
const res = document.querySelector('#game-result');
const retryButton = document.querySelector('#play-again');
function play(e) {
let computerChoice = getComputerChoice();
let playerChoice = (e.target.alt).toLowerCase();
if (pScore.textContent !== '3' && cScore.textContent !== '3') {
if (playRound(playerChoice, computerChoice) === 'win') {
pScore.textContent++;
msg.textContent = `WIN, computer picked ${computerChoice}`;
} else if (playRound(playerChoice, computerChoice) === 'lose') {
cScore.textContent++;
msg.textContent = `LOSE, computer picked ${computerChoice}`;
} else {
msg.textContent = `TIE, computer picked ${computerChoice}`;
}
}
if (pScore.textContent === '3') {
res.innerHTML = 'You Won!';
retryButton.innerHTML = '<button id="play-again-button">play again?</button>';
} else if (cScore.textContent === '3') {
res.innerHTML = 'You Lost!';
retryButton.innerHTML = '<button id="play-again-button">play again?</button>';
}
}
function restart(e) {
msg.textContent = `START!`;
pScore.textContent = '0';
cScore.textContent = '0';
res.innerHTML = '';
retryButton.innerHTML = '';
}
let buttons = document.querySelectorAll('.button');
buttons.forEach(button => button.addEventListener('click', play));
retryButton.addEventListener('click', restart);