Sprite scaling support and a little refactoring
This commit is contained in:
Binary file not shown.
97
eb_engine.py
97
eb_engine.py
@@ -3,13 +3,16 @@ import eb_objects
|
||||
import eb_terrain
|
||||
import eb_creatures
|
||||
|
||||
|
||||
|
||||
cell_classes = {"Ground": eb_terrain.Ground}
|
||||
main_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
sprites_dir = os.path.join(main_dir, "res", "sprites")
|
||||
#file_path = os.path.join(main_dir, "res", "sprites", "grass_small.png")
|
||||
|
||||
def scale_image(image, n):
|
||||
orig_size = image.get_size()
|
||||
new_size = (int(orig_size[0] * n), int(orig_size[1] * n))
|
||||
return pygame.transform.scale(image, new_size)
|
||||
|
||||
@dataclass
|
||||
class Cell:
|
||||
terrain_obj: any
|
||||
@@ -19,16 +22,16 @@ class Cell:
|
||||
|
||||
@dataclass
|
||||
class Map:
|
||||
name: str
|
||||
cells: dict = None
|
||||
color: str = "gray57"
|
||||
target_color: str = "gold"
|
||||
size: int = 150
|
||||
bord: int = 5
|
||||
scale: float = 1
|
||||
cam_x: int = 0
|
||||
cam_y: int = 0
|
||||
cell_dist: int = 2
|
||||
name: str
|
||||
cells: dict = field(default_factory = dict)
|
||||
color: str = "gray57"
|
||||
target_color: str = "gold"
|
||||
size: int = 150
|
||||
bord: int = 5
|
||||
scale: float = 1
|
||||
cam_x: int = 0
|
||||
cam_y: int = 0
|
||||
cell_dist: int = 2
|
||||
|
||||
def __post_init__(self):
|
||||
self.cells = {}
|
||||
@@ -47,47 +50,42 @@ class Map:
|
||||
y = int((l * self.size + self.cam_y) * self.scale)
|
||||
w = int(self.size * self.scale - self.cell_dist)
|
||||
h = int(self.size * self.scale - self.cell_dist)
|
||||
|
||||
#add if scale != prev_scale: no scale
|
||||
scaled = scale_image(sprites[cell.terrain_obj.sprite], self.scale)
|
||||
scaled_rect = scaled.get_rect(center = (x + w/2, y + h/2))
|
||||
screen.blit(scaled, scaled_rect)
|
||||
|
||||
if grid:
|
||||
pygame.draw.rect(screen, self.color, pygame.Rect(x, y, w, h), self.bord)
|
||||
sp = sprites[cell.terrain_obj.sprite].get_rect(center = (x + w/2, y + h/2))
|
||||
screen.blit(sprites[cell.terrain_obj.sprite], sp)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Engine:
|
||||
def __init__(self, width, height, sprites = {}):
|
||||
self.width = width
|
||||
self.height = height
|
||||
self.sprites = sprites
|
||||
sprites: dict = field(default_factory = dict)
|
||||
screen: pygame.Surface = ((1, 1))
|
||||
width: int = 1600
|
||||
height: int = 800
|
||||
camera_step: int = 10
|
||||
scale_step: float = 0.01
|
||||
|
||||
def __post_init__(self):
|
||||
self.sprites = {}
|
||||
pygame.init()
|
||||
|
||||
pygame.display.set_caption('Elvenbane')
|
||||
self.screen = pygame.display.set_mode((self.width, self.height))
|
||||
self.load_sprites()
|
||||
|
||||
def load_sprites(self, folder_path = sprites_dir):
|
||||
for filename in os.listdir(folder_path):
|
||||
if filename.lower().endswith('.png'):
|
||||
name = os.path.splitext(filename)[0]
|
||||
self.sprites[name] = pygame.image.load(os.path.join(folder_path, filename)).convert_alpha()
|
||||
|
||||
|
||||
def main_loop(self):
|
||||
'''
|
||||
#o = eb_terrain.Ground(1, 1, 1)
|
||||
#c = eb_creatures.Unit(1, 1, 1)
|
||||
#print(isinstance(o, eb_objects.Object))
|
||||
#print(isinstance(o, eb_objects.Terrain))
|
||||
#print(isinstance(c, eb_objects.Terrain))
|
||||
'''
|
||||
|
||||
easy_map = Map("def_map.json")
|
||||
# pygame setup
|
||||
|
||||
screen = pygame.display.set_mode((self.width, self.height))
|
||||
clock = pygame.time.Clock()
|
||||
def main_loop(self):
|
||||
clock = pygame.time.Clock()
|
||||
running = True
|
||||
unlock = True
|
||||
camera_step = 10
|
||||
scale_step = 0.1
|
||||
|
||||
|
||||
self.load_sprites()
|
||||
easy_map = Map("def_map.json")
|
||||
#gr = pygame.image.load(file_path).convert_alpha()
|
||||
|
||||
while running:
|
||||
@@ -98,24 +96,24 @@ class Engine:
|
||||
running = False
|
||||
|
||||
# fill the screen with a color to wipe away anything from last frame
|
||||
screen.fill("chartreuse4")
|
||||
self.screen.fill("chartreuse4")
|
||||
|
||||
easy_map.draw(screen, self.sprites)
|
||||
easy_map.draw(self.screen, self.sprites)
|
||||
|
||||
if unlock:
|
||||
keys = pygame.key.get_pressed()
|
||||
if keys[pygame.K_w]:
|
||||
easy_map.cam_y -= camera_step
|
||||
easy_map.cam_y -= self.camera_step
|
||||
if keys[pygame.K_s]:
|
||||
easy_map.cam_y += camera_step
|
||||
easy_map.cam_y += self.camera_step
|
||||
if keys[pygame.K_a]:
|
||||
easy_map.cam_x -= camera_step
|
||||
easy_map.cam_x -= self.camera_step
|
||||
if keys[pygame.K_d]:
|
||||
easy_map.cam_x += camera_step
|
||||
easy_map.cam_x += self.camera_step
|
||||
if keys[pygame.K_q]:
|
||||
easy_map.scale += scale_step
|
||||
if keys[pygame.K_e]:
|
||||
easy_map.scale -= scale_step
|
||||
easy_map.scale += self.scale_step
|
||||
if keys[pygame.K_e] and easy_map.scale >= self.scale_step:
|
||||
easy_map.scale -= self.scale_step
|
||||
if keys[pygame.K_ESCAPE]:
|
||||
running = False
|
||||
|
||||
@@ -124,5 +122,4 @@ class Engine:
|
||||
# limits FPS to 60
|
||||
clock.tick(60)
|
||||
|
||||
|
||||
pygame.quit()
|
||||
14
main.py
14
main.py
@@ -1,18 +1,26 @@
|
||||
import eb_engine
|
||||
|
||||
def main():
|
||||
e = eb_engine.Engine(1600, 900)
|
||||
e = eb_engine.Engine()
|
||||
e.main_loop()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# pydantic instead of dataclasses?
|
||||
# Отрисовка голой сетки, прокрутка, масштаб +
|
||||
# Отрисовка спрайтов
|
||||
# Отрисовка спрайтов:
|
||||
# - сделать масштабирование в соотв. с клеткой +
|
||||
# - посмотреть класс спрайта или сделать свой
|
||||
# - добавить отрисовку существ и предметов
|
||||
# почитать про Surface, Display, доку к pygame-gui
|
||||
# Начало гуя - кнопка, строка ввода, клик
|
||||
# Поиск пути
|
||||
# Редактор карты
|
||||
# Охотник - деревня
|
||||
# Охотник -> деревня
|
||||
# Простой, но основательный гуй внизу экрана, глобальная карта и перемещение
|
||||
# деревня на соседской локации и торговля с ней
|
||||
# перемещение по воде, течение
|
||||
|
||||
# проверить у ллм на ошибки:
|
||||
# - deepcopy
|
||||
# - общие
|
||||
main()
|
||||
72
slop.txt
Normal file
72
slop.txt
Normal file
@@ -0,0 +1,72 @@
|
||||
#o = eb_terrain.Ground(1, 1, 1)
|
||||
#c = eb_creatures.Unit(1, 1, 1)
|
||||
#print(isinstance(o, eb_objects.Object))
|
||||
#print(isinstance(o, eb_objects.Terrain))
|
||||
#print(isinstance(c, eb_objects.Terrain))
|
||||
|
||||
|
||||
|
||||
import pygame
|
||||
pygame.init()
|
||||
screen = pygame.display.set_mode((800, 600))
|
||||
|
||||
original = pygame.image.load('sprite.png').convert_alpha()
|
||||
orig_rect = original.get_rect(center=(200, 300))
|
||||
|
||||
def scale_image(image, n):
|
||||
orig_size = image.get_size()
|
||||
new_size = (int(orig_size[0] * n), int(orig_size[1] * n))
|
||||
return pygame.transform.scale(image, new_size)
|
||||
|
||||
n = 1.5 # Example: 1.5x larger
|
||||
scaled = scale_image(original, n)
|
||||
scaled_rect = scaled.get_rect(center=(600, 300))
|
||||
|
||||
screen.blit(original, orig_rect) # Original size
|
||||
screen.blit(scaled, scaled_rect) # Scaled by n
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def load_sprites_from_folder(self, folder_path = sprites_dir):
|
||||
"""
|
||||
Загружает все PNG изображения из указанной папки в словарь.
|
||||
Ключи - имена файлов без расширения, значения - pygame.Surface
|
||||
"""
|
||||
# Полный путь к папке со спрайтами относительно скрипта
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
full_path = os.path.join(script_dir, folder_path)
|
||||
|
||||
sprites = {}
|
||||
|
||||
if not os.path.exists(full_path):
|
||||
print(f"❌ Папка не найдена: {full_path}")
|
||||
return sprites
|
||||
|
||||
print(f"🔍 Сканируем папку: {full_path}")
|
||||
|
||||
# Проходим по всем файлам в папке
|
||||
for filename in os.listdir(full_path):
|
||||
if filename.lower().endswith('.png'):
|
||||
# Убираем расширение .png для ключа
|
||||
name = os.path.splitext(filename)[0]
|
||||
filepath = os.path.join(full_path, filename)
|
||||
|
||||
try:
|
||||
# Загружаем изображение
|
||||
surface = pygame.image.load(filepath).convert_alpha()
|
||||
self.sprites[name] = surface
|
||||
print(f"✅ Загружен: {name} ({surface.get_size()})")
|
||||
|
||||
except pygame.error as e:
|
||||
print(f"❌ Ошибка загрузки {filename}: {e}")
|
||||
|
||||
print(f"🎉 Загружено {len(sprites)} спрайтов")
|
||||
|
||||
Reference in New Issue
Block a user