<meta charset="UTF-8"> <title>跨界對對碰 - 圖像版</title> <style> body { font-family: sans-serif; text-align: center; background: #f9f9f9; } .info { margin-top: 20px; font-size: 18px; } .grid { display: grid; grid-template-columns: repeat(6, 100px); grid-gap: 10px; justify-content: center; margin-top: 20px; } .card { width: 100px; height: 100px; background: #ccc; border-radius: 8px; overflow: hidden; cursor: pointer; position: relative; } .card img { width: 100%; height: 100%; object-fit: cover; display: none; } .flipped img, .matched img { display: block; } .flipped, .matched { background: #fff; border: 2px solid #00a86b; } </style> <h1>跨界對對碰 🎴</h1> <div class="info"> 分數:<span id="score">0</span> | 時間:<span id="timer">0</span>秒 </div> <div id="game" class="grid"></div> <script> const pairs = [ ["napoleon.jpg", "baguette.jpg"], ["pineapple.jpg", "hawaiian_pizza.jpg"], ["shakespeare.jpg", "theater.jpg"], ["coconut_tree.jpg", "beach.jpg"], ["sunflower.jpg", "vangogh.jpg"], ["totoro.jpg", "busstop.jpg"] // 這裡可以再加入更多對 ]; let cards = pairs.flat(); cards = [...cards].sort(() => Math.random() - 0.5); // Shuffle const game = document.getElementById("game"); let firstCard = null; let lockBoard = false; let score = 0; let timer = 0; let matchedCount = 0; const scoreBoard = document.getElementById("score"); const timerBoard = document.getElementById("timer"); function startTimer() { setInterval(() => { timer++; timerBoard.textContent = timer; }, 1000); } function speakHint(text) { const synth = window.speechSynthesis; const utter = new SpeechSynthesisUtterance(text); utter.lang = "zh-TW"; synth.speak(utter); } function createCard(imgPath, index) { const card = document.createElement("div"); card.className = "card"; card.dataset.index = index; card.dataset.img = imgPath; const img = document.createElement("img"); img.src = `./images/${imgPath}`; // 確保你有 images 資料夾 card.appendChild(img); card.addEventListener("click", () => flipCard(card)); return card; } cards.forEach((imgPath, index) => { const card = createCard(imgPath, index); game.appendChild(card); }); function flipCard(card) { if (lockBoard || card.classList.contains("matched") || card.classList.contains("flipped")) return; card.classList.add("flipped"); speakHint(card.dataset.img.replace(".jpg", "")); if (!firstCard) { firstCard = card; } else { const cardA = firstCard; const cardB = card; lockBoard = true; const pair = pairs.find(p => p.includes(cardA.dataset.img) && p.includes(cardB.dataset.img)); if (pair && cardA.dataset.img !== cardB.dataset.img) { cardA.classList.add("matched"); cardB.classList.add("matched"); score++; scoreBoard.textContent = score; matchedCount++; if (matchedCount === pairs.length) { alert("🎉 遊戲完成!總時間:" + timer + " 秒"); } } else { setTimeout(() => { cardA.classList.remove("flipped"); cardB.classList.remove("flipped"); }, 1000); } firstCard = null; setTimeout(() => lockBoard = false, 1000); } } startTimer(); </script>