Last active
December 22, 2015 11:09
-
-
Save omaraboumrad/6463473 to your computer and use it in GitHub Desktop.
Dealing with a spritesheet of 16 images in a 4x4 matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import pygame | |
class Character(pygame.sprite.Sprite): | |
def __init__(self, *group): | |
super(Character, self).__init__(*group) | |
self.sheet = pygame.image.load('char.png') | |
self.at = 0 | |
self.elapsed = 0 | |
self.rect = pygame.rect.Rect(50, 100, 50, 50) | |
@property | |
def image(self): | |
return self.image_at(self.at) | |
def image_at(self, slot): | |
i, j = slot % 5, slot / 5 | |
SW, SH = 40, 49 | |
SX, SY = (2 + SW) * i, (2 + SH) * j | |
rect = pygame.Rect(SX, SY, SW, SH) | |
image = pygame.Surface(rect.size).convert() | |
image.blit(self.sheet, (0,0), rect) | |
return image | |
def update(self, millis): | |
self.elapsed += millis | |
if self.elapsed > 50: | |
self.elapsed = 0 | |
if self.at == 24: | |
self.at = 0 | |
else: | |
self.at += 1 | |
class SeqCharacter(pygame.sprite.Sprite): | |
def __init__(self, *group): | |
super(SeqCharacter, self).__init__(*group) | |
self.sheet = [pygame.image.load('%s.png' % i) for i in range(1,11)] | |
self.at = 0 | |
self.elapsed = 0 | |
self.rect = pygame.rect.Rect(0, 0, 50, 50) | |
@property | |
def image(self): | |
return self.sheet[self.at] | |
def update(self, millis): | |
self.elapsed += millis | |
if self.elapsed > 50: | |
self.elapsed = 0 | |
if self.at == 9: | |
self.at = 0 | |
else: | |
self.at += 1 | |
pygame.init() | |
SIZE = W, H = 640, 400 | |
FPS = 60 | |
BG = pygame.color.Color('white') | |
is_running = True | |
screen = pygame.display.set_mode(SIZE) | |
clock = pygame.time.Clock() | |
if len(sys.argv) > 1 and sys.argv[1] == 'seq': | |
play = SeqCharacter() | |
else: | |
play = Character() | |
group = pygame.sprite.Group() | |
group.add(play) | |
while is_running: | |
millis = clock.tick(FPS) | |
ev = pygame.event.poll() | |
if ev.type == pygame.KEYDOWN: | |
key = ev.dict['key'] | |
if key == 27: | |
is_running = False | |
screen.fill(BG) | |
group.update(millis) | |
group.draw(screen) | |
pygame.display.flip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment