pygame小游戏-------FlappyBird像素鸟的实现

2023-10-31

简述:对FlappyBird像素鸟游戏的简单复现,仅两百行左右,工程目录结构为image文件夹和run.py文件。
pygame模块的下载直接pip install pygame即可,图片下载地址为像素鸟图片,音频文件自己找一个即可。
在这里插入图片描述

import pygame
import random
import os

#constents
width,height = 288,512
fps = 10

#setup
pygame.init()
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption('小垃圾') #窗口名字
clock = pygame.time.Clock()

#materials 资源
image_dir = {}
for i in os.listdir('./image'):
    name,extension = os.path.splitext(i)
    path = os.path.join('./image',i)
    image_dir[name] = pygame.image.load(path)

music = pygame.mixer.Sound('E:/音乐/夜曲.mp3') #背景音乐

#resize
image_dir['管道'] = pygame.transform.scale(image_dir['管道'],(image_dir['管道'].get_width()+10,300))
image_dir['地面'] = pygame.transform.scale(image_dir['地面'],(width+40,120))

class Bird:
    def __init__(self,x,y):
        self.image_name = '蓝鸟'
        self.image = image_dir[self.image_name+str(random.randint(1,3))]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.y_vel = -10#初始速度
        self.max_y_vel = 10
        self.gravity = 1 #重力

        #角度变化
        self.rotata = 45
        self.max_rotata = -25
        self.rotata_vel = -3


    def updata(self,flap = False):

        if flap == True:
            self.y_vel = -10
            self.rotata = 45

        self.y_vel = min(self.y_vel+self.gravity,self.max_y_vel)#先上后下
        self.rect.y += self.y_vel

        self.rotata = max(self.rotata+self.rotata_vel,self.max_rotata)
        self.image = image_dir[self.image_name + str(random.randint(1, 3))]
        self.image = pygame.transform.rotate(self.image,self.rotata)

    def deathing(self):
        if self.rect.bottom < height-image_dir['地面'].get_height()//2-30:
            self.gravity+=2
            self.rect.y+= self.gravity
            self.image = image_dir[self.image_name + str(random.randint(1, 3))]
            self.image = pygame.transform.rotate(self.image, -40)
            return False
        return True


class Pipe:
    def __init__(self,x,y,cap):
        if cap == True:
            self.image = image_dir['管道']
            self.rect = self.image.get_rect()
            self.rect.x = x  #rect.x = x
            self.rect.y = y

        else:
            self.image = pygame.transform.flip(pygame.transform.scale(image_dir['管道'],(image_dir['管道'].get_width(),height)),False,True)
            self.rect = self.image.get_rect()
            self.rect.x = x  # rect.x = x
            self.rect.y = -height+y-100
        self.x_vel = -4

    def updata(self):
        self.rect.x  +=self.x_vel


class Floor:
    def __init__(self):
        self.floor_grap = image_dir['地面'].get_width() - width
        self.floor_x = 0
    def show_floor(self):
        self.floor_x -= 4
        screen.blit(image_dir['地面'], (self.floor_x, height - image_dir['地面'].get_height()))  # 绘制照片
        if self.floor_x <= -self.floor_grap:
            self.floor_x = 0

def show_score(score,choice):
    if choice == 0:
        w = image_dir['0'].get_width()*1.1
        x = (width - w*len(score))/2
        y = height*0.1
        for i in score:
            screen.blit(image_dir[i],(x,y))
            x += w
    else:
        w = image_dir['0'].get_width()*0.5
        x = width-2*w
        y =10
        for i in score[::-1]:
            screen.blit(image_dir[i],(x,y))
            x -= w


def menu_windows():
    bird_y_vel = 1
    bird_y = height/3-20
    bird1 = Bird(width/3-20, height/3-20)
    bird2 =  Bird(width/3+80, height/3-20)
    bird2.image_name = '红鸟'
    floor = Floor()
    while True:
        bird1.rotata = bird2.rotata = 0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE :
                return

        bird_y +=bird_y_vel
        if bird_y > height/3-20 +8  or bird_y < height/3-20 -8:
            bird_y_vel *= -1

        bird1.updata()
        bird2.updata()
        screen.blit(image_dir['背景'],(0,0))#绘制照片
        screen.blit(image_dir['标题'], ((width-image_dir['标题'].get_width())/2, height/8-image_dir['标题'].get_height()))  # 绘制照片
        screen.blit(image_dir['准备'], ((width - image_dir['准备'].get_width()) / 2, height / 4 - image_dir['准备'].get_height()))  # 绘制照片
        screen.blit(image_dir['信息'], ((width - image_dir['信息'].get_width()) / 2, height/2 - image_dir['信息'].get_height()))

        screen.blit(bird1.image, (width/3-20,bird_y))  # 绘制照片
        screen.blit(bird2.image, (width/3+80,bird_y))  # 绘制照片

        floor.show_floor()
        pygame.display.update()
        clock.tick(fps)


def game_windows():
    score = 0
    bird = Bird(width/3-20, height/3-20)
    floor = Floor()
    distance = 200 #两根管道之间的距离
    pipe_list_down = []
    pipe_list_up = []
    for i in range(4):
        pipe_h = random.randint(image_dir['地面'].get_height()+20,400)
        image_dir['管道'] = pygame.transform.scale(image_dir['管道'],(image_dir['管道'].get_width(),pipe_h))
        pipe_list_down.append(Pipe(width+distance*i,height-pipe_h,1))
        pipe_list_up.append(Pipe(width + distance * i, height - pipe_h,0))

    while True:
        flap = False
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

            if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
                flap = True

            if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
               pass


        #地面运动
        screen.blit(image_dir['背景'], (0, 0))  # 绘制照片

        first_pipe = pipe_list_down[0]
        first_pipe1 = pipe_list_up[0]
        if first_pipe.rect.right <0 and first_pipe1.rect.right <0:
            pipe_list_down.remove(first_pipe)
            pipe_list_up.remove(first_pipe1)
            pipe_h = random.randint(image_dir['地面'].get_height()+20, 400)
            image_dir['管道'] = pygame.transform.scale(image_dir['管道'], (image_dir['管道'].get_width(), pipe_h))
            pipe_list_down.append(Pipe(first_pipe.rect.right+4*distance,height-pipe_h,1))
            pipe_list_up.append(Pipe(first_pipe.rect.right + 4 * distance, height - pipe_h, 0))
            del first_pipe,first_pipe1

        for i in pipe_list_up +pipe_list_down:
            i.updata()
            screen.blit(i.image,i.rect)

            left2right = max(bird.rect.right,i.rect.right) - min(bird.rect.left,i.rect.left)
            top2bottom = max(bird.rect.bottom,i.rect.bottom)- min(bird.rect.top,i.rect.top)

            if left2right < (bird.rect.width +i.rect.width) and top2bottom < (bird.rect.height +i.rect.height):
                if i in pipe_list_up:
                    return {'bird':bird,'pipe1':i,'pipe2':pipe_list_down[pipe_list_up.index(i)],'score':str(score//2)}
                else:
                    return {'bird': bird, 'pipe1': i, 'pipe2': pipe_list_up[pipe_list_down.index(i)],
                            'score': str(score // 2)}

            if bird.rect.y <= 0 or bird.rect.y >= height-image_dir['地面'].get_height()//2:
                result = {'bird': bird, 'pipe1': i, 'pipe2': pipe_list_down[pipe_list_up.index(i)],
                          'score': str(score // 2)}
                return result  #保留结果状态

            if  bird.rect.left +i.x_vel<i.rect.centerx <bird.rect.left:
                score +=1
                #不同得分切换小鸟
                if score > 4:
                    bird.image_name = '黄鸟'
                if score >10:
                    bird.image_name = '红鸟'


        bird.updata(flap)
        floor.show_floor()
        screen.blit(bird.image, (width / 3 - 20, bird.rect.y))  # 绘制照片
        show_score(str(score // 2),1)
        pygame.display.update()
        clock.tick(fps)

def end_windows(result):
    bird = result['bird']
    pipe1 = result['pipe1']
    pipe2 = result['pipe2']
    score = result['score']
    floor = Floor()
    while True:
        temp = bird.deathing()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()
            #死亡过程中不能切换界面
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and temp:
                return

        screen.blit(image_dir['背景'], (0, 0))  # 绘制照片
        screen.blit(pipe1.image, pipe1.rect)
        screen.blit(pipe2.image, pipe2.rect)
        screen.blit(image_dir['结束'], ((width - image_dir['结束'].get_width())/2,height/3-20 - image_dir['结束'].get_height()))
        floor.show_floor()

        screen.blit(bird.image,bird.rect)
        show_score(score,0)
        pygame.display.update()
        clock.tick(fps)

def main():
    music.play()
    while True:
        image_dir['背景'] = random.choice([image_dir['白天'],image_dir['黑夜']])
        image_dir['背景'] = pygame.transform.scale(image_dir['背景'], (width, height))  # 转化大小

        menu_windows()
        result = game_windows()
        end_windows(result)

if __name__ == '__main__':
    main()


在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pygame小游戏-------FlappyBird像素鸟的实现 的相关文章

  • 尽管极其懒惰,但如何在 Python 中模拟 IMAP 服务器?

    我很好奇是否有一种简单的方法来模拟 IMAP 服务器 例如imaplib模块 在Python中 without做很多工作 是否有预先存在的解决方案 理想情况下 我可以连接到现有的 IMAP 服务器 进行转储 并让模拟服务器在真实的邮箱 电子
  • 如何在 Sublime Text 2 的 OSX 终端中显示构建结果

    我刚刚从 TextMate 切换到 Sublime Text 2 我非常喜欢它 让我困扰的一件事是默认的构建结果显示在 ST2 的底部 我的程序产生一些很长的结果 显示它的理想方式 如在 TM2 中 是并排查看它们 如何在 Mac 操作系统
  • Python 多处理示例不起作用

    我正在尝试学习如何使用multiprocessing但我无法让它发挥作用 这是代码文档 http docs python org 2 library multiprocessing html from multiprocessing imp
  • 在 NumPy 中获取 ndarray 的索引和值

    我有一个 ndarrayA任意维数N 我想创建一个数组B元组 数组或列表 其中第一个N每个元组中的元素是索引 最后一个元素是该索引的值A 例如 A array 1 2 3 4 5 6 Then B 0 0 1 0 1 2 0 2 3 1 0
  • Abaqus 将曲面转化为集合

    我一直试图在模型中找到两个表面的中心 参见照片 但未能成功 它们是元素表面 面 查询中没有选项可以查找元素表面的中心 只能查找元素集的中心 找到节点集的中心也很好 但是我的节点集没有出现在工具 gt 查询 gt 质量属性选项中 而且我找不到
  • Geopandas 设置几何图形:MultiPolygon“等于 len 键和值”的 ValueError

    我有 2 个带有几何列的地理数据框 我将一些几何图形从 1 个复制到另一个 这对于多边形效果很好 但对于任何 有效 多多边形都会返回 ValueError 请指教如何解决这个问题 我不知道是否 如何 为什么应该更改 MultiPolygon
  • ExpectedFailure 被计为错误而不是通过

    我在用着expectedFailure因为有一个我想记录的错误 我现在无法修复 但想将来再回来解决 我的理解expectedFailure是它会将测试计为通过 但在摘要中表示预期失败的数量为 x 类似于它如何处理跳过的 tets 但是 当我
  • 如何改变Python中特定打印字母的颜色?

    我正在尝试做一个简短的测验 并且想将错误答案显示为红色 欢迎来到我的测验 您想开始吗 是的 祝你好运 法国的首都是哪里 法国 随机答案不正确的答案 我正在尝试将其显示为红色 我的代码是 print Welcome to my Quiz be
  • 通过数据框与函数进行交互

    如果我有这样的日期框架 氮 EG 00 04 NEG 04 08 NEG 08 12 NEG 12 16 NEG 16 20 NEG 20 24 datum von 2017 10 12 21 69 15 36 0 87 1 42 0 76
  • Python 3 中“map”类型的对象没有 len()

    我在使用 Python 3 时遇到问题 我得到了 Python 2 7 代码 目前我正在尝试更新它 我收到错误 类型错误 map 类型的对象没有 len 在这部分 str len seed candidates 在我像这样初始化它之前 se
  • Nuitka 未使用 nuitka --recurse-all hello.py [错误] 编译 exe

    我正在尝试通过 nuitka 创建一个简单的 exe 这样我就可以在我的笔记本电脑上运行它 而无需安装 Python 我在 Windows 10 上并使用 Anaconda Python 3 我输入 nuitka recurse all h
  • 为美国东部以外地区的 Cloudwatch 警报发送短信?

    AWS 似乎没有为美国东部以外的 SNS 主题订阅者提供 SMS 作为协议 我想连接我的 CloudWatch 警报并在发生故障时接收短信 但无法将其发送到 SMS YES 经过一番挖掘后 我能够让它发挥作用 它比仅仅选择一个主题或输入闹钟
  • 如何从没有结尾的管道中读取 python 中的 stdin

    当管道来自 打开 时 不知道正确的名称 我无法从 python 中的标准输入或管道读取数据 文件 我有作为例子管道测试 py import sys import time k 0 try for line in sys stdin k k
  • 对输入求 Keras 模型的导数返回全零

    所以我有一个 Keras 模型 我想将模型的梯度应用于其输入 这就是我所做的 import tensorflow as tf from keras models import Sequential from keras layers imp
  • 循环标记时出现“ValueError:无法识别的标记样式 -d”

    我正在尝试编码pyplot允许不同标记样式的绘图 这些图是循环生成的 标记是从列表中选取的 为了演示目的 我还提供了一个颜色列表 版本是Python 2 7 9 IPython 3 0 0 matplotlib 1 4 3 这是一个简单的代
  • 协方差矩阵的对角元素不是 1 pandas/numpy

    我有以下数据框 A B 0 1 5 1 2 6 2 3 7 3 4 8 我想计算协方差 a df iloc 0 values b df iloc 1 values 使用 numpy 作为 cov numpy cov a b I get ar
  • 改变字典的哈希函数

    按照此question https stackoverflow com questions 37100390 towards understanding dictionaries 我们知道两个不同的字典 dict 1 and dict 2例
  • Python 分析:“‘select.poll’对象的‘poll’方法”是什么?

    我已经使用 python 分析了我的 python 代码cProfile模块并得到以下结果 ncalls tottime percall cumtime percall filename lineno function 13937860 9
  • Pandas 与 Numpy 数据帧

    看这几行代码 df2 df copy df2 1 df 1 df 1 values 1 df2 ix 0 0 我们的教练说我们需要使用 values属性来访问底层的 numpy 数组 否则我们的代码将无法工作 我知道 pandas Data
  • PyAudio ErrNo 输入溢出 -9981

    我遇到了与用户相同的错误 Python 使用 Pyaudio 以 16000Hz 录制音频时出错 https stackoverflow com questions 12994981 python error audio recording

随机推荐

  • C - Check The Text(string)

    C Check The Texthttps vjudge csgrandeur cn problem Gym 102263C Roze有一个特殊的键盘 只有29个键 26个字母a z键 打印26个小写拉丁字母 空格 键 打印一个空格 Cap
  • 机器学习比较好的视频资源

    吴恩达 经典入门课程 中英字幕 吴恩达机器学习系列课程 哔哩哔哩 bilibili www bilibili com video BV164411b7dx spm id from 333 999 0 0正在上传 重新上传取消 双语字幕 吴恩
  • JavaScript中window.print()打印

    JavaScript中使用window print 打印方法时 打印的是当前页的所有内容 所以如果直接在当前页使用此打印方法应先保存当前页面再把打印部分替换当前页面执行完之后再替换回来 或者新打开一个页面 把所打印的部分都写到新打开的页面上
  • Windows10中CUDA cundnn pytorch环境搭建记录

    关于在win10中安装cuda cudnn及pytorch全家桶 torch torchvision torchaudio 的详细安装步骤 可以参考这个帖子 说的非常详细 win10下pytorch gpu安装以及CUDA详细安装过程 仅在
  • ArchLinux安装slock锁屏(suckless)

    简介 一款suckless团队开发的锁屏小工具 下载 git clone https git suckless org slock 或者点击该链接下载 https dl suckless org tools slock 1 4 tar gz
  • JS高级(2)函数高级 — 原型与原型链

    原型与原型链 1 原型prototype 每个函数都有一个prototype属性 它默认指向一个Object空对象 即原型对象 里面没有我们的属性 原型中有一个属性constructor 它指向函数对象 构造函数和原型对象相互引用 func
  • 从零开发区块链应用(六)--gin框架使用

    文章目录 一 Gin 框架介绍 二 Gin安装 三 Gin使用 3 1 设置gin模式 3 2 创建新路由 3 3 创建多路由分组 3 4 创建路由 3 5 编写接口执行函数 3 6 启动服务 参考文档 Gin框架介绍及使用 https w
  • bread是可数还是不可数_在英语语法里,为什么bread是不可数名词?

    学英语 我们要分清楚名词的类型 可数名词 不可数名词 可数名词就是能够用 1 2 3 4 5 这样数的人或事物 比如苹果 茶杯 汽车 都可以这样数 但是 当我们打算去 数 water 水的时候 就水本身而言 它是液体 没有固定的形状和结构
  • SingleThreaded是如何进入cull_draw()的?

    正如以前所说 单线程模式是通过cull draw 进行剔除绘制的 如何进入的呢 其实很简单 逆推下 最后 回到梦开始的地方
  • React学习之围棋记谱本制作(二)棋盘、棋子、交替落子

    与儿子一起学围棋 上网上找 发现好用的记谱本软件特别少 打算自己做一个 不知能不能克服惰性 完成这个目标 千里之行 始于足下 今天完成了基础工作 棋盘 棋子组件 并完成了交替落子功能 是React基本功能的很好示范 代码贴一下 下一步就是多
  • 状态机的思想

    http blog sina com cn s blog 3e71aaaa0100834m html 转载于 https www cnblogs com as3lib p 3518613 html
  • 谷歌云活动

    Google x Cloud Ace 线下活动即将开始 本期主题 解锁 AIGC 密码 探寻企业发展新商机 期待您的莅临 时间 5月24日13 30 17 00 地点 深圳南山 本次活动定向邀请 CXO 们请扫码报名获取地址信息
  • 因果推断--Uplift model的原理和python实操(三)

    目录 一 Uplift Model的应用场景 二 Uplift Model原理及建模方法 2 1 建模目标 2 2 建模方法 1 双模型 差分响应模型 2 标签转化 Class Transformation Method 2 3 模型评估
  • Anaconda实验环境的搭建

    Anaconda和Jupyter notebook Anaconda Conda Package 和 Environment Data Science IDE vs Developer IDE 从IPython 到 Jupyter mac上
  • 30天自制操作系统学习-第9天

    1 整理源文件 昨天对鼠标键盘的控制函数都放在了HariMain主函数中 今天我们先将这些功能独立一个对应的C文件中即可 修改后的文件目录结构 只需在bootpack h头文件中声明即可 2 内存管理 高速缓存 维基百科 Cache一词来源
  • OSI网络的七大模型简介

    先声明本文摘自https www cnblogs com carlos mm p 6297197 html是一片非常易懂的文章 以下做了压缩的摘要 物理层 它的主要作用是传输比特流 就是由1 0转化为电流强弱来进行传输 到达目的地后在转化为
  • 10G RAC中的CSS TIMEOUT相关的设置和调整(ZT)

    10G RAC中的CSS TIMEOUT相关的设置和调整 作者 天涯 来源 中国自学编程网 发布日期 1214468885 这篇文章是偶用半生不熟的E文翻译过来的 所以很多可能看着很别扭 E文好的建议直接看原文 在METALINK中的294
  • 海康服务器系统装完重启转圈蓝屏,win10重启一直转圈的解决方法 win10重启一直转圈 - 云骑士一键重装系统...

    Ready 品牌型号 联想GeekPro 2020 系统 win10 1909 64位企业版 软件版本 大番茄一键重装系统2 1 6 我们在使用win10系统时 有时会给win10重新启动 但是出现win10重新启动一直转 这是怎么一回事呢
  • 计算机组成原理补充实验,计算机组成原理补充实验.doc

    计算机组成原理补充实验 计算机组成原理补充实验 目 录 第一节 计算机组成原理常用部件实验 1 实验1 数据选择器 2 实验2 寄存器 3 实验3 计数器 5 实验4 译码器 6 实验5 节拍发生器 7 第二节 运算器组成实验 8 实验1
  • pygame小游戏-------FlappyBird像素鸟的实现

    简述 对FlappyBird像素鸟游戏的简单复现 仅两百行左右 工程目录结构为image文件夹和run py文件 pygame模块的下载直接pip install pygame即可 图片下载地址为像素鸟图片 音频文件自己找一个即可 impo