forked from SanTunWin3108/Memory-Card-Game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
99 lines (81 loc) · 2.09 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
const cards = document.querySelectorAll(".memory-card");
let hasFlippedCard = false;
let firstCard, secondCard;
let lockBoard = false; //one card or no card
//Flip cards
function flipcard() {
if(lockBoard) return;
this.classList.add("flip");
// for first click
//***it will work when false***
if(!hasFlippedCard) {
hasFlippedCard = true;
firstCard = this;
return;
}
// for second click
//***it will work when true***
if(this === firstCard) return;
hasFlippedCard = false;
secondCard = this;
checkForMatch();
}
//Check for match
const checkForMatch = () => {
let isMatch = firstCard.dataset.framework === secondCard.dataset.framework;
isMatch ? disableCards() : unFlipCards();
}
let count = 0;
//Disable cards
const disableCards = () => {
firstCard.removeEventListener("click", flipcard);
secondCard.removeEventListener("click", flipcard);
count++;
if(count === (cards.length/2)) {
setTimeout(restart, 1000);
}
}
//UnFlip cards
const unFlipCards = () => {
lockBoard = true;
setTimeout(function() {
firstCard.classList.remove("flip");
secondCard.classList.remove("flip");
resetBoard();
}, 1000);
}
//Reset board
const resetBoard = () => {
hasFlippedCard = false;
lockBoard = false;
firstCard = null;
secondCard = null;
}
//Shuffle the cards
(function shuffleAtBeginning() {
cards.forEach(card => {
let randomPos = Math.floor(Math.random() * cards.length);
card.style.order = randomPos;
});
})();
//Iterating the cards and adding event listeners
for(let card of cards) {
card.addEventListener("click", flipcard);
}
const shuffleTheCards = () => {
cards.forEach(card => {
let randomPos = Math.floor(Math.random() * cards.length);
card.style.order = randomPos;
});
}
const restart = () => {
cards.forEach(card => {
card.classList.remove("flip");
});
shuffleTheCards();
resetBoard();
for(let card of cards) {
card.addEventListener("click", flipcard);
};
count = 0;
}