-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
89 lines (77 loc) · 2.23 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
// Game values
let min = 1,
max = 10,
winningNum = getRandomNum(min, max),
guessesLeft = 3;
//Get elements from Html
let ELgame = document.querySelector('#game'),
ELminNum = document.querySelector('.min-num'),
ELmaxNum = document.querySelector('.max-num'),
ELguessBtn = document.querySelector('#guess-btn'),
ELguessInput = document.querySelector('#guess-input'),
ELmessage = document.querySelector('.message');
//Make min and max dynamic
ELminNum.textContent = min;
ELmaxNum.textContent = max;
//Play again event listner
game.addEventListener('mousedown', function(e) {
if (e.target.className === 'play-again') {
window.location.reload();
}
});
//Listen for guess btn
ELguessBtn.addEventListener('click', function() {
//Make input to int
let guess = parseInt(ELguessInput.value);
//Validate input
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a number between ${min} and ${max}`, 'red');
}
//Check if right number
if (guess === winningNum) {
//Game over - won
gameOver(true, `${winningNum} is the winning number, you win!!`);
} else {
guessesLeft -= 1;
if (guessesLeft === 0) {
//Game over - lost
gameOver(
false,
`Game over, you lost. The winning number was ${winningNum}`
);
} else {
//Game continues - wrong aswer
//Change border color
ELguessInput.style.borderColor = 'red';
//clear input
ELguessInput.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
ELguessInput.disabled = true;
//Change border color
ELguessInput.style.borderColor = color;
//Change color
ELmessage.style.color = color;
//Winning message
setMessage(msg);
//Play again?
ELguessBtn.value = 'Play Again';
ELguessBtn.className += 'play-again';
}
//Get winning num between 0 and 11
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
//Set message
function setMessage(message, color) {
ELmessage.style.color = color;
ELmessage.textContent = message;
}