-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
56 lines (52 loc) · 1.83 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
// return randomly rock paper or scissors
let computerPlay = () => {
const options = ["Rock", "Paper", "Scissors"];
const random = Math.floor(Math.random() * options.length);
return options[random];
};
let playerScore = 0;
let computerScore = 0;
let winner;
// take two parameters
let playRound = (playerSelection, computerSelection) => {
playerSelection = playerSelection.toUpperCase();
computerSelection = computerSelection.toUpperCase();
console.log("Player: " + playerSelection);
console.log("Computer: " + computerSelection);
// compare player selection and computer selection
if (playerSelection === computerSelection) {
return "Draw!";
}
switch (playerSelection) {
case "ROCK":
winner = computerSelection === "PAPER" ? "Computer" : "Player";
break;
case "PAPER":
winner = computerSelection === "SCISSORS" ? "Computer" : "Player";
break;
case "SCISSORS":
winner = computerSelection === "ROCK" ? "Computer" : "Player";
break;
}
if (winner === "Player") {
playerScore++;
return "You win! " + playerSelection + " beats " + computerSelection;
} else if (winner === "Computer") {
computerScore++;
return "You lose! " + computerSelection + " beats " + playerSelection;
}
};
const buttons = document.querySelectorAll("button");
const thisRoundResult = document.querySelector("h2");
const standings = document.querySelector("h3");
const winnerAnnouncement = document.querySelector("h4");
buttons.forEach((button) => {
button.addEventListener("click", function () {
thisRoundResult.textContent = playRound(this.textContent, computerPlay());
standings.textContent =
"Player: " + playerScore + " Computer: " + computerScore;
if (playerScore >= 5 || computerScore >= 5) {
winnerAnnouncement.textContent = winner + " wins the game!";
}
});
});