-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
71 lines (59 loc) · 1.84 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
const cardsArray = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H'];
let cardsChosen = [];
let cardsChosenId = [];
let cardsWon = [];
let gameLock = false;
const grid = document.getElementById('grid');
const restartButton = document.getElementById('restart-btn');
cardsArray.sort(() => 0.5 - Math.random());
function createBoard() {
for (let i = 0; i < cardsArray.length; i++) {
const card = document.createElement('div');
card.classList.add('card');
card.setAttribute('data-id', i);
card.textContent = '';
card.addEventListener('click', flipCard);
grid.appendChild(card);
}
}
function checkForMatch() {
const cards = document.querySelectorAll('.card');
const optionOneId = cardsChosenId[0];
const optionTwoId = cardsChosenId[1];
if (cardsChosen[0] === cardsChosen[1]) {
cards[optionOneId].classList.add('hidden');
cards[optionTwoId].classList.add('hidden');
cardsWon.push(cardsChosen);
} else {
cards[optionOneId].textContent = '';
cards[optionTwoId].textContent = '';
}
cardsChosen = [];
cardsChosenId = [];
gameLock = false;
if (cardsWon.length === cardsArray.length / 2) {
alert('Congratulations! You found all the matches!');
}
}
function flipCard() {
if (gameLock) return;
const cardId = this.getAttribute('data-id');
if (cardsChosenId.includes(cardId)) return;
cardsChosen.push(cardsArray[cardId]);
cardsChosenId.push(cardId);
this.textContent = cardsArray[cardId];
if (cardsChosen.length === 2) {
gameLock = true;
setTimeout(checkForMatch, 500);
}
}
function restartGame() {
grid.innerHTML = '';
cardsWon = [];
cardsChosen = [];
cardsChosenId = [];
gameLock = false;
createBoard();
}
restartButton.addEventListener('click', restartGame);
createBoard();