猫姐提醒:点击文章中的图片可以放大,看的更清楚哦!
# 0. 前言
hello,小伙伴们!我还是带你们一起写游戏的猫姐。
今天是这个游戏的,第 7 集了!上一集,我们让小男孩的双脚,灵活的动起来了,这一集,我们来实现蘑菇的前身 - 蘑菇小方块的代码。
# 1. 定义蘑菇类
我们先来定义一个蘑菇的类,类名叫 MushRoom
,在括号里面我们传入 pygame.sprite.Sprite
,让 MushRoom
继承这个精灵类。然后在类里,实现我们自己的构造函数 def __init__(self)
,用 super
函数来调用精灵父类的构造函数。
class MushRoom(pygame.sprite.Sprite): | |
def __init__(self): | |
super(MushRoom, self).__init__() |
在构造函数里面,我们用 pygame
的 Surface
函数生成一个宽为 30 像素,高为 30 像素的小方块,给这个小方块取个名,叫 self.image
。用 self.image.fill
函数给小方块填充红色。
通过 self.image的get_rect
函数可以得到小方块的矩形区域,在括号里面,需要设置矩形区域的显示位置,也就是程序运行起来后,小方块在哪里显示。在这里,我们让小方块在屏幕顶部的中心显示, center=(WIDTH//2, 15)
,x 的坐标为屏幕的宽度整除 2,y 的坐标为 15。
class MushRoom(pygame.sprite.Sprite): | |
def __init__(self): | |
super(MushRoom, self).__init__() | |
self.image = pygame.Surface((30, 30)) | |
self.image.fill("red") | |
self.rect = self.image.get_rect(center=(WIDTH//2, 15)) |
接下来,我们定义一个 draw
函数,让小方块显示出来。我们调用 screen点blit
函数,括号里面传入的是要显示的图片名称 self.image
,以及图片要在哪里显示。
class MushRoom(pygame.sprite.Sprite): | |
#... | |
def draw(self, screen): | |
screen.blit(self.image, self.rect) |
# 2. 方块的显示
我们现在将小方块显示在游戏窗口,我们在 while
循环外面,生成一个 mushroom
对象,然后在 while
循环里面,调用 mushroom
对象的 draw
函数,绘制出小方块!我们运行程序看看效果!
#... | |
player = Player() | |
# 实例化 MushRoom 对象 | |
mushroom = MushRoom() | |
while True: | |
#... | |
mushroom.draw(screen) |
好了,我们看到小方块已经显示出来了!
这里的方块是代表的蘑菇,只显示出来,还不行,蘑菇要慢慢下落。
所以,在 MushRoom
类里面,还需要写一个 update
函数,让小方块自动往下掉。
class MushRoom(pygame.sprite.Sprite): | |
#... | |
def update(self): | |
self.rect.move_ip(0, self.speed) |
这里,我用了一个新的变量 self.speed
,所以,在 init
函数里面,需要设置 speed 的初始值为 10。
在 while
循环里面,我们只需要调用 mushroom.update
函数,小方块就会往下掉呢。
class MushRoom(pygame.sprite.Sprite): | |
def __init__(self): | |
#... | |
self.speed = 10 | |
while True: | |
#... | |
mushroom.update() |
我们运行游戏,看下效果。可以看到,小方块就自动往下掉了。
这里还有一个问题,小方块掉到屏幕外面后,应该销毁掉,所以我们在 update
函数里面,还要加两行代码,处理这个情况!
小方块的边界处理,当小方块的 y 坐标大于 HEIGHT 时,就让小方块自动消失。
class MushRoom(pygame.sprite.Sprite): | |
#... | |
def update(self): | |
#... | |
if self.rect.top >= HEIGHT: # if 小方块掉到最底部了 | |
self.kill() # 就把自己干掉 |
这里我们就不运行游戏了,运行也看不出来有什么不同,这个 kill
函数只是把自身占用的资源释放掉了!
关注猫姐,下一集我们用定时器这个技术,产生很多下落的蘑菇!本文所涉及到的代码:
class MushRoom(pygame.sprite.Sprite): | |
def __init__(self): | |
super(MushRoom, self).__init__() | |
self.image = pygame.Surface((30, 30)) | |
self.image.fill("red") | |
self.rect = self.image.get_rect(center=(WIDTH//2, 15)) | |
self.speed = 10 | |
def draw(self, screen): | |
screen.blit(self.image, self.rect) | |
def update(self): | |
self.rect.move_ip(0, self.speed) | |
if self.rect.top >= HEIGHT: # if 小方块掉到最底部了 | |
self.kill() # 就把自己干掉 | |
player = Player() | |
# 实例化 MushRoom 对象 | |
mushroom = MushRoom() | |
while True: | |
for event in pygame.event.get(): | |
if event.type == QUIT: | |
sys.exit() | |
# screen.fill("black") | |
screen.blit(bg_image, (0, 0)) | |
player.update() | |
player.move() | |
# 绘制小方块 | |
mushroom.draw(screen) | |
# 更新小方块 | |
mushroom.update() | |
pygame.display.update() | |
clock.tick(FPS) |