added module sprites.py

This commit is contained in:
Nicholas Dyer 2023-05-11 13:10:08 -04:00
parent 296b6df4a0
commit bbe97f0de7

View File

@ -0,0 +1,84 @@
import pygame
import json
class SpriteSheet:
"""
Imports a sprite sheet as separate pygame images given an image file and a json file.
"""
def __init__(self, sprite_sheet, texture_json):
# Load in whole sprite sheet as one image.
self.sprite_sheet = pygame.image.load(sprite_sheet).convert_alpha()
self.images = []
# Get the sprite sheet json file.
with open(texture_json, 'r') as json_file:
self.img_attrib = json.load(json_file)
json_file.close()
# Count for how many images have been added in the image list
image_count = 0
# Get the sprite size as a tuple
sprite_size = self.img_attrib['width'], self.img_attrib['height']
# Iterate through every image location on the sprite sheet given the sprite size
for i in range(self.sprite_sheet.get_size()[1] // sprite_size[1]):
i *= sprite_size[1]
for j in range(self.sprite_sheet.get_size()[0] // sprite_size[0]):
j *= sprite_size[0]
# Create a new transparent surface
sprite = pygame.Surface(sprite_size, pygame.SRCALPHA)
# Blit the sprite onto the image
sprite.blit(self.sprite_sheet, (0, 0), (j, i, sprite_size[0], sprite_size[1]))
# Add the image to the list of images
self.images.append(sprite)
image_count += 1
# Break the loop if the specified number of frames has been reached.
if image_count >= self.img_attrib['frames']:
break
if image_count >= self.img_attrib['frames']:
break
class SelectionEgg(pygame.sprite.Sprite):
"""
Class for the eggs on the egg selection screen.
"""
def __init__(self, egg_color, resources_dir):
pygame.sprite.Sprite.__init__(self)
self.egg_color = egg_color
# Loads the JSON file of the egg to read in data.
with open(resources_dir + '/data/bloop_info/{0}.json'.format(egg_color), 'r') as save_file:
json_file = json.load(save_file)
save_file.close()
# Gets the description off the egg from the JSON file.
self.description = json_file.get('description')
self.contentedness = json_file.get('contentedness')
self.metabolism = json_file.get('metabolism')
# Load the egg from the given color and get the bounding rectangle for the image.
sprite_sheet = SpriteSheet(resources_dir + '/images/bloops/{0}/egg.png'.format(self.egg_color),
resources_dir + '/resources/images/bloops/{0}/egg.json'.format(self.egg_color))
self.images = sprite_sheet.images
# Get the rectangle from the first image in the list
self.rect = self.images[0].get_rect()
self.index = 0
self.image = self.images[self.index]
def update(self):
"""
Updates the sprite object.
"""
# Animate the sprite
self.index = (self.index + 1) % len(self.images)
self.image = self.images[self.index]