PyGame - spritesheet examples

PyGame - spritesheet examples

Postby BenChang » Wed Sep 05, 2012 8:44 pm

Playing an animation from a spritesheet

walkcycle3.png
walkcycle3.png (16.09 KiB) Viewed 919 times

Code: Select all
"""

flipbook.py

asynchronous timing for the image cycling (so you can animate at, say, 12 fps but run the game at higher framerate)
allow different row lengths


"""

import pygame
import sys 


class Player(object):
    def __init__(self):
        super(Player,self).__init__()
        self.img=pygame.image.load("walkcycle3.png").convert_alpha()
        self.framewidth=64   # offset for cells in the animation sequence
        self.frameheight=64

        self.spriterow=0    # which row of frames to use in the sprite sheet
        self.frame=0        # current frame in the sequence
        self.frameCount= [8]   # number of frames in the sequence
       
        self.rect = pygame.Rect(0,0,self.framewidth, self.frameheight)
           
        self.fps=12
        self.lastTime=pygame.time.get_ticks()

    def setPos(self,pos):
        self.rect.midbottom=pos
       
    def draw(self,surface):
        '''
        draw the sprite onto the surface, using the offset rect for this frame of the animation
        '''
        # construct a rect to pull the frame out of the sprite sheet

        frameRect=pygame.Rect(self.frame * self.framewidth,self.spriterow*self.frameheight,self.framewidth,self.frameheight)
        surface.blit(self.img,self.rect,frameRect)

    def update(self):
        '''
        update frame in the sequence and move the player
        '''
       
        t=pygame.time.get_ticks()
        dt=t-self.lastTime
        # do updates based on the FPS for the player animation
       
        if dt >= (1000.0 / self.fps):
                       
            self.frame = (self.frame+1) % self.frameCount [self.spriterow]
            self.lastTime=t
           



class Game(object):
    def __init__(self):
        super(Game,self).__init__()
        pygame.init()
        self.screen=pygame.display.set_mode((640,480))
        self.screen_rect = self.screen.get_rect()
        self.clock=pygame.time.Clock()
        self.player=Player()
        self.player.setPos((self.screen_rect.width/2,self.screen_rect.height-100))
        self.font=pygame.font.Font(None,32)
       
    def process_events(self):
        for event in pygame.event.get():
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_ESCAPE:
                    sys.exit(0)
           
    def update(self,dt):
        self.player.update()
       
    def draw(self):
        self.screen.fill((255,255,255))
        self.player.draw(self.screen)
       
g=Game()
while True:
    dt = g.clock.tick(60)
    g.process_events()
    g.update(dt)
    g.draw()
    pygame.display.flip()


Move the player around, play different spritesheet rows to move left, right, or idle

walkcycle4.png
walkcycle4.png (45 KiB) Viewed 919 times


Code: Select all
"""

walk4.py

asynchronous timing for the image cycling (so you can animate at, say, 12 fps but run the game at higher framerate)
allow different row lengths

need to have a different variable for facing direction, independent of movement

"""

import pygame
import sys 


class Player(object):
    def __init__(self):
        super(Player,self).__init__()
        self.img=pygame.image.load("walkcycle4.png").convert_alpha()
        self.framewidth=64   # offset for cells in the animation sequence
        self.frameheight=64

        self.spriterow=0    # which row of frames to use in the sprite sheet
        self.frame=0        # current frame in the sequence
        self.frameCount= [8,8,1,1]   # number of frames in the sequence
       
        self.rect = pygame.Rect(0,0,self.framewidth, self.frameheight)
        self.walkSpeed=15
       
        self.walkFlags={'left':False,'right':False} 
       
        self.fps=12
        self.facing='left'
        self.lastTime=pygame.time.get_ticks()

    def setPos(self,pos):
        self.rect.midbottom=pos
       
    def draw(self,surface):
        '''
        draw the sprite onto the surface, using the offset rect for this frame of the animation
        '''
        # construct a rect to pull the frame out of the sprite sheet

        frameRect=pygame.Rect(self.frame * self.framewidth,self.spriterow*self.frameheight,self.framewidth,self.frameheight)
        surface.blit(self.img,self.rect,frameRect)

    def update(self):
        '''
        update frame in the sequence and move the player
        '''
       
        t=pygame.time.get_ticks()
        dt=t-self.lastTime
        # do updates based on the FPS for the player animation
       
        if dt >= (1000.0 / self.fps):
           
            # select row in the spritesheet
            if self.walkFlags['left']:
                self.spriterow=0
            elif self.walkFlags['right']:
                self.spriterow=1
            else:
                if self.facing=='left':
                    self.spriterow=2
                else:
                    self.spriterow=3
             
            # calculate current frame in the walk cycle
           
            self.frame = (self.frame+1) % self.frameCount [self.spriterow]
            self.lastTime=t
           
            # calculate current velocity
            dx2=0
            if self.walkFlags['left']:
                dx2 += -1 * self.walkSpeed
            if self.walkFlags['right']:
                dx2 += 1 * self.walkSpeed
               
            self.rect.centerx = self.rect.centerx + dx2
            self.dx=dx2

    def walk(self,direction):
        '''
        set the walk flags to start walking
        '''
       
        self.walkFlags[direction]=True
        self.facing=direction

    def stopWalk(self,direction):
        '''
        stop walking
        '''
        self.walkFlags[direction]=False
       
class Game(object):
    def __init__(self):
        super(Game,self).__init__()
        pygame.init()
        self.screen=pygame.display.set_mode((640,480))
        self.screen_rect = self.screen.get_rect()
        self.clock=pygame.time.Clock()
        self.player=Player()
        self.player.setPos((self.screen_rect.width/2,self.screen_rect.height-100))
        self.font=pygame.font.Font(None,32)
       
    def process_events(self):
        for event in pygame.event.get():
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_ESCAPE:
                    sys.exit(0)
           
                elif event.key==pygame.K_LEFT:
                    self.player.walk('left')
                elif event.key==pygame.K_RIGHT:
                    self.player.walk('right')
                   
            elif event.type==pygame.KEYUP:
                if event.key==pygame.K_LEFT:
                    self.player.stopWalk('left')
                elif event.key==pygame.K_RIGHT:
                    self.player.stopWalk('right')
           
    def update(self,dt):
        self.player.update()
       
    def draw(self):
        self.screen.fill((255,255,255))
        self.player.draw(self.screen)
       
g=Game()
while True:
    dt = g.clock.tick(60)
    g.process_events()
    g.update(dt)
    g.draw()
    pygame.display.flip()
User avatar
BenChang
 
Posts: 176
Joined: Mon Jan 17, 2011 4:48 pm

Re: PyGame - spritesheet examples

Postby cesarn » Fri Sep 07, 2012 2:10 pm

Can you or Professor Destefano please post the slides from the class on September 7th. Thanks!
cesarn
 
Posts: 2
Joined: Wed Aug 29, 2012 7:16 pm


Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest

cron