利用js 写一个打地鼠游戏
时间: 2023-07-08 08:07:27 浏览: 73
js写的打地鼠游戏
5星 · 资源好评率100%
好的,下面是一个简单的打地鼠游戏的实现,你可以参考一下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>打地鼠游戏</title>
<style>
.container {
width: 400px;
height: 400px;
margin: 0 auto;
border: 1px solid #ccc;
position: relative;
overflow: hidden;
}
.hole {
width: 80px;
height: 80px;
background-color: #eee;
border: 1px solid #ccc;
position: absolute;
top: 0;
left: 0;
display: none;
}
.mouse {
width: 80px;
height: 80px;
background-image: url('mouse.png');
background-size: cover;
position: absolute;
top: 0;
left: 0;
display: none;
}
</style>
</head>
<body>
<div class="container">
<div class="hole"></div>
<div class="mouse"></div>
</div>
<button id="start">开始游戏</button>
<script>
var container = document.querySelector('.container');
var hole = document.querySelector('.hole');
var mouse = document.querySelector('.mouse');
var score = 0;
var timer;
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function showMouse() {
var x = getRandom(0, container.offsetWidth - hole.offsetWidth);
var y = getRandom(0, container.offsetHeight - hole.offsetHeight);
hole.style.top = y + 'px';
hole.style.left = x + 'px';
hole.style.display = 'block';
mouse.style.top = y + 'px';
mouse.style.left = x + 'px';
mouse.style.display = 'block';
}
function hideMouse() {
hole.style.display = 'none';
mouse.style.display = 'none';
}
function hitMouse() {
score++;
document.querySelector('#score').innerHTML = score;
}
function startGame() {
if (timer) {
clearInterval(timer);
}
score = 0;
document.querySelector('#score').innerHTML = score;
timer = setInterval(function() {
hideMouse();
setTimeout(function() {
showMouse();
}, 500);
}, 1000);
}
document.querySelector('#start').addEventListener('click', function() {
startGame();
});
mouse.addEventListener('click', function() {
hitMouse();
hideMouse();
});
</script>
</body>
</html>
```
这个游戏的实现比较简单,主要分为三个部分:
1. 随机显示地鼠
2. 隐藏地鼠
3. 处理击中地鼠的事件
通过 setInterval 和 setTimeout 实现地鼠的随机显示和隐藏,通过 click 事件处理击中地鼠的事件。
阅读全文