用canvas写个愤怒的小鸟小游戏
时间: 2023-07-27 09:06:11 浏览: 110
好的,以下是一个简单的愤怒的小鸟游戏的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>愤怒的小鸟</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="480" height="320"></canvas>
<script>
// 获取画布和上下文
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
// 定义鸟
var bird = {
x: 50,
y: canvas.height / 2,
radius: 20,
color: "red",
velocity: 0,
gravity: 0.5,
jump: -10
};
// 定义管道
var pipes = [];
var pipeGap = 100;
var pipeWidth = 50;
var pipeSpeed = 2.5;
// 定义分数
var score = 0;
// 监听空格键按下事件,使小鸟跳跃
document.addEventListener("keydown", function(event) {
if (event.keyCode === 32) {
bird.velocity = bird.jump;
}
});
// 游戏循环
function gameLoop() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 让小鸟受重力影响,更新位置
bird.velocity += bird.gravity;
bird.y += bird.velocity;
// 绘制小鸟
ctx.beginPath();
ctx.arc(bird.x, bird.y, bird.radius, 0, Math.PI * 2, false);
ctx.fillStyle = bird.color;
ctx.fill();
// 生成管道
if (pipes.length === 0 || pipes[pipes.length - 1].x < canvas.width - pipeGap) {
var pipeX = canvas.width + pipeWidth;
var pipeY = Math.floor(Math.random() * (canvas.height - pipeGap * 2)) + pipeGap;
pipes.push({
x: pipeX,
y: pipeY
});
}
// 移动管道
for (var i = 0; i < pipes.length; i++) {
pipes[i].x -= pipeSpeed;
// 绘制上管道
ctx.beginPath();
ctx.rect(pipes[i].x, 0, pipeWidth, pipes[i].y);
ctx.fillStyle = "green";
ctx.fill();
// 绘制下管道
ctx.beginPath();
ctx.rect(pipes[i].x, pipes[i].y + pipeGap, pipeWidth, canvas.height - pipes[i].y - pipeGap);
ctx.fillStyle = "green";
ctx.fill();
// 检测碰撞
if (bird.x + bird.radius > pipes[i].x && bird.x - bird.radius < pipes[i].x + pipeWidth) {
if (bird.y - bird.radius < pipes[i].y || bird.y + bird.radius > pipes[i].y + pipeGap) {
alert("Game Over! Your Score: " + score);
location.reload();
}
}
// 计算分数
if (pipes[i].x + pipeWidth < bird.x - bird.radius) {
score++;
pipes.splice(i, 1);
i--;
}
}
// 绘制分数
ctx.fillStyle = "black";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, 25);
// 循环调用游戏循环
requestAnimationFrame(gameLoop);
}
// 开始游戏循环
gameLoop();
</script>
</body>
</html>
```
这段代码使用canvas绘制了一个简单的愤怒的小鸟游戏,您可以在浏览器中打开并运行它来查看效果。
阅读全文