4 让僵尸动起来
让僵尸能够动起来,也就是让僵尸从屏幕右边走到屏幕左边,此时只需要使用while循环,改变僵尸图片的x轴坐标即可,代码如下所示。
while True:
screen.fill((255,255,255))
z1.rect.x -= 5
z1.draw(screen)
z1.update()
if z1.rect.x<=0:
break
其中,每次显示僵尸时,首先通过screen调用fill()方法将屏幕背景重新设置为白色,掩盖僵尸移动前的影像;之后将z1的rect的x每次减5,表示每次循环僵尸向左侧移动5个单位,之后就是通过draw()和update()来绘制并且在新位置上显示僵尸;最后当僵尸移动到屏幕的最左侧时,跳出循环,此时僵尸停止移动。
5 设置移动速度
运行“4 让僵尸动起来”中提到的代码,此时可以看到僵尸移动的速度非常快。可以通过pygame的time模块中的Clock类通过控制游戏帧速率来控制僵尸的移动速度。
5.1 游戏帧速率
游戏帧速率指的是每秒所运行的帧数(FPS:Frames Per Second),是评价游戏画面是否流畅的关键指标。while循环每执行一次,则有一次僵尸的绘画。每绘画一次,就是一帧。可以通过pygame的time模块中的Clock类来设置FPS,来控制僵尸移动的速度。
5.2 设置FPS
首先,在程序主程序的起始处(while循环之前)定义Clock类的实例,代码如下所示。
clock = pygame.time.Clock()
之后,在while循环的内部,来设置FPS的值,代码如下所示。
clock.tick(10)
tick()函数的作用是设置FPS的值,参数10表示FPS的值10,即每秒所运行的帧数不超过10次,也就是保证了while循环每秒只能循环10次。此时再运行程序,可以看到僵尸的移动速度已经减慢了。
6 完整代码
import pygame, os
from pygame.locals import *
class Zombie(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.image.load('1.png')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def draw(self, screen):
screen.blit(self.image, self.rect)
def update(self):
pygame.display.update()
pygame.init()
screen = pygame.display.set_mode((400, 500))
screen.fill((255,255,255))
clock = pygame.time.Clock()
z1 = Zombie(350, 80)
z1.draw(screen)
z1.update()
while True:
screen.fill((255,255,255))
z1.rect.x -= 5
z1.draw(screen)
z1.update()
if z1.rect.x<=0:
break
clock.tick(10)
pygame.quit()