pygame-KidsCanCode系列jumpy-part15-PowerUp加速器

时间:2024-01-21 22:30:57

这一节我们给游戏增加点额外的奖励,大多数游戏中都会有金币、装备啥的来激励玩家,在jumpy这个游戏中,我们也可以增加类似的道具:加速器。效果图如下:

pygame-KidsCanCode系列jumpy-part15-PowerUp加速器

档板上会随机出现一些加速器(power up),小兔子碰到它后,会获取额外的跳跃速度,跳得更高,得分自然也更高。实现原理如下:

首先得有一个PowerUp类:

 # PowerUp 加速器
class PowerUp(pg.sprite.Sprite):
def __init__(self, game, plat):
pg.sprite.Sprite.__init__(self)
self.game = game
self.plat = plat
self.current_frame = 0
self.last_update = 0
self.images = [self.game.spritesheet.get_image("powerup_empty.png"),
self.game.spritesheet.get_image("powerup_jetpack.png")]
self.image = random.choice(self.images)
self.rect = self.image.get_rect()
# 停在档板的中间
self.rect.centerx = self.plat.rect.centerx
self.rect.bottom = self.plat.rect.top - 5 def update(self):
self.animate()
self.rect.bottom = self.plat.rect.top - 5
if not self.game.platforms.has(self.plat):
self.kill() def animate(self):
now = pg.time.get_ticks()
if now - self.last_update > 200:
self.last_update = now
self.current_frame += 1
self.image = self.images[self.current_frame % len(self.images)]
self.rect = self.image.get_rect()
self.rect.bottom = self.plat.rect.top - 5
self.rect.centerx = self.plat.rect.centerx

大致就是轮播2个图片,形成动画,并停在档板的中间位置。

然后在Platform类中,随机出现这些加速器:

 class Platform(pg.sprite.Sprite):
def __init__(self, game, x, y):
pg.sprite.Sprite.__init__(self)
self.game = game
images = [self.game.spritesheet.get_image("ground_grass_broken.png"),
self.game.spritesheet.get_image("ground_grass_small_broken.png")]
self.image = random.choice(images)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 随机出现power-up加速器
if random.randrange(100) < BOOST_POWER_PERCENT:
power = PowerUp(self.game, self)
self.game.all_sprites.add(power)
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的碰撞检测:

     def update(self):
self.all_sprites.update()
...
if self.player.rect.top < HEIGHT / 4:
self.player.pos.y += max(abs(self.player.vel.y), 2)
for plat in self.platforms:
plat.rect.top += max(abs(self.player.vel.y), 2)
if plat.rect.top > HEIGHT:
plat.kill()
self.score += 10 # 检测power up碰撞
pow_hits = pg.sprite.spritecollide(self.player, self.powerups, True)
for _ in pow_hits:
self.boost_sound.play()
self.player.vel.y = -BOOST_POWER
self.player.jumping = False ...

当然,还可以参考上节的方法,加上音效处理,就不再赘述了。代码可参考:https://github.com/yjmyzz/kids-can-code/tree/master/part_15