实现上一篇扩展内容:
实现添加音效:在小鸟飞行、撞击管道等事件中添加音效,增强游戏体验。
添加难度等级:逐渐增加管道的速度和间隔,使游戏变得更加具有挑战性。
添加背景音乐和界面:美化游戏界面,增加游戏的吸引力。
添加音效
首先,我们需要准备一些音频文件。在小鸟飞行和撞击管道时播放相应的音效。接下来,在代码中添加音效的播放。
import pygame.mixer
# 在游戏初始化中加载音效
pygame.mixer.init()
flap_sound = pygame.mixer.Sound('flap.wav')
hit_sound = pygame.mixer.Sound('hit.wav')
# 在小鸟飞行时播放音效
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird.up()
flap_sound.play()
# 在碰撞时播放音效
if pipe.hits(bird):
# 游戏结束
running = False
hit_sound.play()
添加难度等级
我们可以通过增加管道的速度和间隔来增加难度等级。在游戏循环中根据一定的条件逐渐增加管道的速度和间隔。
# 增加管道的速度
for pipe in pipes:
pipe.speed += 0.001
# 增加管道的间隔
if len(pipes) < 5:
if pipes[-1].x < SCREEN_WIDTH - 200:
pipe_height = random.randint(50, SCREEN_HEIGHT - 250)
gap_increase = score // 10 # 每10分增加一次间隔
pipes.append(Pipe(SCREEN_WIDTH, pipe_height, 150 + gap_increase))
添加背景音乐和界面
为了美化游戏界面,我们可以添加背景音乐和更加吸引人的界面。首先,准备一些背景音乐和界面图片文件。然后,在游戏初始化中加载背景音乐,并在游戏循环中绘制背景图片。
# 在游戏初始化中加载背景音乐
pygame.mixer.music.load('background_music.mp3')
pygame.mixer.music.play(-1) # 循环播放
# 在游戏循环中绘制背景图片
background_image = pygame.image.load('background.jpg')
screen.blit(background_image, (0, 0))
完整代码更新
import pygame
import pygame.mixer
import random
from bird import Bird
from pipe import Pipe
# 游戏初始化
pygame.init()
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Flappy Bird')
# 加载背景音乐
pygame.mixer.init()
pygame.mixer.music.load('background_music.mp3')
pygame.mixer.music.play(-1) # 循环播放
# 加载音效
flap_sound = pygame.mixer.Sound('flap.wav')
hit_sound = pygame.mixer.Sound('hit.wav')
bird = Bird(50, SCREEN_HEIGHT // 2)
pipes = []
pipes.append(Pipe(SCREEN_WIDTH, SCREEN_HEIGHT // 2, 150))
clock = pygame.time.Clock()
score = 0
# 游戏循环
running = True
while running:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird.up()
flap_sound.play()
# 更新游戏状态
bird.update()
# 生成管道
for pipe in pipes:
pipe.update()
if pipe.hits(bird):
# 游戏结束
running = False
hit_sound.play()
if pipe.offscreen():
pipes.remove(pipe)
score += 1
# 增加管道的速度和间隔
for pipe in pipes:
pipe.speed += 0.001
if len(pipes) < 5:
if pipes[-1].x < SCREEN_WIDTH - 200:
pipe_height = random.randint(50, SCREEN_HEIGHT - 250)
gap_increase = score // 10 # 每10分增加一次间隔
pipes.append(Pipe(SCREEN_WIDTH, pipe_height, 150 + gap_increase))
# 渲染画面
screen.fill((0, 128, 255))
background_image = pygame.image.load('background.jpg')
screen.blit(background_image, (0, 0))
bird.show(screen)
for pipe in pipes:
pipe.show(screen)
# 显示分数
font = pygame.font.Font(None, 36)
text = font.render(f'Score: {score}', True, (255, 255, 255))
screen.blit(text, (10, 10))
# 刷新画面
pygame.display.update()
clock.tick(60)
pygame.quit()