js实现见缝插针
实现思路
见缝插针游戏的核心逻辑是在旋转的圆盘上,玩家需要在合适的时机点击屏幕,将针插入圆盘上的空隙而不碰撞到已有的针。以下是一个基于JavaScript和HTML5 Canvas的实现方法。
初始化游戏场景
创建一个Canvas元素并设置基本样式,用于绘制圆盘和针。初始化游戏状态变量,如圆盘旋转速度、针的数量、游戏是否结束等。
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const width = canvas.width = 400;
const height = canvas.height = 400;
let needles = [];
let diskAngle = 0;
let diskSpeed = 0.02;
let gameOver = false;
绘制圆盘和针
在Canvas上绘制旋转的圆盘和已插入的针。圆盘的中心点固定在画布中心,针从圆盘边缘向外延伸。
function drawDisk() {
ctx.save();
ctx.translate(width / 2, height / 2);
ctx.rotate(diskAngle);
ctx.beginPath();
ctx.arc(0, 0, 150, 0, Math.PI * 2);
ctx.fillStyle = '#f0f0f0';
ctx.fill();
ctx.stroke();
ctx.restore();
}
function drawNeedles() {
ctx.save();
ctx.translate(width / 2, height / 2);
needles.forEach(needle => {
ctx.rotate(needle.angle);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -200);
ctx.lineWidth = 5;
ctx.strokeStyle = needle.color;
ctx.stroke();
ctx.rotate(-needle.angle);
});
ctx.restore();
}
处理用户输入
监听点击事件,当玩家点击屏幕时,计算当前圆盘旋转角度并插入新针。检查新针是否与已有针碰撞。
canvas.addEventListener('click', () => {
if (gameOver) return;
const newNeedle = {
angle: diskAngle,
color: `hsl(${Math.random() * 360}, 70%, 50%)`
};
const collision = needles.some(needle => {
return Math.abs(needle.angle - newNeedle.angle) < 0.1;
});
if (collision) {
gameOver = true;
alert('Game Over!');
} else {
needles.push(newNeedle);
}
});
游戏循环
使用requestAnimationFrame实现游戏循环,更新圆盘旋转角度并重绘场景。
function gameLoop() {
ctx.clearRect(0, 0, width, height);
drawDisk();
drawNeedles();
if (!gameOver) {
diskAngle += diskSpeed;
if (diskAngle > Math.PI * 2) {
diskAngle -= Math.PI * 2;
}
}
requestAnimationFrame(gameLoop);
}
gameLoop();
增加难度
随着游戏进行,可以逐渐增加圆盘旋转速度或减少针的宽度以提高难度。
function increaseDifficulty() {
if (needles.length % 5 === 0) {
diskSpeed += 0.005;
}
}
完整代码示例
将以上代码整合到一个HTML文件中,确保Canvas元素已正确创建。
<!DOCTYPE html>
<html>
<head>
<title>见缝插针游戏</title>
<style>
canvas { display: block; margin: 0 auto; background: #eee; }
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
// 上述JavaScript代码放在这里
</script>
</body>
</html>






