-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
92 lines (83 loc) · 2.4 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
92
const getRandomColors = function () {
var ratio = 0.618033988749895;
var hue = (Math.random() + ratio) % 1;
var saturation = Math.round(Math.random() * 100) % 85;
var lightness = Math.round(Math.random() * 100) % 85;
var color =
"hsl(" + Math.round(360 * hue) + "," + saturation + "%," + lightness + "%)";
var oddColor =
"hsl(" +
Math.round(360 * hue) +
"," +
saturation +
"%," +
(lightness + 5) +
"%)";
return {
color,
oddColor,
};
};
function ColorSpotter(colorSpotter, size, scoreElement) {
const grid = document.querySelector(colorSpotter);
const scoreElem = document.querySelector(scoreElement);
var score = 0;
var currGridSize = size;
var isShaking = false;
var traitor = -1;
function formGrid(currGridSize, currScore) {
destroyGrid();
var cellIndex = 0;
traitor = randomIndex(currGridSize);
var colors = getRandomColors();
for (let i = 0; i < currGridSize; i++) {
const row = document.createElement("div");
row.classList.add("row");
for (let j = 0; j < currGridSize; j++) {
const cell = document.createElement("div");
cell.classList.add("cell");
cell.setAttribute("data-index", String(cellIndex));
if (cellIndex == traitor) {
cell.style.backgroundColor = colors.oddColor;
} else {
cell.style.backgroundColor = colors.color;
}
cell.addEventListener("click", onClickHandler);
cellIndex++;
row.appendChild(cell);
}
grid.appendChild(row);
scoreElem.innerHTML = "Score: " + currScore;
}
}
async function onClickHandler(e) {
if (isShaking) return;
let clickedIndex = e.target.dataset.index;
if (traitor === Number(clickedIndex)) {
score++;
formGrid(++currGridSize, score);
} else {
grid.className = "shake";
isShaking = true;
await delay(800);
isShaking = false;
score = 0;
currGridSize = size;
formGrid(currGridSize, score);
}
}
function delay(delayTime) {
return new Promise((resolve) => setTimeout(resolve, delayTime));
}
function randomIndex(currentSize) {
return Math.floor(Math.random() * currentSize * currentSize);
}
function destroyGrid() {
grid.classList.remove("shake");
const des = document.querySelectorAll(".row");
des.forEach((d) => {
d.remove();
});
}
formGrid(currGridSize, 0);
}