-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
62 lines (54 loc) · 1.67 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
// script.js
const board = document.getElementById("game-board");
const cardsArray = [
"✈️", "🌏", "❤️", "🥥", "🥬", "🫛", "🫘", "🥜", "🧆", "🍔", "🍆", "🏦", "🏝", "🌐",
"✈️", "🌏", "❤️", "🥥", "🥬", "🫛", "🫘", "🥜", "🧆", "🍔", "🍆", "🏦", "🏝", "🌐"
];
let flippedCards = [];
let matchedCards = [];
// Shuffle cards
cardsArray.sort(() => 0.5 - Math.random());
// Create cards
cardsArray.forEach((symbol) => {
const card = document.createElement("div");
card.classList.add("card");
card.innerHTML = `<span>${symbol}</span>`;
card.addEventListener("click", handleCardClick);
board.appendChild(card);
});
// Handle card click
function handleCardClick(event) {
const clickedCard = event.target;
if (
flippedCards.length < 2 &&
!flippedCards.includes(clickedCard) &&
!clickedCard.classList.contains("matched")
) {
clickedCard.classList.add("flipped");
flippedCards.push(clickedCard);
if (flippedCards.length === 2) {
checkForMatch();
}
}
}
// Check for a match
function checkForMatch() {
const [card1, card2] = flippedCards;
const symbol1 = card1.querySelector("span").textContent;
const symbol2 = card2.querySelector("span").textContent;
if (symbol1 === symbol2) {
card1.classList.add("matched");
card2.classList.add("matched");
matchedCards.push(card1, card2);
flippedCards = [];
if (matchedCards.length === cardsArray.length) {
setTimeout(() => alert("You won! 🎉"), 500);
}
} else {
setTimeout(() => {
card1.classList.remove("flipped");
card2.classList.remove("flipped");
flippedCards = [];
}, 1000);
}
}