Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- from objectclass import Object
- from os import listdir
- from os.path import isfile, join
- def flip(sprites):
- return [pygame.transform.flip(sprite, True, False) for sprite in sprites]
- def load_sprite_sheets(dir1, dir2, width, height, direction=False):
- path = join("assets", dir1, dir2)
- images = [f for f in listdir(path) if isfile(join(path, f))]
- all_sprites = {}
- for image in images:
- sprite_sheet = pygame.image.load(join(path, image)).convert_alpha()
- sprites = []
- for i in range(sprite_sheet.get_width() // width):
- surface = pygame.Surface((width, height), pygame.SRCALPHA, 32)
- rect = pygame.Rect(i * width, 0, width, height)
- surface.blit(sprite_sheet, (0, 0), rect)
- sprites.append(pygame.transform.scale2x(surface))
- if direction:
- all_sprites[image.replace(".png", "") + "_right"] = sprites
- all_sprites[image.replace(".png", "") + "_left"] = flip(sprites)
- else:
- all_sprites[image.replace(".png", "")] = sprites
- return all_sprites
- class Fruit(Object):
- ANIMATION_DELAY = 3
- def __init__(self, x, y, width, height):
- super().__init__(x, y, width, height, "fruit")
- self.fruit = load_sprite_sheets("Items", "Fruits", width, height, False)
- self.image = self.fruit["Strawberry"][0]
- self.mask = pygame.mask.from_surface(self.image)
- self.animation_count = 0
- self.animation_name = "Strawberry"
- def idle(self):
- self.animation_name = "Strawberry"
- def loop(self):
- sprites = self.fruit[self.animation_name]
- sprite_index = (self.animation_count //
- self.ANIMATION_DELAY) % len(sprites)
- self.image = sprites[sprite_index]
- self.animation_count += 1
- self.rect = self.image.get_rect(topleft=(self.rect.x, self.rect.y))
- self.mask = pygame.mask.from_surface(self.image)
- if self.animation_count // self.ANIMATION_DELAY > len(sprites):
- self.animation_count = 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement