-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
110 lines (74 loc) · 2.23 KB
/
script.js
File metadata and controls
110 lines (74 loc) · 2.23 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// declare vars
let colors = []
let selectedColor = ""
// get needed selectors
let headerH1 = document.querySelector("h1")
let selectedColorSpan = document.querySelector(".currColor")
let messageDiv = document.querySelector(".message")
let restartDiv = document.querySelector(".restart")
let squares = document.querySelectorAll(".square");
// set up game
resetHeader()
setBoard()
// assign colors to squares and add click listeners
for(let i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i]
squares[i].addEventListener("click", function() {
if(this.style.backgroundColor == selectedColor) {
// if clicked on target tile
changeColors(selectedColor)
messageDiv.textContent = "Correct!"
restartDiv.textContent = "Play again!"
} else {
// if not clicked on target tile
this.style.backgroundColor = "#333"
messageDiv.textContent = "Not this tile!"
}
}) // end clickListener
} // end for
function changeColors(color) {
// changes colors of all tiles to one color
for(let i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = color;
}
headerH1.style.backgroundColor = color
}
function generateColors(number) {
// returns an array with $number items
// each item contains an rgb color value
let outputObject = []
for(let i = 0; i < number; i++) {
outputObject.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")"
)
}
return outputObject
}
function pickColor() {
// returns a random item from the colors array
return colors[Math.floor(Math.random() * colors.length)]
}
function setBoard() {
// prepares colors and target tile for game
colors = generateColors(6)
selectedColor = pickColor()
selectedColorSpan.textContent = selectedColor
}
function resetHeader() {
// resets header color and text
headerH1.style.backgroundColor = "#333"
restartDiv.textContent = "Get new colors"
messageDiv.textContent = "Click a tile to start"
}
// assign click logic get new colors
restartDiv.addEventListener("click", () => {
// prepare game
resetHeader()
setBoard()
// reassign colors
for(let i = 0; i< squares.length; i++) {
squares[i].style.backgroundColor = colors[i]
}
})