很难写但好玩的html打地鼠游戏代码
时间: 2023-11-14 18:05:55 浏览: 79
打地鼠游戏代码
以下是一个简单的打地鼠游戏的 HTML 代码,你可以在其中添加更多的元素和样式来使其更加有趣:
```html
<!DOCTYPE html>
<html>
<head>
<title>打地鼠游戏</title>
<style>
body {
margin: 0;
padding: 0;
background: #333;
}
#game-board {
display: flex;
flex-wrap: wrap;
width: 600px;
height: 600px;
margin: 0 auto;
padding: 20px;
background: #fff;
box-shadow: 0 0 10px rgba(0,0,0,0.3);
}
.hole {
flex: 1 0 calc(33.33% - 10px);
height: 200px;
margin: 5px;
background: #ccc;
border-radius: 50%;
cursor: pointer;
transition: background 0.2s;
}
.hole:hover {
background: #eee;
}
.mole {
position: relative;
top: 50%;
left: 50%;
width: 60px;
height: 60px;
background: url('https://i.imgur.com/6fWfLxS.png');
background-size: cover;
border-radius: 50%;
transform: translate(-50%, -50%) scale(0);
transition: transform 0.2s;
}
.mole.active {
transform: translate(-50%, -50%) scale(1);
}
</style>
</head>
<body>
<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');
const moles = document.querySelectorAll('.mole');
let score = 0;
let lastHole;
let timeUp = false;
function getRandomTime(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
function getRandomHole(holes) {
const idx = Math.floor(Math.random() * holes.length);
const hole = holes[idx];
if (hole === lastHole) {
return getRandomHole(holes);
}
lastHole = hole;
return hole;
}
function peep() {
const time = getRandomTime(200, 1000);
const hole = getRandomHole(holes);
hole.classList.add('up');
setTimeout(() => {
hole.classList.remove('up');
if (!timeUp) peep();
}, time);
}
function startGame() {
score = 0;
timeUp = false;
document.querySelector('.score').textContent = score;
peep();
setTimeout(() => {
timeUp = true;
}, 10000);
}
function bonk(e) {
if (!e.isTrusted) return;
score++;
this.parentNode.classList.remove('up');
document.querySelector('.score').textContent = score;
}
moles.forEach(mole => mole.addEventListener('click', bonk));
</script>
</body>
</html>
```
在这个游戏中,地鼠会随机从洞口钻出来,玩家需要在地鼠出现后尽快点击它,以此来得分。在代码中,我们使用了一些 CSS 样式来布局和美化游戏板和地鼠洞口,使用了一些 JavaScript 来控制地鼠的出现和得分等逻辑。
阅读全文