72 lines
3.2 KiB
Python
72 lines
3.2 KiB
Python
# -*- coding: utf-8 -*-
|
|
from pathlib import Path
|
|
from PIL import Image, ImageTk
|
|
from models.resource_manager import ResourceManager
|
|
from resources.code_res.game_constants import OUTCOME_GIF_SIZE, PLAYING_CARD_SIZE
|
|
|
|
|
|
class AssetManager:
|
|
def __init__(self, root_dir: Path):
|
|
self.res = ResourceManager(root_dir)
|
|
self.raw_bg = self._load_pil(self.res.get_ui_image_path("background"))
|
|
self.raw_title = self._load_pil(self.res.get_ui_image_path("title"))
|
|
self.raw_btn = self._load_pil(self.res.get_ui_image_path("btn_normal"))
|
|
self.raw_btn_active = self._load_pil(self.res.get_ui_image_path("btn_active"))
|
|
self.raw_sel = self._load_pil(self.res.get_ui_image_path("sel_inactive"))
|
|
self.raw_sel_active = self._load_pil(self.res.get_ui_image_path("sel_active"))
|
|
self.raw_chat_frame = self._load_pil(self.res.get_ui_image_path("card_frame"))
|
|
self._tk_cache = {}
|
|
|
|
@staticmethod
|
|
def _load_pil(path: Path):
|
|
if path.is_file():
|
|
try:
|
|
return Image.open(path).convert("RGBA")
|
|
except Exception:
|
|
return None
|
|
return None
|
|
|
|
def get_card_photo(self, card_filename: str, size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None:
|
|
key = ("card", self.res.card_theme, card_filename, size)
|
|
if key not in self._tk_cache:
|
|
pil = self._load_pil(self.res.get_card_path(card_filename))
|
|
if pil:
|
|
self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.LANCZOS))
|
|
return self._tk_cache.get(key)
|
|
|
|
def get_card_back_photo(self, color: str = "Black", size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None:
|
|
key = ("card_back", self.res.card_theme, color, size)
|
|
if key not in self._tk_cache:
|
|
pil = self._load_pil(self.res.get_card_back_path(color))
|
|
if pil:
|
|
self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.LANCZOS))
|
|
return self._tk_cache.get(key)
|
|
|
|
def get_scaled_photo(self, name: str, pil_img, size: tuple[int, int]):
|
|
if not pil_img:
|
|
return None
|
|
key = (name, size)
|
|
if key not in self._tk_cache:
|
|
self._tk_cache[key] = ImageTk.PhotoImage(pil_img.resize(size, Image.Resampling.LANCZOS))
|
|
return self._tk_cache[key]
|
|
|
|
def get_gif_frames(self, key_or_filename: str, size=OUTCOME_GIF_SIZE) -> list[ImageTk.PhotoImage]:
|
|
cache_key = ("gif", key_or_filename, size)
|
|
if cache_key not in self._tk_cache:
|
|
frames = []
|
|
path = self.res.get_ui_image_path(key_or_filename)
|
|
if path.is_file():
|
|
try:
|
|
with Image.open(path) as gif:
|
|
idx = 0
|
|
while True:
|
|
frame = gif.copy().convert("RGBA").resize(size, Image.Resampling.LANCZOS)
|
|
frames.append(ImageTk.PhotoImage(frame))
|
|
idx += 1
|
|
gif.seek(idx)
|
|
except EOFError:
|
|
pass
|
|
except Exception:
|
|
pass
|
|
self._tk_cache[cache_key] = frames
|
|
return self._tk_cache[cache_key] |