返回
用JS几十行代码写一个「寻找掘金酱」的小游戏
前端
2023-12-15 16:35:21
在这座被黑夜笼罩的都市里,一位名叫掘金酱的神秘人物悄然现身。她的行踪诡秘,令人难以捉摸。现在,你的任务是编写一个“寻找掘金酱”的小游戏,让玩家通过控制鼠标的光束,在城市中搜索她的踪迹。
游戏规则:
- 玩家控制鼠标移动光束,照亮都市中的某个区域。
- 当光束命中掘金酱时,游戏结束。
- 如果玩家继续滑动鼠标,掘金酱将向玩家鬼畜而来。
代码实现:
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const player = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 10,
color: 'white'
};
const target = {
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
radius: 10,
color: 'yellow'
};
const gameOver = false;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(player.x, player.y, player.radius, 0, Math.PI * 2, false);
ctx.fillStyle = player.color;
ctx.fill();
ctx.beginPath();
ctx.arc(target.x, target.y, target.radius, 0, Math.PI * 2, false);
ctx.fillStyle = target.color;
ctx.fill();
if (gameOver) {
ctx.font = '30px Arial';
ctx.fillStyle = 'red';
ctx.fillText('Game Over!', canvas.width / 2 - 100, canvas.height / 2);
}
requestAnimationFrame(draw);
}
function update() {
if (!gameOver) {
if (player.x + player.radius >= canvas.width || player.x - player.radius <= 0) {
player.x = canvas.width / 2;
}
if (player.y + player.radius >= canvas.height || player.y - player.radius <= 0) {
player.y = canvas.height / 2;
}
if (Math.abs(player.x - target.x) < player.radius + target.radius && Math.abs(player.y - target.y) < player.radius + target.radius) {
gameOver = true;
}
}
}
function handleMouseMove(e) {
player.x = e.clientX;
player.y = e.clientY;
}
canvas.addEventListener('mousemove', handleMouseMove);
draw();
update();
游戏体验:
玩家进入游戏后,将控制鼠标光束在黑夜笼罩的都市中移动。光束照亮城市区域,而玩家需要尽可能快地寻找到掘金酱的身影。当鼠标命中掘金酱时,游戏结束,掘金酱将向玩家鬼畜而来。
这个小游戏用几十行JS代码就能实现,既简单又有趣,充分展示了编程的魅力。