-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
72 lines (63 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
const rock = document.getElementById('rock');
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const roundOutcome = document.getElementById('round-outcome');
const playerScore = document.getElementById('player-score');
const computerScore = document.getElementById('computer-score');
const endGameDiv = document.getElementById('end-game');
const endGameText = document.getElementById('end-game-text');
const restartButton = document.getElementById('restart');
rock.addEventListener('click', playRound);
paper.addEventListener('click', playRound);
scissors.addEventListener('click', playRound);
restartButton.addEventListener('click', restart);
function computerPlay () {
const choices = ['rock', 'paper', 'scissors'];
return choices[Math.floor(Math.random() * choices.length)];
}
function playRound(e) {
let result = 'loss';
const playerSelection = e.target.id;
const computerSelection = computerPlay();
if (computerSelection == 'rock' && playerSelection == 'paper') result = 'win';
else if (computerSelection == 'paper' && playerSelection == 'scissors') result = 'win';
else if (computerSelection == 'scissors' && playerSelection == 'rock') result = 'win';
else if (computerSelection == playerSelection) result = 'tie';
if (result == 'loss') {
roundOutcome.innerText = `You lose! ${capitalizeFirstLetter(computerSelection)} beats ${playerSelection}!`;
updateScore(computerScore);
}
else if (result == 'tie') {
roundOutcome.innerText = `Tie! You both threw ${computerSelection}!`;
}
else {
roundOutcome.innerText = `You win! ${capitalizeFirstLetter(playerSelection)} beats ${computerSelection}!`;
updateScore(playerScore);
}
}
function updateScore(winner) {
score = winner.innerText;
score++;
winner.innerText = score;
if (score >= 5) endGame();
}
function endGame() {
if (playerScore.innerText > computerScore.innerText) endGameText.innerText = 'You win! Yay :)';
else endGameText.innerText = 'You lose! Boo hoo :(';
endGameDiv.style['display'] = 'block';
rock.disabled = true;
paper.disabled = true;
scissors.disabled = true;
}
function restart() {
playerScore.innerText = 0;
computerScore.innerText = 0;
rock.disabled = false;
paper.disabled = false;
scissors.disabled = false;
roundOutcome.innerText = '';
endGameDiv.style['display'] = 'none';
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}