-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
90 lines (71 loc) · 2.54 KB
/
script.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
'use strict';
(function () {
let secretNumber, score, highscore, isPlaying;
const init = function () {
score = 20;
isPlaying = true;
secretNumber = Math.trunc(Math.random() * 20) + 1;
highscore = localStorage.highscore ? Number(localStorage.highscore) : 0;
setHighScore(highscore);
}
const displayMessage = function (message) {
document.querySelector('.message').textContent = message;
};
const changeNumNBody = function (number, width, color) {
document.querySelector('.number').textContent = number;
document.querySelector('.number').style.width = width;
document.querySelector('body').style.backgroundColor = color;
};
const setHighScore = function (sc) {
highscore = sc;
document.querySelector('.highscore').textContent = highscore;
localStorage.highscore = highscore;
}
// Check Button Click Event
document.querySelector('.check').addEventListener('click', function () {
const guess = Number(document.querySelector('.guess').value);
if (isPlaying) {
// When there is no input
if (!guess) {
displayMessage('⛔️ No number!');
// Check for Range
} else if (guess < 1 || guess > 20) {
displayMessage('🙂 Number Out Of Range');
// When player wins
} else if (guess === secretNumber) {
displayMessage('🎉 Correct Number!');
changeNumNBody(secretNumber, '30rem', '#60b347');
isPlaying = false;
if (score > highscore) {
setHighScore(score);
}
// When guess is wrong
} else if (guess !== secretNumber) {
if (score > 4) {
displayMessage(guess > secretNumber ? '📈 Too high!' : '📉 Too low!');
score -= 4;
document.querySelector('.score').textContent = score;
} else {
displayMessage('💥 You lost the game!');
changeNumNBody('?', '30rem', '#c00');
document.querySelector('.score').textContent = 0;
isPlaying = false;
}
}
}
});
// Again Button Click Event
document.querySelector('.again').addEventListener('click', function () {
score = 20;
isPlaying = true;
secretNumber = Math.trunc(Math.random() * 20) + 1;
displayMessage('Start guessing...');
document.querySelector('.score').textContent = score;
document.querySelector('.guess').value = '';
changeNumNBody('?', '15rem', '#222');
});
// Reset Button Click Event
document.querySelector('.reset').addEventListener('click', setHighScore.bind(this, 0));
// Initialize
init();
})();