const gameBoard = document.getElementById('gameBoard');
const scoreElement = document.getElementById('score');
const movesElement = document.getElementById('moves');
const cardValues = ['🎮', '🎯', '🎲', '🎪', '🎨', 'ðŸŽ', '🎸', '🎺'];
const cards = [...cardValues, ...cardValues];
let flippedCards = [];
let matchedPairs = 0;
let moves = 0;
let score = 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]];
}
return array;
}
function createCard(value, index) {
const card = document.createElement('div');
card.className = 'card';
card.dataset.value = value;
card.dataset.index = index;
card.textContent = '?';
card.addEventListener('click', flipCard);
return card;
}
function flipCard(event) {
const card = event.currentTarget;
if (card.classList.contains('flipped') || flippedCards.length === 2) {
return;
}
card.classList.add('flipped');
card.textContent = card.dataset.value;
flippedCards.push(card);
if (flippedCards.length === 2) {
moves++;
movesElement.textContent = moves;
checkMatch();
}
}
function checkMatch() {
const [card1, card2] = flippedCards;
if (card1.dataset.value === card2.dataset.value) {
card1.classList.add('matched');
card2.classList.add('matched');
matchedPairs++;
score += 10;
scoreElement.textContent = score;
if (matchedPairs === cardValues.length) {
setTimeout(() => alert(`You won in ${moves} moves!`), 500);
}
flippedCards = [];
} else {
setTimeout(() => {
card1.classList.remove('flipped');
card2.classList.remove('flipped');
card1.textContent = '?';
card2.textContent = '?';
flippedCards = [];
}, 1000);
}
}
function initGame() {
gameBoard.innerHTML = '';
flippedCards = [];
matchedPairs = 0;
moves = 0;
score = 0;
scoreElement.textContent = score;
movesElement.textContent = moves;
const shuffledCards = shuffle([...cards]);
shuffledCards.forEach((value, index) => {
const card = createCard(value, index);
gameBoard.appendChild(card);
});
}
initGame();This code demonstrates the core game logic. The actual implementation may include additional features and optimizations.