-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
91 lines (80 loc) · 2.38 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const titleText = document.querySelector("#title");
const totalDiv = document.querySelector("#total-text");
const totalNumber = document.querySelector("#total");
const buttons = document.querySelectorAll("button");
const resetBtn = document.querySelector("input");
let num = Math.floor(Math.random() * 100) + 15;
let clicks = 10;
let currTotal = 0;
titleText.innerText = `In ${clicks} clicks get to ${num}`;
function makeRandColour() {
const r = Math.floor(Math.random() * Math.floor(255));
const g = Math.floor(Math.random() * Math.floor(255));
const b = Math.floor(Math.random() * Math.floor(255));
return `rgb(${r}, ${g}, ${b})`;
}
function colorise() {
this.style.backgroundColor = makeRandColour;
}
function takeClicks() {
if (clicks > 0) {
this.style.backgroundColor = makeRandColour();
this.style.outlineColor = makeRandColour();
this.innerText = Math.floor(Math.random() * (50)) + 1;
clicks--;
}
}
function updateScore() {
if (clicks > 0) {
currTotal = 0;
totalDiv.style.opacity = "1";
for (let text of buttons) {
if (text.innerText != "Click") {
currTotal += parseInt(text.innerText);
}
}
titleText.innerText = `In ${clicks} clicks get to ${num}`;
totalNumber.innerText = currTotal;
if (currTotal == num) {
gameOver();
}
} else {
gameOver();
}
}
function gameOver() {
for (let button of buttons) {
button.removeEventListener("mousedown", takeClicks);
button.removeEventListener("mouseup", updateScore);
}
if (currTotal != num) {
titleText.innerText = "Game Over";
totalNumber.innerText = `You were ${Math.abs(num - currTotal)} away from ${num}`;
} else {
titleText.innerText = "You won!";
totalNumber.innerText = `You got to ${num} in ${10 - clicks} click${(clicks == 1) ? 's' : ''}`;
}
}
function reset() {
num = Math.floor(Math.random() * 100) + 15;
clicks = 10;
currTotal = 0;
titleText.innerText = `In ${clicks} clicks get to ${num}`;
totalNumber.innerText = currTotal;
addListeners();
for (let button of buttons) {
button.style.backgroundColor = "";
button.innerText = "Click";
}
}
function addListeners() {
for (let button of buttons) {
button.addEventListener("mousedown", takeClicks);
button.addEventListener("mouseup", updateScore);
}
}
resetBtn.addEventListener("click", function (e) {
e.preventDefault();
reset();
});
addListeners();