sprite_stacking_engine/engine.py

83 lines
2.1 KiB
Python
Raw Normal View History

2024-02-03 17:08:51 +01:00
#!/usr/bin/python3
import pygame
2024-04-18 18:24:41 +02:00
from dataclasses import dataclass
from wobbl_tools import pg
from wobbl_tools import data_file
2024-02-03 17:08:51 +01:00
class Object:
2024-04-18 18:24:41 +02:00
def __init__(self, sprite_path: str="sprites/coffee_cup.png", sprite_spacing: int=1, rotation: int=45, size_multiplier: int=16):
self.sprite_path = sprite_path
2024-02-03 17:08:51 +01:00
self.sprite_spacing = sprite_spacing
2024-04-18 18:24:41 +02:00
self.rotation = rotation
2024-02-03 17:08:51 +01:00
self.size_multiplier = size_multiplier
2024-04-18 18:24:41 +02:00
self.sprite_size = tuple(get_json(get_dir(sprite_path) + "/sprite_properties.json")[get_filename(sprite_path)]["size"])
2024-02-03 17:08:51 +01:00
2024-04-18 18:24:41 +02:00
self.original_sprites = self.get_sprites()
self.sprites = self.rotate_sprites()
2024-02-03 17:08:51 +01:00
self.surface = self.generate_surface()
2024-04-18 18:24:41 +02:00
print(self.sprite_size)
2024-02-03 17:08:51 +01:00
2024-04-18 18:24:41 +02:00
def get_sprites(self):
model = pygame.image.load(self.sprite_path)
2024-02-03 17:08:51 +01:00
sw, sh = self.sprite_size
mw, mh = model.get_size()
sprites = []
for x in range(0, mw, sw):
2024-04-18 18:24:41 +02:00
sprite = pg.crop_surface(model, (x, 0), (sw, sh))
sprites.append(sprite)
return sprites
def rotate_sprites(self):
sprites = []
for sprite in self.original_sprites:
sprite = pygame.transform.rotate(sprite, self.rotation)
2024-02-03 17:08:51 +01:00
sprites.append(sprite)
return sprites
def generate_surface(self):
sw, sh = self.sprites[0].get_size()
surface = pygame.Surface((sw, sh + self.sprite_spacing * len(self.sprites)), flags=pygame.SRCALPHA)
y = surface.get_height() - sh
for sprite in self.sprites:
surface.blit(sprite, (0, y))
y -= self.sprite_spacing
2024-04-18 18:24:41 +02:00
surface = pygame.transform.scale(surface, (surface.get_width() * self.size_multiplier, surface.get_height() * self.size_multiplier))
2024-02-03 17:08:51 +01:00
return surface
def update(self):
return self.rotate_sprites(), self.generate_surface()
2024-02-03 17:08:51 +01:00
2024-04-18 18:24:41 +02:00
def get_dir(path: str):
return path.rsplit("/", 1)[0]
2024-02-03 17:08:51 +01:00
2024-04-18 18:24:41 +02:00
def get_filename(path: str):
return path.rsplit("/", 1)[1]
def get_json(path: str):
file = open(path, "r")
data = eval(file.read())
file.close()
2024-02-03 17:08:51 +01:00
2024-04-18 18:24:41 +02:00
return data
2024-02-03 17:08:51 +01:00
if __name__ == "__main__":
2024-04-18 18:24:41 +02:00
bla = Object()