-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscriptp.js
More file actions
66 lines (57 loc) · 2.06 KB
/
scriptp.js
File metadata and controls
66 lines (57 loc) · 2.06 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
let userScore=0;
let computerScore=0;
const choices=document.querySelectorAll(".choice");
const msg=document.querySelector("#msg");
const userScoreParagraph = document.querySelector("#user-score");
const computerScoreParagraph = document.querySelector("#computer-score");
const genComputerChoice = () => {
const options=["rock", "paper", "scissors"];
const randIdx= Math.floor(Math.random() * 3);
return options[randIdx];
}
const drawGame =() =>{
console.log("game was drawn");
msg.innerHTML = "It's a draw!";
msg.style.backgroundColor = "black";
}
const showWinner = (userWin,userchoice,computerChoice) => {
if (userWin){
userScore++;
userScoreParagraph.innerHTML = userScore;
console.log("user wins");
msg.innerHTML = `You win! Your ${userchoice} beats computer's ${computerChoice}`;
msg.style.backgroundColor = "green";
}
else {
computerScore++;
computerScoreParagraph.innerHTML = computerScore;
console.log("computer wins");
msg.innerHTML = `Computer wins! ${computerChoice} beats your ${userchoice}`;
msg.style.backgroundColor = "red";
}
}
const playgame = (userchoice) =>{
console.log("user choice is", userchoice);
const computerChoice = genComputerChoice();
console.log("computer choice is", computerChoice);
if (userchoice==computerChoice){
drawGame();
} else {
let userWin = true;
if (userchoice=="rock"){
userWin=computerChoice=="paper" ? false : true;
} else if (userchoice=="paper"){
userWin=computerChoice=="scissors" ? false : true;
} else if (userchoice=="scissors"){
userWin=computerChoice=="rock" ? false : true;
}
showWinner(userWin,userchoice,computerChoice);
}
}
choices.forEach((choice) => {
console.log(choice);
choice.addEventListener("click",() => {
const userchoice=choice.getAttribute("id");
playgame(userchoice);
});
});