-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
95 lines (87 loc) · 2.35 KB
/
app.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const startGameBtn = document.getElementById('start-game-btn');
const ROCK = 'ROCK';
const PAPER = 'PAPER';
const SCISSORS = 'SCISSORS';
const DEFAULT_USER_CHOICE = ROCK;
const RESULT_DRAW = 'DRAW';
const RESULT_PLAYER_WINS = 'PLAYER_WINS';
const RESULT_COMPUTER_WINS = 'COMPUTER_WINS';
let gameIsRunning = false;
const getPlayerChoice = () =>
{
const selection = prompt(`${ROCK}, ${PAPER} or ${SCISSORS}?`).toUpperCase();
if(selection!==ROCK && selection!==PAPER && selection!==SCISSORS)
{
alert(`Invalid choice! We chose ${DEFAULT_USER_CHOICE} for you!`);
return DEFAULT_USER_CHOICE;
}
return selection;
}
const getComputerChoice = () =>
{
const randomValue = Math.random();
if(randomValue < 0.34)
{
return ROCK;
} else if(randomValue < 0.67)
{
return PAPER;
} else
{
return SCISSORS;
}
}
const getWinner = (cChoice, pChoice = DEFAULT_USER_CHOICE) =>
cChoice === pChoice ?
RESULT_DRAW
: (cChoice === ROCK && pChoice === PAPER) ||
(cChoice === PAPER && pChoice === SCISSORS) ||
(cChoice === SCISSORS && pChoice === ROCK)
? RESULT_PLAYER_WINS
: RESULT_COMPUTER_WINS;
// if(cChoice === pChoice)
// {
// return RESULT_DRAW;
// } else if(
// cChoice === ROCK && pChoice === PAPER ||
// cChoice === PAPER && pChoice === SCISSORS ||
// cChoice === SCISSORS && pChoice === ROCK
// )
// {
// return RESULT_PLAYER_WINS;
// } else
// {
// return RESULT_COMPUTER_WINS;
// }
startGameBtn.addEventListener('click', () =>
{
if(gameIsRunning)
{
return;
}
gameIsRunning = true;
console.log('Game is starting...');
const playerChoice = getPlayerChoice();
const computerChoice = getComputerChoice();
let winner;
if(playerChoice)
{
winner = getWinner(computerChoice, playerChoice);
} else
{
winner = getWinner(computerChoice, playerChoice);
}
let message = `You chose ${playerChoice}, computer chose ${computerChoice}. Therefore, you `;
if(winner === RESULT_DRAW)
{
message = message + 'had a draw.';
} else if(winner === RESULT_PLAYER_WINS)
{
message = message + 'won.';
} else
{
message = message + 'lost.';
}
alert(message);
gameIsRunning = false;
});