当前位置:天才代写 > tutorial > Python教程 > 【Pygame 课堂】第11课—— GAME OVER

【Pygame 课堂】第11课—— GAME OVER

2018-05-23 08:00 星期三 所属: Python教程 浏览:691

继续我们的打飞机游戏。完成了子弹和敌机之间的碰撞检测之后,在线学习自然还要来处理敌机与本体之间的碰撞检测,这决定了游戏是否结束。
 
之前我们没有把plane作为一个对象来处理,现在为了能更方便地做碰撞检测,我们还是要把它封装一下。这和我们之前对bullet和enemy所做的操作类似。
 
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 = y
 
plane = Plane()
 
在move方法中,依旧根据鼠标的位置改变飞机的位置。
 
然后我们增加一个checkCrash的函数,和checkHit类似,它用来处理敌机和本体之间的碰撞。
 
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_width() < enemy.y + enemy.image.get_height()):
        return True
    return False
 
这里的判断比之前要复杂一些,因为敌机和本体都有一定的面积,不能像子弹一样忽略长宽。但如果两张图片一旦有重合就算是碰撞,会让游戏看上去有些奇怪:有时候你觉得并没有撞上,而实际已经有了重合,游戏就失败了。所以为了避免这一现象,我们要给plane的长宽打上一点折扣。这也就是代码中判断条件里“0.3”“0.7”的意义所在。
 
checkCrash把碰撞检测的结果用True或False返回。在游戏主循环里,我们增加一个记录游戏是否结束的变量gameover。把之前的游戏逻辑放在gameover为False的情况下。而当checkCrash为True时,就把gameover设为True。
 
gameover = False
while True:
    ###
    if not gameover:
        ###省略部分游戏逻辑
        for e in enemies:
            #如果撞上敌机,设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
 
运行代码,当你不幸被敌机撞上后,游戏陷入一片空白。然后,你只好关闭程序。下一课,我们来处理被撞后的善后工作。
 
随着我们功能的不断增加,代码量已经越来越多,在微信上不太好显示。需要代码源文件的,可以去论坛crossin.me上下载。
 
文章来源于Crossin,由课课家在线学习平台整理,转载请注明。

 

    关键字:

天才代写-代写联系方式