当前位置:首页 > JavaScript

js实现flybird

2026-04-06 09:33:12JavaScript

使用JavaScript实现Flappy Bird游戏

游戏基本结构

创建一个HTML文件,包含canvas元素用于绘制游戏界面。引入JavaScript文件处理游戏逻辑。

<!DOCTYPE html>
<html>
<head>
    <title>Flappy Bird</title>
    <style>
        canvas {
            border: 1px solid black;
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="600"></canvas>
    <script src="game.js"></script>
</body>
</html>

游戏核心逻辑

在game.js中实现游戏的主要功能。定义小鸟、管道和游戏状态管理。

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 游戏参数
const gravity = 0.5;
const jumpForce = -10;
const pipeWidth = 60;
const pipeGap = 150;
const pipeInterval = 1500;

// 小鸟对象
const bird = {
    x: 50,
    y: canvas.height / 2,
    width: 30,
    height: 30,
    velocity: 0,
    draw() {
        ctx.fillStyle = 'yellow';
        ctx.fillRect(this.x, this.y, this.width, this.height);
    },
    update() {
        this.velocity += gravity;
        this.y += this.velocity;

        // 防止小鸟飞出画布顶部
        if (this.y < 0) {
            this.y = 0;
            this.velocity = 0;
        }
    },
    flap() {
        this.velocity = jumpForce;
    }
};

// 管道数组
let pipes = [];
let score = 0;
let gameOver = false;
let lastPipeTime = 0;

游戏循环和输入处理

设置游戏循环并处理用户输入,实现小鸟跳跃和碰撞检测。

js实现flybird

// 生成新管道
function generatePipe() {
    const minHeight = 50;
    const maxHeight = canvas.height - pipeGap - minHeight;
    const height = Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight;

    pipes.push({
        x: canvas.width,
        height,
        passed: false
    });
}

// 绘制管道
function drawPipes() {
    ctx.fillStyle = 'green';
    pipes.forEach(pipe => {
        // 上管道
        ctx.fillRect(pipe.x, 0, pipeWidth, pipe.height);
        // 下管道
        ctx.fillRect(pipe.x, pipe.height + pipeGap, pipeWidth, canvas.height - pipe.height - pipeGap);
    });
}

// 更新管道位置
function updatePipes() {
    const currentTime = Date.now();
    if (currentTime - lastPipeTime > pipeInterval) {
        generatePipe();
        lastPipeTime = currentTime;
    }

    pipes.forEach(pipe => {
        pipe.x -= 2;

        // 计分逻辑
        if (!pipe.passed && pipe.x + pipeWidth < bird.x) {
            pipe.passed = true;
            score++;
        }
    });

    // 移除屏幕外的管道
    pipes = pipes.filter(pipe => pipe.x + pipeWidth > 0);
}

// 碰撞检测
function checkCollision() {
    // 地面碰撞
    if (bird.y + bird.height > canvas.height) {
        gameOver = true;
    }

    // 管道碰撞
    for (const pipe of pipes) {
        if (bird.x + bird.width > pipe.x && bird.x < pipe.x + pipeWidth) {
            if (bird.y < pipe.height || bird.y + bird.height > pipe.height + pipeGap) {
                gameOver = true;
            }
        }
    }
}

// 游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    if (!gameOver) {
        bird.update();
        updatePipes();
        checkCollision();
    }

    bird.draw();
    drawPipes();

    // 显示分数
    ctx.fillStyle = 'black';
    ctx.font = '24px Arial';
    ctx.fillText(`Score: ${score}`, 10, 30);

    if (gameOver) {
        ctx.fillStyle = 'red';
        ctx.font = '48px Arial';
        ctx.fillText('Game Over', canvas.width / 2 - 100, canvas.height / 2);
    }

    requestAnimationFrame(gameLoop);
}

// 键盘控制
document.addEventListener('keydown', (e) => {
    if (e.code === 'Space') {
        if (gameOver) {
            // 重置游戏
            bird.y = canvas.height / 2;
            bird.velocity = 0;
            pipes = [];
            score = 0;
            gameOver = false;
            lastPipeTime = Date.now();
        } else {
            bird.flap();
        }
    }
});

// 触摸控制
canvas.addEventListener('click', () => {
    if (gameOver) {
        // 重置游戏
        bird.y = canvas.height / 2;
        bird.velocity = 0;
        pipes = [];
        score = 0;
        gameOver = false;
        lastPipeTime = Date.now();
    } else {
        bird.flap();
    }
});

// 开始游戏
gameLoop();

游戏优化建议

  1. 添加图像资源替换简单的矩形绘制
  2. 实现游戏开始界面和暂停功能
  3. 添加音效增强游戏体验
  4. 实现难度随分数增加而提高
  5. 添加本地存储保存最高分记录

这个实现包含了Flappy Bird游戏的核心功能,包括小鸟控制、管道生成、碰撞检测和计分系统。可以根据需要进一步扩展和完善游戏功能。

标签: jsflybird
分享给朋友:

相关文章

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现乘

js实现乘

JavaScript 实现乘法运算 在 JavaScript 中实现乘法运算可以通过多种方式完成,包括基本运算符、函数封装以及高级算法(如大数乘法)。以下是几种常见方法: 使用基本乘法运算符 Jav…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。 &…