-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
99 lines (84 loc) · 2.47 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
99
const rock = document.getElementById("rock");
const paper = document.getElementById("paper");
const scissors = document.getElementById("scissors");
const playerScoreElement = document.getElementById("score_a");
const computerScoreElement = document.getElementById("score_b");
const mappedOptions = {
rock: 1,
paper: 2,
scissors: 3,
};
let playerScore = 0;
let computerScore = 0;
let hasAlreadyPlayed = false;
let playerChoice;
let computerChoice;
window.onload = newGame();
function randomChoice() {
const randomChoice = Math.floor(Math.random() * 3) + 1;
for (let option in mappedOptions) {
if (mappedOptions[option] === randomChoice) {
computerChoice = option;
}
}
}
function pickOption(selectedOption) {
if (playerChoice === undefined) {
playerChoice = selectedOption;
if (selectedOption === "rock") {
rock.classList = "player";
} else if (selectedOption === "paper") {
paper.classList = "player";
} else {
scissors.classList = "player";
}
if (computerChoice === undefined) {
randomChoice();
while (computerChoice === playerChoice) {
randomChoice();
}
if (computerChoice === "rock") {
rock.classList = "computer";
} else if (computerChoice === "paper") {
paper.classList = "computer";
} else {
scissors.classList = "computer";
}
}
getWin(playerChoice, computerChoice);
} else {
alert("You already played!");
}
hasAlreadyPlayed = false;
}
function getWin(player, computer) {
if (hasAlreadyPlayed === true) {
if (player === "rock" && computer === "paper") {
computerScore++;
} else if (player === "rock" && computer === "scissors") {
playerScore++;
} else if (player === "paper" && computer === "scissors") {
computerScore++;
} else if (player === "paper" && computer === "rock") {
playerScore++;
} else if (player === "scissors" && computer === "rock") {
computerScore++;
} else if (player === "scissors" && computer === "paper") {
playerScore++;
}
playerScoreElement.innerHTML = playerScore;
computerScoreElement.innerHTML = computerScore;
}
}
function newGame() {
if (hasAlreadyPlayed === false) {
hasAlreadyPlayed = true;
playerChoice = undefined;
computerChoice = undefined;
rock.classList = "";
paper.classList = "";
scissors.classList = "";
playerScoreElement.innerHTML = playerScore;
computerScoreElement.innerHTML = computerScore;
}
}