-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
77 lines (63 loc) · 1.79 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
const gameBoard = document.getElementById('gameBoard');
const icons = ['🚍', '📌', '🗺️', '🛣️', '📸', '🎒', '🚏', '🚌'];
let cards = [];
let firstCard, secondCard;
let lockBoard = false;
let matchedPairs = 0;
function shuffle(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]];
}
}
function createBoard() {
cards = [...icons, ...icons];
shuffle(cards);
cards.forEach(icon => {
const card = document.createElement('div');
card.classList.add('card');
card.dataset.icon = icon;
card.addEventListener('click', flipCard);
gameBoard.appendChild(card);
});
}
function flipCard() {
if (lockBoard) return;
if (this === firstCard) return;
this.classList.add('flipped');
this.textContent = this.dataset.icon;
if (!firstCard) {
firstCard = this;
return;
}
secondCard = this;
checkForMatch();
}
function checkForMatch() {
let isMatch = firstCard.dataset.icon === secondCard.dataset.icon;
isMatch ? disableCards() : unflipCards();
}
function disableCards() {
firstCard.classList.add('matched');
secondCard.classList.add('matched');
resetBoard();
matchedPairs++;
if (matchedPairs === icons.length) {
setTimeout(() => alert('¡Felicidades Rutero 🚍!'), 500);
}
}
function unflipCards() {
lockBoard = true;
setTimeout(() => {
firstCard.classList.remove('flipped');
secondCard.classList.remove('flipped');
firstCard.textContent = '';
secondCard.textContent = '';
resetBoard();
}, 1000);
}
function resetBoard() {
[firstCard, secondCard] = [null, null];
lockBoard = false;
}
createBoard();