Pygame 入门实战之简单的flappybird小游戏

这是我大二上学期学python写的课程设计一个小鸟管道小游戏,写的很简单,拿出来分享下,有兴趣的可以进一步优化。
代码如下:

import pygame,sys
import random

class Bird():
    """定义小鸟类"""
    def __init__(self):
        """定义初始化方法"""
        self.birdStatus=[pygame.image.load("assets/0.png"),
                         pygame.image.load("assets/1.png"),
                         pygame.image.load("assets/dead.png")]      #装载小鸟状态图片
        self.status=0
        self.birdX=120
        self.birdY=350
        self.jump=False
        self.jumpSpeed=10
        self.gravity=5
        self.dead=False
        self.birdRect=pygame.Rect(65,50,50,50)

    def birdUpdata(self):
        """定义小鸟移动方法"""
        if self.jump==True:
            """小鸟跳跃状态"""
            self.jumpSpeed-=1
            self.birdY-=self.jumpSpeed
        else:
            self.gravity+=0.2
            self.birdY+=self.gravity
        self.birdRect[1]=self.birdY

class PipeLine():
    """定义管道类"""
    def __init__(self):
        """定义初始化方法"""
        self.wallx=400
        self.wallyUp=-300
        self.wallyDown=500
        self.pineUp=pygame.image.load("assets/top.png")
        self.pineDown=pygame.image.load("assets/bottom.png")


    def pipeLineUpdata(self):
        """定义移动方法"""
        self.wallx-=5
        if self.wallx<-80:
            global score
            score+=1
            self.wallx=400
            for i in range(10): #每次产生不同长度的管道
                y1=random.randint(-400,-100)
                y2=random.randint(207,506)
                if (499+y1)+(706-y2)<566:
                    PipeLine.wallyUp=y1
                    PipeLine.wallyDown=y2
                    break

def createMap():
    """创建游戏界面"""
    screen.blit(background,(0,0))
    #显示管道
    screen.blit(PipeLine.pineUp,(PipeLine.wallx,PipeLine.wallyUp))
    screen.blit(PipeLine.pineDown,(PipeLine.wallx,PipeLine.wallyDown))
    PipeLine.pipeLineUpdata()

    #显示小鸟
    if Bird.dead:
        Bird.status=2
    elif Bird.jump:
        Bird.status=1
    elif not Bird.jump:
        pass

    screen.blit(Bird.birdStatus[Bird.status],(Bird.birdX,Bird.birdY))
    fontRender=font.render("SCORE:"+str(score),-1,(255,255,255))
    screen.blit(fontRender,(100,50))
    Bird.birdUpdata()   #更新小鸟状态
    pygame.display.update()

def CheckDead(birdRect):
    """检测小鸟是否死亡"""
    upRect=pygame.Rect(PipeLine.wallx,PipeLine.wallyUp,PipeLine.pineUp.get_width(),PipeLine.pineUp.get_height())
    downRect=pygame.Rect(PipeLine.wallx,PipeLine.wallyDown,PipeLine.pineDown.get_width(),PipeLine.pineDown.get_height())
    #检测是否与管道发生碰撞
    if upRect.colliderect(birdRect) or downRect.colliderect(birdRect):
        Bird.dead=True
    #检测是否与上下边界接触
    if not 0<Bird.birdRect[1]<height:
        Bird.dead=True
        return True
    else:
        return False

def getResult():
    """游戏结束后获取总分"""
    final_text1="GAME OVER!"
    final_text2="You final score is :"+str(score)
    final_text4="Press any key to continue!"
    ft1_font=pygame.font.SysFont("Arial",70)
    ft1_surf=font.render(final_text1,1,(243,3,36))
    ft2_font=pygame.font.SysFont("Arial",50)
    ft2_surf=font.render(final_text2,1,(243,177,6))
    ft4_font=pygame.font.SysFont("Arial",70)
    ft4_surf=font1.render(final_text4,1,(243,3,36))

    screen.blit(ft1_surf,[screen.get_width()/2-ft1_surf.get_width()/2,100])
    screen.blit(ft2_surf,[screen.get_width()/2-ft2_surf.get_width()/2,200])
    screen.blit(ft4_surf,[screen.get_width()/2-ft4_surf.get_width()/2,300])
    pygame.display.update()

def again_Gmae():
    """重新初始化小鸟和管道的位置"""
    Bird.status=0   #初始化小鸟
    Bird.birdX=120
    Bird.birdY=350
    Bird.jump=False
    Bird.jumpSpeed=10
    Bird.gravity=5
    Bird.dead=False
    Bird.birdRect=pygame.Rect(65,50,50,50)
    #初始化管道
    PipeLine.wallx=400
    PipeLine.wallyUp=-300
    PipeLine.wallyDown=500
    PipeLine.pineUp=pygame.image.load("assets/top.png")
    PipeLine.pineDown=pygame.image.load("assets/bottom.png")

if __name__ == '__main__':
    """主程序"""

    pygame.init()   #初始化pygame
    pygame.mixer.init()     #初始化混音器
    sound_effect = pygame.mixer.Sound("death.wav")  #加载死亡音效
    pygame.mixer.music.load("01. 超级 Mario 兄弟. - 地面的主题(01. S_爱给网_aigei_com.mp3")     #加载背景音乐
    background=pygame.image.load("assets/background.png") #加载背景图片
    icno=pygame.image.load("bitbug_favicon.ico") #加载图标
    size=width,height=400,650
    screen=pygame.display.set_mode(size)    #设置窗体
    clock=pygame.time.Clock()   #设置时钟
    pygame.display.set_caption("Flappy Bird")  #设置窗体的标题
    pygame.display.set_icon(icno)
    Bird=Bird()     #实例化一个小鸟对象
    PipeLine=PipeLine()     #实例化一个管道对象
    score=0 #计分
    pygame.font.init() #初始化字体类
    font=pygame.font.SysFont(None,50)
    font1=pygame.font.SysFont(None,35)
    num=0
    n1=False    #游戏开关

    while True:
        for event in pygame.event.get():
                """事件监测"""
                if event.type==pygame.QUIT:
                    sys.exit()
                if event.type==pygame.KEYDOWN:
                    n1=True
                    pygame.mixer.music.play(-1)     #无限循环背景音乐
        while n1:
            clock.tick(60) #帧率每秒60次
            for event in pygame.event.get():
                """事件监测"""
                if event.type==pygame.QUIT:
                    sys.exit()
                if (event.type==pygame.KEYDOWN or event.type==pygame.MOUSEBUTTONDOWN) and not Bird.dead:
                    Bird.jump=True
                    Bird.gravity=5
                    Bird.jumpSpeed=10

            background=pygame.image.load("assets/background.png")
            if CheckDead(Bird.birdRect):
                getResult()
                sound_effect.play()
                num+=1
                if num>160:
                    sound_effect.stop()
                pygame.mixer.music.stop()
                for event in pygame.event.get():
                    """事件监测"""
                    if event.type==pygame.QUIT:
                        sys.exit()
                    if event.type==pygame.KEYDOWN:
                        pygame.mixer.music.play(-1)     #无限循环背景音乐
                        Bird.dead=False
                        again_Gmae()
                        score=0
                        num=0
                        createMap()
            else:
               createMap()
        screen.blit(background,(0,0))
        final_text3="Press any key to start!"
        ft3_font=pygame.font.SysFont("Arial",50)
        ft3_surf=font.render(final_text3 ,1,(243,177,6))
        screen.blit(ft3_surf,[screen.get_width()/2-ft3_surf.get_width()/2,200])
        pygame.display.update()
    pygame.quit()   #结束游戏

源代码文件和图片,音乐文件见GItHub地址:源代码文件
如有问题欢迎留言探讨。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值