python flappy bird小游戏分步实现流程


Posted in Python onFebruary 15, 2022

导语:

哈喽,哈喽~今天小编又来分享小游戏了——flappy bird(飞扬的小鸟),这个游戏非常的经典,游戏中玩家必须控制一只小鸟,跨越由各种不同长度水管所组成的障碍。这个游戏能对于小编来说还是有点难度的。

python flappy bird小游戏分步实现流程

python flappy bird小游戏分步实现流程

开发工具:

Python版本:3.6.4

相关模块:

pygame模块;

以及一些python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

运行视频:

python flappy bird小游戏分步实现流程

播放链接:https://live.csdn.net/v/embed/184490

正文:

首先,我们来写个开始界面,让他看起来更像个游戏一些。效果大概是这样的:

python flappy bird小游戏分步实现流程

原理也简单,关键点有三个:

(1)下方深绿浅绿交替的地板不断往左移动来制造小鸟向前飞行的假象;

(2)每过几帧切换一下小鸟的图片来实现小鸟翅膀扇动的效果:

python flappy bird小游戏分步实现流程

(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

管道: 

python flappy bird小游戏分步实现流程

python flappy bird小游戏分步实现流程

python flappy bird小游戏分步实现流程

(4) 进入游戏后,随机产生两对管道,并不断左移,当最左边的管道快要因为到达游戏界面的左边界而消失时,重新生成一对管道(注意不要重复生成);

(5) 当小鸟穿越一个上下管道之间的缺口时,游戏得分加一(注意不要重复记分)。

计分表

python flappy bird小游戏分步实现流程

python flappy bird小游戏分步实现流程

这里简单贴下主程序的源代码吧:

# 进入主游戏
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)

结尾:

这期游戏分享就到这结束啦喜欢的友友们动手试试看哦!家人们的支持是小编更新最大的动力

到此这篇关于python flappy bird小游戏分布实现流程的文章就介绍到这了,更多相关python flappy bird内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
树莓派中python获取GY-85九轴模块信息示例
Dec 05 Python
Python的Twisted框架中使用Deferred对象来管理回调函数
May 25 Python
详解Python中open()函数指定文件打开方式的用法
Jun 04 Python
python利用正则表达式排除集合中字符的功能示例
Oct 10 Python
使用Python的package机制如何简化utils包设计详解
Dec 11 Python
python3.6+django2.0开发一套学员管理系统
Mar 03 Python
详解windows python3.7安装numpy问题的解决方法
Aug 13 Python
pyqt5 禁止窗口最大化和禁止窗口拉伸的方法
Jun 18 Python
python+selenium 鼠标事件操作方法
Aug 24 Python
如何理解python面向对象编程
Jun 01 Python
增大python字体的方法步骤
Jul 05 Python
Python list去重且保持原顺序不变的方法
Apr 03 Python
Python 居然可以在 Excel 中画画你知道吗
Feb 15 #Python
Python 恐龙跑跑小游戏实现流程
详解Python+OpenCV进行基础的图像操作
Appium中scroll和drag_and_drop根据元素位置滑动
Feb 15 #Python
python 远程执行命令的详细代码
Feb 15 #Python
python 详解turtle画爱心代码
python分分钟绘制精美地图海报
You might like
Window 7/XP 安装Apache 2.4与PHP 5.4 的过程详解
2013/06/02 PHP
PHP开发框架kohana3 自定义路由设置示例
2014/07/14 PHP
Laravel 5框架学习之Laravel入门和新建项目
2015/04/07 PHP
weiphp微信公众平台授权设置
2016/01/04 PHP
php+flash+jQuery多图片上传源码分享
2020/07/27 PHP
Laravel 创建可以传递参数 Console服务的例子
2019/10/14 PHP
Nigma vs Alliance BO5 第五场2.14
2021/03/10 DOTA
div浮层,滚动条移动,位置保持不变的4种方法汇总
2013/12/11 Javascript
JavaScript动态设置div的样式的方法
2015/12/26 Javascript
文本框只能输入数字的js代码(含小数点)
2016/07/10 Javascript
JavaScript定义函数_动力节点Java学院整理
2017/06/27 Javascript
vue2+el-menu实现路由跳转及当前项的设置方法实例
2017/11/07 Javascript
如何解决js函数防抖、节流出现的问题
2019/06/17 Javascript
koa2+vue实现登陆及登录状态判断
2019/08/15 Javascript
layui table去掉右侧滑动条的实现方法
2019/09/05 Javascript
云服务器部署Node.js项目的方法步骤(小白系列)
2020/03/23 Javascript
[04:27]DOTA2官方论坛水友赛集锦
2013/09/16 DOTA
Python内置函数的用法实例教程
2014/09/08 Python
用 Python 爬了爬自己的微信朋友(实例讲解)
2017/08/25 Python
python实现给scatter设置颜色渐变条colorbar的方法
2018/12/13 Python
Python之——生成动态路由轨迹图的实例
2019/11/22 Python
python3实现从kafka获取数据,并解析为json格式,写入到mysql中
2019/12/23 Python
Django框架获取form表单数据方式总结
2020/04/22 Python
python的链表基础知识点
2020/09/13 Python
python制作微博图片爬取工具
2021/01/16 Python
教师自我鉴定
2013/12/13 职场文书
小学后勤管理制度
2014/01/14 职场文书
简历里的自我评价范文
2014/02/24 职场文书
林肯就职演讲稿
2014/05/19 职场文书
公司领导班子群众路线四风问题对照检查材料
2014/10/02 职场文书
针对吵架老公保证书
2015/05/08 职场文书
民间借贷纠纷答辩状
2015/08/03 职场文书
2016幼儿园新学期寄语
2015/12/03 职场文书
新西兰:最新留学学习计划书写作指南
2019/07/15 职场文书
详解thinkphp的Auth类认证
2021/05/28 PHP
Python连续赋值需要注意的一些问题
2021/06/03 Python