-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
89 lines (66 loc) · 2.73 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
const rockBtn = document.getElementById("rock");
const paperBtn = document.getElementById("paper");
const scissorsBtn = document.getElementById("scissors");
const resultText = document.getElementById("result");
const roundText = document.getElementById("round");
const userScoreText = document.getElementById("user-score");
const computerScoreText = document.getElementById("computer-score");
//event listeners for button clicks clacks;
rockBtn.addEventListener("click", function(){
playRound("rock");
});
paperBtn.addEventListener("click", function(){
playRound("paper");
});
scissorsBtn.addEventListener("click", function(){
playRound("scissors");
});
// Initialize round counter and scores
let round = 0;
let userScore = 0;
let computerScore = 0;
//game logic
function playRound(userChoice){
//generate computer's choice : rock paper or scissors
const choices = ["rock", "paper", "scissors"];
const computerChoice = choices[Math.floor(Math.random() * choices.length)];
//determine the winner
let result;
if (userChoice == computerChoice) {
result = "It's a TIE!";
} else if (
(userChoice == "rock" && computerChoice == "scissors") ||
(userChoice == "paper" && computerChoice == "rock") ||
(userChoice == "scissors" && computerChoice == "paper")
) {
result = " K.O. You win!";
userScore++;
} else {
result = "Computer wins! Better luck next time."
computerScore++;
}
//display the result
resultText.textContent = "You choose " + userChoice + " . " + " Computer chose " + computerChoice + " . " + result;
//update scores
userScoreText.textContent = "Your Score: " + userScore;
computerScoreText.textContent = "Computer's Score: " + computerScore;
//check for the end of the game
if (userScore === 5 || computerScore === 5) {
//determine the final winner
let finalResult;
if(userScore > computerScore) {
finalResult = "You win the game, good job!";
}else if (userScore < computerScore) {
finalResult = "Computer wins the game!";
} else{
finalResult = "It's a TIE!!!";
}
//Display the final result
resultText.textContent = "GAME OVER! " + finalResult;
resultText.classList.add("show");
// Disable button clicks
rockBtn.disabled = true;
paperBtn.disabled = true;
scissorsBtn.disabled = true;
}
}