利用Pygame制作简单动画的示例详解

  import sys

  import pygame

  class MySprite(pygame.sprite.Sprite):

  def __init__(self, target):

  pygame.sprite.Sprite.__init__(self)

  self.master_image = None

  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 = 0

  def load(self, filename, width, height, columns):

  # 载入图片

  # 780 * 300

  self.master_image = pygame.image.load(filename).convert_alpha() # 载入图片

  self.frame_width = width # 260

  self.frame_height = height # 150

  self.rect = 0, 0, width, height

  self.columns = columns # 列宽的数量 是 3

  # try to auto-calculate total frames

  rect = self.master_image.get_rect() # 获取到对应的图片的大小 780 * 300

  self.last_frame = (rect.width // width) * (rect.height // height) - 1 # 5

  def update(self, current_time, rate=30): # current_time 更新频率 为30

  # update animation frame number

  if current_time > self.last_time + rate: # 如果当前事件 大于 最后的时间 + 当前的节奏

  self.frame += 1 # 当前的帧数加一

  if self.frame > self.last_frame: # 当前最后一帧 则从第一帧开始

  self.frame = self.first_frame # 从0开始

  self.last_time = current_time # 将最后帧值为30

  # build current frame only if it changed

  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((400, 300), 0, 32)

  pygame.display.set_caption("动画")

  framerate = pygame.time.Clock()

  # 创建精灵

  dragon = MySprite(screen)

  dragon.load("Fig07-02.png", 260, 150, 3)

  group = pygame.sprite.Group()

  group.add(dragon)

  while True:

  framerate.tick(30)

  ticks = pygame.time.get_ticks()

  print(ticks)

  for event in pygame.event.get():

  if event.type == pygame.QUIT:

  sys.exit()

  key = pygame.key.get_pressed()

  if key[pygame.K_ESCAPE]:

  sys.exit()

  screen.fill((154, 205, 255))

  group.update(ticks)

  group.draw(screen)

  pygame.display.update()