-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRockPaperScissorsGame.js
64 lines (59 loc) · 1.76 KB
/
RockPaperScissorsGame.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
let myChoose;
let computerChoose;
let dataFromApi;
let winner;
let scoreUser = 0;
let scoreComputer = 0;
let result = document.querySelector(".result");
async function fetchData() {
try {
const response = await fetch("./resultWin.json");
const data = await response.json();
if (!response.ok) {
throw new Error("failed to get data from api");
}
return data;
} catch (error) {
console.log(error);
}
}
function ChooseRandom() {
let allChooser = ["rock", "paper", "scissors"];
let computerRandomChoose = allChooser[Math.round(Math.random() * 2)];
return computerRandomChoose;
}
Array.from(document.querySelector(".move").children).forEach((ele) => {
ele.addEventListener("click", async (e) => {
const data = await fetchData();
myChoose = e.target.className;
computerChoose = ChooseRandom();
desicdeWinner(data);
if (winner == myChoose) {
document.querySelector(
".score span.yourScore"
).innerText = `${++scoreUser}`;
document.querySelector("span.result").innerText = `User Is Winner`;
} else if (winner == computerChoose) {
document.querySelector(
".score span.computerScore"
).innerText = `${++scoreComputer}`;
document.querySelector("span.result").innerText = `computer Is Winner`;
} else {
result.innerText = winner;
}
document.querySelector(".chooser span.user").innerText = `${myChoose}`;
document.querySelector(
".chooser span.computer"
).innerText = `${computerChoose}`;
});
function desicdeWinner(data) {
data.forEach((ele) => {
if (
(ele.choose1 == myChoose && ele.choose2 == computerChoose) ||
(ele.choose2 == myChoose && ele.choose1 == computerChoose)
) {
winner = ele.win;
}
});
}
});