用html写一个打地鼠游戏示例代码
时间: 2023-04-11 11:00:40 浏览: 184
我可以回答这个问题。以下是一个简单的打地鼠游戏的 HTML 示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>打地鼠游戏</title>
<style>
#game-board {
display: flex;
flex-wrap: wrap;
width: 400px;
height: 400px;
background-color: #eee;
padding: 10px;
}
.hole {
width: 100px;
height: 100px;
background-color: #fff;
border: 1px solid #ccc;
margin: 5px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
cursor: pointer;
}
.hole.active {
background-color: #f00;
color: #fff;
}
</style>
</head>
<body>
<h1>打地鼠游戏</h1>
<div id="game-board">
<div class="hole"></div>
<div class="hole"></div>
<div class="hole"></div>
<div class="hole"></div>
<div class="hole"></div>
<div class="hole"></div>
<div class="hole"></div>
<div class="hole"></div>
<div class="hole"></div>
</div>
<script>
const holes = document.querySelectorAll('.hole');
let score = 0;
let lastHole;
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 (!timeUp) peep();
}, time);
}
function startGame() {
score = 0;
timeUp = false;
scoreBoard.textContent = 0;
peep();
setTimeout(() => timeUp = true, 10000);
}
function bonk(e) {
if (!e.isTrusted) return; // cheater!
score++;
this.classList.remove('active');
scoreBoard.textContent = score;
}
holes.forEach(hole => hole.addEventListener('click', bonk));
const scoreBoard = document.createElement('div');
scoreBoard.textContent = 0;
document.body.appendChild(scoreBoard);
let timeUp = false;
startButton.addEventListener('click', startGame);
</script>
</body>
</html>
```
这个示例代码使用 HTML、CSS 和 JavaScript 实现了一个简单的打地鼠游戏。游戏板块使用了 flex 布局,每个洞口使用了一个 div 元素表示。在 JavaScript 中,使用了一些函数来随机生成地鼠出现的时间和位置,以及计分和游戏结束的逻辑。