-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (50 loc) · 1.27 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
const cards = document.querySelectorAll(".card");
// variables
var isFlipped = false;
var firstCard;
var secondCard;
let lockBoard = false; // Prevents clicking during card flipping and comparison
cards.forEach((card) => card.addEventListener("click", flip));
function flip() {
if (lockBoard) return;
if (this === firstCard) return; // It ignores clicking on the same card
this.classList.add("flip");
if (!isFlipped) {
isFlipped = true;
firstCard = this;
} else {
secondCard = this;
checkIt();
}
}
function checkIt() {
lockBoard = true;
if (firstCard.dataset.image === secondCard.dataset.image) {
success();
} else {
fail();
}
}
function success() {
firstCard.removeEventListener("click", flip)
secondCard.removeEventListener("click", flip)
reset();
}
function fail() {
setTimeout(() => {
firstCard.classList.remove("flip");
secondCard.classList.remove("flip");
reset();
}, 450);
}
function reset() {
[isFlipped, lockBoard] = [false, false];
[firstCard, secondCard] = [null, null];
}
// Shuffling the cards using the Fisher-Yates shuffle algorithm
(function shuffle() {
cards.forEach((card) => {
const randomIndex = Math.floor(Math.random() * cards.length);
card.style.order = randomIndex;
});
})();