-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
60 lines (49 loc) · 1.71 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
'use strict';
let secretNumber = Math.trunc(Math.random() * 20) + 1;
let score = 20;
let highScore = 0;
function displayMessage(message) {
document.querySelector('.message').textContent = message;
}
function changeScore(score) {
document.querySelector('.score').textContent = score;
}
document.querySelector('.check').addEventListener('click', function () {
const guess = Number(document.querySelector('.guess').value);
// When there is no input
if (!guess) {
displayMessage('You need to enter a number! 😄');
// When the player wins
} else if (guess === secretNumber) {
displayMessage('You entered the correct number! 🎉');
document.querySelector('.number').textContent = secretNumber;
document.querySelector('body').style.backgroundColor = '#60b347';
document.querySelector('.number').style.width = '30rem';
if (score > highScore) {
highScore = score;
document.querySelector('.highscore').textContent = score;
}
// When the guess is wrong
} else if (guess !== secretNumber) {
if (score > 1) {
displayMessage(
guess > secretNumber ? 'Too high, try again!' : 'Too low, try again!'
);
score--;
changeScore(score);
} else {
displayMessage('You lost the game!');
changeScore(0);
}
}
});
document.querySelector('.again').addEventListener('click', function () {
score = 20;
secretNumber = Math.trunc(Math.random() * 20) + 1;
changeScore(score);
document.querySelector('.number').textContent = '?';
displayMessage('Start guessing...');
document.querySelector('.guess').value = '';
document.querySelector('body').style.backgroundColor = '#222';
document.querySelector('number').style.width = '15rem';
});