在當今社會,抖音已成為年輕人時尚娛樂的代表。很多人都會玩一些有趣的小游戲,而這些游戲源代碼的核心,往往是基于HTML編寫的。接下來,我們將介紹一款非常受歡迎的HTML小游戲源代碼:抖音機器人翻牌游戲。
<html> <head> <title>抖音機器人翻牌游戲</title> <style> .card { width: 100px; height: 100px; background-color: #fff; margin: 10px; float: left; cursor: pointer; } .card img { display: none; } .card.show img { display: block; } </style> </head> <body> <div id="game"></div> <script> var images = [ "https://www.example.com/image1.png", "https://www.example.com/image2.png", "https://www.example.com/image3.png", "https://www.example.com/image4.png", "https://www.example.com/image5.png", "https://www.example.com/image6.png", "https://www.example.com/image7.png", "https://www.example.com/image8.png" ]; var cards = []; var matchedCards = []; function init() { for (var i = 0; i< images.length; i++) { var card1 = createCard(images[i]); var card2 = createCard(images[i]); cards.push(card1); cards.push(card2); } shuffleCards(); var gameContainer = document.getElementById("game"); for (var i = 0; i< cards.length; i++) { gameContainer.appendChild(cards[i]); } } function createCard(image) { var card = document.createElement("div"); card.classList.add("card"); card.addEventListener("click", function() { revealCard(card, image); checkMatch(); }); var img = document.createElement("img"); img.setAttribute("src", image); card.appendChild(img); return card; } function shuffleCards() { for (var i = cards.length - 1; i >0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = cards[i]; cards[i] = cards[j]; cards[j] = temp; } } function revealCard(card, image) { card.classList.add("show"); card.querySelector("img").setAttribute("src", image); } function checkMatch() { var shownCards = document.querySelectorAll(".card.show"); if (shownCards.length == 2) { var card1 = shownCards[0]; var card2 = shownCards[1]; if (card1.querySelector("img").getAttribute("src") == card2.querySelector("img").getAttribute("src")) { matchedCards.push(card1, card2); card1.removeEventListener("click", revealCard); card2.removeEventListener("click", revealCard); if (matchedCards.length == cards.length) { alert("你贏了!"); } } else { setTimeout(function() { card1.classList.remove("show"); card2.classList.remove("show"); }, 1000); } } } init(); </script> </body> </html>
以上就是抖音機器人翻牌游戲的HTML小游戲源代碼。該游戲使用了HTML DOM操作和CSS樣式設置,充分體現了HTML在前端開發中的應用。希望大家可以通過學習該小游戲源代碼,了解HTML的基本語法和DOM操作方法,并用HTML打造出更多有趣的小游戲。