-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
58 lines (57 loc) · 1.89 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
let userScore = 0;
let compScore =0;
const choices = document.querySelectorAll(".choice");
let msg = document.querySelector("#msg");
const userScorePara = document.querySelector("#user-score");
const compScorePara = document.querySelector("#comp-score");
const genCompchoice = () => {
const options = ["rock","paper","scissors"];
const randId = Math.floor(Math.random()*3);
return options[randId];
}
const drawGame= () => {
console.log("Game was draw.");
msg.innerText = "Game was draw.";
msg.style.backgroundColor = "Black" ;
};
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{
console.log("You lose")
compScore++;
compScorePara.innerText = compScore;
msg.innerText = `You lost. ${compChoice} beats your ${userChoice}`;
msg.style.backgroundColor = "red";
}
}
const playGame = (userChoice) => {
console.log("User choice =", userChoice);
//generate computer choice
const compChoice = genCompchoice();
console.log("Computer choice =",compChoice);
if(userChoice===compChoice){
drawGame();
}else{
let userWin = true;
if(userChoice==="rock"){
userWin = compChoice === "paper"? false : true;
}else if(userChoice==="scissors"){
userWin = compChoice==="scissor"? false : true;
}else{
userWin = compChoice=== "rock"?false:true;
}
showWinner(userWin, userChoice, compChoice);
}
};
choices.forEach((choice) =>{
choice.addEventListener("click", () =>{
const userId =choice.getAttribute("id");
playGame(userId);
});
});