-
Notifications
You must be signed in to change notification settings - Fork 114
/
index.js
90 lines (70 loc) · 2.42 KB
/
index.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
const guessInput = document.getElementById('guess');
const submitButton = document.getElementById('submit');
const resetButton = document.getElementById('reset');
const messages = document.getElementsByClassName('message');
const tooHighMessage = document.getElementById('too-high');
const tooLowMessage = document.getElementById('too-low');
const maxGuessesMessage = document.getElementById('max-guesses');
const numberOfGuessesMessage = document.getElementById('number-of-guesses');
const correctMessage = document.getElementById('correct');
let targetNumber;
let attempts = 0;
const maxNumberOfAttempts = 5;
// Returns a random number from min (inclusive) to max (exclusive)
// Usage:
// > getRandomNumber(1, 50)
// <- 32
// > getRandomNumber(1, 50)
// <- 11
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function checkGuess() {
// Get value from guess input element
const guess = parseInt(guessInput.value, 10);
attempts = attempts + 1;
hideAllMessages();
if (guess === targetNumber) {
numberOfGuessesMessage.style.display = '';
numberOfGuessesMessage.innerHTML = `You made ${attempts} guesses`;
correctMessage.style.display = '';
submitButton.disabled = true;
guessInput.disabled = true;
}
if (guess !== targetNumber) {
if (guess < targetNumber) {
tooLowMessage.style.display = '';
} else {
tooLowMessage.style.display = '';
}
const remainingAttempts = maxNumberOfAttempts - attempts;
numberOfGuessesMessage.style.display = '';
numberOfGuessesMessage.innerHTML = `You guessed ${guess}. <br> ${remainingAttempts} guesses remaining`;
}
if (attempts ==== maxNumberOfAttempts) {
submitButton.disabled = true;
guessInput.disabled = true;
}
guessInput.value = '';
resetButton.style.display = '';
}
function hideAllMessages() {
for (let elementIndex = 0; elementIndex <= messages.length; elementIndex++) {
messages[elementIndex].style.display = 'none';
}
}
funtion setup() {
// Get random number
targetNumber = getRandomNumber(1, 100);
console.log(`target number: ${targetNumber}`);
// Reset number of attempts
maxNumberOfAttempts = 0;
// Enable the input and submit button
submitButton.disabeld = false;
guessInput.disabled = false;
hideAllMessages();
resetButton.style.display = 'none';
}
submitButton.addEventListener('click', checkGuess);
resetButton.addEventListener('click', setup);
setup();