前端搭建砸地鼠游戏
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
创建一个简单的废地鼠游戏涉及以下步骤:
- 准备HTML和CSS文件。
- 使用JavaScript创建游戏逻辑。
以下是一个简单的废地鼠游戏的示例代码:
HTML (index.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="style.css">
</head>
<body>
<div id="game">
<div id="score">分数: <span>0</span></div>
<canvas id="canvas" width="400" height="400"></canvas>
</div>
<script src="script.js"></script>
</body>
</html>
CSS (style.css
):
#game {
position: relative;
width: 400px;
height: 400px;
background: #e0e0e0;
}
#score {
position: absolute;
top: 0;
left: 0;
padding: 10px;
color: #fff;
background: rgba(0, 0, 0, 0.5);
}
#canvas {
cursor: pointer;
}
JavaScript (script.js
):
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const scoreElement = document.querySelector('#score span');
let mouse = {x: 0, y: 0};
let mousedown = false;
let score = 0;
function updateMousePos(e) {
mouse.x = e.offsetX;
mouse.y = e.offsetY;
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(mouse.x, mouse.y, 10, 0, Math.PI * 2);
context.fillStyle = mousedown ? 'red' : 'green';
context.fill();
}
function updateScore() {
scoreElement.textContent = score;
}
canvas.addEventListener('mousedown', (e) => {
mousedown = true;
updateMousePos(e);
});
canvas.addEventListener('mousemove', (e) => {
updateMousePos(e);
draw();
});
canvas.addEventListener('mouseup', (e) => {
mousedown = false;
updateMousePos(e);
score++;
updateScore();
});
// 初始化画布大小
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
// 绘制鼠标指针
draw();
这个游戏的规则是简单的:用户通过点击并拖动鼠标来绘制一个小圆。当用户释放鼠标按钮时,分数会增加。游戏中没有物理体,只是一个用于教学的简单示例。在实际的废地鼠游戏中,会有鼠标追逐、撞击和逃逸等
评论已关闭