这一节我们给游戏增加点额外的奖励,大多数游戏中都会有金币、装备啥的来激励玩家,在jumpy这个游戏中,我们也可以增加类似的道具:加速器。效果图如下:
档板上会随机出现一些加速器(power up),小兔子碰到它后,会获取额外的跳跃速度,跳得更高,得分自然也更高。实现原理如下:
首先得有一个PowerUp类:
1 # PowerUp 加速器
2 class PowerUp(pg.sprite.Sprite):
3 def __init__(self, game, plat):
4 pg.sprite.Sprite.__init__(self)
5 self.game = game
6 self.plat = plat
7 self.current_frame = 0
8 self.last_update = 0
9 self.images = [self.game.spritesheet.get_image("powerup_empty.png"),
10 self.game.spritesheet.get_image("powerup_jetpack.png")]
11 self.image = random.choice(self.images)
12 self.rect = self.image.get_rect()
13 # 停在档板的中间
14 self.rect.centerx = self.plat.rect.centerx
15 self.rect.bottom = self.plat.rect.top - 5
16
17 def update(self):
18 self.animate()
19 self.rect.bottom = self.plat.rect.top - 5
20 if not self.game.platforms.has(self.plat):
21 self.kill()
22
23 def animate(self):
24 now = pg.time.get_ticks()
25 if now - self.last_update > 200:
26 self.last_update = now
27 self.current_frame += 1
28 self.image = self.images[self.current_frame % len(self.images)]
29 self.rect = self.image.get_rect()
30 self.rect.bottom = self.plat.rect.top - 5
31 self.rect.centerx = self.plat.rect.centerx
大致就是轮播2个图片,形成动画,并停在档板的中间位置。
然后在Platform类中,随机出现这些加速器:
1 class Platform(pg.sprite.Sprite):
2 def __init__(self, game, x, y):
3 pg.sprite.Sprite.__init__(self)
4 self.game = game
5 images = [self.game.spritesheet.get_image("ground_grass_broken.png"),
6 self.game.spritesheet.get_image("ground_grass_small_broken.png")]
7 self.image = random.choice(images)
8 self.rect = self.image.get_rect()
9 self.rect.x = x
10 self.rect.y = y
11 # 随机出现power-up加速器
12 if random.randrange(100) < BOOST_POWER_PERCENT:
13 power = PowerUp(self.game, self)
14 self.game.all_sprites.add(power)
15 self.game.powerups.add(power)
其中常量BOOST_POWER_PERCENT是定义在settings.py中的,代表随机出现的概率。
# power up
BOOST_POWER = 50
BOOST_POWER_PERCENT = 15
另一个常量BOOST_POWER代表小兔子碰到加速器后,获取的额外跳跃速度,下面马上会用到。
main.py的update函数中,加入powerup的碰撞检测:
1 def update(self):
2 self.all_sprites.update()
3 ...
4 if self.player.rect.top < HEIGHT / 4:
5 self.player.pos.y += max(abs(self.player.vel.y), 2)
6 for plat in self.platforms:
7 plat.rect.top += max(abs(self.player.vel.y), 2)
8 if plat.rect.top > HEIGHT:
9 plat.kill()
10 self.score += 10
11
12 # 检测power up碰撞
13 pow_hits = pg.sprite.spritecollide(self.player, self.powerups, True)
14 for _ in pow_hits:
15 self.boost_sound.play()
16 self.player.vel.y = -BOOST_POWER
17 self.player.jumping = False
18
19 ...
当然,还可以参考上节的方法,加上音效处理,就不再赘述了。代码可参考:https://github.com/yjmyzz/kids-can-code/tree/master/part_15