function shuffle(array) {
let currentIndex = array.length,
temporaryValue,
randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
const gameBoard = document.querySelector(".game-board");
const cardIds = Array.from({
length: 8
}, (_, i) => i).concat(Array.from({
length: 8
}, (_, i) => i));
let prevCard = null;
let cardsLeft = 16;
let attemptsCount = 0;
const attemptsElem = document.querySelector(".attempts");
function createCards() {
const shuffledIds = shuffle(cardIds);
gameBoard.innerHTML = "";
shuffledIds.forEach((id) => {
const card = document.createElement("div");
card.innerHTML = `<img src="img-${id}.jpg" alt="">`;
card.setAttribute("data-id", id);
card.className = "card";
card.addEventListener("click", handleClick);
gameBoard.appendChild(card);
});
}
function handleClick(e) {
const card = e.currentTarget;
if (card === prevCard || card.classList.contains("flipped")) return;
attemptsCount++;
attemptsElem.textContent = `${attemptsCount}`;
card.classList.add("flipped");
if (!prevCard) {
prevCard = card;
} else {
gameBoard.style.pointerEvents = "none"; // Deshabilita los clics en el tablero durante las animaciones
setTimeout(() => {
if (card.getAttribute("data-id") === prevCard.getAttribute("data-id")) {
cardsLeft -= 2;
card.removeEventListener("click", handleClick);
prevCard.removeEventListener("click", handleClick);
} else {
card.classList.remove("flipped");
prevCard.classList.remove("flipped");
}
prevCard = null;
gameBoard.style.pointerEvents = "auto"; // Reestablece los clics en el tablero
}, 1000);
}
}
function restartGame() {
prevCard = null;
cardsLeft = 16;
attemptsCount = 0;
attemptsElem.textContent = "0";
createCards();
}
createCards();