python flappy bird小游戏分步实现流程
作者:迢迢x 发布时间:2023-10-09 10:45:41
导语:
哈喽,哈喽~今天小编又来分享小游戏了——flappy bird(飞扬的小鸟),这个游戏非常的经典,游戏中玩家必须控制一只小鸟,跨越由各种不同长度水管所组成的障碍。这个游戏能对于小编来说还是有点难度的。
开发工具:
Python版本:3.6.4
相关模块:
pygame模块;
以及一些python自带的模块。
环境搭建
安装Python并添加到环境变量,pip安装需要的相关模块即可。
运行视频:
播放链接:https://live.csdn.net/v/embed/184490
正文:
首先,我们来写个开始界面,让他看起来更像个游戏一些。效果大概是这样的:
原理也简单,关键点有三个:
(1)下方深绿浅绿交替的地板不断往左移动来制造小鸟向前飞行的假象;
(2)每过几帧切换一下小鸟的图片来实现小鸟翅膀扇动的效果:
(3)有规律地改变小鸟竖直方向上的位置来实现上下移动的效果。
具体而言,代码实现如下:
'''显示开始界面'''
def startGame(screen, sounds, bird_images, other_images, backgroud_image, cfg):
base_pos = [0, cfg.SCREENHEIGHT*0.79]
base_diff_bg = other_images['base'].get_width() - backgroud_image.get_width()
msg_pos = [(cfg.SCREENWIDTH-other_images['message'].get_width())/2, cfg.SCREENHEIGHT*0.12]
bird_idx = 0
bird_idx_change_count = 0
bird_idx_cycle = itertools.cycle([0, 1, 2, 1])
bird_pos = [cfg.SCREENWIDTH*0.2, (cfg.SCREENHEIGHT-list(bird_images.values())[0].get_height())/2]
bird_y_shift_count = 0
bird_y_shift_max = 9
shift = 1
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
return {'bird_pos': bird_pos, 'base_pos': base_pos, 'bird_idx': bird_idx}
sounds['wing'].play()
bird_idx_change_count += 1
if bird_idx_change_count % 5 == 0:
bird_idx = next(bird_idx_cycle)
bird_idx_change_count = 0
base_pos[0] = -((-base_pos[0] + 4) % base_diff_bg)
bird_y_shift_count += 1
if bird_y_shift_count == bird_y_shift_max:
bird_y_shift_max = 16
shift = -1 * shift
bird_y_shift_count = 0
bird_pos[-1] = bird_pos[-1] + shift
screen.blit(backgroud_image, (0, 0))
screen.blit(list(bird_images.values())[bird_idx], bird_pos)
screen.blit(other_images['message'], msg_pos)
screen.blit(other_images['base'], base_pos)
pygame.display.update()
clock.tick(cfg.FPS)
点击空格键或者↑键进入主程序。对于主程序,在进行了必要的初始化工作之后,在游戏开始界面中实现的内容的基础上,主要还需要实现的内容有以下几个部分:
(1) 管道和深绿浅绿交替的地板不断往左移来实现小鸟向前飞行的效果;
(2) 按键检测,当玩家点击空格键或者↑键时,小鸟向上做加速度向下的均减速直线运动直至向上的速度衰减为0,否则小鸟做自由落体运动(实现时为了方便,可以认为在极短的时间段内小鸟的运动方式为匀速直线运动);
(3) 碰撞检测,当小鸟与管道/游戏边界碰撞到时,游戏失败并进入游戏结束界面。注意,为了碰撞检测更精确,我们使用:
pygame.sprite.collide_mask
管道:
(4) 进入游戏后,随机产生两对管道,并不断左移,当最左边的管道快要因为到达游戏界面的左边界而消失时,重新生成一对管道(注意不要重复生成);
(5) 当小鸟穿越一个上下管道之间的缺口时,游戏得分加一(注意不要重复记分)。
计分表
这里简单贴下主程序的源代码吧:
# 进入主游戏
score = 0
bird_pos, base_pos, bird_idx = list(game_start_info.values())
base_diff_bg = other_images['base'].get_width() - backgroud_image.get_width()
clock = pygame.time.Clock()
# --管道类
pipe_sprites = pygame.sprite.Group()
for i in range(2):
pipe_pos = Pipe.randomPipe(cfg, pipe_images.get('top'))
pipe_sprites.add(Pipe(image=pipe_images.get('top'), position=(cfg.SCREENWIDTH+200+i*cfg.SCREENWIDTH/2, pipe_pos.get('top')[-1])))
pipe_sprites.add(Pipe(image=pipe_images.get('bottom'), position=(cfg.SCREENWIDTH+200+i*cfg.SCREENWIDTH/2, pipe_pos.get('bottom')[-1])))
# --bird类
bird = Bird(images=bird_images, idx=bird_idx, position=bird_pos)
# --是否增加pipe
is_add_pipe = True
# --游戏是否进行中
is_game_running = True
while is_game_running:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
bird.setFlapped()
sounds['wing'].play()
# --碰撞检测
for pipe in pipe_sprites:
if pygame.sprite.collide_mask(bird, pipe):
sounds['hit'].play()
is_game_running = False
# --更新小鸟
boundary_values = [0, base_pos[-1]]
is_dead = bird.update(boundary_values, float(clock.tick(cfg.FPS))/1000.)
if is_dead:
sounds['hit'].play()
is_game_running = False
# --移动base实现小鸟往前飞的效果
base_pos[0] = -((-base_pos[0] + 4) % base_diff_bg)
# --移动pipe实现小鸟往前飞的效果
flag = False
for pipe in pipe_sprites:
pipe.rect.left -= 4
if pipe.rect.centerx < bird.rect.centerx and not pipe.used_for_score:
pipe.used_for_score = True
score += 0.5
if '.5' in str(score):
sounds['point'].play()
if pipe.rect.left < 5 and pipe.rect.left > 0 and is_add_pipe:
pipe_pos = Pipe.randomPipe(cfg, pipe_images.get('top'))
pipe_sprites.add(Pipe(image=pipe_images.get('top'), position=pipe_pos.get('top')))
pipe_sprites.add(Pipe(image=pipe_images.get('bottom'), position=pipe_pos.get('bottom')))
is_add_pipe = False
elif pipe.rect.right < 0:
pipe_sprites.remove(pipe)
flag = True
if flag: is_add_pipe = True
# --绑定必要的元素在屏幕上
screen.blit(backgroud_image, (0, 0))
pipe_sprites.draw(screen)
screen.blit(other_images['base'], base_pos)
showScore(screen, score, number_images)
bird.draw(screen)
pygame.display.update()
clock.tick(cfg.FPS)
游戏结束
假如我们的主角真的一个不小心如我们所料的撞死在了钢管上(往上翻,就在游戏开始那里),那就表示gameOver();
'''游戏结束界面'''
def endGame(screen, sounds, showScore, score, number_images, bird, pipe_sprites, backgroud_image, other_images, base_pos, cfg):
sounds['die'].play()
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
return
boundary_values = [0, base_pos[-1]]
bird.update(boundary_values, float(clock.tick(cfg.FPS))/1000.)
screen.blit(backgroud_image, (0, 0))
pipe_sprites.draw(screen)
screen.blit(other_images['base'], base_pos)
showScore(screen, score, number_images)
bird.draw(screen)
pygame.display.update()
clock.tick(cfg.FPS)
结尾:
这期游戏分享就到这结束啦喜欢的友友们动手试试看哦!家人们的支持是小编更新最大的动力
来源:https://blog.csdn.net/a55656aq/article/details/122537940


猜你喜欢
- 实现的功能:在win7下,每天晚上1点,自动将 F:/data中所有文件进行压缩,以[mongodb+日期]命名,将压缩好的文件存储在本地目
- 一:操作redis1:redis拓展安装composer require predis/predis或者你也可以通过 PECL 安装&nbs
- 查看并打印matplotlib中所有的colormap(cmap)类型代码如下:方法一import matplotlib.pyplot as
- SocketServer简化了网络服务器的编写。它有4个类:TCPServer,UDPServer,UnixStreamServer,Uni
- [编者注:]提起数据库,第一个想到的公司,一般都会是Oracle(即甲骨文公司)。Oracle在数据库领域一直处于领先地位。Oracle关系
- 前言本文给大家详细介绍了解决php-fpm.service not found问题的相关内容,文中介绍的非常详细,下面来一起看看详细的介绍:
- 在安装库的时候,一定要特别注意包之间的依赖性一、在Pycharm中直接安装第三方库1、打开Pycharm,点击左上角的File,点击Sett
- 写作背景最近本菜鸡有几个网站想要爬,每个爬虫的代码不一样,但 有某种联系,可以抽出一部分通用的代码制成模板,减少代码工作量,于是就有了这篇文
- 1、主动删除对象调用del 对象;程序运行结束后,python也会自动进行删除其他的对象。class Animal: &nbs
- $("input").attr("checked","checked") 设置以
- Web性能优化最佳实践中最重要的一条是减少HTTP请求,它也是YSlow中比重最大的一条规则。减少HTTP请求的方案主要有合并JavaScr
- !!!本博客,是对图像的背景颜色的修改的基础讲解~!!!还包括一个练习——是对背景色修改的一点应用尝试!!!——始终相信学习多一点探索,脚步
- atom(一款开源的代码编辑器)是github专门为程序员推出的一个跨平台文本编辑器。具有简洁和直观的图形用户界面,并有很多有趣的特点:支持
- 如何使用快捷键按出代码提示框更新win10,发现可以改取消ctrl + space快捷键的占用了!!!我们在平时写代码的时候难免会出现敲错字
- django rest framework使用django-filter注意事项:一定要在setting文件里面加载如下代码,而不是只安装包
- 导语前段时间不是制作了一款升级版本五子棋的嘛!但是居然有粉丝私信我说:“准备拿到代码玩一下ok过去了!太难了准备放收藏夹落灰q@q~”所噶,
- 一、使用以下命令查看当前安装mysql情况,查找以前是否装有mysqlrpm -qa|grep -i mysql可以看到如下图的所示:显示之
- 本文实例为大家分享了Python socket实现简单聊天室的具体代码,供大家参考,具体内容如下服务端使用了select模块,实现了对多个s
- remove 删除单个元素,删除首个符合条件的元素,按值删除,返回值为空List_remove = [1, 2, 2, 2, 3, 4]pr
- Softmax原理Softmax函数用于将分类结果归一化,形成一个概率分布。作用类似于二分类中的Sigmoid函数。对于一个k维向量z,我们