-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrock-paper-scissors.js
114 lines (89 loc) · 3.02 KB
/
rock-paper-scissors.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
102
103
104
105
106
107
108
109
110
111
112
113
114
function getComputerChoice() {
let choice = Math.floor(Math.random() * 3 + 1);
switch(choice){
case 1:
return("rock");
case 2:
return("paper");
case 3:
return("scissors");
};
};
// function getPlayerChoice() {
// const VALID = ["rock", "paper", "scissors"];
// let choice = "";
// while(!VALID.includes(choice)){
// choice = prompt("Choose Rock, Paper or Scissors").toLowerCase();
// if (!VALID.includes(choice)){
// alert("Invalid choice, please choose Rock, Paper or Scissors");
// };
// };
// return(choice);
// };
function playRound(playerSelection, computerSelection,) {
switch(playerSelection){
case "rock":
switch(computerSelection) {
case "rock":
return "Draw!";
case "paper":
return "Computer wins!";
case "scissors":
return "Player wins!";
};
case "paper":
switch(computerSelection) {
case "rock":
return "Player wins!";
case "paper":
return "Draw!";
case "scissors":
return "Computer wins!";
};
case "scissors":
switch(computerSelection) {
case "rock":
return "Computer wins!";
case "paper":
return "Player wins!";
case "scissors":
return "Draw!";
};
};
};
function game(playerSelection, score, round, results, buttons){
let computerSelection = "";
computerSelection = getComputerChoice();
result = playRound(playerSelection, computerSelection);
if (result == "Player wins!"){
score[0]++
} else if (result == "Computer wins!") {
score[1]++
}
results.innerHTML = "<p>Round " + (round) + ": Player chose " + playerSelection + " and Computer chose " + computerSelection + " , " + result + "</p>" +
"<p>Score is Player: " + score[0]+ " - Computer: " + score[1] + "</p>";
if (round == 5) {
if (score[0] > score[1]){
results.textContent = `Player wins the game ${score[0]} to ${score[1]}!`;
} else if (score[1] > score[0]){
results.textContent = `Computer wins the game ${score[1]} to ${score[0]}!`;
} else {
results.textContent = "It's a draw!";
}
document.getElementById("intro").remove();
buttons.forEach((button) => {
button.remove()
});
}
return score
};
const buttons = document.querySelectorAll('button');
let results = document.querySelector('#results');
results.setAttribute('style', 'white-space: pre;');
let score = [0 , 0], round = 0;
buttons.forEach((button) => {
button.addEventListener('click', () => {
round++;
score = game(button.id, score, round, results, buttons);
});
});