-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolorGame.js
95 lines (83 loc) · 2.76 KB
/
colorGame.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
92
93
var squares = document.querySelectorAll(".square");
var colorDisplay = document.querySelector("#colorDisplay");
var message = document.querySelector("#message");
var h1 = document.querySelector("h1");
var resetButton = document.querySelector("#reset");
var modeButtons = document.querySelectorAll(".modeButton");
var colors;
var pickedColor;
init();
function init() {
resetColors(6);
setUpSquares();
setUpModeButtons();
}
function resetColors(num) {
colors = generateRandomColors(num);
for (var i = 0; i < colors.length; i++) {
squares[i].style.backgroundColor = colors[i];
}
pickedColor = colors[pickColor(num)];
colorDisplay.textContent = pickedColor;
h1.style.backgroundColor = "steelblue";
resetButton.textContent = "New Colors";
message.textContent = "";
}
function setUpSquares() {
for (var i = 0; i < squares.length; i++) {
squares[i].addEventListener("click", function () {
if (this.style.backgroundColor === pickedColor) {
message.textContent = "You win!";
changeColors();
resetButton.textContent = "Play Again?";
} else {
this.style.backgroundColor = "#232323";
message.textContent = "Try again.";
}
});
}
}
function setUpModeButtons () {
for (var i = 0; i < modeButtons.length; i++) {
modeButtons[i].addEventListener("click", function () {
if (!this.classList.contains("selected")) {
modeButtons[0].classList.remove("selected");
modeButtons[1].classList.remove("selected");
this.classList.add("selected");
if (this.textContent === "EASY") {
resetColors(3);
for (var i = 3; i < 6; i++) {
squares[i].style.display = "none";
}
} else {
resetColors(6);
for (var i = 3; i < 6; i++) {
squares[i].style.display = "block";
}
}
}
});
}
}
function changeColors() {
for (var i = 0; i < colors.length; i++) {
squares[i].style.backgroundColor = pickedColor;
}
h1.style.backgroundColor = pickedColor;
}
function generateRandomColors(num) {
var result = [];
for (var i = 0; i < num; i++) {
result.push(randomColor());
}
return result;
}
function randomColor() {
return "rgb(" + pickColor(255) + ", " + pickColor(255) + ", " + pickColor(255) + ")";
}
function pickColor(num) {
return Math.floor(Math.random() * num);
}
resetButton.addEventListener("click", function () {
modeButtons[0].classList.contains("selected") ? resetColors(3) : resetColors(6);
});