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

6 篇文章 0 订阅
订阅专栏
本文档展示了如何使用Python的Pygame库来简单复现经典游戏FlappyBird。代码包括游戏的主要元素,如鸟类、管道、地面以及游戏逻辑。玩家可以通过键盘控制鸟类飞行,避开管道障碍。游戏包含开始菜单、游戏窗口和死亡窗口三个阶段。
摘要由CSDN通过智能技术生成

简述:对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()


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

pygame制作flappy bird小游戏
黑马程序员广州中心的专栏
12-26 832
Python弱智,请各位大神勿喷 思路:flappy bird的游戏过程非常简单: 1. 小鸟会自动往前飞行,在往前飞行的过程中,自身会往下以一定速度下坠(实际游戏可能是有加速度,我暂时以固定速度) 2. 飞行过程中的管道随机从图片上下方生成,同时生成的管道必须给小鸟留有一定的空间飞过去。 3. 每次点击或键盘敲击都会使小鸟往上飞行一段距离,持续按键盘不会...
pygame写的flappy bird
01-24
第一次用pygame,仿照flappybird写的小游戏
使用pygame制作Flappy bird小游戏
拇指笔记
03-12 4263
最近看到很多大佬用强化学习玩Flappy bird。所以打算也上手玩一玩,但是苦于没找到pc上的这个游戏,找了点资料,发现并不是很难,所以来自己一个。本文持续更新,欢迎关注~
pygame 200行小游戏FlappyBird
一个新时代的好少年的博客
02-12 1991
开发准备 pip install pygame 新建文件夹将代码和资源放在一起 功能 鼠标移出窗口暂停游戏,移入恢复 播放我喜欢的背景音乐 Chain Hang Low 标题栏显示当前得分,撞柱子时游戏终止 效果 undefined 代码 # -*- codin...
python小游戏源码-python 像素小鸟小游戏源码(flappybird)
weixin_37988176的博客
11-01 1253
【实例简介】像素小鸟这个简单的游戏于2014年在网络上爆红,游戏上线一段时间内appleStore上的下载量一度达到5000万次,风靡一时【实例截图】【核心代码】from Class import *# 检查停止事件def checkEvent():time.sleep(0.1)press = pygame.key.get_pressed() # 检测按下ESC键退出游戏if (press[K_...
使用pygame编写Flappy bird小游戏
09-17
总的来说,通过学习这个Flappy Bird小游戏实现,我们可以了解到pygame库在创建2D游戏中的核心功能,包括窗口管理、图像加载、事件处理和屏幕更新。在实际开发中,我们需要进一步完善代码,增加游戏逻辑和交互性,...
Python小游戏-像素小鸟(Fallppybird)
最新发布
12-21
"像素小鸟(Fallppybird)"是一款基于Python小游戏,模仿了经典的Flappy Bird,它以像素艺术风格呈现,简单却富有挑战性。这个项目的核心是通过Pythonpygame库来创建和管理游戏的图形用户界面和游戏逻辑。 pygame...
flappy-bird:飞扬的鸟游戏
03-04
在当今数字化时代,游戏开发已经成为一个热门领域,而Python作为一门易学且功能强大的编程语言,也逐渐被用来开发各种类型的游戏,包括经典的小游戏——"飞扬的鸟"。"flappy-bird"项目就是一个基于Python实现的飞扬...
flappy-bird
10-17
本篇将详细讲解如何使用PythonPygame模块来实现经典的Flappy Bird游戏。 Flappy Bird是一款简单却极具挑战性的手机游戏,玩家通过控制小鸟避开管道障碍物,尽可能地飞行得更远。在Python中,我们同样可以利用...
像素鸟源代码
08-11
这是像素鸟游戏的源代码,包括Untiy版本和cocos2dx版本
python像素鸟代码,附图片音效
02-19
这是我自己敲的代码,减去注释大概两百多行,非常适合想学python的新手。 这个资源给大家主要是用于学python。 这是我第一次在csdn上发资源,有什么不好的地方望大家指正.
Flappy Bird游戏Python源码(使用Pygame实现
05-02
# Pygame小游戏 Flappy Bird 经典版 1. 使用经典素材1比1复原经典版Flappy Bird游戏界面; 2. 地面和水管流畅移动,水管高度随机生成; 3. 定义小鸟下落加速度,体验自然; 4. 新回合随机选择小鸟颜色; 5. 小鸟煽动翅膀动效; 6. 鼠标单击进行游戏。
像素鸟小游戏源代码
05-30
用JAVA,swing写的小游戏哟,涉及到线程、IO流、窗口等知识。
像素鸟游戏
04-11
听了一节游戏开发的公开课,简单的实现一个像素鸟游戏,自娱自乐
PythonPygame写一个Flappy Bird经典小游戏
leleprogrammer的博客
07-05 2685
PygamePython用于开发游戏的外置库,可通过pip install pygame安装~这篇文章,我们将用Pygame编写一个Flappy Bird小游戏,游戏效果如下: 设计该游戏需要的照片如下,大家可以下载使用:0.png 1.png 2.png bg_day.png 现在开始写代码吧!先导入模块,导入pygamepygame的常量,random随机库,sys用于退出程序,copy用于深度克隆,避免不必要的错误 定义常量,path是图片储存目录,后面两个分别是pygame事件中给用户用的接
使用pygame制作flappybird游戏
qq_44772470的博客
12-30 1479
利用pygame开发游戏 学习python尝试到的第一个项目,不是很规范 成品展示 源代码,可直接使用 import pygame import random class Background(pygame.sprite.Sprite): def __init__(self, is_alt=False): super().__init__() ...
Python游戏开发,pygame模块,Python实现FlappyBird小游戏
08-26 216
前言: 本期我们将制作一个仿“FlappyBird”的小游戏。 让我们愉快地开始吧~ 效果图 环境搭建 安装Python并添加到环境变量,pip安装需要的相关模块即可。 原理介绍 FlappyBird游戏简介: 玩家通过空格键控制一只小鸟,使其跨越由各种不同长度水管所组成的障碍物,当小鸟碰撞到障碍物或跌至屏幕最底端时,游戏结束。 逐步实现: Step1:定义精灵类 为了方便实现小鸟和水管之间碰撞的检测,我们先定义一些精灵类,包括: ① 小鸟类随着游戏时间的推移,小鸟应当具有更新自身位置
python小游戏像素鸟
“落花难回枝头上”
04-04 2071
python小游戏像素鸟 参考B站up:趣派编程 一·准备工作: 1.编辑器 2.库: pygame 3.蔬菜包 二·初始界面 #导入需要的库 import pygame import random,os #Constants 常量 W, H = 288,512 FPS = 30 #绘制界面 Setup 设置 pygame.init() #初始化 SCREEN = pygame.display.set_mode((W,H)) #(宽,高) py
写文章

热门文章

  • YOLOV5源码的详细解读 39775
  • YOLO与voc格式互转,超详细 19188
  • 问题解决:OpenCV报-210:Unsupported format or combination of formats 12064
  • forward() missing 1 required positional argument: ‘indices‘错误解决 9200
  • 基于用户行为特征的推荐算法 8943

分类专栏

  • 推荐系统 4篇
  • 前端知识 3篇
  • 前端入门效果 6篇
  • 经典模型 8篇
  • Python杂文 6篇
  • 数据库 3篇
  • YOLOv5笔记 4篇
  • 金蛋错误 9篇
  • 图像处理 12篇
  • TensorFlow 1篇
  • socket 3篇

最新评论

  • YOLO与voc格式互转,超详细

    ysjxyyds1: 你好 请问能解决吗

  • YOLO与voc格式互转,超详细

    2301_76534644: 同问 这是为啥啊

  • YOLO与voc格式互转,超详细

    鹿总挺能闹: voc转yolo用不了啊,所有的labels文件都没有内容

  • YOLO与voc格式互转,超详细

    weixin_46329132: train.txt这些没有生成呀

  • YOLO与voc格式互转,超详细

    Chirping-owl: w改成a

最新文章

  • 推荐系统常用数据集汇总(20个)
  • 解决ant desgin charts柱状图 柱子上浮
  • 动画效果-精灵图人物移动
2024年10篇
2023年2篇
2022年7篇
2021年40篇

目录

目录

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值

玻璃钢生产厂家玻璃钢卡通雕塑制作流程安庆春季商场美陈海南玻璃钢仿真水果雕塑价格室外不锈钢玻璃钢仿铜雕塑厂新余动物玻璃钢雕塑销售电话七台河校园玻璃钢雕塑安装广东开业商场美陈供货商天津抽象玻璃钢雕塑销售厂家驻马店玻璃钢雕塑哪家好乐陵玻璃钢花盆厂家新乡太湖石玻璃钢雕塑武陵玻璃钢花盆花器庆阳彩色玻璃钢雕塑定做优质校园玻璃钢雕塑生产厂家甘南卡通玻璃钢雕塑价格无锡玻璃钢广场雕塑雅安欧式玻璃钢雕塑河北喷泉雕塑玻璃钢广东玻璃钢动漫雕塑厂宁波玻璃钢造型雕塑南京拉丝玻璃钢雕塑报价意大利商场美陈雕塑中山玻璃钢模型雕塑玻璃钢古代人物雕塑定制玻璃钢dp美陈雕塑玻璃钢花盆生产技术与视频南宁玻璃钢雕塑制作厂家上海中庭商场美陈销售企业山西卡通玻璃钢造型雕塑制作玻璃钢花盆户外香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声单亲妈妈陷入热恋 14岁儿子报警汪小菲曝离婚始末遭遇山火的松茸之乡雅江山火三名扑火人员牺牲系谣言何赛飞追着代拍打萧美琴窜访捷克 外交部回应卫健委通报少年有偿捐血浆16次猝死手机成瘾是影响睡眠质量重要因素高校汽车撞人致3死16伤 司机系学生315晚会后胖东来又人满为患了小米汽车超级工厂正式揭幕中国拥有亿元资产的家庭达13.3万户周杰伦一审败诉网易男孩8年未见母亲被告知被遗忘许家印被限制高消费饲养员用铁锨驱打大熊猫被辞退男子被猫抓伤后确诊“猫抓病”特朗普无法缴纳4.54亿美元罚金倪萍分享减重40斤方法联合利华开始重组张家界的山上“长”满了韩国人?张立群任西安交通大学校长杨倩无缘巴黎奥运“重生之我在北大当嫡校长”黑马情侣提车了专访95后高颜值猪保姆考生莫言也上北大硕士复试名单了网友洛杉矶偶遇贾玲专家建议不必谈骨泥色变沉迷短剧的人就像掉进了杀猪盘奥巴马现身唐宁街 黑色着装引猜测七年后宇文玥被薅头发捞上岸事业单位女子向同事水杯投不明物质凯特王妃现身!外出购物视频曝光河南驻马店通报西平中学跳楼事件王树国卸任西安交大校长 师生送别恒大被罚41.75亿到底怎么缴男子被流浪猫绊倒 投喂者赔24万房客欠租失踪 房东直发愁西双版纳热带植物园回应蜉蝣大爆发钱人豪晒法院裁定实锤抄袭外国人感慨凌晨的中国很安全胖东来员工每周单休无小长假白宫:哈马斯三号人物被杀测试车高速逃费 小米:已补缴老人退休金被冒领16年 金额超20万

玻璃钢生产厂家 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化