以下是一个使用HTML、CSS和JavaScript实现的简单打地鼠效果示例:
一、基础概念
二、相关优势
三、类型(这里主要从功能角度)
四、应用场景
五、代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
<meta name="viewport" content="width=device-width, initial - scale = 1.0">
<title>打地鼠游戏</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="game - area">
<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 src="script.js"></script>
</body>
</html>
#game - area {
display: flex;
justify - content: space - around;
width: 600px;
margin: 0 auto;
}
.hole {
width: 100px;
height: 100px;
background: url('hole.png') no - repeat center center;
background - size: cover;
position: relative;
}
.mole {
width: 80px;
height: 80px;
background: url('mole.png') no - repeat center center;
background - size: cover;
position: absolute;
bottom: 0;
left: 10px;
}
const holes = document.querySelectorAll('.hole');
let score = 0;
function randomTime(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
function peep() {
const time = randomTime(500, 2000);
const hole = holes[randomTime(0, holes.length)];
hole.classList.add('mole');
setTimeout(() => {
hole.classList.remove('mole');
if (!gameOver) {
peep();
}
}, time);
}
holes.forEach(hole => {
hole.addEventListener('click', () => {
if (hole.classList.contains('mole')) {
score++;
hole.classList.remove('mole');
}
});
});
let gameOver = false;
peep();
在这个示例中:
如果遇到问题,例如地鼠不出现:
peep
函数没有被正确调用。检查是否有语法错误或者逻辑错误阻止了函数的执行。holes.forEach
循环中的代码是否正确执行。如果想要增加更多功能,如计分显示:
<div id="score">0</div>
。document.getElementById('score').innerText = score;
。没有搜到相关的文章