打地鼠游戏是一款经典的休闲游戏,深受各个年龄段玩家的喜爱。在HTML5技术兴起的今天,我们也可以轻松地用HTML5技术制作一款打地鼠游戏。下面,我就为大家详细介绍打地鼠游戏的玩法,并分享一份免费源码。
游戏玩法
游戏规则
- 游戏界面分为两个区域:地鼠区域和玩家操作区域。
- 地鼠区域会随机出现地鼠,玩家需要点击地鼠进行打击。
- 每次成功打击地鼠,玩家会获得相应的分数。
- 游戏有时间限制,玩家需要在规定时间内获得足够的分数才能胜利。
- 游戏结束后,会显示玩家的最终得分。
游戏界面
- 地鼠区域:使用HTML5的
canvas元素绘制地鼠,并随机放置在地鼠区域。 - 玩家操作区域:使用HTML5的
canvas元素绘制玩家操作的按钮。
游戏源码
以下是打地鼠游戏的免费源码,你可以将其复制到本地,然后用浏览器打开预览游戏效果。
<!DOCTYPE html>
<html>
<head>
<title>HTML5打地鼠游戏</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="600" height="400"></canvas>
<script>
// 游戏变量
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let score = 0;
let timer = null;
let gameover = false;
// 地鼠对象
class Mole {
constructor() {
this.x = Math.random() * (canvas.width - 100) + 50;
this.y = Math.random() * (canvas.height - 100) + 50;
this.width = 50;
this.height = 50;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.width / 2, 0, Math.PI * 2);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
hit(x, y) {
return x > this.x - this.width / 2 && x < this.x + this.width / 2 &&
y > this.y - this.height / 2 && y < this.y + this.height / 2;
}
}
// 初始化游戏
function init() {
score = 0;
gameover = false;
clearInterval(timer);
timer = setInterval(createMole, 1000);
}
// 创建地鼠
function createMole() {
const mole = new Mole();
ctx.clearRect(0, 0, canvas.width, canvas.height);
mole.draw();
}
// 检测点击事件
canvas.addEventListener('click', function(event) {
const mole = new Mole();
const x = event.clientX - canvas.offsetLeft;
const y = event.clientY - canvas.offsetTop;
if (mole.hit(x, y)) {
score++;
createMole();
}
if (score >= 10) {
gameover = true;
clearInterval(timer);
alert('游戏结束!你的得分是:' + score);
}
});
// 开始游戏
init();
</script>
</body>
</html>
总结
本文详细介绍了HTML5打地鼠游戏的玩法和源码。你可以根据自己的需求修改代码,添加更多有趣的元素,让游戏更加丰富。希望这篇文章能帮助你了解HTML5游戏开发,祝你在游戏开发的道路上越走越远!
