-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrps.js
More file actions
99 lines (87 loc) · 2.85 KB
/
Copy pathrps.js
File metadata and controls
99 lines (87 loc) · 2.85 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
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 userScore=0;
let compScore=0;
let rounds=0;
const maxRounds=10;
const choices=document.querySelectorAll(".choice");
const msg=document.querySelector("#msg");
const userScorePara=document.querySelector(".p2");
const compScorePara=document.querySelector(".p4");
const roundCount=document.querySelector(".round");
const showResult=(userWin,userChoice,compChoice)=>{
if(userWin===true){
userScore++;
userScorePara.innerText=userScore;
msg.innerText=`You Won! Your ${userChoice} beats ${compChoice}`;
msg.style.backgroundColor="white";
msg.style.color="green";
}else{
compScore++;
compScorePara.innerText=compScore;
msg.innerText=`You Lost! ${compChoice} beats Your ${userChoice}`;
msg.style.backgroundColor="white";
msg.style.color="red";
}
}
const drawGame=()=>{
msg.innerText="DRAW GAME!!! Play Again";
msg.style.backgroundColor="white";
msg.style.color="grey";
}
const genCompChoice=()=>{
let options=["rock","paper","scissor"];
let ranIdx=Math.floor(Math.random() * 3);
return options[ranIdx];
}
const checkGameOver = () => {
if (rounds === maxRounds) {
if (userScore > compScore) {
msg.innerText = `Hurry! You Won 🏆 ${userScore} - ${compScore}`;
msg.style.backgroundColor = "green";
msg.style.color="white";
} else if (compScore > userScore) {
msg.innerText = `Computer Wins 😞 ${compScore} - ${userScore}`;
msg.style.backgroundColor = "red";
msg.style.color="white";
} else {
msg.innerText = `It's a Tie 🤝 ${userScore} - ${compScore}`;
msg.style.backgroundColor = "grey";
msg.style.color="white";
}
setTimeout(() => {
userScore = 0;
compScore = 0;
rounds = 0;
userScorePara.innerText = userScore;
compScorePara.innerText = compScore;
msg.innerText = "New Game! Play Again.";
msg.style.backgroundColor = "black";
}, 3000);
}
};
const playGame=(userChoice)=>{
if(rounds<maxRounds){
const compChoice= genCompChoice();
if(userChoice===compChoice){
drawGame();
} else {
let userWin=true;
if(userChoice==="rock"){
userWin=compChoice === "paper"?false:true;
} else if(userChoice==="paper"){
userWin=compChoice === "scissor"?false:true;
}else if(userChoice === "scissor"){
userWin=compChoice === "rock"?false:true;
}
showResult(userWin,userChoice,compChoice);
}
rounds++;
roundCount.innerText=`ROUND ${rounds} out of ${maxRounds}`;
checkGameOver();
}
}
choices.forEach((choice)=>{
choice.addEventListener("click",()=>{
let userChoice=choice.getAttribute("id");
playGame(userChoice);
});
});