Pygame开发Flappy Bird小游戏(下)

我们继续进行设计,根据上节,我们已经设计了小鸟类和管道类。剩下的就是得分和碰撞监测。下面就逐一进行设计。

根据游戏设想,当小鸟飞过管道,玩家得分加1.这里对于飞过管道的逻辑做了简化处理:当管道移动到窗体左侧一定距离后,默认为小鸟飞过管道,使分数加1,并显示在屏幕上。在updatePipeline()方法中已经实现该功能,代码如下:

import pygame
import sys
import random

class Bird(object):
    """定义一个鸟类"""
    def __init__(self):
        """"定义初始化方法"""
        self.birdRect = pygame.Rect(65, 50, 50, 50)  # 鸟的矩形
        # 定义鸟的3种状态列表
        self.birdStatus = [pygame.image.load("assets/1.png"),
                           pygame.image.load("assets/2.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
    def birdUpdate(self):
        if self.jump:
            self.jumpSpeed-=1
            self.birdY-=self.jumpSpeed
        else:
            self.gravity+=0.2
            self.birdY+=self.gravity
        self.birdRect[1]=self.birdY

class Pipeline(object):
    """定义一个管道类"""
    def __init__(self):
        """定义初始化方法"""
        self.wallx=400
        self.pineUp=pygame.image.load("assets/top.png")
        self.pineDown=pygame.image.load("assets/bottom.png")
    def updatePipeline(self):
        """水平移动"""
        self.wallx-=5
        #当管道运行到一定位置,即小鸟飞跃管道,分数加1,并且重置管道
        if self.wallx<-80:
            global score
            score+=1
            self.wallx=400

def createMap():
    """定义创建地图的方法"""
    screen.fill((255,255,255))     #填充颜色
    screen.blit(background,(0,0))  #填入到背景
    #显示管道
    screen.blit(Pipeline.pineUp,(Pipeline.wallx,-300))
    screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500))
    Pipeline.updatePipeline()
    if Bird.dead:
        Bird.status=2
    elif Bird.jump:
        Bird.status=1
    screen.blit(Bird.birdStatus[Bird.status],(Bird.birdX,Bird.birdY))
    Bird.birdUpdate()
    #显示分数
    screen.blit(font.render(str(score),-1,(255,255,255)),(200,50))
    pygame.display.update()        #更新显示
if __name__=='__main__':
    """主程序"""
    pygame.init()                 #初始化pygame
    pygame.font.init()
    font=pygame.font.SysFont(None,50)#设置默认字体和大小
    size=width,height=400,680     #设置窗口
    screen=pygame.display.set_mode(size)  #显示窗口
    clock=pygame.time.Clock()     #设置时钟
    Pipeline=Pipeline()           #实例化管道类
    Bird=Bird()                   #实例化鸟类
    score=0
    while True:
        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")  #加载背景图片
        createMap()               #绘制地图
    pygame.quit()                 #退出

运行结果如下:

这时的运行效果是当管道向左移动消失在画布中,就会增加一得分,但是,目前由于没有对小鸟阵亡机制的设置,当小鸟不再控制落到画布外,得分仍然在增长。

所以我们来完善这以功能,加上碰撞监测,并控制游戏的结束。

根据设想,当小鸟与管道相撞时,小鸟颜色变为灰色,游戏结束,并且显示总分数,。在checkDead()函数中通过pygame.Rect()可以分别获取小鸟的矩形区域对象和管道的矩形区域对象,该对象有一个colliderect()方法可以判断两个矩形区域是否相撞。如果相撞,设置Bird.dead属性为True。此外,当小鸟废除窗体时,也设置Bird.dead属性为True。最后,用两行文字显示总成绩。代码如下:

# encoding:utf-8
import pygame
import sys
import random

class Bird(object):
    """定义一个鸟类"""
    def __init__(self):
        """"定义初始化方法"""
        self.birdRect = pygame.Rect(65, 50, 50, 50)  # 鸟的矩形
        # 定义鸟的3种状态列表
        self.birdStatus = [pygame.image.load("assets/1.png"),
                           pygame.image.load("assets/2.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
    def birdUpdate(self):
        if self.jump:
            self.jumpSpeed-=1
            self.birdY-=self.jumpSpeed
        else:
            self.gravity+=0.2
            self.birdY+=self.gravity
        self.birdRect[1]=self.birdY

class Pipeline(object):
    """定义一个管道类"""
    def __init__(self):
        """定义初始化方法"""
        self.wallx=400
        self.pineUp=pygame.image.load("assets/top.png")
        self.pineDown=pygame.image.load("assets/bottom.png")
    def updatePipeline(self):
        """水平移动"""
        self.wallx-=5
        #当管道运行到一定位置,即小鸟飞跃管道,分数加1,并且重置管道
        if self.wallx<-80:
            global score
            score+=1
            self.wallx=400

def createMap():
    """定义创建地图的方法"""
    screen.fill((255,255,255))     #填充颜色
    screen.blit(background,(0,0))  #填入到背景
    #显示管道
    screen.blit(Pipeline.pineUp,(Pipeline.wallx,-300))
    screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500))
    Pipeline.updatePipeline()
    if Bird.dead:
        Bird.status=2
    elif Bird.jump:
        Bird.status=1
    screen.blit(Bird.birdStatus[Bird.status],(Bird.birdX,Bird.birdY))
    Bird.birdUpdate()
    #显示分数
    screen.blit(font.render(str(score),-1,(255,255,255)),(200,50))
    pygame.display.update()        #更新显示
def checkDead():
    # 上方管子的矩形位置
    upRect = pygame.Rect(Pipeline.wallx,-300,
                         Pipeline.pineUp.get_width() - 10,
                         Pipeline.pineUp.get_height())

    # 下方管子的矩形位置
    downRect = pygame.Rect(Pipeline.wallx,500,
                           Pipeline.pineDown.get_width() - 10,
                           Pipeline.pineDown.get_height())
    # 检测小鸟与上下方管子是否碰撞
    if upRect.colliderect(Bird.birdRect) or downRect.colliderect(Bird.birdRect):
        Bird.dead = True
    # 检测小鸟是否飞出上下边界
    if not 0 < Bird.birdRect[1] < height:
        Bird.dead = True
        return True
    else :
        return False

def getResultl():
    final_text1="Game Over!"
    u="your final score is:"+str(score)

    ft1_font=pygame.font.SysFont("Arial",70)
    ft1_surf=font.render(final_text1,1,(242,3,35))  #设置第一行文字颜色
    ft2_font = pygame.font.SysFont("Arial", 50)
    ft2_surf = font.render(u, 1, (242, 177, 8))  # 设置第二行文字颜色
    #设置第一行文字显示位置
    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])
    pygame.display.flip() #更新整个待显示的Surface对象到屏幕上
if __name__=='__main__':
    """主程序"""
    pygame.init()                 #初始化pygame
    pygame.font.init()
    font=pygame.font.SysFont(None,50)#设置默认字体和大小
    size=width,height=400,680     #设置窗口
    screen=pygame.display.set_mode(size)  #显示窗口
    clock=pygame.time.Clock()     #设置时钟
    Pipeline=Pipeline()           #实例化管道类
    Bird=Bird()                   #实例化鸟类
    score=0
    while True:
        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():
            getResultl()
        else:
            createMap()   #绘制地图
    pygame.quit()                 #退出

最终运行效果:

此时就完成了Flappy Bird的设计,小鸟在碰撞管道和离开屏幕都视为阵亡,然后游戏结束。

这里暂时没有解决中文乱码的问题,已经设置为编码格式为utf-8,但不知道怎么回事,还是显示乱码,如果解决后,会再写一遍关于解决Python中文乱码的文章。敬请关注。

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mez_Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值