今天我們要介紹一個非常有趣的小游戲,這是基于HTML5技術(shù)制作的翻牌游戲。該游戲可以幫助你練習(xí)你的記憶力和集中力,同時也是一個很好的編程練習(xí)。
以下是該翻牌小游戲的HTML代碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>翻牌小游戲</title> <style> .card { width: 100px; height: 150px; float: left; margin: 10px; border: 1px solid #ccc; background: #fff; position: relative; } .card .front, .card .back { width: 100%; height: 100%; position: absolute; top: 0; left: 0; backface-visibility: hidden; } .card .front { transform: rotateY(0deg); } .card .back { transform: rotateY(180deg); } </style> </head> <body> <div id="game"></div> <script> var cards = [ { id: 1, image: 'card1.jpg' }, { id: 2, image: 'card2.jpg' }, { id: 3, image: 'card3.jpg' }, { id: 4, image: 'card4.jpg' }, { id: 5, image: 'card5.jpg' }, { id: 6, image: 'card6.jpg' }, { id: 7, image: 'card7.jpg' }, { id: 8, image: 'card8.jpg' } ]; var game = document.getElementById('game'); var selectedCards = []; // Shuffle the cards cards.sort(function() { return 0.5 - Math.random(); }); // Create the cards for (var i = 0; i < cards.length; i++) { var card = document.createElement('div'); var front = document.createElement('img'); var back = document.createElement('img'); card.className = 'card'; card.dataset.id = cards[i].id; front.className = 'front'; front.src = 'blank.jpg'; back.className = 'back'; back.src = cards[i].image; card.appendChild(front); card.appendChild(back); game.appendChild(card); // Set event listener card.addEventListener('click', function() { var id = this.dataset.id; // Check if the card has already been selected if (selectedCards.indexOf(id) !== -1) { return; } // Flip the card this.classList.add('flipped'); // Add the card to the list of selected cards selectedCards.push(id); // Check if two cards have been selected if (selectedCards.length === 2) { // Get the two cards var card1 = document.querySelector('.card[data-id="' + selectedCards[0] + '"]'); var card2 = document.querySelector('.card[data-id="' + selectedCards[1] + '"]'); // Check if the cards match if (card1.querySelector('.back').src === card2.querySelector('.back').src) { // The cards match, so leave them face up and remove from selected cards selectedCards = []; } else { // The cards don't match, so flip them back over and remove from selected cards setTimeout(function() { card1.classList.remove('flipped'); card2.classList.remove('flipped'); selectedCards = []; }, 1000); } } }); } </script> </body> </html>
該代碼包括一個包含8張牌的游戲區(qū)域,每張牌都有一個翻轉(zhuǎn)效果(使用CSS3的transform屬性)。當(dāng)你單擊一張牌時,它會翻轉(zhuǎn)并顯示它的背面,同時添加到選定卡片的列表中。如果你選擇了兩張牌并且它們匹配,則兩張牌將正面朝上留下,否則它們將翻轉(zhuǎn)回到背面并從選定卡片的列表中刪除。
現(xiàn)在你可以使用該代碼來創(chuàng)建你自己的翻牌游戲。如果你想添加更多的牌,只需將它們添加到cards數(shù)組即可。