This repository has been archived by the owner on Mar 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
100 lines (82 loc) · 2.51 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
96
97
98
99
100
/*
GAME FUNCTION:
- Player must guess a number between a min and max
- Player gets a certain amount of guesses
- Notify player of guesses remaining
- Notify the player of the correct answer if loose
- Let player choose to play again
*/
// Game values
let min = 1,
max = 10,
winningNum = getRandomNum(min, max),
guessesLeft = 3;
// UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessBtn = document.querySelector('#guess-btn'),
guessInput = document.querySelector('#guess-input'),
message = document.querySelector('.message');
// Assign UI min and max
minNum.textContent = min;
maxNum.textContent = max;
// Play again event listener
game.addEventListener('mousedown', function (e) {
if (e.target.className === 'play-again') {
window.location.reload();
}
});
// Listen for guess
guessBtn.addEventListener('click', function () {
let guess = parseInt(guessInput.value);
// Validate
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a number between ${min} and ${max}`, 'red');
}
// Check if won
if (guess === winningNum) {
// Game over - won
gameOver(true, `${winningNum} is correct, YOU WIN!`);
} else {
// Wrong number
guessesLeft -= 1;
if (guessesLeft === 0) {
// Game over - lost
gameOver(false, `Game Over, you lost. The correct number was ${winningNum}`);
} else {
// Game continues - answer wrong
// Change border color
guessInput.style.borderColor = 'red';
// Clear Input
guessInput.value = '';
// Tell user its the wrong number
setMessage(`${guess} is not correct, ${guessesLeft} guesses left`, 'red');
}
}
});
// Game over
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
// Disable input
guessInput.disabled = true;
// Change border color
guessInput.style.borderColor = color;
// Set text color
message.style.color = color;
// Set message
setMessage(msg);
// PLay Again?
guessBtn.value = 'Play Again';
guessBtn.className += 'play-again';
}
// Get Winning Number
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// Set message
function setMessage(msg, color) {
message.style.color = color;
message.textContent = msg;
}