游戏的虚拟世界中,最让人happy的一个因素就是主角挂了,而且重来,只要restart就行了,不象现实中人的生命只有1次。回顾上节的效果,如果方块向下落时,挡板没接住,整个游戏就跪了:

如果我们希望方块挂了之后,可以重新来过,可以这样做,修改Game类的update方法:
def update(self):
self.all_sprites.update()
if self.player.vel.y > 0:
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.vel.y = 0
if self.player.rect.top < HEIGHT / 4:
self.player.pos.y += abs(self.player.vel.y)
for plat in self.platforms:
plat.rect.top += abs(self.player.vel.y)
if plat.rect.top > HEIGHT:
plat.kill()
# 如果方块跌落到屏幕之外
if self.player.rect.bottom > HEIGHT:
# 为了让体验更好,整个屏幕上滚,然后将所有方块干掉
for sprite in self.all_sprites:
sprite.rect.top -= max(self.player.vel.y, 5)
if sprite.rect.bottom < 0:
sprite.kill()
# 如果1个档板都没有了,游戏结束,然后run()本次运行结束,下一轮主循环进来时,new()重新初始化,所有sprite实例重新初始化,满血复活
if len(self.platforms) <= 0:
self.playing = False
while len(self.platforms) <= 5:
width = random.randint(50, 100)
p = Platform(random.randint(0, WIDTH - width),
random.randint(-70, -30),
width, 10)
self.platforms.add(p)
self.all_sprites.add(p)
效果如下:

可以看到,方块挂了后,屏幕自动下滚,然后重新开始了。
pygame-KidsCanCode系列jumpy-part6-主角挂掉重新开始
原文:https://www.cnblogs.com/yjmyzz/p/ygame-kidscancode-part6-restart.html