创建一个简单的打地鼠游戏涉及HTML5、CSS和JavaScript。以下是一个基本的示例,你可以在此基础上进行扩展和改进。
1. HTML结构
<!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>
<h1>打地鼠游戏</h1>
<div id="gameArea">
<!-- 地鼠洞 -->
<div class="hole">
<div class="mole"></div>
</div>
<!-- 你可以添加更多的地鼠洞 -->
</div>
<script src="script.js"></script>
</body>
</html>
2. CSS样式 (styles.css)
#gameArea {
width: 600px;
height: 400px;
position: relative;
background-color: #f0f0f0;
border: 2px solid #000;
}
.hole {
width: 100px;
height: 100px;
background-color: #888;
border: 2px solid #000;
position: absolute;
}
.mole {
width: 80px;
height: 80px;
background-color: brown;
border-radius: 50%;
position: absolute;
bottom: 0;
left: 10px;
transform: translateY(100%);
transition: transform 0.3s;
}
.hole.active .mole {
transform: translateY(0%);
}
3. JavaScript逻辑 (script.js)
document.addEventListener('DOMContentLoaded', function() {
const holes = document.querySelectorAll('.hole');
const mole = document.querySelector('.mole');
let lastHole;
let timeUp = false;
let score = 0;
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 showMole() {
const time = randomTime(500, 1000);
const hole = randomHole(holes);
hole.classList.add('active');
setTimeout(() => {
hole.classList.remove('active');
if (!timeUp) showMole();
}, time);
}
function startGame() {
score = 0;
timeUp = false;
showMole();
setTimeout(() => timeUp = true, 10000); // 游戏持续10秒
}
function hitMole(e) {
if (!e.isTrusted) return; // 防止作弊
if (e.target.classList.contains('mole')) {
score++;
console.log('打中地鼠! 得分:', score);
}
}
holes.forEach(hole => hole.addEventListener('click', hitMole));
startGame();
});
这个示例创建了一个简单的打地鼠游戏,其中地鼠会随机出现在一个洞穴中,并且玩家可以点击地鼠来增加得分。游戏持续10秒,然后停止。你可以根据需要扩展此示例,例如添加更多的洞穴、改进样式、添加得分板等。
标签:function,const,holes,一个打,地鼠,小游戏,HTML5,hole,mole From: https://www.cnblogs.com/ai888/p/18623041