-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
74 lines (61 loc) · 2.05 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"use strict";
let answer = Math.trunc(Math.random() * 20) + 1;
console.log(answer);
let score = 20;
let highscore = 0;
const changeMessage = function (message) {
document.querySelector(".message").textContent = message;
};
const changeScore = function (score) {
document.querySelector(".score").textContent = score;
};
const setHighscore = function (score) {
if (score > highscore) {
highscore = score;
}
document.querySelector(".highscore").textContent = highscore;
};
const gameOver = function () {
changeMessage("GAME OVER!");
document.querySelector("body").style.backgroundColor = "#ff5050";
document.querySelector(".number").style.width = "30rem";
document.querySelector(".number").textContent = answer;
changeScore(0);
};
const checker = function () {
const userGuess = Number(document.querySelector(".guess").value);
console.log(userGuess);
// if player hasn't put an input
if (!userGuess) {
changeMessage("Please input a number.");
// if player wins
} else if (userGuess === answer) {
changeMessage("Correct!");
document.querySelector("body").style.backgroundColor = "#60b347";
document.querySelector(".number").style.width = "30rem";
document.querySelector(".number").textContent = answer;
setHighscore(score);
// when guess is wrong
} else if (userGuess !== answer) {
if (score > 1) {
changeMessage(userGuess > answer ? "Too High!" : "Too Low!");
score -= 1;
changeScore(score);
} else {
gameOver();
}
}
};
const restartGame = function () {
score = 20;
answer = Math.trunc(Math.random() * 20) + 1;
console.log("new answer: ", answer);
document.querySelector("body").style.backgroundColor = "#222";
document.querySelector(".number").style.width = "15rem";
document.querySelector(".number").textContent = "?";
document.querySelector(".guess").value = "";
changeScore(score);
changeMessage("Start guessing...");
};
document.querySelector(".check").addEventListener("click", checker);
document.querySelector(".again").addEventListener("click", restartGame);