Return to repo list

heart-of-gold

Tactical RPG written in python, using pygame.
Return to HMagellan.com

commit ee287c66981b18caaf8266e55dec849058090070
parent 8f414b86a4048487b7b68fe4b6a866f805d9dcfe
Author: Erik Letson <hmagellan@hmagellan.com>
Date:   Wed, 26 Aug 2020 02:14:01 -0500

Added images basics

Diffstat:
Asrc/images.py | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 77 insertions(+), 0 deletions(-)

diff --git a/src/images.py b/src/images.py @@ -0,0 +1,77 @@ +import pygame, os + +class Sheet(object): + """ + Class for the spritesheets that entity images are loaded + from. Supports regularized spritesheets only (all sprites + feature the same dimensions). + """ + + def __init__(self, game, name, sprite_size, total_sprites): + + self.game = game + + #try and load all sprites on the sheet + success = self.load_sheet(name, sprite_size, total_sprites) + + if success == 1: #failure, cleanup vals + + self.sprites = {} + print("Failed to load sheet: " + name) #error message + + def load_sheet(self, name, sprite_size, total_sprites): + """ + Load a sheet and divide it into subsurfaces for + use as images by sprite entities. + """ + + #remember important variables + self.name = name + self.sprite_size = sprite_size + self.total_sprites = total_sprites + + #Step 1: attempt to load the appropriate image file + try: + + self.sheet = pygame.image.load(os.path.join(os.getcwd(), "data", "img", name)) + + #catch a missing file error and stop, set up graceful failure + except: + + self.sheet = None + + #Step 2: if sheet exists, divide it into sprites + if self.sheet != None: + + self.sprites = {} # empty dict to hold our loaded images + + #vals to track our progress thru the sheet + x = 0 + y = 0 + + #while we still have more sprites to load, load them + while len(self.sprites) < total_sprites: + + #get a rect that can be used to make a subsurface of the sheet + new_rect = pygame.Rect((x * sprite_size[0], y * sprite_size[1]), + sprite_size) + + #load image, store it in our dict, set its colorkey + self.sprites[(x, y)] = self.sheet.subsurface(new_rect).convert() + self.sprites[(x, y)].set_colorkey((255, 0, 255)) + + x += 1 # scoot over to the right + + #if we're hanging off the right side, scoot down and start over + #again from the far left + if x * sprite_size[0] >= self.sheet.get_width(): + + x = 0 + y += 1 + + return 0 # SUCCESS!! + + #No sheet exists + else: + + return 1 # failure :C