当前位置:首页 > 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实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以直…

jquery js

jquery js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够更高…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…

js验证码实现

js验证码实现

验证码的基本原理 验证码(CAPTCHA)用于区分人类用户和自动化程序。常见类型包括图形验证码、滑动验证码、短信验证码等。JavaScript 可用于前端验证码的生成和验证逻辑。 图形验证码实现 使…

js实现vue模板

js实现vue模板

使用纯 JavaScript 实现 Vue 模板功能 要实现类似 Vue 的模板功能,可以通过以下步骤完成: 1. 数据绑定与响应式更新 通过 Object.defineProperty 或 Pr…

vue.js实现checkbox

vue.js实现checkbox

使用 v-model 绑定复选框 在 Vue.js 中,可以通过 v-model 指令实现复选框的双向数据绑定。复选框的值会与 Vue 实例中的数据属性同步。 <template>…