-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
101 lines (79 loc) · 2.9 KB
/
main.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
95
96
97
98
99
100
101
let playerScore = 0;
let computerScore = 0;
const buttons = document.querySelectorAll('button');
buttons.forEach((button) => {
button.addEventListener('click', function handlePressButtonEvent(event) {
// How do we get the player's selection?
let playerSelection = button.id;
const gameWinner = document.querySelector('#gameWinner');
gameWinner.textContent = '';
const playerSelectionPara = document.querySelector('#playerSelection')
playerSelectionPara.textContent = 'You selected ' + playerSelection;
let computerSelection = computerPlay();
const computerSelectionPara = document.querySelector('#computerSelection');
computerSelectionPara.textContent = 'Computer selected ' + computerSelection;
let winner = playRound(playerSelection, computerSelection);
let winnerText;
switch (winner) {
case 0:
winnerText = "You lose";
computerScore++;
break;
case 1:
winnerText = "It's a tie";
break;
case 2:
winnerText = "You win!";
playerScore++;
break;
}
const roundWinner = document.querySelector('#roundWinner');
roundWinner.textContent = winnerText;
const runningScore = document.querySelector('#runningScore');
runningScore.textContent = "Your score: " + playerScore + " Computer's score: " + computerScore;
// Check if the game is over
if (playerScore == 3 || computerScore == 3) {
// Figure out who won
let gameWinnerText;
if (playerScore > computerScore) {
gameWinnerText = 'Congrats you win the game!';
} else {
gameWinnerText = 'Sorry, computer wins.';
}
const gameWinner = document.querySelector('#gameWinner');
gameWinner.textContent = gameWinnerText;
playerScore = 0;
computerScore = 0;
}
});
});
// getting the computer's choices
function computerPlay() {
compChoice = Math.floor(Math.random() * 3) + 1;
switch (compChoice) {
case 1:
compChoice = 'rock';
break;
case 2:
compChoice = 'paper';
break;
case 3:
compChoice = 'scissors';
break;
}
return compChoice;
}
// finding a winner in each round of play
function playRound(playerSelection, computerSelection) {
if (playerSelection === 'rock' && computerSelection === 'scissors') {
return 2;
} else if (playerSelection === 'paper' && computerSelection === 'rock') {
return 2;
} else if (playerSelection === 'scissors' && computerSelection === 'paper') {
return 2;
} else if (playerSelection === computerSelection) {
return 1;
} else {
return 0;
}
}