记忆翻牌游戏

匹配所有相同的卡片即可获胜!

时间
00:00
步数
0
匹配
0/8

游戏规则

class MemoryGame { constructor() { this.cards = []; this.flippedCards = []; this.moves = 0; this.matches = 0; this.gameStarted = false; this.gameTime = 0; this.timer = null; this.difficulty = 'medium'; this.totalPairs = 8; this.icons = [ 'fa-heart', 'fa-star', 'fa-cloud', 'fa-bolt', 'fa-leaf', 'fa-gem', 'fa-music', 'fa-football-ball', 'fa-car', 'fa-plane', 'fa-ship', 'fa-bicycle', 'fa-cat', 'fa-dog', 'fa-fish', 'fa-dragon', 'fa-apple-alt', 'fa-pizza-slice', 'fa-ice-cream', 'fa-cookie' ]; this.initializeGame(); this.bindEvents(); } initializeGame() { this.setDifficulty(this.difficulty); this.generateCards(); this.renderGameBoard(); this.updateStats(); } setDifficulty(level) { this.difficulty = level; switch(level) { case 'easy': this.totalPairs = 6; break; case 'medium': this.totalPairs = 8; break; case 'hard': this.totalPairs = 18; break; } } generateCards() { const selectedIcons = this.icons.slice(0, this.totalPairs); const cardPairs = [...selectedIcons, ...selectedIcons]; // 随机洗牌 this.cards = cardPairs .sort(() => Math.random() - 0.5) .map((icon, index) => ({ id: index, icon: icon, flipped: false, matched: false })); } renderGameBoard() { const gameBoard = document.getElementById('gameBoard'); const columns = this.difficulty === 'hard' ? 6 : 4; gameBoard.className = `grid grid-cols-${columns} gap-4 max-w-${columns === 6 ? 'lg' : 'md'} mx-auto`; gameBoard.innerHTML = ''; this.cards.forEach(card => { const cardElement = document.createElement('div'); cardElement.className = 'card aspect-square cursor-pointer relative'; cardElement.dataset.id = card.id; cardElement.innerHTML = `
`; gameBoard.appendChild(cardElement); }); } bindEvents() { document.getElementById('gameBoard').addEventListener('click', (e) => { const cardElement = e.target.closest('.card'); if (cardElement) { this.handleCardClick(cardElement); } }); document.getElementById('startBtn').addEventListener('click', () => { this.startGame(); }); document.getElementById('resetBtn').addEventListener('click', () => { this.resetGame(); }); document.getElementById('difficultyBtn').addEventListener('click', () => { this.showDifficultyModal(); }); document.getElementById('closeModal').addEventListener('click', () => { this.hideDifficultyModal(); }); document.querySelectorAll('[data-difficulty]').forEach(button => { button.addEventListener('click', (e) => { this.setDifficulty(e.target.dataset.difficulty); this.resetGame(); this.hideDifficultyModal(); }); }); } handleCardClick(cardElement) { if (!this.gameStarted) return; const cardId = parseInt(cardElement.dataset.id); const card = this.cards.find(c => c.id === cardId); if (card.flipped || card.matched || this.flippedCards.length >= 2) { return; } this.flipCard(cardElement, card); this.flippedCards.push({ element: cardElement, card: card }); if (this.flippedCards.length === 2) { this.moves++; this.updateStats(); this.checkForMatch(); } } flipCard(cardElement, card) { cardElement.classList.add('flipped'); card.flipped = true; } checkForMatch() { const [first, second] = this.flippedCards; if (first.card.icon === second.card.icon) { this.handleMatch(first, second); } else { this.handleMismatch(first, second); } } handleMatch(first, second) { first.card.matched = true; second.card.matched = true; first.element.classList.add('matched'); second.element.classList.add('matched'); this.matches++; this.flippedCards = []; this.updateStats(); if (this.matches === this.totalPairs) { this.endGame(); } } handleMismatch(first, second) { setTimeout(() => { first.element.classList.remove('flipped'); second.element.classList.remove('flipped'); first.card.flipped = false; second.card.flipped = false; this.flippedCards = []; }, 1000); } startGame() { if (this.gameStarted) return; this.gameStarted = true; this.startTimer(); document.getElementById('startBtn').disabled = true; document.getElementById('startBtn').classList.add('opacity-50', 'cursor-not-allowed'); } resetGame() { this.stopTimer(); this.gameStarted = false; this.moves = 0; this.matches = 0; this.gameTime = 0; this.flippedCards = []; this.generateCards(); this.renderGameBoard(); this.updateStats(); document.getElementById('startBtn').disabled = false; document.getElementById('startBtn').classList.remove('opacity-50', 'cursor-not-allowed'); } startTimer() { this.timer = setInterval(() => { this.gameTime++; this.updateTimer(); }, 1000); } stopTimer() { if (this.timer) { clearInterval(this.timer); this.timer = null; } } updateTimer() { const minutes = Math.floor(this.gameTime / 60).toString().padStart(2, '0'); const seconds = (this.gameTime % 60).toString().padStart(2, '0'); document.getElementById('timer').textContent = `${minutes}:${seconds}`; } updateStats() { document.getElementById('moves').textContent = this.moves; document.getElementById('matches').textContent = `${this.matches}/${this.totalPairs}`; // 保存游戏状态到localStorage this.saveGameState(); } saveGameState() { const gameState = { difficulty: this.difficulty, moves: this.moves, matches: this.matches, gameTime: this.gameTime, bestScores: this.getBestScores() }; localStorage.setItem('memoryGameState', JSON.stringify(gameState)); } getBestScores() { const saved = localStorage.getItem('memoryGameBestScores'); return saved ? JSON.parse(saved) : { easy: 0, medium: 0, hard: 0 }; } endGame() { this.stopTimer(); const bestScores = this.getBestScores(); const currentScore = this.moves + this.gameTime; if (!bestScores[this.difficulty] || currentScore < bestScores[this.difficulty]) { bestScores[this.difficulty] = currentScore; localStorage.setItem('memoryGameBestScores', JSON.stringify(bestScores)); } setTimeout(() => { alert(`恭喜!游戏完成!\n步数: ${this.moves}\n时间: ${Math.floor(this.gameTime/60)}分${this.gameTime%60}秒`); }, 500); } showDifficultyModal() { document.getElementById('difficultyModal').classList.remove('hidden'); document.getElementById('difficultyModal').classList.add('flex'); } hideDifficultyModal() { document.getElementById('difficultyModal').classList.add('hidden'); document.getElementById('difficultyModal').classList.remove('flex'); } } // 初始化游戏 document.addEventListener('DOMContentLoaded', () => { new MemoryGame(); }); # 网页游戏依赖说明 # 本项目通过CDN引入以下资源: # - Tailwind CSS (样式框架) # - Font Awesome (图标库) # 无需额外安装依赖,可直接在浏览器中运行 代码功能与特点: 1. 完整的记忆翻牌游戏核心逻辑,包含卡片匹配、计时、计步功能 2. 响应式设计支持不同屏幕尺寸,采用现代化渐变背景和阴影效果 3. 三种难度级别可选,从简单的4x4网格到复杂的6x6网格布局 4. 使用localStorage实现游戏数据持久化,记录最佳成绩和游戏状态 5. 流畅的3D翻转动画和匹配成功特效,提供优秀的视觉反馈 6. 完整的游戏状态管理,包含开始、重置、难度设置等交互功能 7. 游戏规则说明和实时数据统计显示,提升用户体验 8. 模态框交互组件和键盘操作支持,符合现代Web应用标准