Python-pygame 使用subsurface()遍歷圖片達到動畫效果

Python作業貼

網絡上很多介紹subsurface()的使用方法, 但畢竟不是自己手動寫的,看着難受
遂按照自己的理解重新寫一遍

在這裏插入圖片描述

#! /usr/bin/python3

# @File:   test4.py
# @Author: tiannanyihao
# @DATE:   2019-01-16
# @TIME:   10:13
# @Software: PyCharm
# @Production:

import pygame


class ImgGif(pygame.sprite.Sprite):
    """
    創建精靈子類ImaGif
    通過subsurface()方法遍歷大圖中的每一塊小圖,達到動畫效果
    需指定row/cloumn 行/列數
    需要一張連續的主圖 image_Real
    要設置一個窗口圖片 image
    記錄當前遍歷的下標 index
    記錄上次遍歷的下標 lastIndex
    記錄循環中,上一次tick時間增量的 lastTick
    """

    def __init__(self, row, cloumn):
        super().__init__()
        self.index = 0
        self.lastIndex = 0
        self.lastTick = 0

        self.row = row
        self.cloumn = cloumn
        self.allIndex = self.row * self.cloumn
        self.image = pygame.image.load('../src/images/me1.png')
        self.rect = self.image.get_rect()
        self.image_Real = pygame.image.load("../src/images/me4.png")

    def update(self, *args):
        # 獲取時間增量
        currentTick = args[0]
        # 判斷當前時間增量是否大於上次時間增量
        if currentTick > self.lastTick:
            # 下標遞增,當下標達到最大下標數,重置下標再次循環
            self.index += 1
            if self.index > self.allIndex - 1:
                self.index = 0
            self.lastTick = currentTick

        # 檢測是否是新下標
        if self.index != self.lastIndex:
            singleImg_X = (self.index // self.row) * self.rect.width
            singleImg_Y = (self.index % self.row) * self.rect.height
            singleRect = (singleImg_X, singleImg_Y, self.rect.width, self.rect.height)
            # 替換當前應該展示的圖片
            self.image = self.image_Real.subsurface(singleRect)
            self.lastIndex = self.index
        pass


pygame.init()
screen = pygame.display.set_mode((900, 400))
clock = pygame.time.Clock()

imgSprite = ImgGif(1, 4)
spritesGroup = pygame.sprite.Group()
spritesGroup.add(imgSprite)

while True:
    screen.fill((10, 110, 100))
    for event in pygame.event.get():
        pass

    clock.tick(10)
    ticks = pygame.time.get_ticks()

    spritesGroup.update(ticks)
    spritesGroup.draw(screen)

    pygame.display.update()

純粹記錄,以供自己後期翻閱

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章