-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
62 lines (55 loc) · 1.67 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
let userScore=0;
let compScore=0;
const choices=document.querySelectorAll(".choice");
const msgP=document.querySelector("#msg");
const userScoreP=document.querySelector("#user-score");
const compScorep=document.querySelector("#comp-score");
const genCompChoice=()=>{
const option=["rock","paper","scissors"];
const randIdx=Math.floor(Math.random()*3);
return option[randIdx];
}
const drawn=()=>{
console.log("The game is drawn");
msgP.innerText="Game is Drawn";
msgP.style.backgroundColor="#99BC85";
}
const showWinner=(userWin,userChoice,compChoice)=>{
if(userWin){
userScore++;
userScoreP.innerText=userScore;
msgP.innerText=`YOU WON!.Your ${userChoice} beats ${compChoice}`;
msgP.style.backgroundColor="green";
}else{
compScore++;
compScorep.innerText=compScore;
msgP.innerText=`YOU LOSE!.${compChoice} beats your ${userChoice}`;
msgP.style.backgroundColor="red";
}
};
const playGame=(userChoice)=>{
console.log("users choice =",userChoice);
//generate computer choice
const compChoice=genCompChoice();
console.log("Computers choice =",compChoice);
//check winnner
if(userChoice===compChoice){
drawn();
}else{
let userWin=true;
if(userChoice==='rock'){
userWin=compChoice==='paper'?false:true;
}else if(userChoice==='paper'){
userWin=compChoice==='scissors'?false:true;
}else{
userWin=compChoice==="rock"?false:true;
}
showWinner(userWin,userChoice,compChoice);
}
};
choices.forEach((choice)=>{
choice.addEventListener("click",()=>{
const userChoice=choice.getAttribute("id");
playGame(userChoice);
})
})