接上回继续,之前的游戏背景过于单调,今天加几朵白云的背景效果。
要点:
先定义白云:
# 白云背景
class Cloud(pg.sprite.Sprite):
def __init__(self, game, x, y, scale=1):
pg.sprite.Sprite.__init__(self)
self.game = game
self.image = self.game.spritesheet.get_image("cloud.png", scale)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
main.py中初始化:
def new(self):
self.score = 0
self.all_sprites = pg.sprite.LayeredUpdates()
...
self.clouds = pg.sprite.Group()
...
# 初始化生成白云
for i in range(2, 4):
scale = random.choice([2.5, 3.0, 3.5, 4.0, 4.5])
c = Cloud(self, random.randrange(0, WIDTH), random.randrange(-100, HEIGHT), scale)
self.all_sprites.add(c, layer=CLOUD_LAYER)
self.clouds.add(c)
...
其中常量CLOUD_LAYER的值,仍在settings.py中定义:
# layer
PLAYER_LAYER = 4
MOB_LAYER = 3
PLATFORM_LAYER = 1
POWERUP_LAYER = 2
CLOUD_LAYER = 0
update时,更新白云的滚动效果,以及数量不足时,自动补足:
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)
...
# 屏幕滚动时,白云也自动滚动(注:为了视觉效果更自然,滚动速度是挡板的1半)
for cloud in self.clouds:
cloud.rect.top += max(abs(self.player.vel.y) // 2, 2)
if cloud.rect.top > HEIGHT:
cloud.kill()
...
# cloud不够时,自动补充
while len(self.clouds) <= 3 and self.player.rect.bottom < HEIGHT:
scale = random.choice([2.5, 3.0, 3.5, 4.0, 4.5])
c = Cloud(self, random.randrange(0, WIDTH), random.randrange(-200, -50), scale)
self.all_sprites.add(c, layer=CLOUD_LAYER)
self.clouds.add(c)
示例源码:https://github.com/yjmyzz/kids-can-code/tree/master/part_18