Advertisement
Maluia

fruitclass

Oct 19th, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | Gaming | 0 0
  1. import pygame
  2. from objectclass import Object
  3. from os import listdir
  4. from os.path import isfile, join
  5.  
  6. def flip(sprites):
  7.     return [pygame.transform.flip(sprite, True, False) for sprite in sprites]
  8.  
  9. def load_sprite_sheets(dir1, dir2, width, height, direction=False):
  10.     path = join("assets", dir1, dir2)
  11.     images = [f for f in listdir(path) if isfile(join(path, f))]
  12.  
  13.     all_sprites = {}
  14.  
  15.     for image in images:
  16.         sprite_sheet = pygame.image.load(join(path, image)).convert_alpha()
  17.  
  18.         sprites = []
  19.         for i in range(sprite_sheet.get_width() // width):
  20.             surface = pygame.Surface((width, height), pygame.SRCALPHA, 32)
  21.             rect = pygame.Rect(i * width, 0, width, height)
  22.             surface.blit(sprite_sheet, (0, 0), rect)
  23.             sprites.append(pygame.transform.scale2x(surface))
  24.  
  25.         if direction:
  26.             all_sprites[image.replace(".png", "") + "_right"] = sprites
  27.             all_sprites[image.replace(".png", "") + "_left"] = flip(sprites)
  28.         else:
  29.             all_sprites[image.replace(".png", "")] = sprites
  30.  
  31.     return all_sprites
  32.  
  33. class Fruit(Object):
  34.     ANIMATION_DELAY = 3
  35.  
  36.     def __init__(self, x, y, width, height):
  37.         super().__init__(x, y, width, height, "fruit")
  38.         self.fruit = load_sprite_sheets("Items", "Fruits", width, height, False)
  39.         self.image = self.fruit["Strawberry"][0]
  40.         self.mask = pygame.mask.from_surface(self.image)
  41.         self.animation_count = 0
  42.         self.animation_name = "Strawberry"
  43.  
  44.    
  45.     def idle(self):
  46.         self.animation_name = "Strawberry"
  47.  
  48.  
  49.     def loop(self):
  50.         sprites = self.fruit[self.animation_name]
  51.         sprite_index = (self.animation_count //
  52.                         self.ANIMATION_DELAY) % len(sprites)
  53.         self.image = sprites[sprite_index]
  54.         self.animation_count += 1
  55.        
  56.         self.rect = self.image.get_rect(topleft=(self.rect.x, self.rect.y))
  57.         self.mask = pygame.mask.from_surface(self.image)
  58.  
  59.         if self.animation_count // self.ANIMATION_DELAY > len(sprites):
  60.             self.animation_count = 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement