Python实现经典游戏Flybird:从零开始编写飞翔小鸟程序

引言

还记得那款让无数玩家抓狂却又欲罢不能的手机游戏《Flappy Bird》吗?这款由越南开发者Dong Nguyen开发的游戏,以其简洁的画风和极高的难度,迅速在全球范围内走红。今天,我们将使用Python编程语言和Pygame库,从零开始复刻这款经典游戏,带大家体验编程的乐趣和成就感。

环境配置

在开始编写代码之前,我们需要准备好开发环境。以下是所需的环境配置:

  1. Python版本:建议使用Python 3.6或更高版本。
  2. Pygame库:可以通过pip安装,命令如下:
    
    pip install pygame
    

游戏设计思路

《Flappy Bird》的核心玩法非常简单:玩家通过点击屏幕控制小鸟飞行,避开一系列绿色管道。游戏的主要组成部分包括:

  1. 小鸟:玩家控制的角色,通过点击屏幕上升,松开则下降。
  2. 管道:随机生成的障碍物,小鸟需要从中穿过。
  3. 背景和地板:提供视觉效果的背景和地板。
  4. 分数系统:记录玩家穿过的管道数量。

代码实现

接下来,我们将逐步实现游戏的各个部分。

1. 初始化游戏

首先,我们需要初始化Pygame并设置游戏窗口。

import pygame
import random

# 初始化Pygame
pygame.init()

# 设置屏幕尺寸
SCREEN_WIDTH = 288
SCREEN_HEIGHT = 512
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# 设置游戏标题
pygame.display.set_caption('Flybird')

# 设置帧率
FPS = 60
clock = pygame.time.Clock()
2. 加载资源
# 加载图片
bird_images = [
    pygame.image.load('assets/bird1.png'),
    pygame.image.load('assets/bird2.png'),
    pygame.image.load('assets/bird3.png')
]
background = pygame.image.load('assets/background.png')
floor = pygame.image.load('assets/floor.png')
pipe_top = pygame.image.load('assets/pipe_top.png')
pipe_bottom = pygame.image.load('assets/pipe_bottom.png')

# 设置地板位置
floor_x = 0
3. 小鸟类

定义一个Bird类来管理小鸟的状态和行为。

class Bird:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.velocity = 0
        self.image_index = 0
        self.images = bird_images
        self.rect = self.images[0].get_rect(center=(x, y))

    def update(self):
        self.velocity += 0.5  # 重力效果
        self.y += self.velocity
        self.rect.y = self.y

        # 更新小鸟图片,实现翅膀扇动效果
        self.image_index = (self.image_index + 1) % 3
        self.image = self.images[self.image_index]

    def jump(self):
        self.velocity = -10  # 向上跳跃

    def draw(self, screen):
        screen.blit(self.image, self.rect)
4. 管道类

定义一个Pipe类来管理管道的生成和移动。

class Pipe:
    def __init__(self, x):
        self.x = x
        self.height = random.randint(100, 300)
        self.top_pipe = pygame.transform.flip(pipe_top, False, True)
        self.bottom_pipe = pipe_bottom
        self.top_rect = self.top_pipe.get_rect(midbottom=(x, self.height - 150))
        self.bottom_rect = self.bottom_pipe.get_rect(midtop=(x, self.height + 150))

    def update(self):
        self.x -= 5
        self.top_rect.x = self.x
        self.bottom_rect.x = self.x

    def draw(self, screen):
        screen.blit(self.top_pipe, self.top_rect)
        screen.blit(self.bottom_pipe, self.bottom_rect)

    def off_screen(self):
        return self.x < -50
5. 游戏主循环

最后,我们需要实现游戏的主循环,处理用户输入、更新游戏状态和渲染画面。

def main():
    bird = Bird(50, SCREEN_HEIGHT // 2)
    pipes = [Pipe(300), Pipe(500)]
    score = 0
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                bird.jump()

        # 更新游戏状态
        bird.update()
        for pipe in pipes:
            pipe.update()
            if pipe.off_screen():
                pipes.remove(pipe)
                pipes.append(Pipe(SCREEN_WIDTH + 100))

        # 检测碰撞
        for pipe in pipes:
            if bird.rect.colliderect(pipe.top_rect) or bird.rect.colliderect(pipe.bottom_rect):
                running = False

        # 渲染画面
        screen.blit(background, (0, 0))
        bird.draw(screen)
        for pipe in pipes:
            pipe.draw(screen)
        screen.blit(floor, (floor_x, SCREEN_HEIGHT - 100))
        floor_x -= 5
        if floor_x < -SCREEN_WIDTH:
            floor_x = 0

        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()

if __name__ == '__main__':
    main()

总结

通过以上步骤,我们成功使用Python和Pygame库复刻了经典游戏《Flappy Bird》。这个过程不仅让我们掌握了Pygame的基本使用方法,还锻炼了我们的编程思维和问题解决能力。希望这篇文章能激发你对编程的兴趣,动手尝试更多有趣的项目吧!

扩展阅读

  • Pygame官方文档
  • FlapPyBird开源项目

希望你在编程的道路上越走越远,享受每一个创造的瞬间!