width, height = 288, 512
window = pygame.display.set_mode((width, height))
pygame.display.set_caption(“Flappy Bird”)
#### 2、加载游戏资源
Flappy Bird游戏需要一些图像和音效资源,可以直接在互联网上找到适合的资源,将它们保存在项目文件夹中,然后通过使用Pygame库提供的函数,可以加载这些资源到游戏中。
加载背景图像
background = pygame.image.load(“background.png”)
加载鸟的图像
bird = pygame.image.load(“bird.png”)
加载管道图像
pipe = pygame.image.load(“pipe.png”)
加载音效
flap_sound = pygame.mixer.Sound(“flap.wav”)
#### 3、游戏循环
接下来,需要创建一个游戏循环来更新游戏状态和处理用户输入,游戏循环将一直运行,直到玩家退出游戏为止。
游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新游戏状态
# 绘制游戏画面
window.blit(background, (0, 0))
window.blit(bird, (100, 200))
window.blit(pipe, (200, 300))
# 刷新屏幕
pygame.display.flip()
退出游戏
pygame.quit()
#### 4、添加游戏逻辑
为了让游戏变得有趣,需要添加一些游戏逻辑,比如让小鸟能够上下飞行,并且在与管道碰撞时游戏结束,可以使用变量来跟踪小鸟的位置和速度,并使用条件语句来检测碰撞。
小鸟的位置和速度
bird_x = 100
bird_y = 200
bird_speed = 0
游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_speed = -5
flap_sound.play()
# 更新游戏状态
bird_y += bird_speed
bird_speed += 0.2
# 检测碰撞
if bird_y < 0 or bird_y > height:
running = False
# 绘制游戏画面
window.blit(background, (0, 0))
window.blit(bird, (bird_x, bird_y))
window.blit(pipe, (200, 300))
# 刷新屏幕
pygame.display.flip()
退出游戏
pygame.quit()
#### 5、完善游戏逻辑
为了让这款游戏更加完善,还可以添加管道的移动和生成,通过使用列表来存储多个管道可以实现管道的连续移动。当一个管道离开屏幕时,可以将其移出列表,并在屏幕的右侧生成一个新的管道。
管道列表
pipes = []
游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_speed = -5
flap_sound.play()
# 更新游戏状态
bird_y += bird_speed
bird_speed += 0.2
# 生成管道
if len(pipes) == 0 or pipes[-1][0] < width - 200:
pipe_x = width
pipe_y = random.randint(100, height - 200)
pipes.append((pipe_x, pipe_y))
# 移动管道
for i in range(len(pipes)):
pipes[i] = (pipes[i][0] - 2, pipes[i][1])
# 移除离开屏幕的管道
if pipes[0][0] < -pipe.get_width():
pipes.pop(0)
# 检测碰撞
最后
不知道你们用的什么环境,我一般都是用的Python3.6环境和pycharm解释器,没有软件,或者没有资料,没人解答问题,都可以免费领取(包括今天的代码),过几天我还会做个视频教程出来,有需要也可以领取~
给大家准备的学习资料包括但不限于:
Python 环境、pycharm编辑器/永久激活/翻译插件
python 零基础视频教程
Python 界面开发实战教程
Python 爬虫实战教程
Python 数据分析实战教程
python 游戏开发实战教程
Python 电子书100本
Python 学习路线规划

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
这篇博客详细介绍了如何使用Python的pygame库制作Flappy Bird游戏。从加载背景、鸟和管道的图像,到设置游戏循环和处理事件,再到实现小鸟的位置和速度控制,以及添加音效,逐步展示了游戏的实现过程。最后,博主提供了Python3.6环境及PyCharm相关资源的免费领取信息,鼓励大家系统学习并加入技术交流圈子。


被折叠的 条评论
为什么被折叠?



