the_goth_cardgame_collection/view/assets_manager.py

723 lines
29 KiB
Python

# -*- coding: utf-8 -*-
# view/assets_manager.py
from __future__ import annotations
import re
import tkinter as tk
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageFont, ImageTk
from models.resource_manager import ResourceManager
from resources.code_res.game_constants import (
FONTS_REL_DIR,
FONT_COLOR_BODY_DEFAULT,
FONT_FILE_ALTERNATE,
FONT_FILE_PRIMARY,
FONT_FORCE_MIXED_CASE,
FONT_LETTER_SPACING_PX,
FONT_LINE_HEIGHT_FACTOR,
FONT_OUTLINE_COLOR,
FONT_OUTLINE_THICKNESS_PX,
FONT_SHADOW_COLOR,
FONT_SHADOW_ENABLED,
FONT_SHADOW_OFFSET_DEFAULT,
FONT_VERTICAL_OFFSET_PX,
OUTCOME_GIF_SIZE,
PLAYING_CARD_SIZE,
)
BOX_SOURCE_CORNER_RATIO = {
"box_big": 0.16,
"box_gold_small": 0.24,
"box_gold_double": 0.16,
"box_purple": 0.22,
"dropdown_box": 0.085,
}
BOX_TARGET_CORNER_SPEC = {
"box_big": (0.14, 18, 46),
"box_gold_small": (0.22, 14, 34),
"box_gold_double": (0.18, 12, 26),
"box_purple": (0.18, 14, 32),
"dropdown_box": (0.10, 10, 18),
}
_ALL_CAPS_WORD_RE = re.compile(r"\b[A-ZÄÖÜ]{4,}\b")
def _clean_box_matte_fast(pil_img: Image.Image | None, hollow_center: bool = True) -> Image.Image | None:
if pil_img is None:
return None
rgba = pil_img.convert("RGBA")
w, h = rgba.size
if w < 8 or h < 8:
return rgba
r, g, b, a = rgba.split()
luma = ImageChops.lighter(ImageChops.lighter(r, g), b)
seed_img = luma.point(lambda p: 0 if p < 18 else 255)
seeds = [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)]
if hollow_center:
seeds.append((w // 2, h // 2))
changed = False
for sx, sy in seeds:
if rgba.getpixel((sx, sy))[3] > 240 and seed_img.getpixel((sx, sy)) == 0:
ImageDraw.floodfill(seed_img, (sx, sy), 128)
changed = True
if changed:
ext_alpha = seed_img.point(lambda p: 0 if p == 128 else 255)
rgba.putalpha(ImageChops.darker(a, ext_alpha))
return rgba
class AssetManager:
def __init__(self, root_dir: Path):
self.root_dir = root_dir
self.res = ResourceManager(root_dir)
self._tk_cache: dict = {}
self._pil_cache: dict = {}
self._raw_card_cache: dict[str, Image.Image | None] = {}
self._font_cache: dict[tuple[bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
self._bg_scaled_key: tuple[bool, int, int] | None = None
self._bg_scaled_pil: Image.Image | None = None
self.raw_bg_horizontal = self._load_ui_flexible("bg_horizontal", "background_horizontal")
self.raw_bg_vertical = self._load_ui_flexible("bg_vertical", "background_vertical")
self.raw_bg = self.raw_bg_horizontal or self._load_ui_flexible("background", "background")
self.raw_title = self._load_ui_flexible("title", "title")
self.raw_general_table = None
self.raw_poker_table = self._load_ui_flexible("poker_table", "poker_table")
self.raw_btn_default = self._load_ui_flexible("btn_default", "button")
self.raw_btn_purple = self._load_ui_flexible("btn_purple", "button_highlighted_purple")
self.raw_btn_fire = self._load_ui_flexible("btn_fire", "button_highlighted_fire")
self.raw_boxes: dict[str, Image.Image | None] = {
"box_big": _clean_box_matte_fast(
self._load_ui_flexible("box_big", "box_big"), hollow_center=True
),
"box_gold_small": _clean_box_matte_fast(
self._load_ui_flexible("box_gold_small", "box_gold_smal", "box_gold_small"), hollow_center=True
),
"box_gold_double": _clean_box_matte_fast(
self._load_ui_flexible("box_gold_double", "box_gold_small_double"), hollow_center=True
),
"box_purple": _clean_box_matte_fast(
self._load_ui_flexible("box_purple", "box_small_purple"), hollow_center=True
),
"dropdown_box": _clean_box_matte_fast(
self._load_ui_flexible("dropdown_box", "dropdown_box"), hollow_center=False
),
}
self.raw_chat_frame = self.raw_boxes["box_big"]
self.raw_input = self._load_ui_flexible("input_field", "input")
self.raw_dropdown_closed = self._load_ui_flexible("dropdown_closed", "dropdown_closed")
self.raw_dropdown_closed_btn = self._load_ui_flexible("dropdown_closed_btn", "dropdown_closed_button")
self.raw_dropdown_open = self._load_ui_flexible(
"dropdown_open", "dropdown_box_hightlighted", "dropdown_box_highlighted"
)
self.raw_dropdown_open_btn = self._load_ui_flexible(
"dropdown_open_btn", "dropdown_box_hightlighted_button", "dropdown_box_highlighted_button"
)
self.raw_dropdown_box = self.raw_boxes["dropdown_box"]
self.raw_dropdown_selection = self._load_ui_flexible("dropdown_selection", "dropdown_selection")
self._optimize_raw_for_display()
self.raw_btn = self.raw_btn_fire or self.raw_btn_default
self.raw_btn_active = self.raw_btn_fire or self.raw_btn_purple
self.raw_sel = self.raw_btn_default
self.raw_sel_active = self.raw_btn_purple or self.raw_btn_default
@staticmethod
def _load_pil(path: Path | None) -> Image.Image | None:
if path and path.is_file():
try:
return Image.open(path).convert("RGBA")
except Exception:
return None
return None
def _load_ui_flexible(self, ui_key: str, *stem_fallbacks: str) -> Image.Image | None:
try:
p = self.res.get_ui_image_path(ui_key)
pil = self._load_pil(p)
if pil is not None:
return pil
except Exception:
pass
img_dir = self.root_dir / "resources" / "images"
for stem in stem_fallbacks:
for ext in (".png", ".jpg", ".jpeg"):
cand = img_dir / f"{stem}{ext}"
if cand.is_file():
loaded = self._load_pil(cand)
if loaded is not None:
return loaded
return None
def _optimize_raw_for_display(self):
try:
r = tk._default_root
sw = r.winfo_screenwidth() if r else 1920
sh = r.winfo_screenheight() if r else 1080
except Exception:
sw, sh = 1920, 1080
btn_cap_h = 200 if max(sw, sh) >= 2500 else 130
for attr in ("raw_btn_default", "raw_btn_purple", "raw_btn_fire"):
img = getattr(self, attr, None)
if img is not None and img.height > btn_cap_h:
ratio = btn_cap_h / img.height
nw = max(1, int(round(img.width * ratio)))
setattr(self, attr, img.resize((nw, btn_cap_h), Image.Resampling.LANCZOS))
if max(sw, sh) >= 2500:
return
max_bg_w = int(sw * 1.15)
max_bg_h = int(sh * 1.15)
for attr in ("raw_bg_horizontal", "raw_bg_vertical", "raw_bg", "raw_poker_table"):
img = getattr(self, attr, None)
if img is not None and (img.width > max_bg_w or img.height > max_bg_h):
ratio = min(max_bg_w / img.width, max_bg_h / img.height)
nw = max(1, int(round(img.width * ratio)))
nh = max(1, int(round(img.height * ratio)))
setattr(self, attr, img.resize((nw, nh), Image.Resampling.LANCZOS))
# ------------------------------------------------------------------
# ZENTRALER HINTERGRUND-CACHE & MODAL-ABDUNKLUNG
# ------------------------------------------------------------------
def get_window_bg_pil(self, rw: int, rh: int) -> Image.Image | None:
rw, rh = max(64, int(rw)), max(64, int(rh))
is_vert = bool(rh > rw and self.raw_bg_vertical is not None)
key = (is_vert, rw, rh)
if key == self._bg_scaled_key and self._bg_scaled_pil is not None:
return self._bg_scaled_pil
src = self.raw_bg_vertical if is_vert else (self.raw_bg_horizontal or self.raw_bg)
if src is None:
return None
rgb_src = src.convert("RGB") if src.mode != "RGB" else src
self._bg_scaled_pil = rgb_src.resize((rw, rh), Image.Resampling.BILINEAR)
self._bg_scaled_key = key
return self._bg_scaled_pil
def get_bg_patch_photo(
self, rw: int, rh: int, ox: int, oy: int, w: int, h: int
) -> ImageTk.PhotoImage | None:
w, h = max(1, int(w)), max(1, int(h))
rw, rh = max(w, int(rw)), max(h, int(rh))
ox = max(0, min(rw - w, int(ox)))
oy = max(0, min(rh - h, int(oy)))
tk_key = ("bg_patch", rw, rh, ox, oy, w, h)
if tk_key in self._tk_cache:
return self._tk_cache[tk_key]
base = self.get_window_bg_pil(rw, rh)
if base is None:
return None
if len(self._tk_cache) > 360:
stale = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "bg_patch"]
for k in stale[:-12]:
self._tk_cache.pop(k, None)
cropped = base.crop((ox, oy, ox + w, oy + h))
photo = ImageTk.PhotoImage(cropped)
self._tk_cache[tk_key] = photo
return photo
def get_dim_veil_photo(
self, width: int, height: int, alpha: int = 148
) -> ImageTk.PhotoImage:
"""
Erzeugt einen halbtransparenten RGBA-Abdunklungsschleier für gesperrte Spieltische,
sodass Karten und Tischdetails darunter gedimmt/ausgegraut sichtbar bleiben.
"""
w, h = max(8, int(width)), max(8, int(height))
a = max(0, min(240, int(alpha)))
tk_key = ("dim_veil", w, h, a)
if tk_key not in self._tk_cache:
stale = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "dim_veil"]
for k in stale[:-6]:
self._tk_cache.pop(k, None)
veil_pil = Image.new("RGBA", (w, h), (10, 8, 16, a))
self._tk_cache[tk_key] = ImageTk.PhotoImage(veil_pil)
return self._tk_cache[tk_key]
# ------------------------------------------------------------------
# FONT-LOADER & OLD-LONDON TEXT-RENDERER (PIL RGBA)
# ------------------------------------------------------------------
def get_pil_font(self, size_px: int, alternate: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
size_px = max(12, int(size_px))
key = (alternate, size_px)
if key not in self._font_cache:
fname = FONT_FILE_ALTERNATE if alternate else FONT_FILE_PRIMARY
fpath = self.root_dir / FONTS_REL_DIR / fname
if not fpath.is_file():
fpath = self.root_dir / FONTS_REL_DIR / FONT_FILE_PRIMARY
try:
self._font_cache[key] = ImageFont.truetype(str(fpath), size_px)
except Exception:
self._font_cache[key] = ImageFont.load_default()
return self._font_cache[key]
@staticmethod
def sanitize_goth_case(text: str) -> str:
if not text or not FONT_FORCE_MIXED_CASE:
return text
return _ALL_CAPS_WORD_RE.sub(lambda m: m.group(0).capitalize(), text)
def _measure_tracked_line(
self,
draw: ImageDraw.ImageDraw,
line: str,
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
letter_spacing: int,
) -> float:
if not line:
return 0.0
if letter_spacing == 0:
return float(draw.textlength(line, font=font))
adv_fn = draw.textlength
total = 0.0
for ch in line:
total += adv_fn(ch, font=font)
return total + letter_spacing * (len(line) - 1)
def _draw_tracked_line(
self,
draw: ImageDraw.ImageDraw,
x: float,
y: float,
line: str,
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
fill: str,
letter_spacing: int,
shadow_offset: tuple[int, int] | None,
outline_px: int,
):
if not line:
return
has_shadow = bool(FONT_SHADOW_ENABLED and shadow_offset and (shadow_offset[0] or shadow_offset[1]))
sx = shadow_offset[0] if (has_shadow and shadow_offset) else 0
sy = shadow_offset[1] if (has_shadow and shadow_offset) else 0
if letter_spacing == 0:
if has_shadow:
draw.text((x + sx, y + sy), line, font=font, fill=FONT_SHADOW_COLOR)
if outline_px > 0:
draw.text((x, y), line, font=font, fill=fill, stroke_width=outline_px, stroke_fill=FONT_OUTLINE_COLOR)
else:
draw.text((x, y), line, font=font, fill=fill)
return
adv_fn = draw.textlength
cur_x = x
for ch in line:
if has_shadow:
draw.text((cur_x + sx, y + sy), ch, font=font, fill=FONT_SHADOW_COLOR)
if outline_px > 0:
draw.text(
(cur_x, y),
ch,
font=font,
fill=fill,
stroke_width=outline_px,
stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((cur_x, y), ch, font=font, fill=fill)
cur_x += adv_fn(ch, font=font) + letter_spacing
def render_goth_text_pil(
self,
text: str,
size_px: int,
color: str = FONT_COLOR_BODY_DEFAULT,
max_width: int | None = None,
align: str = "center",
shadow_offset: tuple[int, int] | None = FONT_SHADOW_OFFSET_DEFAULT,
outline_px: int = FONT_OUTLINE_THICKNESS_PX,
letter_spacing: int = FONT_LETTER_SPACING_PX,
alternate: bool = False,
uncached: bool = False,
) -> Image.Image:
clean_text = self.sanitize_goth_case(str(text or ""))
cache_key = (
"goth_txt_pil", clean_text, size_px, color, max_width,
align, shadow_offset, outline_px, letter_spacing, alternate,
)
if not uncached and cache_key in self._pil_cache:
return self._pil_cache[cache_key]
font = self.get_pil_font(size_px, alternate=alternate)
dummy = Image.new("RGBA", (8, 8), (0, 0, 0, 0))
d_draw = ImageDraw.Draw(dummy)
raw_paragraphs = clean_text.split("\n")
lines: list[str] = []
for para in raw_paragraphs:
if not max_width or max_width <= 20 or not para.strip():
lines.append(para)
continue
words = para.split(" ")
cur = ""
for w in words:
cand = f"{cur} {w}".strip() if cur else w
if self._measure_tracked_line(d_draw, cand, font, letter_spacing) <= max_width or not cur:
cur = cand
else:
lines.append(cur)
cur = w
lines.append(cur)
if not lines:
lines = [""]
try:
ascent, descent = font.getmetrics() # type: ignore[attr-defined]
except Exception:
ascent, descent = size_px, max(6, size_px // 3)
base_line_h = max(size_px + 4, ascent + descent)
step_y = int(round(base_line_h * FONT_LINE_HEIGHT_FACTOR))
pad_x = max(6, outline_px * 2 + (abs(shadow_offset[0]) if shadow_offset else 0) + 4)
pad_top = max(6, outline_px * 2 + 4)
pad_bot = max(8, descent // 2 + outline_px * 2 + (abs(shadow_offset[1]) if shadow_offset else 0) + 6)
line_widths = [self._measure_tracked_line(d_draw, ln, font, letter_spacing) for ln in lines]
content_w = int(round(max(line_widths, default=1.0)))
img_w = max(4, content_w + pad_x * 2)
img_h = max(4, pad_top + base_line_h + max(0, len(lines) - 1) * step_y + pad_bot)
canvas_img = Image.new("RGBA", (img_w, img_h), (0, 0, 0, 0))
draw = ImageDraw.Draw(canvas_img)
for idx, (ln, lw) in enumerate(zip(lines, line_widths)):
if align == "left":
lx = float(pad_x)
elif align == "right":
lx = float(img_w - pad_x) - lw
else:
lx = (img_w - lw) / 2.0
ly = float(pad_top + idx * step_y + FONT_VERTICAL_OFFSET_PX)
self._draw_tracked_line(
draw, lx, ly, ln, font, color, letter_spacing, shadow_offset, outline_px
)
if not uncached:
if len(self._pil_cache) > 500:
txt_keys = [k for k in self._pil_cache if isinstance(k, tuple) and k and k[0] == "goth_txt_pil"]
for k in txt_keys[:150]:
self._pil_cache.pop(k, None)
self._pil_cache[cache_key] = canvas_img
return canvas_img
def get_goth_text_photo(
self,
text: str,
size_px: int,
color: str = FONT_COLOR_BODY_DEFAULT,
max_width: int | None = None,
align: str = "center",
shadow_offset: tuple[int, int] | None = FONT_SHADOW_OFFSET_DEFAULT,
outline_px: int = FONT_OUTLINE_THICKNESS_PX,
letter_spacing: int = FONT_LETTER_SPACING_PX,
alternate: bool = False,
) -> ImageTk.PhotoImage:
tk_key = (
"goth_txt_tk", text, size_px, color, max_width,
align, shadow_offset, outline_px, letter_spacing, alternate,
)
if tk_key not in self._tk_cache:
pil_img = self.render_goth_text_pil(
text=text,
size_px=size_px,
color=color,
max_width=max_width,
align=align,
shadow_offset=shadow_offset,
outline_px=outline_px,
letter_spacing=letter_spacing,
alternate=alternate,
)
if len(self._tk_cache) > 500:
txt_keys = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "goth_txt_tk"]
for k in txt_keys[:150]:
self._tk_cache.pop(k, None)
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_img)
return self._tk_cache[tk_key]
# ------------------------------------------------------------------
# 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN
# ------------------------------------------------------------------
def get_9slice_pil(
self,
box_key: str,
target_size: tuple[int, int],
corner_ratio: float | None = None,
border_scale: float = 1.0,
) -> Image.Image | None:
src = self.raw_boxes.get(box_key)
tw, th = max(16, int(target_size[0])), max(16, int(target_size[1]))
if src is None:
return None
src_ratio = corner_ratio if corner_ratio is not None else BOX_SOURCE_CORNER_RATIO.get(box_key, 0.16)
pil_key = ("9slice_pil", box_key, (tw, th), src_ratio, round(border_scale, 3))
if pil_key in self._pil_cache:
return self._pil_cache[pil_key]
sw, sh = src.size
sc = max(12, int(round(min(sw, sh) * src_ratio)))
rel_target, min_dc, max_dc = BOX_TARGET_CORNER_SPEC.get(box_key, (0.14, 12, 36))
scaled_dc = int(round(min(tw, th) * rel_target * border_scale))
dc = max(min_dc, min(max_dc, scaled_dc))
dc = min(dc, sc, tw // 2 - 1, th // 2 - 1)
if dc < 6:
out = src.resize((tw, th), Image.Resampling.BILINEAR)
self._pil_cache[pil_key] = out
return out
out = Image.new("RGBA", (tw, th), (0, 0, 0, 0))
tl = src.crop((0, 0, sc, sc)).resize((dc, dc), Image.Resampling.LANCZOS)
tr = src.crop((sw - sc, 0, sw, sc)).resize((dc, dc), Image.Resampling.LANCZOS)
bl = src.crop((0, sh - sc, sc, sh)).resize((dc, dc), Image.Resampling.LANCZOS)
br = src.crop((sw - sc, sh - sc, sw, sh)).resize((dc, dc), Image.Resampling.LANCZOS)
out.paste(tl, (0, 0))
out.paste(tr, (tw - dc, 0))
out.paste(bl, (0, th - dc))
out.paste(br, (tw - dc, th - dc))
mid_w = tw - 2 * dc
if mid_w > 0:
top_edge = src.crop((sc, 0, sw - sc, sc)).resize((mid_w, dc), Image.Resampling.BILINEAR)
bot_edge = src.crop((sc, sh - sc, sw - sc, sh)).resize((mid_w, dc), Image.Resampling.BILINEAR)
out.paste(top_edge, (dc, 0))
out.paste(bot_edge, (dc, th - dc))
mid_h = th - 2 * dc
if mid_h > 0:
left_edge = src.crop((0, sc, sc, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR)
right_edge = src.crop((sw - sc, sc, sw, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR)
out.paste(left_edge, (0, dc))
out.paste(right_edge, (tw - dc, dc))
if mid_w > 0 and mid_h > 0 and box_key == "dropdown_box":
center_patch = src.crop((sc, sc, sw - sc, sh - sc)).resize((mid_w, mid_h), Image.Resampling.BILINEAR)
out.paste(center_patch, (dc, dc))
self._pil_cache[pil_key] = out
return out
def get_box_photo(
self,
box_key: str,
size: tuple[int, int],
corner_ratio: float | None = None,
border_scale: float = 1.0,
) -> ImageTk.PhotoImage | None:
tk_key = ("9slice_tk", box_key, size, corner_ratio, round(border_scale, 3))
if tk_key not in self._tk_cache:
pil_box = self.get_9slice_pil(
box_key, size, corner_ratio=corner_ratio, border_scale=border_scale
)
if pil_box is not None:
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_box)
return self._tk_cache.get(tk_key)
# ------------------------------------------------------------------
# KARTEN, BANNER & WIN/LOSE-GIFS MIT ALPHA-KANAL
# ------------------------------------------------------------------
def _get_raw_card_pil(self, path: Path | None) -> Image.Image | None:
if not path:
return None
key = str(path)
if key not in self._raw_card_cache:
pil = self._load_pil(path)
if pil is not None and pil.width > 340:
nh = max(1, int(round(pil.height * (340.0 / pil.width))))
pil = pil.resize((340, nh), Image.Resampling.LANCZOS)
self._raw_card_cache[key] = pil
return self._raw_card_cache[key]
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._get_raw_card_pil(self.res.get_card_path(card_filename))
if pil:
self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.BILINEAR))
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._get_raw_card_pil(self.res.get_card_back_path(color))
if pil:
self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.BILINEAR))
return self._tk_cache.get(key)
def get_scaled_photo(self, name: str, pil_img, size: tuple[int, int]) -> ImageTk.PhotoImage | None:
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_proportional_photo(self, name: str, pil_img, target_width: int) -> ImageTk.PhotoImage | None:
if not pil_img or target_width <= 10:
return None
src_w, src_h = pil_img.size
target_height = max(1, int(round(target_width * (src_h / src_w))))
return self.get_scaled_photo(name, pil_img, (target_width, target_height))
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: list[ImageTk.PhotoImage] = []
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.BILINEAR)
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]
def get_win_lose_gif_sequence(
self, stem_or_filename: str, size: tuple[int, int]
) -> tuple[list[ImageTk.PhotoImage], list[int]]:
"""
Lädt transparente RGBA-GIFs aus resources/images/win_lose/ inklusive ihrer
echten Frame-Dauern (ms) und cacht sie für verzögerungsfreie Partikel-Spawns.
"""
tw, th = max(24, int(size[0])), max(24, int(size[1]))
cache_key = ("win_lose_gif", stem_or_filename, (tw, th))
if cache_key in self._tk_cache:
return self._tk_cache[cache_key]
raw_pil_key = ("win_lose_raw_pil", stem_or_filename)
if raw_pil_key not in self._pil_cache:
raw_frames: list[Image.Image] = []
raw_durs: list[int] = []
path = self.res.get_win_lose_gif_path(stem_or_filename)
if path.is_file():
try:
with Image.open(path) as gif:
idx = 0
while True:
dur = int(gif.info.get("duration", 65) or 65)
dur = max(35, min(200, dur))
raw_frames.append(gif.copy().convert("RGBA"))
raw_durs.append(dur)
idx += 1
gif.seek(idx)
except EOFError:
pass
except Exception:
pass
self._pil_cache[raw_pil_key] = (raw_frames, raw_durs)
src_frames, src_durs = self._pil_cache[raw_pil_key]
tk_frames = [
ImageTk.PhotoImage(fr.resize((tw, th), Image.Resampling.LANCZOS))
for fr in src_frames
]
result = (tk_frames, list(src_durs))
self._tk_cache[cache_key] = result
return result
# ------------------------------------------------------------------
# STARTUP-PRELOADER
# ------------------------------------------------------------------
def preload_startup_assets(self, init_win_size: tuple[int, int] = (1280, 760), on_step=None):
from resources.code_res.game_constants import SUITS, RANKS
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton, _trim_button_art
from view.widgets.goth_dropdown import _trim_outer_black_bbox
def _notify(msg: str):
if callable(on_step):
on_step(msg)
_notify("Fonts...")
for px in (14, 15, 16, 18, 20, 22, 24, 26, 30, 34, 38):
self.get_pil_font(px, alternate=False)
_notify("Background...")
w, h = max(800, init_win_size[0]), max(600, init_win_size[1])
self.get_bg_patch_photo(w, h, 0, 0, w, h)
if self.raw_title is not None:
self.get_proportional_photo("title_main_header", self.raw_title, 265)
_notify("UI Controls...")
for raw_b in (self.raw_btn_default, self.raw_btn_purple, self.raw_btn_fire):
if raw_b is not None:
_trim_button_art(raw_b)
for raw_dd in (
self.raw_dropdown_closed,
self.raw_dropdown_closed_btn,
self.raw_dropdown_open,
self.raw_dropdown_open_btn,
):
if raw_dd is not None:
_trim_outer_black_bbox(raw_dd)
dummy_root = tk._default_root
if dummy_root is not None and self.raw_btn_default is not None:
common_specs = [
(t("btn_back_main"), 110, 32),
(t("btn_back_game_menu"), 108, 32),
(t("btn_stats"), 96, 32),
(t("btn_lang"), 96, 32),
(t("btn_audio"), 76, 32),
(t("btn_switch_profile"), 124, 34),
]
for lbl, bw, bh in common_specs:
tmp = ImageButton(
dummy_root, lbl, self.raw_btn_default, self.raw_btn_purple,
None, width=bw, height=bh, style="amethyst"
)
tmp._ensure_hover()
tmp.destroy()
_notify("Cards...")
for suit in SUITS:
for rank in RANKS:
fname = f"{rank}_of_{suit}.png"
p = self.res.get_card_path(fname)
if p and p.is_file():
self._get_raw_card_pil(p)
for back_col in ("Black", "Red", "Blue", "Purple", "Gold"):
bp = self.res.get_card_back_path(back_col)
if bp and bp.is_file():
self._get_raw_card_pil(bp)
_notify("Animations...")
for wl_name in ("firework_start", "bat_explosion", "pumpkin_explosion", "foul_pumpkin"):
self.get_win_lose_gif_sequence(wl_name, (170, 170))