-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
115 lines (99 loc) · 2.75 KB
/
script.js
File metadata and controls
115 lines (99 loc) · 2.75 KB
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
const cardscontainer= [
{ name: 'A', value: 'A' },
{ name: 'B', value: 'B' },
{ name: 'C', value: 'C' },
{ name: 'D', value: 'D' },
{ name: 'E', value: 'E' },
{ name: 'F', value: 'F' },
{ name: 'G', value: 'G' },
{ name: 'H', value: 'H' },
{ name: 'A', value: 'A' },
{ name: 'B', value: 'B' },
{ name: 'C', value: 'C' },
{ name: 'D', value: 'D' },
{ name: 'E', value: 'E' },
{ name: 'F', value: 'F' },
{ name: 'G', value: 'G' },
{ name: 'H', value: 'H' }
];
let firstCard, secondCard;
let lockBoard = false;
let matchedPairs = 0;
function flipgame(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function createBoard() {
const gameBoard = document.getElementById('gameBoard');
gameBoard.innerHTML = '';
flipgame(cardscontainer).forEach(card => {
const cardElement = document.createElement('div');
cardElement.classList.add('card');
cardElement.dataset.name = card.name;
cardElement.innerText = card.value;
cardElement.addEventListener('click', flipCard);
gameBoard.appendChild(cardElement);
});
}
function flipCard() {
if (lockBoard) return;
if (this === firstCard) return;
this.classList.add('flipped');
if (!firstCard) {
firstCard = this;
return;
}
secondCard = this;
checkForMatch();
}
function checkForMatch() {
let isMatch = firstCard.dataset.name === secondCard.dataset.name;
if (isMatch) {
disableCards();
matchedPairs++;
if (matchedPairs === cardscontainer.length / 2) {
setTimeout(showCustomAlert, 500);
}
} else {
unflipCards();
}
}
function showCustomAlert() {
const modal = document.getElementById('customAlert');
modal.style.display = 'block';
document.getElementById('closeModal').onclick = () => {
modal.style.display = 'none';
};
window.onclick = (event) => {
if (event.target === modal) {
modal.style.display = 'none';
}
};
}
function disableCards() {
firstCard.classList.add('matched');
secondCard.classList.add('matched');
resetBoard();
}
function unflipCards() {
lockBoard = true;
setTimeout(() => {
firstCard.classList.remove('flipped');
secondCard.classList.remove('flipped');
resetBoard();
}, 1000);
}
const resetBoard = () => {
[firstCard, secondCard] = [null, null];
lockBoard = false;
}
document.getElementById('restartButton').addEventListener('click', () => restartGame());
const restartGame = () => {
matchedPairs = 0;
resetBoard();
createBoard();
}
createBoard();