好玩的html代码小游戏
时间: 2023-10-14 15:07:38 浏览: 47
以下是一个叫做“打地鼠”的小游戏的 HTML 代码,你可以在浏览器中打开并尝试玩一下:
```
<!DOCTYPE html>
<html>
<head>
<title>打地鼠小游戏</title>
<script>
var holes = document.querySelectorAll('.hole');
var scoreBoard = document.querySelector('.score');
var moles = document.querySelectorAll('.mole');
var lastHole;
var timeUp = false;
var score = 0;
function randomTime(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
function randomHole(holes) {
var idx = Math.floor(Math.random() * holes.length);
var hole = holes[idx];
if (hole === lastHole) {
return randomHole(holes);
}
lastHole = hole;
return hole;
}
function peep() {
var time = randomTime(200, 1000);
var hole = randomHole(holes);
hole.classList.add('up');
setTimeout(function() {
hole.classList.remove('up');
if (!timeUp) {
peep();
}
}, time);
}
function startGame() {
scoreBoard.textContent = 0;
timeUp = false;
score = 0;
peep();
setTimeout(function() {
timeUp = true;
}, 10000);
}
function bonk(e) {
if (!e.isTrusted) {
return;
}
score++;
this.classList.remove('up');
scoreBoard.textContent = score;
}
moles.forEach(function(mole) {
mole.addEventListener('click', bonk);
});
</script>
<style>
.hole {
background: #c9c9c9;
border-radius: 50%;
display: inline-block;
margin: 20px;
height: 80px;
width: 80px;
position: relative;
}
.mole {
background: url('https://github.com/wesbos/JavaScript30/blob/master/30%20-%20Whack%20A%20Mole/whack-a-mole/worm.png?raw=true');
background-size: 60%;
background-repeat: no-repeat;
background-position: center bottom;
position: absolute;
width: 100%;
height: 100%;
top: 100%;
left: 0;
transition: all 0.4s;
will-change: transform;
}
.hole.up .mole {
top: 0;
}
.score {
font-size: 3em;
text-align: center;
margin-bottom: 30px;
}
button {
display: block;
margin: 0 auto;
font-size: 2em;
}
</style>
</head>
<body>
<div class="score">0</div>
<div class="game">
<div class="hole hole1">
<div class="mole"></div>
</div>
<div class="hole hole2">
<div class="mole"></div>
</div>
<div class="hole hole3">
<div class="mole"></div>
</div>
<div class="hole hole4">
<div class="mole"></div>
</div>
<div class="hole hole5">
<div class="mole"></div>
</div>
<div class="hole hole6">
<div class="mole"></div>
</div>
</div>
<button onclick="startGame()">开始游戏</button>
</body>
</html>
```
这个小游戏的规则很简单:你需要在一定的时间内,尽可能地打中地鼠。每打中一个地鼠,得分就会加一分。