-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
77 lines (68 loc) · 1.98 KB
/
game.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
let userScore = 0;
let computerScore = 0;
const rock = document.getElementById("rock");
const paper = document.getElementById("paper");
const scissors = document.getElementById("scissors");
const userChoice = document.getElementById("user-choice");
const updateBoard = document.getElementById("update-board");
const computerChoicedisplay = document.getElementById("computer-choice");
const computerScoreBoard = document.getElementById("computer-score");
const userScoreBoard = document.getElementById("user-score");
rock.addEventListener("click", () => runGame("Rock"));
paper.addEventListener("click", () => runGame("Paper"));
scissors.addEventListener("click", () => runGame("Scissors"));
function runGame(game) {
const computer = generateComputerChoice();
const gameResult = computeMatch(game, computer);
userChoice.innerText = game;
computerChoicedisplay.innerText = computer;
updateScore(gameResult);
}
function updateScore(result) {
switch (result) {
case "win":
updateBoard.innerText = "User Wins!";
userScore++;
userScoreBoard.innerText = userScore;
break;
case "loss":
updateBoard.innerText = "Computer Wins!";
computerScore++;
computerScoreBoard.innerText = computerScore;
break;
case "tie":
updateBoard.innerText = "Tie";
break;
default:
break;
}
}
function generateComputerChoice() {
const choices = ["Rock", "Paper", "Scissors"];
const result = choices[Math.floor(Math.random() * 3)];
return result;
}
function computeMatch(userChoice, computerChoice) {
const gameState = [
{
choice: "Rock",
Rock: "tie",
Paper: "loss",
Scissors: "win",
},
{
choice: "Paper",
Rock: "win",
Paper: "tie",
Scissors: "loss",
},
{
choice: "Scissors",
Rock: "loss",
Paper: "win",
Scissors: "tie",
},
];
const gameConditions = gameState.find(({ choice }) => choice === userChoice);
return gameConditions[computerChoice];
}