textContent = value; this.element.style.backgroundColor = this.getColor(); } getColor() { const colors = { '🍎': '#FF6B6B', '🍌': '#FFD166', '🍇': '#A05195', '🍉': '#FF7C7C', '🍍': '#F7B32B', '🍒': '#D62246', '🍊': '#FF9F1C', '🍓': '#E71D36' }; return colors[this.value] || '#4ECDC4'; } flip() { this.isFlipped = !this.isFlipped; this.element.classList.toggle('flipped', this.isFlipped); } match() { this.isMatched = true; this.element.style.opacity = '0.7'; this.element.style.cursor = 'default'; } reset() { this.isFlipped = false; this.isMatched = false; this.element.classList.remove('flipped'); this.element.style.opacity = '1'; this.element.style.cursor = 'pointer'; } } // Клас для спеціальної картки (поліморфізм) class BonusCard extends Card { constructor(value, element) { super(value, element); this.element.style.border = '3px solid gold'; } match() { super.match(); this.element.style.transform = 'scale(1.1)'; this.element.style.boxShadow = '0 0 15px gold'; } } // Основний клас гри class MemoryGame { constructor() { this.levels = [ { name: 'Легкий', pairs: 2, bonus: false }, { name: 'Середній', pairs: 3, bonus: false }, { name: 'Складний', pairs: 4, bonus: true } ]; this.currentLevel = 0; this.moves = 0; this.matches = 0; this.flippedCards = []; this.cards = []; this.startTime = 0; this.timer = null; // DOM елементи this.dom = { menuScreen: document.getElementById('menuScreen'), gameScreen: document.getElementById('gameScreen'), resultScreen: document.getElementById('resultScreen'), gameGrid: document.getElementById('gameGrid'), levelTitle: document.getElementById('levelTitle'), movesCounter: document.getElementById('movesCounter'), matchesCounter: document.getElementById('matchesCounter'), resultMessage: document.getElementById('resultMessage'), finalMoves: document.getElementById('finalMoves'), finalTime: document.getElementById('finalTime') }; this.initEvents(); } initEvents() { // Кнопки рівнів document.querySelectorAll('.level-buttons button').forEach(btn => { btn.addEventListener('click', () => { this.currentLevel = parseInt(btn.dataset.level); this.startGame(); }); }); // Інші кнопки document.getElementById('backToMenuBtn').addEventListener('click', () => this.showMenu()); document.getElementById('playAgainBtn').addEventListener('click', () => this.startGame()); document.getElementById('newLevelBtn').addEventListener('click', () => { this.showMenu(); }); document.getElementById('instructionsBtn').addEventListener('click', () => { document.getElementById('instructionsScreen').classList.remove('hidden'); }); document.getElementById('closeInstructionsBtn').addEventListener('click', () => { document.getElementById('instructionsScreen').classList.add('hidden'); }); } startGame() { this.resetGame(); this.dom.menuScreen.classList.add('hidden'); this.dom.gameScreen.classList.remove('hidden'); this.dom.resultScreen.classList.add('hidden'); const level = this.levels[this.currentLevel]; this.dom.levelTitle.textContent = Рівень: ${level.name}; this.createCards(level.pairs, level.bonus); this.startTime = Date.now(); this.updateTimer(); } createCards(pairsCount, hasBonus) { this.dom.gameGrid.innerHTML = ''; this.cards = []; // Вибір emoji для гри const allEmojis = ['🍎', '🍌', '🍇', '🍉', '🍍', '🍒', '🍊', '🍓']; const selectedEmojis = allEmojis.slice(0, pairsCount); // Створення пар карток let cardValues = []; selectedEmojis.forEach(emoji => { cardValues.push(emoji, emoji); }); // Перемішування this.shuffleArray(cardValues); // Створення карток cardValues.forEach((value, index) => { const cardElement = document.createElement('div'); cardElement.className = 'card'; // Створення звичайної або бонусної картки (поліморфізм) const card = hasBonus && Math.random() > 0.7 ? new BonusCard(value, cardElement) : new Card(value, cardElement); cardElement.addEventListener('click', () => this.handleCardClick(card)); this.dom.gameGrid.appendChild(cardElement); this.cards.push(card); }); // Оновлення розмітки сітки this.dom.gameGrid.style.gridTemplateColumns = repeat(${Math.min(pairsCount * 2, 4)}, 1fr); } handleCardClick(card) { // Ігноруємо кліки, якщо картка вже знайдена або перевернута if (card.isMatched card.isFlipped this.flippedCards.length >= 2) return; card.flip(); this.flippedCards.push(card); if (this.flippedCards.length === 2) { this.moves++; this.dom.movesCounter.textContent = Ходи: ${this.moves}; setTimeout(() => this.checkMatch(), 500); } } checkMatch() { const [card1, card2] = this.flippedCards; if (card1.value === card2.value) { // Знайдено пару card1.match(); card2.match(); this.matches++; this.dom.matchesCounter.textContent = Знайдено пар: ${this.matches}; // Перевірка на завершення гри if (this.matches === this.levels[this.currentLevel].pairs) { this.endGame(); } } else { // Не знайдено пару - перевертаємо назад card1.flip(); card2.flip(); } this.flippedCards = []; } endGame() { clearInterval(this.timer); const time = Math.floor((Date.now() - this.startTime) / 1000); this.dom.gameScreen.classList.add('hidden'); this.dom.resultScreen.classList.remove('hidden'); this.dom.resultMessage.textContent = Вітаємо! Ви пройшли ${this.levels[this.currentLevel].name} рівень!; this.dom.finalMoves.textContent = this.moves; this.dom.finalTime.textContent = time; } updateTimer() { clearInterval(this.timer); this.timer = setInterval(() => { const time = Math.floor((Date.now() - this.startTime) / 1000); document.getElementById('gameTime').textContent = Час: ${time} сек; }, 1000); } resetGame() { this.moves = 0; this.matches = 0; this.flippedCards = []; this.dom.movesCounter.textContent = 'Ходи: 0'; this.dom.matchesCounter.textContent = 'Знайдено пар: 0'; clearInterval(this.timer); } showMenu() { this.dom.menuScreen.classList.remove('hidden'); this.dom.gameScreen.classList.add('hidden'); this.dom.resultScreen.classList.add('hidden'); } shuffleArray(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]]; } } } // Ініціалізація гри при завантаженні сторінки document.addEventListener('DOMContentLoaded', () => { const game = new MemoryGame(); });