yahtzee-py/views/asset_manager.py

204 lines
9.2 KiB
Python

import os
import sys
try:
from PIL import Image, ImageTk, ImageSequence
HAS_PIL = True
except ImportError:
HAS_PIL = False
print("WARNUNG: Pillow (PIL) nicht gefunden!")
class AssetManager:
"""Lädt alle Bilder und hält die Referenzen dauerhaft im Speicher."""
def __init__(self):
self.raw_bg = None
self.raw_title = None
self.raw_logo = None
self.raw_chat_bg = None
self.raw_btn_orange = None
self.raw_btn_orange_active = None
self.raw_sel_inactive = None
self.raw_sel_active = None
self._btn_cache = {}
self.btn_orange = None
self.btn_orange_active = None
self.sel_active = None
self.sel_inactive = None
self.bonus_achieved_img = None
self.yahtzee_achieved_img = None
self.additional_yahtzee_img = None
self.raw_dice = {}
self.raw_anim_frames = []
self.anim_cache_large = []
self.win_frames = []
self.lose_frames = []
if not HAS_PIL:
return
def get_full_path(rel_path):
if hasattr(sys, "_MEIPASS"):
base_path = sys._MEIPASS
else:
base_path = os.path.abspath(".")
return os.path.join(base_path, rel_path)
def load_raw(paths):
if isinstance(paths, str):
paths = [paths]
for p in paths:
full_path = get_full_path(p)
if os.path.exists(full_path):
return Image.open(full_path).convert("RGBA")
return None
# 1. Rohe Bilder laden (für dynamisches Skalieren)
self.raw_bg = load_raw(["ressources/background.jpeg", "ressources/background.jpg", "ressources/background.png"])
self.raw_title = load_raw(["ressources/title1.png"])
self.raw_logo = load_raw(["ressources/logo.jpg", "ressources/logo.png"])
# Chat-Hintergrund laden & äußeren Rand automatisch zuschneiden
chat_img = load_raw([
"ressources/chat_window_2.png",
"ressources/chat_window.png",
"ressources/chat_window_2.jpg",
"ressources/chat_window.jpg"
])
if not chat_img and os.path.exists(get_full_path("ressources")):
for root_dir, _, files in os.walk(get_full_path("ressources")):
for f in sorted(files, reverse=True):
if "chat_window" in f.lower() and f.lower().endswith((".png", ".jpg", ".jpeg")):
chat_img = Image.open(os.path.join(root_dir, f)).convert("RGBA")
break
if chat_img:
px = chat_img.load()
w, h = chat_img.size
min_x, min_y, max_x, max_y = w, h, 0, 0
for y in range(h):
for x in range(w):
r, g, b, a = px[x, y]
if a > 20 and not (r > 240 and g > 240 and b > 240):
if x < min_x: min_x = x
if y < min_y: min_y = y
if x > max_x: max_x = x
if y > max_y: max_y = y
if max_x > min_x and max_y > min_y:
chat_img = chat_img.crop((min_x, min_y, max_x + 1, max_y + 1))
self.raw_chat_bg = chat_img
# 2. Rohe UI-Buttons laden + Standard-Instanzen erzeugen
self.raw_btn_orange = load_raw(["ressources/button1.png", "ressources/button1.jpeg"])
self.raw_btn_orange_active = load_raw(["ressources/button1_active.png"])
self.raw_sel_inactive = load_raw(["ressources/selection_inactive.png"])
self.raw_sel_active = load_raw(["ressources/selection_active.png"])
self.btn_orange, self.btn_orange_active = self.get_btn_pair("orange", 200, 50)
self.sel_inactive, self.sel_active = self.get_btn_pair("purple", 150, 35)
# 3. Erfolgs-Banner laden (inkl. automatischer Suche in ressources/)
self.bonus_achieved_img = load_raw([
"ressources/bonus_achived.jpg", "ressources/bonus_achieved.jpg",
"ressources/bonus_achived.png", "ressources/bonus_achieved.png",
"ressources/bonus_achived.jpeg", "ressources/bonus_achieved.jpeg",
"ressources/bonus.png", "ressources/bonus.jpg"
])
self.yahtzee_achieved_img = load_raw([
"ressources/yahtzee_achived.jpg", "ressources/yahtzee_achieved.jpg",
"ressources/yahtzee_achived.png", "ressources/yahtzee_achieved.png",
"ressources/yahtzee_achived.jpeg", "ressources/yahtzee_achieved.jpeg",
"ressources/yahtzee.png", "ressources/yahtzee.jpg"
])
self.additional_yahtzee_img = load_raw([
"ressources/additional_yahtzee_achieved.png",
"ressources/additional_yahtzee_achived.png",
"ressources/additional_yahtzee_achieved.jpg",
"ressources/additional_yahtzee_achived.jpg"
])
# Falls noch nicht gefunden: Suche flexibel nach Dateinamen in ressources/
res_dir = get_full_path("ressources")
if os.path.exists(res_dir):
for root_dir, _, files in os.walk(res_dir):
for f in files:
low = f.lower()
if low.endswith((".png", ".jpg", ".jpeg")):
full_f = os.path.join(root_dir, f)
if not self.bonus_achieved_img and "bonus" in low:
self.bonus_achieved_img = Image.open(full_f).convert("RGBA")
elif not self.additional_yahtzee_img and "additional" in low and "yahtzee" in low:
self.additional_yahtzee_img = Image.open(full_f).convert("RGBA")
elif not self.yahtzee_achieved_img and "yahtzee" in low and "additional" not in low:
self.yahtzee_achieved_img = Image.open(full_f).convert("RGBA")
# 4. Rohe Würfel für dynamische Größen
for i in range(1, 7):
self.raw_dice[i] = load_raw(f"ressources/dices/default/dice{i}.png")
# 5. Animations-GIF laden und alle Frames cachen
gif_paths = ["ressources/dice.gif", "ressources/dices/dice.gif", "ressources/dice_2.gif"]
anim_full_path = None
for gp in gif_paths:
full = get_full_path(gp)
if os.path.exists(full):
anim_full_path = full
break
if anim_full_path:
try:
gif = Image.open(anim_full_path)
for frame in ImageSequence.Iterator(gif):
f_rgba = frame.copy().convert("RGBA")
self.raw_anim_frames.append(f_rgba)
self.anim_cache_large.append(ImageTk.PhotoImage(f_rgba.resize((150, 150), Image.Resampling.LANCZOS)))
except Exception as e:
print(f"Fehler beim Laden des GIFs: {e}")
# 6. Win & Lose GIFs (oder Bilder) laden
def load_anim_or_img(candidates, size=(200, 150)):
frames = []
found_path = None
for c in candidates:
full = get_full_path(c)
if os.path.exists(full):
found_path = full
break
if not found_path and os.path.exists(get_full_path("ressources")):
key_word = "win" if "win" in candidates[0] else "lose"
for r_dir, _, f_list in os.walk(get_full_path("ressources")):
for f in f_list:
low = f.lower()
if low.startswith(key_word) and low.endswith((".gif", ".png", ".jpg", ".jpeg")):
found_path = os.path.join(r_dir, f)
break
if found_path:
try:
im = Image.open(found_path)
for frame in ImageSequence.Iterator(im):
f_rgba = frame.copy().convert("RGBA")
frames.append(ImageTk.PhotoImage(f_rgba.resize(size, Image.Resampling.LANCZOS)))
except Exception as e:
print(f"Fehler beim Laden von {found_path}: {e}")
return frames
self.win_frames = load_anim_or_img(["ressources/win.gif", "ressources/win.jpg", "ressources/win.png"])
self.lose_frames = load_anim_or_img(["ressources/lose.gif", "ressources/lose.jpg", "ressources/lose.png"])
def get_btn_pair(self, style="purple", width=150, height=35):
"""Gibt ein exakt auf (width, height) skaliertes Bildpaar (normal, hover) zurück."""
if not HAS_PIL:
return None, None
key = (style, int(width), int(height))
if key not in self._btn_cache:
if style == "orange":
r_norm, r_act = self.raw_btn_orange, self.raw_btn_orange_active
else:
r_norm, r_act = self.raw_sel_inactive, self.raw_sel_active
img_n = ImageTk.PhotoImage(r_norm.resize((int(width), int(height)), Image.Resampling.LANCZOS)) if r_norm else None
img_a = ImageTk.PhotoImage(r_act.resize((int(width), int(height)), Image.Resampling.LANCZOS)) if r_act else img_n
self._btn_cache[key] = (img_n, img_a)
return self._btn_cache[key]