目标:实现单张、多种图片的加载,实现动态画面
把方式(一)和方式(二)两种方式结合,简化了一些代码。在一个类里,实现了两种方式的加载
load_image 单张
load_images 加载多张
代码如下:
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.rect = None
self.frame = 0
self.first_frame = 0
self.last_frame = 0
self.columns = 1
self.images = []
self.last_time = pygame.time.get_ticks()
self.rate = 100
def load_images(self, filename_prefix, begin_num, end_num,
filename_suffix):
self.images = [
pygame.image.load(filename_prefix + str(v) + filename_suffix)
for v in range(begin_num, end_num + 1)
]
self.image = self.images[0]
self.rect = self.image.get_rect()
self.last_frame = end_num -1
def load_image(self, filename, width, height, rows, columns):
frame_width = width // columns
frame_height = height // rows
self.boom_picture = pygame.image.load(filename)
for row in range(rows):
for col in range(columns):
frame = self.boom_picture.subsurface([
col * frame_width, row * frame_height, frame_width,
frame_height
])
self.images.append(frame)
self.image = self.images[0]
self.last_frame = rows * columns - 1
self.rect = self.images[0].get_rect()
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
self.image = self.images[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()
blast1 = Blast(screen)
blast1.load_image('blast9.png', 658, 329, 4,8)
blast2 = Blast(screen)
blast2.load_images('blast', 1, 11, '.gif')
group = pygame.sprite.Group()
blast1.set_pos(200, 220)
blast2.set_pos(400,200)
group.add(blast1)
group.add(blast2)
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()
其中 blast9.png 是一张图,长658,宽329,切割 4行,8列。
blast1~~~blast11 是一组动态图。