-
Notifications
You must be signed in to change notification settings - Fork 0
/
myscript.js
72 lines (61 loc) · 2.07 KB
/
myscript.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
const result = document.getElementById("result");
const rock = document.getElementById("rock");
const paper = document.getElementById("paper");
const scissors = document.getElementById("scissors");
const reset = document.getElementById("reset");
function convertToWord(word) {
if (word === "rock") return "Rock";
if (word === "paper") return "Paper";
if (word === "scissors") return "Scissors";
}
function getComputerChoice() {
const choices = ['rock', 'paper', 'scissors'];
const randomNumber = Math.floor(Math.random() * 3);
return choices[randomNumber];
}
function win(userChoice, computerChoice) {
result.innerHTML = convertToWord(userChoice) + " beats " + convertToWord(computerChoice) + ". You win!";
// THE ES6 WAY
//result.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)}. You win!`;
}
function lose(userChoice, computerChoice) {
result.innerHTML = convertToWord(userChoice) + " beats " + convertToWord(computerChoice) + "... You lose.";
}
function tie(userChoice, computerChoice) {
result.innerHTML = convertToWord(userChoice) + " ties " + convertToWord(computerChoice) + ". It's a draw.";
}
function game(userChoice) {
const computerChoice = getComputerChoice();
switch (userChoice + computerChoice) {
case "rockscissors":
case "paperrock":
case "scissorspaper":
win(userChoice, computerChoice);
break;
case "rockpaper":
case "paperscissors":
case "scissorsrock":
lose(userChoice, computerChoice);
break;
case "rockrock":
case "paperpaper":
case "scissorsscissors":
tie(userChoice, computerChoice);
break;
}
}
function main() {
rock.addEventListener("click", function () {
game("rock");
})
paper.addEventListener("click", function () {
game("paper");
})
scissors.addEventListener("click", function () {
game("scissors");
})
reset.addEventListener("click", function () {
window.location.reload();
})
}
main();