Crossin先生的微信打飞机游戏(4)

来源:互联网 发布:技术支持0538泰安网络 编辑:程序博客网 时间:2024/05/01 19:46

(不好意思同学们........我前几天忘了放素材的图片了,现在我补上哦 http://download.csdn.net/detail/heart_to_heart/9545566

现在我们还没有完成的是游戏结束的判定,为了方便的做碰撞检测,Crossin先生对飞机进行了类封装:

class Plane:    def restart(self):        self.x = 200        self.y = 600            def __init__(self):        self.restart()        self.image = pygame.image.load('plane.png').convert_alpha()    def move(self):        x, y = pygame.mouse.get_pos()        x-= self.image.get_width() / 2        y-= self.image.get_height() / 2        self.x = x        self.y = yplane = Plane()

再定义一个检测飞机与敌机碰撞的函数checkCrash函数,因为图片是做过透明化处理的,所以不能简单的认为只要飞机图片与敌机图片相重合就算机毁人亡,也许你视觉上觉得躲开了敌机,可实际上两张图片间已经重合了,所以要对碰撞检测有一个模糊处理:

def checkCrash(enemy, plane):    if (plane.x + 0.7*plane.image.get_width() > enemy.x) and (plane.x + 0.3*plane.image.get_width() < enemy.x + enemy.image.get_width()) and (plane.y + 0.7*plane.image.get_height() > enemy.y) and (plane.y + 0.3*plane.image.get_height() < enemy.y + enemy.image.get_height()):        return True    return False
这个碰撞函数返回的是True or False,我们可以设置一个gameover变量来记录游戏是否结束:

gameover = Falsewhile True:    ###    if not gameover:        ###省略部分游戏逻辑        for e in enemy:            #如果撞上敌机,设gameover为True            if checkCrash(e, plane):                gameover = True            e.move()            screen.blit(e.image, (e.x, e.y))        #检测本体的运动        plane.move()        screen.blit(plane.image, (plane.x, plane.y))    else:        #待处理        pass
做到这里游戏的结束条件已经完成了,但还缺少结束后的游戏响应和分数的统计,为了能实时显示分数,需要对crashHit函数添加一个bool变量:

def checkHit(enemy, bullet):    if (bullet.x > enemy.x and bullet.x < enemy.x + enemy.image.get_width()) and (        bullet.y > enemy.y and bullet.y < enemy.y + enemy.image.get_height()    ):        enemy.restart()        bullet.active = False        #增加返回值        return True    return False
当bullet.active为True时,在游戏的主循环中Score变量递增:
for b in bullets:    if b.active:        for e in enemy:            #击中敌机后,分数加100            if checkHit(e, b):                score += 100        b.move()        screen.blit(b.image, (b.x, b.y))
为了将Score显示在游戏界面上,还需要下面的一些代码:

font = pygame.font.Font(None, 32)text = font.render("Socre: %d" % score, 1, (0, 0, 0))screen.blit(text, (0, 0))
这里再讲下font.Font()和font.render()函数:

  • font.Font() 这个函数有两个参数,第一个是参数用来设置字体名称,None表示使用默认字体,第二个参数表示字体的大小。
  • font.render() 这个函数是将创建好的字体对象显示出来,它有四个参数,第一个参数表示显示的内容,第二个参数表示是否开启抗锯齿,就是说True的话字体会比较平滑,不过相应的速度有一点点影响,第三个参数表示字体颜色,用三原色的元组形式表示,第四个参数是字体背景的颜色
最后加一个游戏结束的响应处理:

#判断在gameover状态下点击了鼠标if gameover and event.type == pygame.MOUSEBUTTONUP:    #重置游戏    plane.restart()    for e in enemy:        e.restart()    for b in bullets:        b.active = False    score = 0    gameover = False
这样在你的飞机与敌机相撞后,游戏会显示你的最终得分,当你点击鼠标后又会重新开始游戏。

做到这里Crossin先生的微信打飞机游戏已经结束了(其实这几篇写的也很机械......),但是离原版的打飞机游戏还有很多功能没有实现,作为一个打飞机游戏的痴迷爱好者,我会继续实现双发子弹以及敌机飞艇的实现,以及原版微信游戏没有的关卡功能。

先附上源码,接下来几天我就开始讲Crossin先生没有做的功能。

(我的下载页)http://download.csdn.net/detail/heart_to_heart/9545552



0 0
原创粉丝点击