Flappy Bird 是一款经典的 2D 游戏,玩家需要控制一只小鸟在一系列管道之间穿梭,避免碰撞到管道或者落地,同时尽可能多地通过管道以获得高分。本文使用 Pygame 编写了一个 Flappy Bird 游戏的示例代码。
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 游戏区域宽度和高度
WIDTH = 288
HEIGHT = 512
# 初始化 Pygame
pygame.init()
# 设置游戏区域大小
WINDOW_SIZE = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(WINDOW_SIZE)
# 设置窗口标题
pygame.display.set_caption("Flappy Bird")
class Bird:
def __init__(self):
self.image = pygame.image.load("bird.png").convert_alpha()
self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2))
self.speed = 0
# 处理按键事件
def handle_event(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
self.speed = -10
# 更新鸟的位置和速度
def update(self):
self.speed += 1
self.rect.y += self.speed
# 绘制鸟
def draw(self):
screen.blit(self.image, self.rect)
class Pipe:
def __init__(self, x):
self.image = pygame.image.load("pipe.png").convert_alpha()
self.rect_top = self.image.get_rect(topleft=(x, -random.randint(100, 300)))
self.rect_bottom = self.image.get_rect(topleft=(x, self.rect_top.bottom + 150))
# 更新管道的位置
def update(self):
self.rect_top.x -= 2
self.rect_bottom.x -= 2
# 绘制管道
def draw(self):
screen.blit(self.image, self.rect_top)
screen.blit(pygame.transform.flip(self.image, False, True), self.rect_bottom)
# 加载游戏资源
font = pygame.font.Font(pygame.font.get_default_font(), 25)
score_sound = pygame.mixer.Sound("score.wav")
hit_sound = pygame.mixer.Sound("hit.wav")
game_over_sound = pygame.mixer.Sound("gameover.wav")
bird = Bird()
pipes = [Pipe(WIDTH + i * 150) for i in range(3)]
score = 0
# 游戏循环
game_over = False
clock = pygame.time.Clock()
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
else:
bird.handle_event(event)
# 更新鸟和管道
bird.update()
for pipe in pipes:
pipe.update()
# 判断是否碰到管道
if bird.rect.colliderect(pipe.rect_top) or bird.rect.colliderect(pipe.rect_bottom):
hit_sound.play()
game_over = True
# 判断是否通过管道
if bird.rect.left > pipe.rect_top.right and not pipe.rect_top.collidedictall(pipes[0].rect_top) and not pipe.rect_top.collidedictall(pipes[1].rect_top):
score += 1
score_sound.play()
# 重置管道位置
if pipe.rect_top.right < 0:
pipe.rect_top.left = WIDTH
pipe.rect_top.top = -random.randint(100, 300)
pipe.rect_bottom.left = WIDTH
pipe.rect_bottom.top = pipe.rect_top.bottom + 150
# 渲染屏幕
screen.fill(BLACK)
# 绘制鸟和管道
bird.draw()
for pipe in pipes:
pipe.draw()
# 绘制得分
score_text = font.render(str(score), True, WHITE)
screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, 50))
# 更新屏幕
pygame.display.update()
# 控制游戏速度
clock.tick(60)
# 播放游戏结束音效
game_over_sound.play()
# 等待一段时间,然后退出 Pygame
pygame.time.wait(2000)
pygame.quit()