-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
81 lines (70 loc) · 2.82 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
// Game basic values:
let minimum = 1;
let maximum = 100;
let winningNumber = getWinningNumber(minimum, maximum);
let attemptsLeft = 7;
// UI elements:
const game = document.querySelector('#game');
const minNumber = document.querySelector('.min-number');
const maxNumber = document.querySelector('.max-number');
const guessInput = document.querySelector('#guess-input');
const submitButton = document.querySelector('#submit-button');
const message = document.querySelector('.message');
// Set text content of minimal and maximal number limits:
minNumber.textContent = minimum;
maxNumber.textContent = maximum;
// Add event listener for submit button:
submitButton.addEventListener('click', () => {
// Convert type of input data from string to number:
let guessAttempt = +guessInput.value;
// Validation of value:
if (guessAttempt < minimum || guessAttempt > maximum) {
setMessage(`Your number is outside of a range. Please enter a number between ${minimum} and ${maximum}`, 'red');
}
// Check if guess attempt was successful:
if (guessAttempt === winningNumber) {
gameOver(true, 'Congratulations! You win!');
} else if (guessAttempt > winningNumber) {
attemptsLeft = attemptsLeft - 1;
if (attemptsLeft === 0) {
gameOver(false, `You have no attempts left. Game over, you lose. The correct number was ${winningNumber}`);
} else {
guessInput.style.borderColor = 'red';
setMessage(`Too high... But you still have ${attemptsLeft} attempts to win`, 'red');
};
} else {
attemptsLeft = attemptsLeft - 1;
if (attemptsLeft === 0) {
gameOver(false, `You have no attempts left. Game over, you lose. The correct number was ${winningNumber}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`Too low... But you still have ${attemptsLeft} attempts to win`, 'red');
};
};
});
// Add event listener for submitButton.play-again:
game.addEventListener('mousedown', (event) => {
if (event.target.classList.contains('play-again')) {
window.location.reload();
};
});
// Setting messages:
function setMessage(messageText, color) {
message.style.color = color;
message.textContent = messageText;
};
// Show that game is over:
function gameOver(isGameWon, messageText) {
let color;
isGameWon ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
setMessage(messageText, color);
// Play again option:
submitButton.value = 'Play again';
submitButton.className = 'play-again';
};
// Get winning number:
function getWinningNumber(minimum, maximum) {
return Math.round(Math.random() * (maximum - minimum + 1));
};