HTML5 打地鼠源代碼是一款小游戲的源代碼,它采用了 HTML5 技術,并以經典的打地鼠游戲為藍本,讓玩家在網頁上體驗游戲的樂趣。
下面是 HTML5 打地鼠源代碼,其中使用了 pre 標簽來標記代碼,方便顯示。
<!DOCTYPE html> <html> <head> <title>打地鼠</title> <style> .hole { width: 50px; height: 50px; background-image: url('hole.png'); background-position: center center; background-repeat: no-repeat; border: 1px solid black; } .active { background-image: url('mole.png'); } </style> </head> <body> <div id="game"></div> <script> const game = document.querySelector('#game'); let score = 0; let timeLeft = 10; function randomTime(min, max) { return Math.round(Math.random() * (max - min) + min); } function randomHole(holes) { const idx = Math.floor(Math.random() * holes.length); const hole = holes[idx]; if (hole === lastHole) { return randomHole(holes); } lastHole = hole; return hole; } function peep() { const time = randomTime(200, 1000); const hole = randomHole(holes); hole.classList.add('active'); setTimeout(() =>{ hole.classList.remove('active'); if (timeLeft >0) { peep(); } }, time); } function startGame() { score = 0; timeLeft = 10; scoreBoard.textContent = score; countdown(); peep(); setTimeout(() =>{ gameOver(); }, 10000); } function countdown() { const timeInterval = setInterval(() =>{ timeLeft--; timeLeftDisplay.textContent = timeLeft; if (timeLeft === 0) { clearInterval(timeInterval); } }, 1000); } function bonk(e) { if (!e.isTrusted) return; score++; this.classList.remove('active'); scoreBoard.textContent = score; } function gameOver() { alert(`Game over! Your final score is ${score}.`); } const holes = document.querySelectorAll('.hole'); let lastHole; const scoreBoard = document.createElement('div'); scoreBoard.textContent = score; document.body.insertBefore(scoreBoard, game); const timeLeftDisplay = document.createElement('div'); timeLeftDisplay.textContent = timeLeft; document.body.insertBefore(timeLeftDisplay, game); startButton = document.createElement('button'); startButton.textContent = 'Start'; document.body.insertBefore(startButton, game); startButton.addEventListener('click', startGame); holes.forEach(hole =>hole.addEventListener('click', bonk)); </script> </body> </html>
上一篇text內容換行css
下一篇HTML5手機能寫代碼嗎