-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
80 lines (67 loc) · 2.24 KB
/
app.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
let userScore=0;
let compScore=0;
const userScorePara=document.querySelector("#user-score");
const compScorePara=document.querySelector("#comp-score");
const choices=document.querySelectorAll(".choice");
const msg=document.querySelector("#msg");
const genCompChoice= () =>{
const options=["rock","paper","scissor"];
//randomly select array index
//math.floor-remove decimal
//math.random generates b/w 0and1 so to generate for 0,1,2 idx we do *3
const randIdx= Math.floor(Math.random()*3);
return options[randIdx];
}
const playGame=(userChoice) =>{
console.log("user choice =",userChoice);
//Generate computer choice
const compChoice=genCompChoice();
console.log("comp choice =",compChoice);
if (userChoice===compChoice){
drawGame();
}else{
let userWin=true;
if(userChoice==="rock"){
userWin=compChoice==="paper"?false:true;
}
//user clicked rock, comp has 2 opt paper or scissor.
//if comp chooses paper , user looses i.e. false
//if comp chooses scissor, user wins i.e. true.
else if (userChoice==="paper"){
userWin=compChoice==="scissor"?false:true;
}
else{
userWin=compChoice==="rock"?false:true;
}
//user has scissor
showWinner(userWin);
}
}
;
const drawGame=()=>{
console.log("Draw");
msg.innerText="Draw Game!";
msg.style.backgroundColor="blue";
};
const showWinner=(userWin,userChoice,compChoice)=>{
if(userWin){
userScore++;
userScorePara.innerText=userScore;
console.log("you win");
msg.innerText=`You Win! Your ${userChoice} beats ${compChoice}`;
msg.style.backgroundColor="green";
}else{
compScore++;
compScorePara.innerText=compScore;
console.log("you loose");
msg.innerText=`You Loose! ${compChoice} beats your ${userChoice}`;
msg.style.backgroundColor="red";
}
};
choices.forEach((choice) => {
choice.addEventListener("click",()=>{
const userChoice=choice.getAttribute("id");
// console.log("choice was clicked", userChoice);
playGame(userChoice);
});
});