HTML小游戲是開發者喜歡嘗試的一種有趣方式。在下面的示例中,我們將展示100行代碼的游戲。
<!DOCTYPE html> <html> <head> <title>翻轉記憶游戲</title> <style type="text/css"> .card { height: 100px; width: 70px; background-color: #f2f2f2; border: 2px solid #ccc; display: inline-block; margin: 10px; cursor: pointer; transform: rotateY(180deg); transition: transform 0.3s ease-in-out; } .revealed { transform: rotateY(0deg); background-color: #aaa; cursor: default; } h1 { text-align: center; } </style> </head> <body> <h1>翻轉記憶游戲</h1> <div id="cards"></div> <script type="text/javascript"> var cards = []; var revealedCards = []; var numOfMatches = 0; var numOfAttempts = 0; function generateCards() { var values = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']; for(var i=0; i<values.length; i++) { cards.push(values[i]); cards.push(values[i]); } shuffleCards(); } function shuffleCards() { for(var i=0; i<cards.length; i++) { var randomIndex = Math.floor(Math.random() * cards.length); var temp = cards[i]; cards[i] = cards[randomIndex]; cards[randomIndex] = temp; } } function createCardElements() { var cardsHtml = ''; for(var i=0; i<cards.length; i++) { cardsHtml += '<div class="card" id="'+i+'" onclick="cardClicked(this)"><div class="front">' + cards[i] + '</div><div class="back"></div></div>'; } document.getElementById('cards').innerHTML = cardsHtml; } function cardClicked(card) { if(revealedCards.length < 2 && !revealedCards.includes(card)) { card.classList.toggle('revealed'); revealedCards.push(card); } if(revealedCards.length == 2) { numOfAttempts++; if(revealedCards[0].innerHTML == revealedCards[1].innerHTML) { setTimeout(function() { revealedCards[0].classList.add('matched'); revealedCards[1].classList.add('matched'); revealedCards = []; numOfMatches++; if(numOfMatches == 8) { alert('游戲結束!您用 ' +numOfAttempts+ ' 次嘗試贏得了勝利。'); } }, 1000); } else { setTimeout(function() { revealedCards[0].classList.remove('revealed'); revealedCards[1].classList.remove('revealed'); revealedCards = []; }, 1000); } } } generateCards(); createCardElements(); </script> </body> </html>
該游戲使用 HTML、CSS 和 JavaScript 編寫而成,具有翻轉卡片、匹配卡片和計算嘗試次數的功能。該代碼中,包含了 HTML 標簽、CSS 樣式以及 JavaScript 腳本。開發者可以在此基礎上對代碼進行修改,實現更復雜的游戲功能。
上一篇python 找不到包
下一篇goole json