目标:用sprite 类来实现动态画面,例如爆炸效果,BOSS机的炫酷展示
用了python游戏编程入门里的例题,改变了一下。
load 函数加载一张图片,对指定高宽,列的图片切割存
update 函数每次更新都计算,大于刷新间隔,就显示下一张图片,刷完图片又从第一张开始
set_pos 函数可以设置图片在屏幕中显示的位置
import pygame
from pygame.locals import *
class Blast(pygame.sprite.Sprite):
def __init__(self, scene):
pygame.sprite.Sprite.__init__(self)
self.main_scene = scene
self.image = None
self.master_image = None
self.rect = None
self.topleft = 0,0
self.frame = 0
self.old_frame = -1
self.frame_width = 1
self.frame_height = 1
self.first_frame = 0
self.last_frame = 0
self.columns = 1
self.last_time = pygame.time.get_ticks()
self.rate = 60
def load(self, filename, width, height, columns):
self.master_image = pygame.image.load(filename).convert_alpha()
self.frame_width = width
self.frame_height = height
self.rect = self.master_image.get_rect()
self.columns = columns
rect = self.master_image.get_rect()
self.last_frame = (rect.width // width) * (rect.height // height) - 1
def set_pos(self,x,y):
self.rect.x = x
self.rect.y = y
def update(self):
current_time = pygame.time.get_ticks()
if current_time > self.last_time + self.rate:
self.frame += 1
if self.frame > self.last_frame:
self.frame = self.first_frame
self.last_time = current_time
if self.frame != self.old_frame:
frame_x = (self.frame % self.columns) * self.frame_width
frame_y = (self.frame // self.columns) * self.frame_height
rect = ( frame_x, frame_y, self.frame_width, self.frame_height )
self.image = self.master_image.subsurface(rect)
self.old_frame = self.frame
显示代码如下:
pygame.init()
screen = pygame.display.set_mode((800,600),0,32)
pygame.display.set_caption("精灵类测试")
font = pygame.font.Font(None, 18)
framerate = pygame.time.Clock()
blast = Blast(screen)
blast.load('blast0.png',77,72,6)
group = pygame.sprite.Group()
blast.set_pos(200,220)
group.add(blast)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
key = pygame.key.get_pressed()
if key[pygame.K_ESCAPE]:
exit()
screen.fill((0,0,0))
group.update()
group.draw(screen)
pygame.display.update()
火焰效果就出来了。blast0.png 为一张 77*6宽,72高,切割6个小图的图
可以用self.last_time > 2000 :
self.kill()
爆炸效果两秒后消失