-
Notifications
You must be signed in to change notification settings - Fork 0
/
home.js
79 lines (67 loc) · 2.01 KB
/
home.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
let guessList = [];
let correctNumber;
window.onload = () => {
correctNumber = randomNumber();
document.querySelector(".button-checkme").addEventListener("click", playGame);
document.querySelector(".button-restart").addEventListener("click", restartGame);
};
const randomNumber = () => Math.floor(Math.random() * 100) + 1;
const playGame = () => {
let newGuess = document.querySelector(".input-guess").value;
displayResults(newGuess);
saveGuessHistory(newGuess);
displayHistory(guessList);
};
const restartGame = () => {
correctNumber = randomNumber();
resetDialogDisplay();
saveGuessHistory();
guessList = [];
displayHistory();
};
const saveGuessHistory = (guess) => {
guessList.push(guess);
};
const displayHistory = () => {
let nextguess = guessList.length - 1;
let list = "<ul class='guess-history'>";
while (nextguess >= 0) {
list += "<li class='new-history'>" + "You guessed " + guessList[nextguess] + "</li>";
nextguess -= 1;
}
list += "</ul>";
document.querySelector(".guess-history").innerHTML = list;
};
const displayResults = (newGuess) => {
if (newGuess > correctNumber) {
tooHigh();
} else if (newGuess < correctNumber) {
tooLow();
} else if (newGuess == correctNumber) {
youWon();
}
};
const getDialog = (dialogType, text) => {
let dialog = `<div class= ${dialogType == "wrong" ? "alert-wrong" : "alert-success"}>`;
dialog += text;
dialog += `</div>`;
return dialog;
};
const resetDialogDisplay = () => {
document.querySelector(".results").innerHTML = "";
};
const youWon = () => {
const text = "Awesome job, you got it!";
let dialog = getDialog("won", text);
document.querySelector(".results").innerHTML = dialog;
};
const tooHigh = () => {
const text = "Your guess is too high!";
let dialog = getDialog("wrong", text);
document.querySelector(".results").innerHTML = dialog;
};
const tooLow = () => {
const text = "Your guess is too low!";
let dialog = getDialog("wrong", text);
document.querySelector(".results").innerHTML = dialog;
};