-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
241 lines (220 loc) · 7.42 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
const state = {
timerId: null,
guessedPairsAmount: 0,
flipped: null,
guessedPairs: [],
guessedIds: [],
cardContainers: [],
bodyNode: null,
timerNode: null,
};
const startTimer = () => {
let minutes = 0;
let seconds = 0;
const increaseTimer = () => {
seconds++;
if (seconds === 60) {
minutes++;
seconds = 0;
}
};
const getFormattedTimer = ({ minutes, seconds }) => {
const addPriorZero = (number) => {
if (number < 10) return "0" + number;
else return +number;
};
return addPriorZero(minutes) + ":" + addPriorZero(seconds);
};
state.timerId = setInterval(() => {
increaseTimer();
state.timerNode.textContent = getFormattedTimer({ minutes, seconds });
}, 1000);
};
const antiCheat = () => {
if (state.cardContainers.length === 0)
state.cardContainers = Array.from(
document.querySelectorAll(".card-container")
);
state.cardContainers.forEach((node) => {
if (
state.guessedIds.includes(
node
.getAttribute("class")
.split(" ")
.find((className) => {
return className.includes("card_");
})
)
)
node.classList.add("guessed");
else node.classList.remove("guessed");
});
};
const getCardName = (node) => {
return node.getAttribute("src").slice(9, -4) || undefined;
};
const clickHandler = ({ target }) => {
if (
target.matches(".back") &&
target.parentNode.childElementCount === 2 &&
!target.closest('*[class*="card_"].flip-to-face')
) {
target.closest('*[class*="card_"]').classList.add("flip-to-face");
setTimeout(() => {
const currentCardContainer = target.closest('*[class*="card_"]');
const currentCardFace =
target.closest('*[class*="card_"]').children[1];
if (!state.flipped) {
state.flipped = {
container: currentCardContainer,
face: currentCardFace,
};
} else {
if (
getCardName(state.flipped.face) ===
getCardName(currentCardFace)
) {
currentCardContainer.classList.remove("flip-to-face");
state.flipped.container.classList.remove("flip-to-face");
state.guessedIds.push(
state.flipped.face.getAttribute("id")
);
state.guessedIds.push(currentCardFace.getAttribute("id"));
state.flipped = null;
state.guessedPairsAmount++;
if (state.guessedPairsAmount === 6) {
state.guessedPairsAmount = 0;
stopGame("win");
}
} else {
currentCardContainer.classList.remove("flip-to-face");
state.flipped.container.classList.remove("flip-to-face");
state.flipped = null;
}
}
antiCheat();
}, 1000);
}
};
const startGame = () => {
clearInterval(state.timerId);
state.guessedPairs = 0;
state.guessedIds = [];
document
.querySelectorAll(".guessed")
.forEach((elem) => elem.classList.remove("guessed"));
setTimeout(() => {
const cardImageNodes = getDoubledRandomImageNodes(6);
moveCardsIntoDOM(cardImageNodes);
startTimer();
}, 1000);
};
const stopGame = (result = "win") => {
clearInterval(state.timerId);
const span = document.createElement("span");
span.classList.add("result");
span.textContent =
result === "win"
? `You won! You time:${state.timerNode.textContent}`
: "You lost!";
state.bodyNode.appendChild(span);
span.addEventListener("click", () => {
state.bodyNode.removeChild(span);
});
};
const getDoubledRandomImageNodes = (amountOfElements) => {
if (amountOfElements <= 0) return [];
const getCardNames = (amount) => {
const cardNames = [
"ace_1",
"ace_2",
"ace_3",
"ace_4",
"king_1",
"king_2",
"king_3",
"king_4",
"queen_1",
"queen_2",
"queen_3",
"queen_4",
];
const result = [];
while (result.length < amount) {
const nameIndex = Math.floor(Math.random() * cardNames.length);
if (!result.includes(cardNames[nameIndex]))
result.push(cardNames[nameIndex]);
}
return result;
};
const convertNamesToNodes = (arrayOfNames) => {
const result = [];
arrayOfNames.forEach((name, i) => {
const img = document.createElement("img");
img.setAttribute("src", `./images/${name}.gif`);
img.setAttribute("id", `card_${i + 1}`);
img.classList.add("face");
result.push(img);
});
return result;
};
const doubleAndShuffle = (arr) => {
const doubledArr = [...arr, ...arr];
const result = [];
while (doubledArr.length > 0) {
const randomIndex = Math.floor(Math.random() * doubledArr.length);
result.push(doubledArr.splice(randomIndex, 1)[0]);
}
return result;
};
return convertNamesToNodes(
doubleAndShuffle(getCardNames(amountOfElements))
);
};
const moveCardsIntoDOM = (cards) => {
const cardContainers = document.querySelectorAll("div.card-container");
if (cardContainers[0].childElementCount === 1)
cardContainers.forEach((cardContainer, i) => {
cardContainer.insertAdjacentElement("beforeend", cards[i]);
});
else
cardContainers.forEach((cardContainer, i) => {
cardContainer.replaceChild(cards[i], cardContainer.lastChild);
});
};
const initialField = (amountOfCardOnField) => {
const container = document.createElement("div");
container.classList.add("field");
for (let i = 1; i <= amountOfCardOnField; i++) {
const perspectiveContainer = document.createElement("div");
const cardContainer = document.createElement("div");
cardContainer.classList.add("card-container", `card_${i}`);
const img = document.createElement("img");
img.setAttribute("src", "./images/back.gif");
img.setAttribute("alt", "");
img.classList.add("back");
perspectiveContainer.classList.add("perspective-container");
perspectiveContainer.appendChild(cardContainer);
cardContainer.appendChild(img);
container.appendChild(perspectiveContainer);
}
return container;
};
document.addEventListener("DOMContentLoaded", () => {
state.bodyNode = document.querySelector(".body");
state.timerNode = document.querySelector(".timer");
state.bodyNode.appendChild(initialField(12));
document
.querySelector("#game-button")
.addEventListener("click", (event) => {
event.preventDefault();
startGame();
});
document.querySelector(".field").addEventListener("click", clickHandler);
});
function sum(number, s = 0){
if(number === 0)
return s
else
return sum(number - 1, s + number)
}