-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
98 lines (80 loc) · 2.8 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
95
96
97
98
let playerScore = 0;
let computerScore = 0;
let winningScore = 5;
const rock = document.querySelector("#rock");
const paper = document.querySelector("#paper");
const scissors = document.querySelector("#scissors");
const buttons = document.querySelectorAll("button");
const resultText = document.getElementById("resultText");
const score1 = document.getElementById("score1");
const score2 = document.getElementById("score2");
const disableButtons = () => {
buttons.forEach(button => {
button.disabled = true;
})
};
const getComputerChoice = () => {
let randomChoice = Math.floor(Math.random() * 3);
switch (randomChoice) {
case 0:
return "ROCK";
break;
case 1:
return "PAPER";
break;
case 2:
return "SCISSORS";
break;
};
};
const computerSelection = getComputerChoice();
const playRound = (playerSelection, computerSelection) => {
const win =
(playerSelection === "ROCK" && computerSelection === "SCISSORS") ||
(playerSelection === "PAPER" && computerSelection === "ROCK") ||
(playerSelection === "SCISSORS" && computerSelection === "PAPER");
if(playerSelection === computerSelection) {
return "It's a tie!";
}
if(win) {
playerScore++;
return "You win!";
} else {
computerScore++;
return "You lose!";
}
};
rock.addEventListener("click", function() {
const computerSelection = getComputerChoice();
const result = playRound("ROCK", computerSelection);
resultText.textContent = `${result} You chose ROCK and the computer chose ${computerSelection}.`;
finalScore();
checkGameResult();
});
paper.addEventListener("click", function() {
const computerSelection = getComputerChoice();
const result = playRound("PAPER", computerSelection);
resultText.textContent = `${result} You chose PAPER and the computer chose ${computerSelection}.`;
finalScore();
checkGameResult();
});
scissors.addEventListener("click", function() {
const computerSelection = getComputerChoice();
const result = playRound("SCISSORS", computerSelection);
resultText.textContent = `${result} You chose SCISSORS and the computer chose ${computerSelection}.`;
finalScore();
checkGameResult();
});
const finalScore = () => {
score1.textContent = `Your Score: ${playerScore}`;
score2.textContent = `Computer's Score: ${computerScore}`;
};
const checkGameResult = () => {
if (playerScore === winningScore) {
resultText.textContent = "Congratulations, you won the game! Refresh page to play again.";
disableButtons();
} else if (computerScore === winningScore) {
resultText.textContent = "Sorry, you lost the game! Refresh page to try again.";
disableButtons();
}
};