-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (58 loc) · 1.8 KB
/
index.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
const tilesContainer = document.querySelector(".tiles");
const colors = ["aqua", "aquamarine", "crimson", "blue", "dodgerblue", "gold", "greenyellow", "teal"];
const colorsPicklist = [...colors, ...colors];
const tileCount = colorsPicklist.length;
// Game state
let revealedCount = 0;
let activeTile = null;
let awaitingEndOfMove = false;
function buildTile(color) {
const element = document.createElement("div");
element.classList.add("tile");
element.setAttribute("data-color", color);
element.setAttribute("data-revealed", "false");
element.addEventListener("click", () => {
const revealed = element.getAttribute("data-revealed");
if (
awaitingEndOfMove
|| revealed === "true"
|| element == activeTile
) {
return;
}
// Reveal this color
element.style.backgroundColor = color;
if (!activeTile) {
activeTile = element;
return;
}
const colorToMatch = activeTile.getAttribute("data-color");
if (colorToMatch === color) {
element.setAttribute("data-revealed", "true");
activeTile.setAttribute("data-revealed", "true");
activeTile = null;
awaitingEndOfMove = false;
revealedCount += 2;
if (revealedCount === tileCount) {
alert("You win! Refresh to start again.");
}
return;
}
awaitingEndOfMove = true;
setTimeout(() => {
activeTile.style.backgroundColor = null;
element.style.backgroundColor = null;
awaitingEndOfMove = false;
activeTile = null;
}, 1000);
});
return element;
}
// Build up tiles
for (let i = 0; i < tileCount; i++) {
const randomIndex = Math.floor(Math.random() * colorsPicklist.length);
const color = colorsPicklist[randomIndex];
const tile = buildTile(color);
colorsPicklist.splice(randomIndex, 1);
tilesContainer.appendChild(tile);
}