继续我们的打飞机游戏。完成了子弹和敌机之间的碰撞检测之后,自然还要来处理敌机与本体之间的碰撞检测,这决定了游戏是否结束。
之前我们没有把plane作为一个对象来处理,现在为了能更方便地做碰撞检测,我们还是要把它封装一下。这和我们之前对bullet和enemy所做的操作类似。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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类似,它用来处理敌机和本体之间的碰撞。
1 2 3 4 5 6 7 | 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 |
这里的判断比之前要复杂一些,因为敌机和本体都有一定的面积,不能像子弹一样忽略长宽。但如果两张图片一旦有重合就算是碰撞,会让游戏看上去有些奇怪:有时候你觉得并没有撞上,而实际已经有了重合,游戏就失败了。所以为了避免这一现象,我们要给plane的长宽打上一点折扣。这也就是代码中判断条件里“0.3”“0.7”的意义所在。
checkCrash把碰撞检测的结果用True或False返回。在游戏主循环里,我们增加一个记录游戏是否结束的变量gameover。把之前的游戏逻辑放在gameover为False的情况下。而当checkCrash为True时,就把gameover设为True。
g
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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 |
运行代码,当你不幸被敌机撞上后,游戏陷入一片空白。然后,你只好关闭程序。下一课,我们来处理被撞后的善后工作。
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
个人编程学习网
本文地址: Pygame-GAME OVER
本文地址: Pygame-GAME OVER
您必须 登录 才能发表评论