pygame精灵测试

强颜欢笑 提交于 2020-03-15 12:31:16

介绍

pygame.sprite.Sprite是Pygame里面 用来实现精灵的一个类,使用时并不需要 对它实例化,只需要继承它, 然后按需写 出自己的类,因此非常简单实用。

精灵图

代码

'''
@Author: your name
@Date: 2020-03-15 11:45:46
@LastEditTime: 2020-03-15 12:09:16
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: \3.14\精灵.py
'''
import pygame
from pygame.locals import *
class MySprite(pygame.sprite.Sprite):
    def __init__(self,target):
        pygame.sprite.Sprite.__init__(self)
        self.sprite_surface=target
        self.image=None
        self.master_image=None
        self.rect=None
        self.topleft=0,0
        self.frame=0
        self.old_fram=-1
        self.fram_width=1
        self.fram_height=1
        self.first_fram=0
        self.last_fram=0
        self.columns=1
        self.last_time=0
    def load(self,filename,width,height,columns):
        self.master_image=pygame.image.load(filename).convert_alpha()
        self.fram_width=width
        self.fram_height=height
        self.rect=0,0,width,height
        self.columns=columns
        rect=self.master_image.get_rect()
        self.last_fram=(rect.width//width)*(rect.height//height)-1
    def update(self,current_time,rate=60):
        if current_time>self.last_time+rate:
            self.frame+=1
        if self.frame>self.last_fram:
            self.frame=self.first_fram
            self.last_time=current_time
        if self.frame!=self.old_fram:
            frame_x=(self.frame%self.columns)*self.fram_width
            frame_y=(self.frame//self.columns)*self.fram_height
            rect=(frame_x,frame_y,self.fram_width,self.fram_height)
            self.image=self.master_image.subsurface(rect)
            self.old_fram=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()
cat=MySprite(screen)
cat.load("sprite2.png",92,95,4)
group=pygame.sprite.Group()
group.add(cat)
while True:
    framerate.tick(10)
    ticks=pygame.time.get_ticks()
    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,255))

    cat.update(ticks)
    screen.blit(cat.image,cat.rect)
    pygame.display.update()

运行结果

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!