-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
68 lines (61 loc) · 1.91 KB
/
script.js
File metadata and controls
68 lines (61 loc) · 1.91 KB
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
let userScore = 0;
let compScore = 0;
const choices = document.querySelectorAll(".choice");
const msgs = document.querySelector("#msg");
const userScoreSpan = document.querySelector("#userscore");
const compScoreSpan = document.querySelector("#compscore");
// function for game win
const showWinner = ((userWin, userChoice, computerChoice) => {
if (userWin) {
userScore++;
userScoreSpan.innerHTML = userScore;
msgs.innerHTML = `You win!`;
msgs.style.backgroundColor = "green";
} else {
compScore++;
compScoreSpan.innerHTML = compScore;
msgs.innerHTML = `You lost.`;
msgs.style.backgroundColor = "red";
}
})
// function for draw game
const gameDraw = (() => {
msgs.innerHTML = "Game is draw. Play again!";
})
// function for computer choice
const getComputerChoice = (() => {
const choicesArray = ["rock", "paper", "scissors"];
const randomChoice = Math.floor(Math.random() * 3);
return choicesArray[randomChoice];
})
// play game function
const playGame = ((userChoice) => {
// get computer choice
const computerChoice = getComputerChoice();
// statements for playing games
if (userChoice === computerChoice) {
gameDraw();
} else {
let userWin = true;
if (userChoice === "rock"){
// paper, scissors
userWin = (computerChoice === "scissors") ? true : false;
}
else if (userChoice === "paper"){
// rock, scissors
userWin = (computerChoice === "rock") ? true : false;
}
else{
// rock, paper
userWin = (computerChoice === "paper") ? true : false;
}
showWinner(userWin, userChoice, computerChoice);
}
})
// main function
choices.forEach((choice) => {
choice.addEventListener("click", () => {
const userChoice = choice.getAttribute("id");
playGame(userChoice);
})
})