-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame.js
99 lines (58 loc) · 2.17 KB
/
Game.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
let msg = document.querySelector("#msg");
let userScores = document.querySelector("#user-score");
let compScores = document.querySelector("#comp-score");
let userScore= 0;
let compScore= 0;
const choices = document.querySelectorAll(".choice");
// to create random computer's choice
const GenCompChoice = () =>{
let options = ["rock", "paper", "scissors"];
const randIdx = Math.floor(Math.random()*3 )// multiply with 3 to math.random() to get range from 0 to 2
return options[randIdx];
};
// action to be performed when game draw
const drawGame = () => {
msg.innerText= "The game is draw😒 Try Again";
};
// to show the winner
const showWinner =(userWin,compChoice) =>{
if (userWin===true) {
userScore++;
userScores.innerText = userScore
console.log("you are winner")
msg.innerText = `You Won Khushi!😁🥳Computer choosed ${compChoice}`;
}else{
compScore++;
compScores.innerText = compScore;
console.log("computer is winner")
msg.innerText = `Computer Won!😖 Computer choosed ${compChoice}`;
};
};
//conditions for playing the game
const playGame = (userChoice) =>{
console.log("users choice",userChoice);
//computer choice
const compChoice = GenCompChoice();
console.log("computer's choice" ,compChoice);
// to draw the game
if (userChoice === compChoice) {
drawGame();
}else{
let userWin = true;
if (userChoice=== "rock") {
userWin = compChoice==="paper"? false : true ;
}else if(userChoice=== "paper"){
userWin = compChoice==="scissors"? false : true;
}else if(userChoice=== "scissors"){
userWin = compChoice==="rock"? false : true;
}
showWinner(userWin,compChoice);
}
};
// for adding event listener when clicked
choices.forEach((choice)=> {
choice.addEventListener("click", ()=>{
const userChoice = choice.getAttribute("id");
playGame(userChoice);
})
});