Compare commits

..

No commits in common. "6f614c8595d02e6ffe16230b721c203ca604b396" and "4caed5bc153d56652009d14fa97a154263547a64" have entirely different histories.

77 changed files with 2455 additions and 5186 deletions

View File

@ -1,248 +1,13 @@
# -*- coding: utf-8 -*-
# controller/app_context.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from models.database import Database
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
)
from resources.code_res.game_constants import ACCENT_GOLD, ACCENT_GOTH, ERROR_FG, FG_COLOR, PANEL_BG, SUBTLE_BORDER
from resources.code_res.i18n import t
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
class _CanvasTextLabelProxy:
"""
Kompatibler Proxy für topbar.title_label / extra_label / level_label:
Nimmt .configure(text=..., fg=...) wie ein tk.Label entgegen, zeichnet aber
rahmenlosen PIL-Old-London-Text direkt auf das Topbar-Canvas.
"""
def __init__(self, bar_canvas: "GothTopbar", slot_name: str, text: str, color: str, size_px: int):
self._bar = bar_canvas
self._slot = slot_name
self.text = str(text or "")
self.color = color
self.size_px = size_px
def configure(self, **kwargs):
changed = False
if "text" in kwargs and str(kwargs["text"]) != self.text:
self.text = str(kwargs["text"])
changed = True
if "fg" in kwargs and kwargs["fg"] != self.color:
self.color = kwargs["fg"]
changed = True
if changed:
self._bar.refresh_text_slots()
config = configure
class GothTopbar(tk.Canvas):
"""Rahmenlose Spiel-Kopfleiste, die den echten Hintergrund-Ausschnitt durchscheinen lässt."""
BAR_HEIGHT = 56
def __init__(
self,
parent,
ctx: "AppContext",
title: str,
on_game_menu=None,
on_stats=None,
stats_enabled: bool = True,
extra_right_text: str = "",
on_lang_refresh=None,
locked_exit: bool = False,
):
super().__init__(
parent,
height=self.BAR_HEIGHT,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
)
self.ctx = ctx
self.assets = ctx.assets
self.sounds = ctx.sounds
self._locked_exit = locked_exit
self._bg_slice_photo: ImageTk.PhotoImage | None = None
self._text_photos: list[ImageTk.PhotoImage] = []
self._last_size: tuple[int, int] = (0, 0)
self._left_widgets: list[tuple[tk.Widget, int]] = []
self._right_widgets: list[tuple[tk.Widget, int]] = []
self.stats_btn: ImageButton | None = None
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
if not locked_exit:
b_main = ImageButton(
self, t("btn_back_main"), btn_norm, btn_purp,
ctx.back_to_main_menu, sound_mgr=self.sounds, width=136, height=36, style="amethyst"
)
self._left_widgets.append((b_main, 136))
if on_game_menu is not None:
b_gmenu = ImageButton(
self, t("btn_back_game_menu"), btn_norm, btn_purp,
on_game_menu, sound_mgr=self.sounds, width=132, height=36, style="amethyst"
)
self._left_widgets.append((b_gmenu, 132))
if on_stats is not None:
self.stats_btn = ImageButton(
self, t("btn_stats"), btn_norm, btn_purp,
on_stats, sound_mgr=self.sounds, width=114, height=36,
enabled=stats_enabled, style="amethyst"
)
self._left_widgets.append((self.stats_btn, 114))
b_lang = ImageButton(
self, t("btn_lang"), btn_norm, btn_purp,
lambda: ctx.toggle_language(on_lang_refresh),
sound_mgr=self.sounds, width=112, height=34, style="amethyst"
)
b_audio = ImageButton(
self, t("btn_audio"), btn_norm, btn_purp,
ctx.open_audio_settings, sound_mgr=self.sounds, width=90, height=34, style="amethyst"
)
self._right_widgets.append((b_lang, 112))
self._right_widgets.append((b_audio, 90))
prof = ctx.profile
prog = ctx.game_progress
init_lvl_txt = t(
"level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]
)
self.title_label = _CanvasTextLabelProxy(
self, "title", title, FONT_COLOR_TITLE_MAIN, FONT_SIZE_HEADING
)
self.extra_label = _CanvasTextLabelProxy(
self, "extra", extra_right_text, FONT_COLOR_HEADING_SUB, FONT_SIZE_BODY
)
self.level_label = _CanvasTextLabelProxy(
self, "level", init_lvl_txt, FONT_COLOR_BODY_DEFAULT, max(FONT_SIZE_SMALL_MIN, FONT_SIZE_BODY - 1)
)
self.bind("<Configure>", self._on_configure)
def _render_bg_slice(self, w: int):
root_win = self.winfo_toplevel()
rw = max(w, root_win.winfo_width())
rh = max(self.BAR_HEIGHT, root_win.winfo_height())
src = (
self.assets.raw_bg_vertical
if (rh > rw and self.assets.raw_bg_vertical is not None)
else (self.assets.raw_bg_horizontal or self.assets.raw_bg)
)
if src is None:
return
full_scaled = src.resize((rw, rh), Image.Resampling.BILINEAR)
cropped = full_scaled.crop((0, 0, w, self.BAR_HEIGHT))
self._bg_slice_photo = ImageTk.PhotoImage(cropped)
self.delete("topbar_bg")
self.create_image(0, 0, image=self._bg_slice_photo, anchor="nw", tags="topbar_bg")
self.tag_lower("topbar_bg")
def _on_configure(self, event):
w, h = max(1, event.width), max(1, event.height)
if w < 100 or (w, h) == self._last_size:
return
self._last_size = (w, h)
self._render_bg_slice(w)
self._layout_items(w)
def refresh_text_slots(self):
if not self.winfo_exists():
return
w = self.winfo_width()
if w >= 100:
self._layout_items(w)
def _layout_items(self, w: int):
self.delete("topbar_fg")
self.delete("topbar_txt")
self._text_photos.clear()
cy = self.BAR_HEIGHT // 2
pad_x = max(28, int(w * 0.03))
# 1. Linke Navigation (oder Devil's Deal Sperr-Badge)
left_x = pad_x
if self._locked_exit:
lock_ph = self.assets.get_goth_text_photo(
t("devils_deal_locked_badge"),
size_px=FONT_SIZE_BODY,
color=FONT_COLOR_STATUS_LOSS,
align="left",
)
self._text_photos.append(lock_ph)
self.create_image(left_x, cy, image=lock_ph, anchor="w", tags="topbar_txt")
left_x += lock_ph.width() + 12
else:
for wgt, bw in self._left_widgets:
self.create_window(left_x, cy, window=wgt, anchor="w", tags="topbar_fg")
left_x += bw + 6
# 2. Rechte Buttons (Audio + Sprache) von rechts nach links
right_x = w - pad_x
for wgt, bw in reversed(self._right_widgets):
self.create_window(right_x, cy, window=wgt, anchor="e", tags="topbar_fg")
right_x -= (bw + 6)
# 3. Level-Badge & Gold-Extra-Anzeige links neben den Sprach-/Audio-Buttons
compact = (w < 1380)
lvl_px = FONT_SIZE_SMALL_MIN if compact else self.level_label.size_px
extra_px = FONT_SIZE_SMALL_MIN if compact else self.extra_label.size_px
if self.level_label.text:
lvl_ph = self.assets.get_goth_text_photo(
self.level_label.text, size_px=lvl_px, color=self.level_label.color, align="right"
)
self._text_photos.append(lvl_ph)
self.create_image(right_x - 4, cy, image=lvl_ph, anchor="e", tags="topbar_txt")
right_x -= (lvl_ph.width() + 12)
if self.extra_label.text:
ext_ph = self.assets.get_goth_text_photo(
self.extra_label.text, size_px=extra_px, color=self.extra_label.color, align="right"
)
self._text_photos.append(ext_ph)
self.create_image(right_x - 2, cy, image=ext_ph, anchor="e", tags="topbar_txt")
right_x -= (ext_ph.width() + 12)
# 4. Spieltitel mittig im verbleibenden freien Raum
avail_title_w = max(80, right_x - left_x - 12)
if self.title_label.text and avail_title_w >= 90:
t_px = (FONT_SIZE_HEADING - 4) if compact else self.title_label.size_px
title_ph = self.assets.get_goth_text_photo(
self.title_label.text,
size_px=t_px,
color=self.title_label.color,
max_width=avail_title_w,
align="center",
)
self._text_photos.append(title_ph)
title_cx = (left_x + right_x) // 2
self.create_image(title_cx, cy, image=title_ph, anchor="center", tags="topbar_txt")
class AppContext:
def __init__(self, controller, game_folder: str):
self._ctrl = controller
@ -263,15 +28,12 @@ class AppContext:
return Database.get_game_progress(self.profile["id"], self.game_folder)
def back_to_main_menu(self):
GothDropdown.close_any_open_popup()
self._ctrl.show_main_menu()
def open_audio_settings(self):
GothDropdown.close_any_open_popup()
AudioSettingsDialog.open(self.root, self.assets, self.sounds)
def toggle_language(self, refresh_callback=None):
GothDropdown.close_any_open_popup()
self._ctrl.toggle_language(refresh_callback)
def record_result(
@ -308,17 +70,67 @@ class AppContext:
extra_right_text: str = "",
on_lang_refresh=None,
locked_exit: bool = False,
) -> GothTopbar:
bar = GothTopbar(
parent=parent,
ctx=self,
title=title,
on_game_menu=on_game_menu,
on_stats=on_stats,
stats_enabled=stats_enabled,
extra_right_text=extra_right_text,
on_lang_refresh=on_lang_refresh,
locked_exit=locked_exit,
)
) -> tk.Frame:
bar = tk.Frame(parent, bg=PANEL_BG, padx=12, pady=8, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
bar.pack(fill="x", side="top")
stats_btn = None
if locked_exit:
tk.Label(
bar, text=t("devils_deal_locked_badge"),
font=("Helvetica", 10, "bold"), fg=ERROR_FG, bg=PANEL_BG
).pack(side="left", padx=(4, 12))
else:
ImageButton(
bar, t("btn_back_main"), self.assets.raw_sel, self.assets.raw_sel_active,
self.back_to_main_menu, sound_mgr=self.sounds, width=135, height=36, font=("Helvetica", 10, "bold")
).pack(side="left", padx=(0, 6))
if on_game_menu is not None:
ImageButton(
bar, t("btn_back_game_menu"), self.assets.raw_sel, self.assets.raw_sel_active,
on_game_menu, sound_mgr=self.sounds, width=135, height=36, font=("Helvetica", 10, "bold")
).pack(side="left", padx=(0, 6))
if on_stats is not None:
stats_btn = ImageButton(
bar, t("btn_stats"), self.assets.raw_sel, self.assets.raw_sel_active,
on_stats, sound_mgr=self.sounds, width=115, height=36,
font=("Helvetica", 10, "bold"), enabled=stats_enabled
)
stats_btn.pack(side="left")
title_lbl = tk.Label(bar, text=title, font=("Georgia", 15, "bold"), fg=FG_COLOR, bg=PANEL_BG)
title_lbl.pack(side="left", expand=True)
right_box = tk.Frame(bar, bg=PANEL_BG)
right_box.pack(side="right")
extra_lbl = tk.Label(right_box, text=extra_right_text, font=("Helvetica", 11, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG)
extra_lbl.pack(side="left", padx=(0, 14))
prof = self.profile
prog = self.game_progress
lvl_lbl = tk.Label(
right_box,
text=t("level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]),
font=("Helvetica", 10, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG
)
lvl_lbl.pack(side="left", padx=(0, 10))
ImageButton(
right_box, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active,
lambda: self.toggle_language(on_lang_refresh),
sound_mgr=self.sounds, width=108, height=34, font=("Helvetica", 9, "bold")
).pack(side="left", padx=(0, 6))
ImageButton(
right_box, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active,
self.open_audio_settings, sound_mgr=self.sounds, width=92, height=34, font=("Helvetica", 9, "bold")
).pack(side="left")
bar.title_label = title_lbl
bar.extra_label = extra_lbl
bar.level_label = lvl_lbl
bar.stats_btn = stats_btn
return bar

View File

@ -1,39 +1,22 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_menu_view.py
from __future__ import annotations
import sqlite3
import tkinter as tk
from tkinter import ttk
from games.blackjack.views.blackjack_stats_view import BlackjackStatsView
from games.blackjack.views.blackjack_table_view import BlackjackTableView
from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
BJ_INITIAL_ANTE,
BJ_MAX_BOTS,
BJ_STARTING_GOLD,
BJ_VARIANTS,
DEVILS_DEAL_GOLD_REWARD,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_DISABLED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
GOLD_MAX_ACCOUNTS,
GOLD_MIN_TABLE_ENTRY,
XP_TO_GOLD_AMOUNT,
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BJ_INITIAL_ANTE, BJ_MAX_BOTS,
BJ_STARTING_GOLD, BJ_VARIANTS, BORDER_COLOR, CELL_BG,
DEVILS_DEAL_GOLD_REWARD, ERROR_FG, FG_COLOR, GOLD_MAX_ACCOUNTS,
GOLD_MIN_TABLE_ENTRY, INPUT_BG, MUTED_FG, PANEL_BG,
SUBTLE_BORDER, XP_TO_GOLD_AMOUNT
)
from resources.code_res.i18n import t
from view.widgets.bot_setup_widget import BotSetupWidget
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "blackjack"
@ -43,11 +26,11 @@ class BlackjackMenuView:
def __init__(self, context):
self.ctx = context
self.bot_widget: BotSetupWidget | None = None
self._photo_refs: list = []
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
pid = self.ctx.profile["id"]
# Aktiver Devil's Deal zwingt direkt an den Tisch
devils_acc = Database.get_active_devils_bj_account(pid)
if devils_acc is not None:
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
@ -64,7 +47,6 @@ class BlackjackMenuView:
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
bj_prog = self.ctx.refresh_game_progress()
dyn_xp_cost = bj_prog["xp_exchange_cost"]
@ -81,6 +63,7 @@ class BlackjackMenuView:
if saved_id_str.isdigit():
preselect_id = int(saved_id_str)
# Im Dropdown stehen nur noch die sauberen Kontonamen; Gold wird prominent separat angezeigt!
acc_by_name = {a["account_name"]: a for a in accounts}
acc_names = list(acc_by_name.keys())
@ -97,7 +80,7 @@ class BlackjackMenuView:
selected_name_var = tk.StringVar(
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
)
state_msg = {"text": status_msg, "ok": status_is_ok}
feedback_var = tk.StringVar(value=status_msg)
def get_current_acc() -> dict | None:
return acc_by_name.get(selected_name_var.get())
@ -111,7 +94,7 @@ class BlackjackMenuView:
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
BlackjackStatsView(
self.ctx,
on_back_to_bj_menu=lambda aid: self.show(preselect_id=aid),
on_back_to_bj_menu=lambda aid: self.show(preselect_id=aid)
).show(selected_acc_id=cur["id"])
def refresh_on_lang_switch():
@ -135,38 +118,54 @@ class BlackjackMenuView:
on_lang_refresh=refresh_on_lang_switch,
)
cv = create_menu_body_canvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14)
container.place(relx=0.5, rely=0.52, anchor="center", relwidth=0.92, relheight=0.82)
# --- Widgets Spalte 1: Kontoverwaltung ---
table_buttons: list[ImageButton] = []
def on_account_switched(_val=None):
cur = get_current_acc()
if cur is not None:
fresh = Database.get_blackjack_account(cur["id"])
Database.save_setting(setting_key, str(fresh["id"]))
topbar.extra_label.configure(text=t("bj_header_gold", fresh["account_name"], fresh["gold"]))
playable = fresh["gold"] >= GOLD_MIN_TABLE_ENTRY
for tb in table_buttons:
tb.set_enabled(playable)
state_msg["text"] = ""
if cv.winfo_exists() and cv.winfo_width() >= 200:
draw_layout(cv.winfo_width(), cv.winfo_height())
acc_dd = GothDropdown(
cv,
self.ctx.assets,
values=acc_names if has_accounts else [t("bj_no_account_item")],
textvariable=selected_name_var,
on_change=on_account_switched,
sound_mgr=self.ctx.sounds,
width=215,
height=36,
enabled=has_accounts,
main_card = tk.Frame(
container, bg=PANEL_BG, padx=24, pady=18,
highlightthickness=1, highlightbackground=BORDER_COLOR
)
main_card.pack(fill="x")
upper_split = tk.Frame(main_card, bg=PANEL_BG)
upper_split.pack(fill="x", pady=(0, 12))
upper_split.columnconfigure(0, weight=1, uniform="cols")
upper_split.columnconfigure(1, weight=1, uniform="cols")
# =====================================================================
# SPALTE 1: Goldkonto-Verwaltung (exaktes 3-Spalten-Grid für gleiche Breiten!)
# =====================================================================
left_col = tk.Frame(upper_split, bg=PANEL_BG)
left_col.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
tk.Label(
left_col,
text=t("bj_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, BJ_STARTING_GOLD),
font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
).pack(anchor="w", pady=(0, 6))
acc_box = tk.Frame(left_col, bg=CELL_BG, padx=14, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
acc_box.pack(fill="both", expand=True)
form_grid = tk.Frame(acc_box, bg=CELL_BG)
form_grid.pack(fill="x")
form_grid.columnconfigure(1, weight=1)
# --- Zeile 0: Aktives Konto (Dropdown + XP-Tausch Button) ---
tk.Label(
form_grid, text=t("bj_active_acc_lbl"),
font=("Helvetica", 10, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
acc_cb = ttk.Combobox(
form_grid,
textvariable=selected_name_var,
values=acc_names if has_accounts else [t("bj_no_account_item")],
state="readonly" if has_accounts else "disabled",
font=("Helvetica", 10),
style="Goth.TCombobox",
)
acc_cb.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=2)
def exchange_xp_action():
cur = get_current_acc()
@ -182,15 +181,37 @@ class BlackjackMenuView:
can_afford_xp = is_divine or (bj_prog["total_points"] >= dyn_xp_cost)
can_exchange = has_accounts and (not at_floor) and can_afford_xp
ex_btn_txt = (
t("bj_exchange_divine_btn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
if is_divine else t("bj_exchange_btn", dyn_xp_cost, XP_TO_GOLD_AMOUNT)
)
exchange_btn = ImageButton(
cv, ex_btn_txt, btn_norm, btn_purp,
form_grid, ex_btn_txt,
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
exchange_xp_action, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_exchange, style="amethyst",
width=185, height=34, font=("Helvetica", 9, "bold"),
enabled=can_exchange,
)
exchange_btn.grid(row=0, column=2, sticky="e", pady=4)
# --- Zeile 1: Prominente Gold-Anzeige + Konto löschen ---
gold_banner = tk.Frame(
acc_box, bg=PANEL_BG, padx=12, pady=8,
highlightthickness=1, highlightbackground=BORDER_COLOR if has_accounts else SUBTLE_BORDER
)
gold_banner.pack(fill="x", pady=(8, 8))
gold_var = tk.StringVar(
value=t("bj_gold_display_lbl", active_acc["gold"]) if active_acc else t("bj_gold_display_none")
)
gold_lbl = tk.Label(
gold_banner, textvariable=gold_var,
font=("Georgia", 13, "bold"),
fg=ACCENT_GOLD if active_acc else MUTED_FG,
bg=PANEL_BG,
)
gold_lbl.pack(side="left")
def delete_selected_account():
cur = get_current_acc()
@ -199,29 +220,48 @@ class BlackjackMenuView:
self.show()
delete_btn = ImageButton(
cv, t("bj_delete_acc_btn"), btn_norm, btn_purp,
gold_banner, t("bj_delete_acc_btn"),
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
delete_selected_account, sound_mgr=self.ctx.sounds,
width=136, height=32, enabled=has_accounts, style="amethyst",
width=120, height=30, font=("Helvetica", 9, "bold"),
enabled=has_accounts,
)
delete_btn.pack(side="right")
# --- Zeile 2: Neues Konto anlegen (exakt gleiche Eingabefeld-Breite wie Dropdown oben!) ---
create_grid = tk.Frame(acc_box, bg=CELL_BG)
create_grid.pack(fill="x")
create_grid.columnconfigure(1, weight=1)
# Unsichtbarer Platzhalter hält Spalte 0 exakt so breit wie "Aktives Konto:" oben
lbl_w = max(len(t("bj_active_acc_lbl")), len(t("bj_new_acc_lbl")))
form_grid.grid_slaves(row=0, column=0)[0].configure(width=lbl_w, anchor="w")
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
tk.Label(
create_grid, text=t("bj_new_acc_lbl"), width=lbl_w, anchor="w",
font=("Helvetica", 10, "bold" if not has_accounts else "normal"),
fg=ACCENT_GOLD if not has_accounts else (FG_COLOR if can_create_more else MUTED_FG),
bg=CELL_BG,
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
next_idx = len(accounts) + 1
new_acc_var = tk.StringVar(
value=t("bj_default_acc_name", next_idx) if can_create_more else t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)
)
new_entry = GothEntry(
cv, self.ctx.assets, width=215, height=36,
textvariable=new_acc_var, enabled=can_create_more,
new_entry = tk.Entry(
create_grid, textvariable=new_acc_var, font=("Helvetica", 10),
bg=INPUT_BG, fg=FG_COLOR, disabledbackground="#16141c", disabledforeground="#666070",
bd=0, highlightthickness=1, highlightbackground=ACCENT_GOLD if not has_accounts else BORDER_COLOR,
insertbackground="white", state="normal" if can_create_more else "disabled"
)
new_entry.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=5)
def create_new_account():
if not can_create_more:
return
name = new_entry.get().strip()
name = new_acc_var.get().strip()
if not name:
state_msg["text"] = t("bj_err_empty_name")
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
feedback_var.set(t("bj_err_empty_name"))
return
try:
if self.bot_widget is not None and has_accounts:
@ -231,34 +271,38 @@ class BlackjackMenuView:
Database.save_setting(setting_key, str(created["id"]))
self.show(preselect_id=created["id"])
except (sqlite3.IntegrityError, RuntimeError) as exc:
state_msg["text"] = t("bj_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc)
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
feedback_var.set(t("bj_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc))
if can_create_more:
new_entry.bind_return(lambda _e: create_new_account())
new_entry.bind("<Return>", lambda _e: create_new_account())
create_style = "fire" if not has_accounts else "amethyst"
create_btn = ImageButton(
cv, t("bj_create_acc_btn", BJ_STARTING_GOLD),
btn_fire if not has_accounts else btn_norm,
btn_fire if not has_accounts else btn_purp,
ImageButton(
create_grid, t("bj_create_acc_btn", BJ_STARTING_GOLD),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
create_new_account, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_create_more, style=create_style,
)
width=185, height=34, font=("Helvetica", 9, "bold"),
enabled=can_create_more,
).grid(row=0, column=2, sticky="e", pady=4)
# Optional Devil's Deal Controls
sac_dd = None
devil_btn = None
# --- Info / Divine Punishment / The Devil's Deal ---
min_sac_lvl = Progression.get_devils_deal_min_level()
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID) if (devils_deal_open and has_accounts) else []
if devils_deal_open and has_accounts:
tk.Label(
acc_box,
text=t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
font=("Helvetica", 8, "bold"), fg=ERROR_FG, bg=CELL_BG, wraplength=480, justify="left"
).pack(anchor="w", pady=(6, 4))
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID)
if sac_candidates:
devil_row = tk.Frame(acc_box, bg=CELL_BG)
devil_row.pack(fill="x", pady=(2, 0))
sac_map = {f"{c['name']} ({c['title']} • Lv. {c['level']})": c["id"] for c in sac_candidates}
sac_var = tk.StringVar(value=next(iter(sac_map.keys())))
sac_dd = GothDropdown(
cv, self.ctx.assets, values=list(sac_map.keys()),
textvariable=sac_var, sound_mgr=self.ctx.sounds, width=250, height=34,
)
ttk.Combobox(
devil_row, textvariable=sac_var, values=list(sac_map.keys()),
state="readonly", font=("Helvetica", 9), width=26, style="Goth.TCombobox"
).pack(side="left", fill="x", expand=True, padx=(0, 8))
def seal_devils_deal():
cur = get_current_acc()
@ -278,18 +322,62 @@ class BlackjackMenuView:
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
)
devil_btn = ImageButton(
cv, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
btn_fire, btn_fire, seal_devils_deal,
sound_mgr=None, width=180, height=34, style="fire",
ImageButton(
devil_row, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
seal_devils_deal, sound_mgr=None, width=185, height=32, font=("Helvetica", 9, "bold")
).pack(side="right")
else:
tk.Label(
acc_box, text=t("bj_devils_deal_none", min_sac_lvl),
font=("Helvetica", 8), fg=MUTED_FG, bg=CELL_BG
).pack(anchor="w")
else:
info_text = (
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
if is_divine
else t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
)
tk.Label(
acc_box, text=info_text,
font=("Helvetica", 8, "bold" if is_divine else "normal"),
fg=ERROR_FG if is_divine else MUTED_FG,
bg=CELL_BG, wraplength=480, justify="left"
).pack(anchor="w", pady=(6, 0))
# =====================================================================
# SPALTE 2: Gegner-Setup (inaktiv ausgegraut, solange kein Konto existiert)
# =====================================================================
right_col = tk.Frame(upper_split, bg=PANEL_BG)
right_col.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
tk.Label(
right_col, text=t("bj_bots_sec_title"),
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
).pack(anchor="w", pady=(0, 6))
# --- Spalte 2: Gegner-Setup ---
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
self.bot_widget = BotSetupWidget(cv, saved_bots, max_bots=BJ_MAX_BOTS, enabled=has_accounts)
self.bot_widget = BotSetupWidget(right_col, saved_bots, max_bots=BJ_MAX_BOTS, enabled=has_accounts)
self.bot_widget.pack(fill="both", expand=True)
fb_lbl = tk.Label(
main_card, textvariable=feedback_var,
font=("Helvetica", 9, "bold"),
fg="#7be08a" if status_is_ok else ERROR_FG,
bg=PANEL_BG
)
fb_lbl.pack(anchor="w", pady=(2, 4))
# =====================================================================
# SEKTION 3: Spielvariante wählen (Buttons mit Graufilter, wenn Konto fehlt / < 10 Gold)
# =====================================================================
tk.Label(
main_card, text=t("bj_sec3_title"),
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
).pack(anchor="w", pady=(2, 8))
# --- Sektion 3: Varianten-Buttons ---
def enter_table(v_key: str):
fb_lbl.configure(fg=ERROR_FG)
cur = get_current_acc()
if not cur:
return
@ -302,215 +390,60 @@ class BlackjackMenuView:
cur_bj_prog = self.ctx.refresh_game_progress()
if acc["gold"] < GOLD_MIN_TABLE_ENTRY:
state_msg["text"] = t(
feedback_var.set(t(
"bj_err_not_enough_gold_entry",
acc["account_name"], GOLD_MIN_TABLE_ENTRY, acc["gold"],
cur_bj_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT,
)
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
cur_bj_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT
))
return
BlackjackTableView(
self.ctx, v_key, acc["id"], active_bots,
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg)
)
variants_row = tk.Frame(main_card, bg=PANEL_BG)
variants_row.pack(fill="x")
for idx in range(len(BJ_VARIANTS)):
variants_row.columnconfigure(idx, weight=1)
table_buttons: list[ImageButton] = []
can_enter_now = bool(active_acc and active_acc["gold"] >= GOLD_MIN_TABLE_ENTRY)
variant_items = list(BJ_VARIANTS.items())
for v_key, _cfg in variant_items:
for idx, (v_key, cfg) in enumerate(BJ_VARIANTS.items()):
card = tk.Frame(variants_row, bg=CELL_BG, padx=16, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
card.grid(row=0, column=idx, padx=(0, 8) if idx == 0 else (8, 0), sticky="nsew")
tk.Label(
card, text=t(f"variant_{v_key}"),
font=("Georgia", 12, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
).pack(anchor="w")
tk.Label(
card, text=t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE),
font=("Helvetica", 9), fg=MUTED_FG, bg=CELL_BG
).pack(anchor="w", pady=(4, 10))
t_btn = ImageButton(
cv, t("bj_enter_table_btn"), btn_fire, btn_fire,
card, t("bj_enter_table_btn"),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
lambda k=v_key: enter_table(k),
sound_mgr=self.ctx.sounds, width=168, height=38,
enabled=can_enter_now, style="fire",
sound_mgr=self.ctx.sounds, width=160, height=36,
font=("Helvetica", 10, "bold"), enabled=can_enter_now,
)
t_btn.pack(anchor="e")
table_buttons.append(t_btn)
def draw_layout(w: int, h: int):
cv._sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
# Live-Aktualisierung beim Konto-Wechsel im Dropdown
def on_account_switched(*_):
cur = get_current_acc()
if cur is not None:
fresh = Database.get_blackjack_account(cur["id"])
Database.save_setting(setting_key, str(fresh["id"]))
gold_var.set(t("bj_gold_display_lbl", fresh["gold"]))
topbar.extra_label.configure(text=t("bj_header_gold", fresh["account_name"], fresh["gold"]))
playable = fresh["gold"] >= GOLD_MIN_TABLE_ENTRY
for tb in table_buttons:
tb.set_enabled(playable)
feedback_var.set("")
compact = (h < 700)
pad_x = max(44, int(w * 0.045))
usable_w = min(1240, w - 2 * pad_x)
x0 = (w - usable_w) // 2
col_gap = 20
col_w = (usable_w - col_gap) // 2
left_x = x0
right_x = x0 + col_w + col_gap
top_sec_y = 14 if compact else 22
upper_h = 282 if compact else 302
# Überschriften Spalte 1 & 2
s1_ph = self.ctx.assets.get_goth_text_photo(
t("bj_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, BJ_STARTING_GOLD),
FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, max_width=col_w - 10, align="left",
)
s2_ph = self.ctx.assets.get_goth_text_photo(
t("bj_bots_sec_title"),
FONT_SIZE_HEADING - 3,
FONT_COLOR_HEADING_SUB if has_accounts else FONT_COLOR_DISABLED,
max_width=col_w - 10, align="left",
)
self._photo_refs.extend([s1_ph, s2_ph])
cv.create_image(left_x + 8, top_sec_y + 12, image=s1_ph, anchor="w", tags="fg")
cv.create_image(right_x + 8, top_sec_y + 12, image=s2_ph, anchor="w", tags="fg")
box_top = top_sec_y + 34
box_cy = box_top + upper_h // 2
# Rahmen links (box_big) & rechts (box_purple)
l_frame = self.ctx.assets.get_box_photo("box_big", (col_w, upper_h))
r_frame = self.ctx.assets.get_box_photo("box_purple", (col_w, upper_h))
if l_frame:
self._photo_refs.append(l_frame)
cv.create_image(left_x + col_w // 2, box_cy, image=l_frame, anchor="center", tags="fg")
if r_frame:
self._photo_refs.append(r_frame)
cv.create_image(right_x + col_w // 2, box_cy, image=r_frame, anchor="center", tags="fg")
# Spalte 1 Inhalt
in_pad = 22
lbl_col_w = 118
btn_w = 180
mid_field_w = max(140, col_w - 2 * in_pad - lbl_col_w - btn_w - 16)
if acc_dd._width != mid_field_w:
acc_dd._width = mid_field_w
acc_dd.configure(width=mid_field_w)
acc_dd._render_closed()
r1_y = box_top + 40
l_act = self.ctx.assets.get_goth_text_photo(
t("bj_active_acc_lbl"), FONT_SIZE_BODY,
FONT_COLOR_BODY_DEFAULT if has_accounts else FONT_COLOR_DISABLED, align="left",
)
self._photo_refs.append(l_act)
cv.create_image(left_x + in_pad, r1_y, image=l_act, anchor="w", tags="fg")
cv.create_window(left_x + in_pad + lbl_col_w, r1_y, window=acc_dd, anchor="w", tags="fg")
cv.create_window(left_x + col_w - in_pad, r1_y, window=exchange_btn, anchor="e", tags="fg")
# Gold-Banner (box_gold_double)
gb_y = r1_y + 54
gb_w = col_w - 2 * in_pad
gb_frame = self.ctx.assets.get_box_photo("box_gold_double", (gb_w, 50))
if gb_frame:
self._photo_refs.append(gb_frame)
cv.create_image(left_x + col_w // 2, gb_y, image=gb_frame, anchor="center", tags="fg")
cur_acc_obj = get_current_acc()
fresh_gold = Database.get_blackjack_account(cur_acc_obj["id"])["gold"] if cur_acc_obj else 0
gold_str = t("bj_gold_display_lbl", fresh_gold) if cur_acc_obj else t("bj_gold_display_none")
g_ph = self.ctx.assets.get_goth_text_photo(
gold_str, FONT_SIZE_HEADING - 3,
FONT_COLOR_TITLE_MAIN if cur_acc_obj else FONT_COLOR_BODY_MUTED, align="left",
)
self._photo_refs.append(g_ph)
cv.create_image(left_x + in_pad + 18, gb_y, image=g_ph, anchor="w", tags="fg")
cv.create_window(left_x + col_w - in_pad - 14, gb_y, window=delete_btn, anchor="e", tags="fg")
# Neues Konto Zeile
r3_y = gb_y + 54
l_new = self.ctx.assets.get_goth_text_photo(
t("bj_new_acc_lbl"), FONT_SIZE_BODY,
FONT_COLOR_TITLE_MAIN if not has_accounts else (FONT_COLOR_BODY_DEFAULT if can_create_more else FONT_COLOR_DISABLED),
align="left",
)
self._photo_refs.append(l_new)
cv.create_image(left_x + in_pad, r3_y, image=l_new, anchor="w", tags="fg")
cv.create_window(left_x + in_pad + lbl_col_w, r3_y, window=new_entry, anchor="w", tags="fg")
cv.create_window(left_x + col_w - in_pad, r3_y, window=create_btn, anchor="e", tags="fg")
# Info / Devil's Deal Fußbereich in Spalte 1
info_y = r3_y + 42
if devils_deal_open and has_accounts:
warn_ph = self.ctx.assets.get_goth_text_photo(
t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
FONT_SIZE_SMALL_MIN, FONT_COLOR_STATUS_LOSS, max_width=gb_w, align="left",
)
self._photo_refs.append(warn_ph)
cv.create_image(left_x + in_pad, info_y, image=warn_ph, anchor="nw", tags="fg")
if sac_dd is not None and devil_btn is not None:
dy = box_top + upper_h - 30
cv.create_window(left_x + in_pad, dy, window=sac_dd, anchor="w", tags="fg")
cv.create_window(left_x + col_w - in_pad, dy, window=devil_btn, anchor="e", tags="fg")
else:
none_ph = self.ctx.assets.get_goth_text_photo(
t("bj_devils_deal_none", min_sac_lvl), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
)
self._photo_refs.append(none_ph)
cv.create_image(left_x + in_pad, box_top + upper_h - 28, image=none_ph, anchor="w", tags="fg")
else:
info_txt = (
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
if is_divine
else t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
)
inf_ph = self.ctx.assets.get_goth_text_photo(
info_txt, FONT_SIZE_SMALL_MIN,
FONT_COLOR_STATUS_LOSS if is_divine else FONT_COLOR_BODY_MUTED,
max_width=gb_w, align="left",
)
self._photo_refs.append(inf_ph)
cv.create_image(left_x + in_pad, info_y + 4, image=inf_ph, anchor="nw", tags="fg")
# Spalte 2: BotSetupWidget einbetten
if self.bot_widget is not None:
bw_w = col_w - 40
bw_h = BJ_MAX_BOTS * BotSetupWidget.ROW_HEIGHT + 8
cv.create_window(
right_x + col_w // 2, box_cy,
window=self.bot_widget, width=bw_w, height=bw_h, anchor="center", tags="fg"
)
# Feedback-Zeile + Sektion 3 Überschrift
sec3_hdr_y = box_top + upper_h + (22 if compact else 30)
if state_msg["text"]:
fb_ph = self.ctx.assets.get_goth_text_photo(
state_msg["text"], FONT_SIZE_BODY,
FONT_COLOR_STATUS_WIN if state_msg["ok"] else FONT_COLOR_STATUS_LOSS,
max_width=usable_w // 2, align="right",
)
self._photo_refs.append(fb_ph)
cv.create_image(x0 + usable_w - 6, sec3_hdr_y, image=fb_ph, anchor="e", tags="fg")
s3_ph = self.ctx.assets.get_goth_text_photo(
t("bj_sec3_title"), FONT_SIZE_HEADING - 3,
FONT_COLOR_HEADING_SUB if has_accounts else FONT_COLOR_DISABLED, align="left",
)
self._photo_refs.append(s3_ph)
cv.create_image(left_x + 8, sec3_hdr_y, image=s3_ph, anchor="w", tags="fg")
# 2 Varianten-Karten im box_gold_small Rahmen
var_top = sec3_hdr_y + 22
var_h = max(124, min(154, h - var_top - 22))
var_cy = var_top + var_h // 2
v_frame = self.ctx.assets.get_box_photo("box_gold_small", (col_w, var_h))
if v_frame:
self._photo_refs.append(v_frame)
for idx, (v_key, cfg) in enumerate(variant_items):
vx = left_x if idx == 0 else right_x
if v_frame:
cv.create_image(vx + col_w // 2, var_cy, image=v_frame, anchor="center", tags="fg")
vt_ph = self.ctx.assets.get_goth_text_photo(
t(f"variant_{v_key}"), FONT_SIZE_HEADING - 2,
FONT_COLOR_TITLE_MAIN if has_accounts else FONT_COLOR_DISABLED, align="left",
)
vd_ph = self.ctx.assets.get_goth_text_photo(
t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE),
FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=col_w - 56, align="left",
)
self._photo_refs.extend([vt_ph, vd_ph])
cv.create_image(vx + 28, var_top + 32, image=vt_ph, anchor="w", tags="fg")
cv.create_image(vx + 28, var_top + 64, image=vd_ph, anchor="w", tags="fg")
cv.create_window(vx + col_w - 28, var_top + var_h - 32, window=table_buttons[idx], anchor="e", tags="fg")
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
acc_cb.bind("<<ComboboxSelected>>", on_account_switched)

View File

@ -1,12 +1,9 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_stats_view.py
from __future__ import annotations
from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas
import tkinter as tk
from models.database import Database
from resources.code_res.game_constants import (
FONT_COLOR_HEADING_SUB,
FONT_SIZE_BODY,
ACCENT_GOLD, BG_COLOR, BORDER_COLOR, PANEL_BG
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
@ -16,19 +13,16 @@ GAME_FOLDER_ID = "blackjack"
class BlackjackStatsView:
"""Rahmenlose Statistik-Ansicht für die einzelnen Blackjack-Goldbeutel."""
"""Eigene Statistik-Ansicht für die einzelnen Blackjack-Goldbeutel."""
def __init__(self, context, on_back_to_bj_menu):
self.ctx = context
self.on_back_to_bj_menu = on_back_to_bj_menu
self._photo_refs: list = []
def show(self, selected_acc_id: int | None = None):
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
pid = self.ctx.profile["id"]
accounts = Database.get_blackjack_accounts(pid)
if not accounts:
self.on_back_to_bj_menu(None)
return
@ -48,28 +42,34 @@ class BlackjackStatsView:
on_lang_refresh=lambda: self.show(active_acc["id"]),
)
cv = create_menu_body_canvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=18)
container.place(relx=0.5, rely=0.54, anchor="center", relwidth=0.88, relheight=0.82)
selector_panel = tk.Frame(
container, bg=PANEL_BG, padx=18, pady=14,
highlightthickness=1, highlightbackground=BORDER_COLOR
)
selector_panel.pack(fill="x", pady=(0, 16))
tk.Label(
selector_panel, text=t("bj_stats_select_acc_lbl"),
font=("Georgia", 13, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
).pack(anchor="w", pady=(0, 10))
tabs_row = tk.Frame(selector_panel, bg=PANEL_BG)
tabs_row.pack(fill="x")
acc_btns: list[tuple[ImageButton, int]] = []
btn_w = 186
for acc in accounts:
is_sel = (acc["id"] == active_acc["id"])
pil_norm = self.ctx.assets.raw_btn if is_sel else self.ctx.assets.raw_sel
pil_hov = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
b = ImageButton(
cv,
btn_lbl,
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
ImageButton(
tabs_row, btn_lbl, pil_norm, pil_hov,
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
sound_mgr=self.ctx.sounds,
width=btn_w,
height=38,
style="fire" if is_sel else "amethyst",
)
acc_btns.append((b, btn_w))
sound_mgr=self.ctx.sounds, width=185, height=38, font=("Helvetica", 9, "bold")
).pack(side="left", padx=(0, 8))
bj_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
bj_filter_map = {t("bj_filter_all_tables"): None}
@ -77,57 +77,9 @@ class BlackjackStatsView:
bj_filter_map[v["translated_name"]] = v["id"]
board = StatsBoardWidget(
cv,
container,
title=t("bj_stats_acc_title", active_acc["account_name"]),
filter_map=bj_filter_map,
fetch_callback=lambda vid: Database.get_bj_account_stats_overview(active_acc["id"], vid),
fetch_callback=lambda vid: Database.get_bj_account_stats_overview(active_acc["id"], vid)
)
def draw_layout(w: int, h: int):
cv._sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
pad_x = max(56, int(w * 0.065))
content_w = min(1060, w - 2 * pad_x)
left_edge = (w - content_w) // 2
sel_h = 114
sel_top = max(24, int(h * 0.05))
sel_cy = sel_top + sel_h // 2
sel_box = self.ctx.assets.get_box_photo("box_purple", (content_w, sel_h))
if sel_box:
self._photo_refs.append(sel_box)
cv.create_image(w // 2, sel_cy, image=sel_box, anchor="center", tags="fg")
lbl_ph = self.ctx.assets.get_goth_text_photo(
t("bj_stats_select_acc_lbl"),
size_px=FONT_SIZE_BODY + 2,
color=FONT_COLOR_HEADING_SUB,
align="left",
)
self._photo_refs.append(lbl_ph)
cv.create_image(left_edge + 26, sel_cy - 26, image=lbl_ph, anchor="w", tags="fg")
cur_bx = left_edge + 26
for b_wgt, bw in acc_btns:
cv.create_window(cur_bx, sel_cy + 18, window=b_wgt, anchor="w", tags="fg")
cur_bx += bw + 10
board_top = sel_top + sel_h + 22
board_h = max(238, min(270, h - board_top - 32))
cv.create_window(
w // 2,
board_top + board_h // 2,
window=board,
width=content_w,
height=board_h,
anchor="center",
tags="fg",
)
board.after(10, lambda: board._on_configure(type("Evt", (), {"width": content_w, "height": board_h})()))
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(600, cv.winfo_height()))
board.pack(fill="x")

View File

@ -1,38 +1,17 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/round_result_dialog.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
OUTCOME_GIF_SIZE,
SUBTLE_BORDER,
ACCENT_GOLD, ACCENT_GOTH, CELL_BG, ERROR_FG,
FG_COLOR, MODAL_BG, MUTED_FG, PANEL_BG, SUBTLE_BORDER
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
SHOWDOWN_MINI_CARD_SIZE = (48, 70)
SHOWDOWN_MINI_CARD_SIZE = (52, 76)
class BlackjackResultDialog(tk.Canvas):
"""
Rahmenloses Gothic-Showdown-Overlay für Blackjack:
Hintergrund background_vertical.jpg + box_big.png, Gewinner-Sitze in box_gold_smal.png,
übrige Sitze in box_small_purple.png und kompakte Kartenfächer für 768p-Bildschirme.
"""
class BlackjackResultDialog(tk.Frame):
def __init__(
self,
parent,
@ -42,265 +21,176 @@ class BlackjackResultDialog(tk.Canvas):
on_next_round,
on_back_to_menu,
):
hands_list = result_data.get("showdown_hands", [])
cols = min(3, max(1, len(hands_list)))
rows = (len(hands_list) + 2) // 3 if hands_list else 0
has_gif = result_data.get("player_won") is not None
extra_lines = len(result_data.get("other_gains", []))
dlg_w = max(560, min(830, cols * 250 + 64))
dlg_h = (
(116 if has_gif else 54)
+ (48 if result_data.get("reason_text") else 8)
+ (rows * 140 + 28 if rows else 0)
+ 92 + min(2, extra_lines) * 20
+ (24 if result_data.get("new_level_title") else 0)
+ 62
)
# Sicherstellen, dass das Dialogfenster auch auf 768p-Displays komplett sichtbar bleibt
try:
max_h = max(460, parent.winfo_toplevel().winfo_height() - 74)
dlg_h = min(dlg_h, max_h)
except Exception:
pass
super().__init__(
parent,
width=dlg_w,
height=dlg_h,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
parent, bg=MODAL_BG, padx=26, pady=18,
highlightthickness=2, highlightbackground=ACCENT_GOTH
)
self.assets = assets
self.sounds = sounds
self.data = result_data
self.on_next_round = on_next_round
self.on_back_to_menu = on_back_to_menu
self._dlg_w = dlg_w
self._dlg_h = dlg_h
self._gif_job: str | None = None
self._gif_item: int | None = None
self._photo_refs: list = []
self._gif_job = None
self._card_photos = []
self.place(relx=0.5, rely=0.5, anchor="center")
self.tk.call("raise", self._w)
self._build_scene()
self.lift()
self._build()
def _build_scene(self):
w, h = self._dlg_w, self._dlg_h
cx = w // 2
self._photo_refs.clear()
def _build(self):
# Kompaktere Kopfzeile (GIF + Headline), damit alle Karten sauber Platz haben
header_row = tk.Frame(self, bg=MODAL_BG)
header_row.pack(pady=(0, 6))
# 1. Hintergrund + äußerer Zierrahmen box_big.png
bg_src = self.assets.raw_bg_vertical or self.assets.raw_bg_horizontal or self.assets.raw_bg
if bg_src is not None:
bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS))
self._photo_refs.append(bg_ph)
self.create_image(0, 0, image=bg_ph, anchor="nw")
self.gif_lbl = tk.Label(header_row, bg=MODAL_BG, bd=0)
self.gif_lbl.pack(pady=(0, 4))
if self.data.get("player_won") is True:
self._start_gif("win_gif")
elif self.data.get("player_won") is False:
self._start_gif("lose_gif")
outer_box = self.assets.get_box_photo("box_big", (w - 6, h - 6))
if outer_box:
self._photo_refs.append(outer_box)
self.create_image(cx, h // 2, image=outer_box, anchor="center")
cur_y = 20
# 2. Win/Lose GIF + Headline
p_won = self.data.get("player_won")
gif_key = "win_gif" if p_won is True else ("lose_gif" if p_won is False else "")
frames = self.assets.get_gif_frames(gif_key, size=(145, 80)) if gif_key else []
if frames:
self._gif_item = self.create_image(cx, cur_y + 40, image=frames[0], anchor="center")
cur_y += 84
if len(frames) > 1:
self._animate_gif(frames, 0)
hl_col = (
FONT_COLOR_TITLE_MAIN
if p_won is True
else (FONT_COLOR_BODY_MUTED if p_won is None else FONT_COLOR_STATUS_LOSS)
headline_color = ACCENT_GOLD if self.data.get("player_won") else (
MUTED_FG if self.data.get("player_won") is None else ERROR_FG
)
hl_ph = self.assets.get_goth_text_photo(
self.data["headline"], FONT_SIZE_TITLE_LG - 4, hl_col, max_width=w - 60
)
self._photo_refs.append(hl_ph)
self.create_image(cx, cur_y + hl_ph.height() // 2, image=hl_ph, anchor="center")
cur_y += hl_ph.height() + 6
tk.Label(
header_row, text=self.data["headline"],
font=("Georgia", 17, "bold"), fg=headline_color, bg=MODAL_BG,
).pack()
# 3. Begründung im schmalen Gold-Doppelrahmen
# Klare Begründung (z. B. warum Natural BJ gegen 3-Karten-21 gewonnen hat)
reason_txt = self.data.get("reason_text", "")
if reason_txt:
r_ph = self.assets.get_goth_text_photo(
reason_txt, FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, max_width=w - 92
reason_box = tk.Frame(
self, bg=PANEL_BG, padx=14, pady=7,
highlightthickness=1, highlightbackground=ACCENT_GOLD
)
self._photo_refs.append(r_ph)
rb_h = max(36, r_ph.height() + 14)
rb_cy = cur_y + rb_h // 2
rb_box = self.assets.get_box_photo("box_gold_double", (w - 56, rb_h))
if rb_box:
self._photo_refs.append(rb_box)
self.create_image(cx, rb_cy, image=rb_box, anchor="center")
self.create_image(cx, rb_cy, image=r_ph, anchor="center")
cur_y += rb_h + 8
reason_box.pack(fill="x", pady=(2, 10))
tk.Label(
reason_box, text=reason_txt,
font=("Helvetica", 10, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG,
wraplength=760, justify="center"
).pack()
# 4. Showdown-Karten aller Teilnehmer
# =========================================================
# SHOWDOWN-KARTENANSICHT ALLER TEILNEHMER (Dealer, Du, Bots)
# =========================================================
hands_list = self.data.get("showdown_hands", [])
if hands_list:
sec_ph = self.assets.get_goth_text_photo(
t("bj_showdown_section_title"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
hands_outer = tk.Frame(
self, bg=CELL_BG, padx=12, pady=10,
highlightthickness=1, highlightbackground=SUBTLE_BORDER
)
self._photo_refs.append(sec_ph)
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
cur_y += 22
hands_outer.pack(fill="x", pady=(0, 10))
max_cols = 3
rows = (len(hands_list) + max_cols - 1) // max_cols
seat_w = min(242, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(hands_list))))
seat_h = 128 if rows > 1 else 136
tk.Label(
hands_outer, text=t("bj_showdown_section_title"),
font=("Georgia", 10, "bold"), fg=ACCENT_GOTH, bg=CELL_BG
).pack(anchor="w", pady=(0, 6))
win_box = self.assets.get_box_photo("box_gold_small", (seat_w, seat_h))
std_box = self.assets.get_box_photo("box_purple", (seat_w, seat_h))
if win_box:
self._photo_refs.append(win_box)
if std_box:
self._photo_refs.append(std_box)
cards_grid = tk.Frame(hands_outer, bg=CELL_BG)
cards_grid.pack()
max_cols = 3 if len(hands_list) <= 3 else 3
for idx, entry in enumerate(hands_list):
r_i, c_i = divmod(idx, max_cols)
in_row = min(max_cols, len(hands_list) - r_i * max_cols)
row_total_w = in_row * seat_w + (in_row - 1) * 10
sx = (w - row_total_w) // 2 + c_i * (seat_w + 10) + seat_w // 2
sy = cur_y + r_i * (seat_h + 6) + seat_h // 2
r_idx = idx // max_cols
c_idx = idx % max_cols
is_win = entry.get("is_winner", False)
is_dead = entry.get("busted", False) or entry.get("folded", False)
border_col = ACCENT_GOLD if is_win else (ERROR_FG if is_dead else SUBTLE_BORDER)
frame_ph = win_box if is_win else std_box
if frame_ph:
self.create_image(sx, sy, image=frame_ph, anchor="center")
o_col = (
FONT_COLOR_TITLE_MAIN
if is_win
else (FONT_COLOR_HEADING_SUB if entry.get("is_dealer") else FONT_COLOR_BODY_DEFAULT)
seat_card = tk.Frame(
cards_grid, bg=PANEL_BG, padx=10, pady=7,
highlightthickness=2 if is_win else 1, highlightbackground=border_col
)
o_ph = self.assets.get_goth_text_photo(
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
seat_card.grid(row=r_idx, column=c_idx, padx=5, pady=4, sticky="nsew")
title_col = ACCENT_GOLD if is_win else (ACCENT_GOTH if entry.get("is_dealer") else FG_COLOR)
tk.Label(
seat_card, text=entry["owner_label"],
font=("Georgia", 10, "bold"), fg=title_col, bg=PANEL_BG
).pack()
c_row = tk.Frame(seat_card, bg=PANEL_BG)
c_row.pack(pady=4)
for img_name in entry.get("card_images", []):
photo = self.assets.get_card_photo(img_name, size=SHOWDOWN_MINI_CARD_SIZE)
if photo:
self._card_photos.append(photo)
tk.Label(c_row, image=photo, bg=PANEL_BG, bd=0).pack(side="left", padx=2)
badge_col = (
"#7be08a" if is_win else (ERROR_FG if is_dead else FG_COLOR)
)
self._photo_refs.append(o_ph)
self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center")
tk.Label(
seat_card, text=entry["rank_label"],
font=("Helvetica", 9, "bold"), fg=badge_col, bg=PANEL_BG
).pack()
# Überlappender Mini-Kartenfächer
c_imgs = entry.get("card_images", [])
c_photos = []
for img_name in c_imgs:
ph = self.assets.get_card_photo(img_name, size=SHOWDOWN_MINI_CARD_SIZE)
if ph:
self._photo_refs.append(ph)
c_photos.append(ph)
if c_photos:
cw_c, ch_c = SHOWDOWN_MINI_CARD_SIZE
n_c = len(c_photos)
step = 24
if n_c > 1 and (cw_c + (n_c - 1) * step) > (seat_w - 28):
step = max(14, (seat_w - 28 - cw_c) // (n_c - 1))
fan_w = cw_c + (n_c - 1) * step if n_c > 1 else cw_c
start_cx = sx - fan_w // 2
card_top = sy - ch_c // 2 + 2
for ci, cph in enumerate(c_photos):
self.create_image(start_cx + ci * step, card_top, image=cph, anchor="nw")
rk_col = (
FONT_COLOR_STATUS_WIN
if is_win
else (FONT_COLOR_STATUS_LOSS if is_dead else FONT_COLOR_BODY_DEFAULT)
# =========================================================
# GOLD- & XP-ABRECHNUNG
# =========================================================
info_box = tk.Frame(
self, bg=CELL_BG, padx=18, pady=10,
highlightthickness=1, highlightbackground=SUBTLE_BORDER
)
rk_ph = self.assets.get_goth_text_photo(
entry["rank_label"], FONT_SIZE_SMALL_MIN, rk_col, max_width=seat_w - 22
)
self._photo_refs.append(rk_ph)
self.create_image(sx, sy + seat_h // 2 - 18, image=rk_ph, anchor="center")
cur_y += rows * (seat_h + 6) + 6
# 5. Gold- & XP-Abrechnung
self.create_line(36, cur_y, w - 36, cur_y, fill=SUBTLE_BORDER, width=1)
cur_y += 10
info_box.pack(fill="x", pady=(0, 10))
p_net = self.data["player_net"]
if p_net > 0:
own_txt, own_col = t("bj_popup_your_gain", p_net), FONT_COLOR_STATUS_WIN
own_txt, own_col = t("bj_popup_your_gain", p_net), "#7be08a"
elif p_net < 0:
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), FONT_COLOR_STATUS_LOSS
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), ERROR_FG
else:
own_txt, own_col = t("bj_popup_your_even"), FONT_COLOR_BODY_DEFAULT
own_txt, own_col = t("bj_popup_your_even"), FG_COLOR
own_ph = self.assets.get_goth_text_photo(own_txt, FONT_SIZE_BODY + 2, own_col, max_width=w - 72)
self._photo_refs.append(own_ph)
self.create_image(cx, cur_y + own_ph.height() // 2, image=own_ph, anchor="center")
cur_y += own_ph.height() + 2
tk.Label(info_box, text=own_txt, font=("Helvetica", 11, "bold"), fg=own_col, bg=CELL_BG).pack(pady=2)
other_gains = self.data.get("other_gains", [])
if other_gains:
joined_others = " • ".join(other_gains)
oth_ph = self.assets.get_goth_text_photo(
joined_others, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=w - 72
)
self._photo_refs.append(oth_ph)
self.create_image(cx, cur_y + oth_ph.height() // 2, image=oth_ph, anchor="center")
cur_y += oth_ph.height() + 2
for extra_line in self.data.get("other_gains", []):
tk.Label(info_box, text=extra_line, font=("Helvetica", 10), fg=MUTED_FG, bg=CELL_BG).pack(pady=1)
tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=6)
tk.Label(
info_box, text=t("bj_popup_xp_earned", self.data["xp_gained"]),
font=("Helvetica", 11, "bold"), fg=ACCENT_GOTH, bg=CELL_BG,
).pack(pady=1)
xp_line = t("bj_popup_xp_earned", self.data["xp_gained"])
if self.data.get("new_level_title"):
xp_line = f"{xp_line} • {self.data['new_level_title']}"
xp_ph = self.assets.get_goth_text_photo(
xp_line, FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN if self.data.get("new_level_title") else FONT_COLOR_HEADING_SUB,
max_width=w - 72,
)
self._photo_refs.append(xp_ph)
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
tk.Label(
info_box, text=self.data["new_level_title"],
font=("Georgia", 10, "bold"), fg=ACCENT_GOLD, bg=CELL_BG,
).pack(pady=(3, 0))
# 6. Untere Buttons
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
btn_row = tk.Frame(self, bg=MODAL_BG)
btn_row.pack(fill="x", pady=(4, 0))
btn_y = h - 34
can_next = self.data.get("can_continue", True)
can_menu = self.data.get("can_leave_menu", True)
if self.data.get("can_continue", True):
ImageButton(
btn_row, t("bj_popup_next_round_btn"),
self.assets.raw_btn, self.assets.raw_btn_active,
self._handle_next, sound_mgr=self.sounds, width=195, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=(0, 10))
if can_next and can_menu:
b_next = ImageButton(
self, t("bj_popup_next_round_btn"), btn_fire, btn_fire,
self._handle_next, sound_mgr=self.sounds, width=205, height=38, style="fire"
)
b_menu = ImageButton(
self, t("bj_popup_to_menu_btn"), btn_norm, btn_purp,
self._handle_menu, sound_mgr=self.sounds, width=175, height=38, style="amethyst"
)
self.create_window(42, btn_y, window=b_next, anchor="w")
self.create_window(w - 42, btn_y, window=b_menu, anchor="e")
elif can_next:
b_next = ImageButton(
self, t("bj_popup_next_round_btn"), btn_fire, btn_fire,
self._handle_next, sound_mgr=self.sounds, width=215, height=38, style="fire"
)
self.create_window(cx, btn_y, window=b_next, anchor="center")
elif can_menu:
b_menu = ImageButton(
self, t("bj_popup_to_menu_btn"), btn_fire, btn_fire,
self._handle_menu, sound_mgr=self.sounds, width=195, height=38, style="fire"
)
self.create_window(cx, btn_y, window=b_menu, anchor="center")
if self.data.get("can_leave_menu", True):
ImageButton(
btn_row, t("bj_popup_to_menu_btn"),
self.assets.raw_sel, self.assets.raw_sel_active,
self._handle_menu, sound_mgr=self.sounds, width=165, height=38, font=("Helvetica", 10, "bold")
).pack(side="right")
def _animate_gif(self, frames: list, idx: int):
if not self.winfo_exists() or self._gif_item is None:
def _start_gif(self, key: str):
frames = self.assets.get_gif_frames(key)
if not frames:
return
self.itemconfigure(self._gif_item, image=frames[idx % len(frames)])
self._gif_job = self.after(90, self._animate_gif, frames, (idx + 1) % len(frames))
def _step(idx=0):
if not self.gif_lbl.winfo_exists():
return
self.gif_lbl.configure(image=frames[idx])
self._gif_job = self.after(90, _step, (idx + 1) % len(frames))
_step(0)
def close_dialog(self):
if self._gif_job:
@ -309,7 +199,7 @@ class BlackjackResultDialog(tk.Canvas):
except Exception:
pass
self._gif_job = None
self._photo_refs.clear()
self._card_photos.clear()
if self.winfo_exists():
self.destroy()

View File

@ -1,37 +1,21 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_menu_view.py
from __future__ import annotations
import sqlite3
import tkinter as tk
from tkinter import ttk
from games.poker.views.poker_stats_view import PokerStatsView
from games.poker.views.poker_table_view import PokerTableView
from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
DEVILS_DEAL_GOLD_REWARD,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_DISABLED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
GOLD_MAX_ACCOUNTS,
PK_MAX_BOTS,
PK_STARTING_GOLD,
PK_VARIANTS,
XP_TO_GOLD_AMOUNT,
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, CELL_BG,
DEVILS_DEAL_GOLD_REWARD, ERROR_FG, FG_COLOR, GOLD_MAX_ACCOUNTS,
INPUT_BG, MUTED_FG, PANEL_BG, PK_MAX_BOTS, PK_STARTING_GOLD,
PK_VARIANTS, SUBTLE_BORDER, XP_TO_GOLD_AMOUNT
)
from resources.code_res.i18n import t
from view.widgets.bot_setup_widget import BotSetupWidget
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "poker"
@ -41,7 +25,6 @@ class PokerMenuView:
def __init__(self, context):
self.ctx = context
self.bot_widget: BotSetupWidget | None = None
self._photo_refs: list = []
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
pid = self.ctx.profile["id"]
@ -62,7 +45,6 @@ class PokerMenuView:
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
pk_prog = self.ctx.refresh_game_progress()
dyn_xp_cost = pk_prog["xp_exchange_cost"]
@ -95,7 +77,7 @@ class PokerMenuView:
selected_name_var = tk.StringVar(
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
)
state_msg = {"text": status_msg, "ok": status_is_ok}
feedback_var = tk.StringVar(value=status_msg)
def get_current_acc() -> dict | None:
return acc_by_name.get(selected_name_var.get())
@ -109,7 +91,7 @@ class PokerMenuView:
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
PokerStatsView(
self.ctx,
on_back_to_pk_menu=lambda aid: self.show(preselect_id=aid),
on_back_to_pk_menu=lambda aid: self.show(preselect_id=aid)
).show(selected_acc_id=cur["id"])
def refresh_on_lang_switch():
@ -133,36 +115,54 @@ class PokerMenuView:
on_lang_refresh=refresh_on_lang_switch,
)
cv = create_menu_body_canvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=12)
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.93, relheight=0.85)
table_buttons: list[tuple[str, ImageButton]] = []
def on_account_switched(_val=None):
cur = get_current_acc()
if cur is not None:
fresh = Database.get_poker_account(cur["id"])
Database.save_setting(setting_key, str(fresh["id"]))
topbar.extra_label.configure(text=t("pk_header_gold", fresh["account_name"], fresh["gold"]))
for v_k, tb in table_buttons:
tb.set_enabled(fresh["gold"] >= PK_VARIANTS[v_k]["min_entry"])
state_msg["text"] = ""
if cv.winfo_exists() and cv.winfo_width() >= 200:
draw_layout(cv.winfo_width(), cv.winfo_height())
acc_dd = GothDropdown(
cv,
self.ctx.assets,
values=acc_names if has_accounts else [t("bj_no_account_item")],
textvariable=selected_name_var,
on_change=on_account_switched,
sound_mgr=self.ctx.sounds,
width=215,
height=36,
enabled=has_accounts,
main_card = tk.Frame(
container, bg=PANEL_BG, padx=24, pady=16,
highlightthickness=1, highlightbackground=BORDER_COLOR
)
main_card.pack(fill="x")
upper_split = tk.Frame(main_card, bg=PANEL_BG)
upper_split.pack(fill="x", pady=(0, 10))
upper_split.columnconfigure(0, weight=1, uniform="cols")
upper_split.columnconfigure(1, weight=1, uniform="cols")
# =====================================================================
# SPALTE 1: Poker-Goldkonto
# =====================================================================
left_col = tk.Frame(upper_split, bg=PANEL_BG)
left_col.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
tk.Label(
left_col,
text=t("pk_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, PK_STARTING_GOLD),
font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
).pack(anchor="w", pady=(0, 6))
acc_box = tk.Frame(left_col, bg=CELL_BG, padx=14, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
acc_box.pack(fill="both", expand=True)
form_grid = tk.Frame(acc_box, bg=CELL_BG)
form_grid.pack(fill="x")
form_grid.columnconfigure(1, weight=1)
lbl_w = max(len(t("bj_active_acc_lbl")), len(t("bj_new_acc_lbl")))
tk.Label(
form_grid, text=t("bj_active_acc_lbl"), width=lbl_w, anchor="w",
font=("Helvetica", 10, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
acc_cb = ttk.Combobox(
form_grid,
textvariable=selected_name_var,
values=acc_names if has_accounts else [t("bj_no_account_item")],
state="readonly" if has_accounts else "disabled",
font=("Helvetica", 10),
style="Goth.TCombobox",
)
acc_cb.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=2)
def exchange_xp_action():
cur = get_current_acc()
@ -178,15 +178,35 @@ class PokerMenuView:
can_afford_xp = is_divine or (pk_prog["total_points"] >= dyn_xp_cost)
can_exchange = has_accounts and (not at_floor) and can_afford_xp
ex_btn_txt = (
t("bj_exchange_divine_btn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
if is_divine else t("bj_exchange_btn", dyn_xp_cost, XP_TO_GOLD_AMOUNT)
)
exchange_btn = ImageButton(
cv, ex_btn_txt, btn_norm, btn_purp,
ImageButton(
form_grid, ex_btn_txt,
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
exchange_xp_action, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_exchange, style="amethyst",
width=185, height=34, font=("Helvetica", 9, "bold"),
enabled=can_exchange,
).grid(row=0, column=2, sticky="e", pady=4)
# Prominente Gold-Anzeige
gold_banner = tk.Frame(
acc_box, bg=PANEL_BG, padx=12, pady=8,
highlightthickness=1, highlightbackground=BORDER_COLOR if has_accounts else SUBTLE_BORDER
)
gold_banner.pack(fill="x", pady=(8, 8))
gold_var = tk.StringVar(
value=t("bj_gold_display_lbl", active_acc["gold"]) if active_acc else t("bj_gold_display_none")
)
tk.Label(
gold_banner, textvariable=gold_var,
font=("Georgia", 13, "bold"),
fg=ACCENT_GOLD if active_acc else MUTED_FG,
bg=PANEL_BG,
).pack(side="left")
def delete_selected_account():
cur = get_current_acc()
@ -194,30 +214,45 @@ class PokerMenuView:
Database.delete_poker_account(cur["id"])
self.show()
delete_btn = ImageButton(
cv, t("bj_delete_acc_btn"), btn_norm, btn_purp,
ImageButton(
gold_banner, t("bj_delete_acc_btn"),
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
delete_selected_account, sound_mgr=self.ctx.sounds,
width=136, height=32, enabled=has_accounts, style="amethyst",
)
width=120, height=30, font=("Helvetica", 9, "bold"),
enabled=has_accounts,
).pack(side="right")
# Neues Konto anlegen (exakt gleiche Spaltenbreite)
create_grid = tk.Frame(acc_box, bg=CELL_BG)
create_grid.pack(fill="x")
create_grid.columnconfigure(1, weight=1)
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
tk.Label(
create_grid, text=t("bj_new_acc_lbl"), width=lbl_w, anchor="w",
font=("Helvetica", 10, "bold" if not has_accounts else "normal"),
fg=ACCENT_GOLD if not has_accounts else (FG_COLOR if can_create_more else MUTED_FG),
bg=CELL_BG,
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
next_idx = len(accounts) + 1
new_acc_var = tk.StringVar(
value=t("pk_default_acc_name", next_idx) if can_create_more else t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)
)
new_entry = GothEntry(
cv, self.ctx.assets, width=215, height=36,
textvariable=new_acc_var, enabled=can_create_more,
new_entry = tk.Entry(
create_grid, textvariable=new_acc_var, font=("Helvetica", 10),
bg=INPUT_BG, fg=FG_COLOR, disabledbackground="#16141c", disabledforeground="#666070",
bd=0, highlightthickness=1, highlightbackground=ACCENT_GOLD if not has_accounts else BORDER_COLOR,
insertbackground="white", state="normal" if can_create_more else "disabled"
)
new_entry.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=5)
def create_new_account():
if not can_create_more:
return
name = new_entry.get().strip()
name = new_acc_var.get().strip()
if not name:
state_msg["text"] = t("bj_err_empty_name")
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
feedback_var.set(t("bj_err_empty_name"))
return
try:
if self.bot_widget is not None and has_accounts:
@ -227,34 +262,39 @@ class PokerMenuView:
Database.save_setting(setting_key, str(created["id"]))
self.show(preselect_id=created["id"])
except (sqlite3.IntegrityError, RuntimeError) as exc:
state_msg["text"] = t("pk_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc)
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
feedback_var.set(t("pk_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc))
if can_create_more:
new_entry.bind_return(lambda _e: create_new_account())
new_entry.bind("<Return>", lambda _e: create_new_account())
create_btn = ImageButton(
cv, t("bj_create_acc_btn", PK_STARTING_GOLD),
btn_fire if not has_accounts else btn_norm,
btn_fire if not has_accounts else btn_purp,
ImageButton(
create_grid, t("bj_create_acc_btn", PK_STARTING_GOLD),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
create_new_account, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_create_more,
style="fire" if not has_accounts else "amethyst",
)
width=185, height=34, font=("Helvetica", 9, "bold"),
enabled=can_create_more,
).grid(row=0, column=2, sticky="e", pady=4)
sac_dd = None
devil_btn = None
# Info / Divine Punishment / The Devil's Deal (Poker-autark!)
min_sac_lvl = Progression.get_devils_deal_min_level()
classic_cfg = PK_VARIANTS["poker_holdem"]
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID) if (devils_deal_open and has_accounts) else []
if devils_deal_open and has_accounts:
tk.Label(
acc_box,
text=t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
font=("Helvetica", 8, "bold"), fg=ERROR_FG, bg=CELL_BG, wraplength=480, justify="left"
).pack(anchor="w", pady=(6, 4))
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID)
if sac_candidates:
devil_row = tk.Frame(acc_box, bg=CELL_BG)
devil_row.pack(fill="x", pady=(2, 0))
sac_map = {f"{c['name']} ({c['title']} • Lv. {c['level']})": c["id"] for c in sac_candidates}
sac_var = tk.StringVar(value=next(iter(sac_map.keys())))
sac_dd = GothDropdown(
cv, self.ctx.assets, values=list(sac_map.keys()),
textvariable=sac_var, sound_mgr=self.ctx.sounds, width=250, height=34,
)
ttk.Combobox(
devil_row, textvariable=sac_var, values=list(sac_map.keys()),
state="readonly", font=("Helvetica", 9), width=26, style="Goth.TCombobox"
).pack(side="left", fill="x", expand=True, padx=(0, 8))
def seal_devils_deal():
cur = get_current_acc()
@ -263,9 +303,7 @@ class PokerMenuView:
return
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
if not active_bots:
state_msg["text"] = t("pk_err_need_one_bot")
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
feedback_var.set(t("pk_err_need_one_bot"))
return
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
ok, _msg = Database.execute_devils_deal(pid, GAME_FOLDER_ID, victim_id, cur["id"])
@ -279,21 +317,68 @@ class PokerMenuView:
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
)
devil_btn = ImageButton(
cv, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
btn_fire, btn_fire, seal_devils_deal,
sound_mgr=None, width=180, height=34, style="fire",
ImageButton(
devil_row, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
seal_devils_deal, sound_mgr=None, width=185, height=32, font=("Helvetica", 9, "bold")
).pack(side="right")
else:
tk.Label(
acc_box, text=t("bj_devils_deal_none", min_sac_lvl),
font=("Helvetica", 8), fg=MUTED_FG, bg=CELL_BG
).pack(anchor="w")
else:
info_text = (
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
if is_divine
else t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic_cfg["sb"], classic_cfg["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
)
tk.Label(
acc_box, text=info_text,
font=("Helvetica", 8, "bold" if is_divine else "normal"),
fg=ERROR_FG if is_divine else MUTED_FG,
bg=CELL_BG, wraplength=480, justify="left"
).pack(anchor="w", pady=(6, 0))
# =====================================================================
# SPALTE 2: 6-Max Gegner-Setup (1 bis 5 Bots)
# =====================================================================
right_col = tk.Frame(upper_split, bg=PANEL_BG)
right_col.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
tk.Label(
right_col, text=t("pk_bots_sec_title"),
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
).pack(anchor="w", pady=(0, 6))
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
if not saved_bots:
# Komfort-Default beim allerersten Poker-Besuch: 2 solide Gegner voreingestellt
saved_bots = {
0: (t("bot_default_name", 1), 1),
1: (t("bot_default_name", 2), 2),
}
self.bot_widget = BotSetupWidget(cv, saved_bots, max_bots=PK_MAX_BOTS, enabled=has_accounts)
self.bot_widget = BotSetupWidget(right_col, saved_bots, max_bots=PK_MAX_BOTS, enabled=has_accounts)
self.bot_widget.pack(fill="both", expand=True)
fb_lbl = tk.Label(
main_card, textvariable=feedback_var,
font=("Helvetica", 9, "bold"),
fg="#7be08a" if status_is_ok else ERROR_FG,
bg=PANEL_BG
)
fb_lbl.pack(anchor="w", pady=(2, 4))
# =====================================================================
# SEKTION 3: Tischvariante wählen
# =====================================================================
tk.Label(
main_card, text=t("pk_sec3_title"),
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
).pack(anchor="w", pady=(2, 8))
def enter_table(v_key: str):
fb_lbl.configure(fg=ERROR_FG)
cur = get_current_acc()
if not cur:
return
@ -305,215 +390,63 @@ class PokerMenuView:
Database.save_bot_configs(pid, GAME_FOLDER_ID, configs_to_save)
if not active_bots:
state_msg["text"] = t("pk_err_need_one_bot")
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
feedback_var.set(t("pk_err_need_one_bot"))
return
min_req = PK_VARIANTS[v_key]["min_entry"]
cur_pk_prog = self.ctx.refresh_game_progress()
if acc["gold"] < min_req:
state_msg["text"] = t(
feedback_var.set(t(
"bj_err_not_enough_gold_entry",
acc["account_name"], min_req, acc["gold"],
cur_pk_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT,
)
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
cur_pk_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT
))
return
PokerTableView(
self.ctx, v_key, acc["id"], active_bots,
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg)
)
variant_items = list(PK_VARIANTS.items())
for v_key, cfg in variant_items:
variants_row = tk.Frame(main_card, bg=PANEL_BG)
variants_row.pack(fill="x")
for idx in range(len(PK_VARIANTS)):
variants_row.columnconfigure(idx, weight=1)
table_buttons: list[tuple[str, ImageButton]] = []
for idx, (v_key, cfg) in enumerate(PK_VARIANTS.items()):
card = tk.Frame(variants_row, bg=CELL_BG, padx=16, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
card.grid(row=0, column=idx, padx=(0, 8) if idx == 0 else (8, 0), sticky="nsew")
tk.Label(
card, text=t(f"variant_{v_key}"),
font=("Georgia", 12, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
).pack(anchor="w")
tk.Label(
card, text=t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"]),
font=("Helvetica", 9), fg=MUTED_FG, bg=CELL_BG
).pack(anchor="w", pady=(4, 10))
can_play_v = bool(active_acc and active_acc["gold"] >= cfg["min_entry"])
t_btn = ImageButton(
cv, t("bj_enter_table_btn"), btn_fire, btn_fire,
card, t("bj_enter_table_btn"),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
lambda k=v_key: enter_table(k),
sound_mgr=self.ctx.sounds, width=168, height=38,
enabled=can_play_v, style="fire",
sound_mgr=self.ctx.sounds, width=160, height=36,
font=("Helvetica", 10, "bold"), enabled=can_play_v,
)
t_btn.pack(anchor="e")
table_buttons.append((v_key, t_btn))
def draw_layout(w: int, h: int):
cv._sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
def on_account_switched(*_):
cur = get_current_acc()
if cur is not None:
fresh = Database.get_poker_account(cur["id"])
Database.save_setting(setting_key, str(fresh["id"]))
gold_var.set(t("bj_gold_display_lbl", fresh["gold"]))
topbar.extra_label.configure(text=t("pk_header_gold", fresh["account_name"], fresh["gold"]))
for v_k, tb in table_buttons:
tb.set_enabled(fresh["gold"] >= PK_VARIANTS[v_k]["min_entry"])
feedback_var.set("")
compact = (h < 710)
pad_x = max(44, int(w * 0.045))
usable_w = min(1240, w - 2 * pad_x)
x0 = (w - usable_w) // 2
col_gap = 20
col_w = (usable_w - col_gap) // 2
left_x = x0
right_x = x0 + col_w + col_gap
top_sec_y = 10 if compact else 18
upper_h = max(296, PK_MAX_BOTS * BotSetupWidget.ROW_HEIGHT + 44)
s1_ph = self.ctx.assets.get_goth_text_photo(
t("pk_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, PK_STARTING_GOLD),
FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, max_width=col_w - 10, align="left",
)
s2_ph = self.ctx.assets.get_goth_text_photo(
t("pk_bots_sec_title"), FONT_SIZE_HEADING - 3,
FONT_COLOR_HEADING_SUB if has_accounts else FONT_COLOR_DISABLED,
max_width=col_w - 10, align="left",
)
self._photo_refs.extend([s1_ph, s2_ph])
cv.create_image(left_x + 8, top_sec_y + 12, image=s1_ph, anchor="w", tags="fg")
cv.create_image(right_x + 8, top_sec_y + 12, image=s2_ph, anchor="w", tags="fg")
box_top = top_sec_y + 32
box_cy = box_top + upper_h // 2
l_frame = self.ctx.assets.get_box_photo("box_big", (col_w, upper_h))
r_frame = self.ctx.assets.get_box_photo("box_purple", (col_w, upper_h))
if l_frame:
self._photo_refs.append(l_frame)
cv.create_image(left_x + col_w // 2, box_cy, image=l_frame, anchor="center", tags="fg")
if r_frame:
self._photo_refs.append(r_frame)
cv.create_image(right_x + col_w // 2, box_cy, image=r_frame, anchor="center", tags="fg")
in_pad = 22
lbl_col_w = 118
btn_w = 180
mid_field_w = max(140, col_w - 2 * in_pad - lbl_col_w - btn_w - 16)
if acc_dd._width != mid_field_w:
acc_dd._width = mid_field_w
acc_dd.configure(width=mid_field_w)
acc_dd._render_closed()
r1_y = box_top + 40
l_act = self.ctx.assets.get_goth_text_photo(
t("bj_active_acc_lbl"), FONT_SIZE_BODY,
FONT_COLOR_BODY_DEFAULT if has_accounts else FONT_COLOR_DISABLED, align="left",
)
self._photo_refs.append(l_act)
cv.create_image(left_x + in_pad, r1_y, image=l_act, anchor="w", tags="fg")
cv.create_window(left_x + in_pad + lbl_col_w, r1_y, window=acc_dd, anchor="w", tags="fg")
cv.create_window(left_x + col_w - in_pad, r1_y, window=exchange_btn, anchor="e", tags="fg")
gb_y = r1_y + 54
gb_w = col_w - 2 * in_pad
gb_frame = self.ctx.assets.get_box_photo("box_gold_double", (gb_w, 50))
if gb_frame:
self._photo_refs.append(gb_frame)
cv.create_image(left_x + col_w // 2, gb_y, image=gb_frame, anchor="center", tags="fg")
cur_acc_obj = get_current_acc()
fresh_gold = Database.get_poker_account(cur_acc_obj["id"])["gold"] if cur_acc_obj else 0
gold_str = t("pk_gold_display_lbl", fresh_gold) if cur_acc_obj else t("bj_gold_display_none")
g_ph = self.ctx.assets.get_goth_text_photo(
gold_str, FONT_SIZE_HEADING - 3,
FONT_COLOR_TITLE_MAIN if cur_acc_obj else FONT_COLOR_BODY_MUTED, align="left",
)
self._photo_refs.append(g_ph)
cv.create_image(left_x + in_pad + 18, gb_y, image=g_ph, anchor="w", tags="fg")
cv.create_window(left_x + col_w - in_pad - 14, gb_y, window=delete_btn, anchor="e", tags="fg")
r3_y = gb_y + 54
l_new = self.ctx.assets.get_goth_text_photo(
t("bj_new_acc_lbl"), FONT_SIZE_BODY,
FONT_COLOR_TITLE_MAIN if not has_accounts else (FONT_COLOR_BODY_DEFAULT if can_create_more else FONT_COLOR_DISABLED),
align="left",
)
self._photo_refs.append(l_new)
cv.create_image(left_x + in_pad, r3_y, image=l_new, anchor="w", tags="fg")
cv.create_window(left_x + in_pad + lbl_col_w, r3_y, window=new_entry, anchor="w", tags="fg")
cv.create_window(left_x + col_w - in_pad, r3_y, window=create_btn, anchor="e", tags="fg")
info_y = r3_y + 42
if devils_deal_open and has_accounts:
warn_ph = self.ctx.assets.get_goth_text_photo(
t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
FONT_SIZE_SMALL_MIN, FONT_COLOR_STATUS_LOSS, max_width=gb_w, align="left",
)
self._photo_refs.append(warn_ph)
cv.create_image(left_x + in_pad, info_y, image=warn_ph, anchor="nw", tags="fg")
if sac_dd is not None and devil_btn is not None:
dy = box_top + upper_h - 30
cv.create_window(left_x + in_pad, dy, window=sac_dd, anchor="w", tags="fg")
cv.create_window(left_x + col_w - in_pad, dy, window=devil_btn, anchor="e", tags="fg")
else:
none_ph = self.ctx.assets.get_goth_text_photo(
t("bj_devils_deal_none", min_sac_lvl), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
)
self._photo_refs.append(none_ph)
cv.create_image(left_x + in_pad, box_top + upper_h - 28, image=none_ph, anchor="w", tags="fg")
else:
info_txt = (
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
if is_divine
else t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic_cfg["sb"], classic_cfg["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
)
inf_ph = self.ctx.assets.get_goth_text_photo(
info_txt, FONT_SIZE_SMALL_MIN,
FONT_COLOR_STATUS_LOSS if is_divine else FONT_COLOR_BODY_MUTED,
max_width=gb_w, align="left",
)
self._photo_refs.append(inf_ph)
cv.create_image(left_x + in_pad, info_y + 4, image=inf_ph, anchor="nw", tags="fg")
if self.bot_widget is not None:
bw_w = col_w - 40
bw_h = PK_MAX_BOTS * BotSetupWidget.ROW_HEIGHT + 8
cv.create_window(
right_x + col_w // 2, box_cy,
window=self.bot_widget, width=bw_w, height=bw_h, anchor="center", tags="fg"
)
sec3_hdr_y = box_top + upper_h + (18 if compact else 26)
if state_msg["text"]:
fb_ph = self.ctx.assets.get_goth_text_photo(
state_msg["text"], FONT_SIZE_BODY,
FONT_COLOR_STATUS_WIN if state_msg["ok"] else FONT_COLOR_STATUS_LOSS,
max_width=usable_w // 2, align="right",
)
self._photo_refs.append(fb_ph)
cv.create_image(x0 + usable_w - 6, sec3_hdr_y, image=fb_ph, anchor="e", tags="fg")
s3_ph = self.ctx.assets.get_goth_text_photo(
t("pk_sec3_title"), FONT_SIZE_HEADING - 3,
FONT_COLOR_HEADING_SUB if has_accounts else FONT_COLOR_DISABLED, align="left",
)
self._photo_refs.append(s3_ph)
cv.create_image(left_x + 8, sec3_hdr_y, image=s3_ph, anchor="w", tags="fg")
var_top = sec3_hdr_y + 20
var_h = max(118, min(148, h - var_top - 18))
var_cy = var_top + var_h // 2
v_frame = self.ctx.assets.get_box_photo("box_gold_small", (col_w, var_h))
if v_frame:
self._photo_refs.append(v_frame)
for idx, (v_key, cfg) in enumerate(variant_items):
vx = left_x if idx == 0 else right_x
if v_frame:
cv.create_image(vx + col_w // 2, var_cy, image=v_frame, anchor="center", tags="fg")
vt_ph = self.ctx.assets.get_goth_text_photo(
t(f"variant_{v_key}"), FONT_SIZE_HEADING - 2,
FONT_COLOR_TITLE_MAIN if has_accounts else FONT_COLOR_DISABLED, align="left",
)
vd_ph = self.ctx.assets.get_goth_text_photo(
t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"]),
FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=col_w - 56, align="left",
)
self._photo_refs.extend([vt_ph, vd_ph])
cv.create_image(vx + 28, var_top + 30, image=vt_ph, anchor="w", tags="fg")
cv.create_image(vx + 28, var_top + 60, image=vd_ph, anchor="w", tags="fg")
cv.create_window(
vx + col_w - 28, var_top + var_h - 30,
window=table_buttons[idx][1], anchor="e", tags="fg"
)
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
acc_cb.bind("<<ComboboxSelected>>", on_account_switched)

View File

@ -1,13 +1,8 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_stats_view.py
from __future__ import annotations
from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas
import tkinter as tk
from models.database import Database
from resources.code_res.game_constants import (
FONT_COLOR_HEADING_SUB,
FONT_SIZE_BODY,
)
from resources.code_res.game_constants import ACCENT_GOLD, BG_COLOR, BORDER_COLOR, PANEL_BG
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
from view.widgets.stats_board_widget import StatsBoardWidget
@ -16,19 +11,16 @@ GAME_FOLDER_ID = "poker"
class PokerStatsView:
"""Rahmenlose Statistik-Ansicht für die einzelnen Poker-Goldbeutel."""
"""Dedizierte Statistik-Ansicht für die einzelnen Poker-Goldbeutel."""
def __init__(self, context, on_back_to_pk_menu):
self.ctx = context
self.on_back_to_pk_menu = on_back_to_pk_menu
self._photo_refs: list = []
def show(self, selected_acc_id: int | None = None):
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
pid = self.ctx.profile["id"]
accounts = Database.get_poker_accounts(pid)
if not accounts:
self.on_back_to_pk_menu(None)
return
@ -48,28 +40,34 @@ class PokerStatsView:
on_lang_refresh=lambda: self.show(active_acc["id"]),
)
cv = create_menu_body_canvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=18)
container.place(relx=0.5, rely=0.54, anchor="center", relwidth=0.88, relheight=0.82)
selector_panel = tk.Frame(
container, bg=PANEL_BG, padx=18, pady=14,
highlightthickness=1, highlightbackground=BORDER_COLOR
)
selector_panel.pack(fill="x", pady=(0, 16))
tk.Label(
selector_panel, text=t("bj_stats_select_acc_lbl"),
font=("Georgia", 13, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
).pack(anchor="w", pady=(0, 10))
tabs_row = tk.Frame(selector_panel, bg=PANEL_BG)
tabs_row.pack(fill="x")
acc_btns: list[tuple[ImageButton, int]] = []
btn_w = 186
for acc in accounts:
is_sel = (acc["id"] == active_acc["id"])
pil_norm = self.ctx.assets.raw_btn if is_sel else self.ctx.assets.raw_sel
pil_hov = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
b = ImageButton(
cv,
btn_lbl,
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
ImageButton(
tabs_row, btn_lbl, pil_norm, pil_hov,
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
sound_mgr=self.ctx.sounds,
width=btn_w,
height=38,
style="fire" if is_sel else "amethyst",
)
acc_btns.append((b, btn_w))
sound_mgr=self.ctx.sounds, width=185, height=38, font=("Helvetica", 9, "bold")
).pack(side="left", padx=(0, 8))
pk_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
pk_filter_map = {t("pk_filter_all_tables"): None}
@ -77,57 +75,9 @@ class PokerStatsView:
pk_filter_map[v["translated_name"]] = v["id"]
board = StatsBoardWidget(
cv,
container,
title=t("bj_stats_acc_title", active_acc["account_name"]),
filter_map=pk_filter_map,
fetch_callback=lambda vid: Database.get_pk_account_stats_overview(active_acc["id"], vid),
fetch_callback=lambda vid: Database.get_pk_account_stats_overview(active_acc["id"], vid)
)
def draw_layout(w: int, h: int):
cv._sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
pad_x = max(56, int(w * 0.065))
content_w = min(1060, w - 2 * pad_x)
left_edge = (w - content_w) // 2
sel_h = 114
sel_top = max(24, int(h * 0.05))
sel_cy = sel_top + sel_h // 2
sel_box = self.ctx.assets.get_box_photo("box_purple", (content_w, sel_h))
if sel_box:
self._photo_refs.append(sel_box)
cv.create_image(w // 2, sel_cy, image=sel_box, anchor="center", tags="fg")
lbl_ph = self.ctx.assets.get_goth_text_photo(
t("bj_stats_select_acc_lbl"),
size_px=FONT_SIZE_BODY + 2,
color=FONT_COLOR_HEADING_SUB,
align="left",
)
self._photo_refs.append(lbl_ph)
cv.create_image(left_edge + 26, sel_cy - 26, image=lbl_ph, anchor="w", tags="fg")
cur_bx = left_edge + 26
for b_wgt, bw in acc_btns:
cv.create_window(cur_bx, sel_cy + 18, window=b_wgt, anchor="w", tags="fg")
cur_bx += bw + 10
board_top = sel_top + sel_h + 22
board_h = max(238, min(270, h - board_top - 32))
cv.create_window(
w // 2,
board_top + board_h // 2,
window=board,
width=content_w,
height=board_h,
anchor="center",
tags="fg",
)
board.after(10, lambda: board._on_configure(type("Evt", (), {"width": content_w, "height": board_h})()))
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(600, cv.winfo_height()))
board.pack(fill="x")

View File

@ -1,111 +0,0 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_menu_chrome.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_TITLE_LG,
)
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
def create_menu_body_canvas(ctx, topbar_h: int = 56) -> tk.Canvas:
"""Erstellt ein vollflächiges Menü-Canvas unterhalb der GothTopbar, das background_*.jpg nahtlos zeigt."""
GothDropdown.close_any_open_popup()
cv = tk.Canvas(ctx.root, bg=BG_COLOR, bd=0, highlightthickness=0)
cv.place(x=0, y=topbar_h, relwidth=1.0, relheight=1.0, height=-topbar_h)
state = {"last": (0, 0), "bg_ph": None}
def _sync_bg(w: int, h: int):
if (w, h) == state["last"] or w < 80 or h < 80:
return
state["last"] = (w, h)
rw = max(w, ctx.root.winfo_width())
rh = max(h + topbar_h, ctx.root.winfo_height())
src = (
ctx.assets.raw_bg_vertical
if (rh > rw and ctx.assets.raw_bg_vertical is not None)
else (ctx.assets.raw_bg_horizontal or ctx.assets.raw_bg)
)
if src is None:
return
full_img = src.resize((rw, rh), Image.Resampling.LANCZOS)
cropped = full_img.crop((0, topbar_h, min(rw, w), min(rh, topbar_h + h)))
state["bg_ph"] = ImageTk.PhotoImage(cropped)
cv.delete("menu_bg")
cv.create_image(0, 0, image=state["bg_ph"], anchor="nw", tags="menu_bg")
cv.tag_lower("menu_bg")
cv._sync_bg = _sync_bg # type: ignore[attr-defined]
return cv
def open_goth_modal(
ctx,
title_txt: str,
body_txt: str,
buttons: list[tuple[str, str, object]],
is_danger: bool = False,
) -> tk.Canvas:
"""Rahmenloses Gothic-Modal auf background_vertical.jpg + box_big.png für Solitaire-Dialoge."""
GothDropdown.close_any_open_popup()
dlg_w = 560 if len(buttons) >= 3 else 490
dlg_h = 265
overlay = tk.Canvas(
ctx.root, width=dlg_w, height=dlg_h, bg=BG_COLOR, bd=0, highlightthickness=0
)
overlay.place(relx=0.5, rely=0.53, anchor="center")
refs: list = []
overlay._goth_refs = refs # type: ignore[attr-defined]
bg_src = ctx.assets.raw_bg_vertical or ctx.assets.raw_bg_horizontal or ctx.assets.raw_bg
if bg_src is not None:
bg_ph = ImageTk.PhotoImage(bg_src.resize((dlg_w, dlg_h), Image.Resampling.LANCZOS))
refs.append(bg_ph)
overlay.create_image(0, 0, image=bg_ph, anchor="nw")
box_ph = ctx.assets.get_box_photo("box_big", (dlg_w - 6, dlg_h - 6))
if box_ph:
refs.append(box_ph)
overlay.create_image(dlg_w // 2, dlg_h // 2, image=box_ph, anchor="center")
t_col = FONT_COLOR_STATUS_LOSS if is_danger else FONT_COLOR_TITLE_MAIN
t_ph = ctx.assets.get_goth_text_photo(title_txt, FONT_SIZE_TITLE_LG - 4, t_col, max_width=dlg_w - 60)
b_ph = ctx.assets.get_goth_text_photo(
body_txt, FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=dlg_w - 72, align="center"
)
refs.extend([t_ph, b_ph])
overlay.create_image(dlg_w // 2, 52, image=t_ph, anchor="center")
overlay.create_image(dlg_w // 2, 124, image=b_ph, anchor="center")
btn_norm = ctx.assets.raw_btn_default
btn_purp = ctx.assets.raw_btn_purple
btn_fire = ctx.assets.raw_btn_fire or btn_purp
bw = 160 if len(buttons) >= 3 else 182
gap = 10
total_w = len(buttons) * bw + max(0, len(buttons) - 1) * gap
cur_x = (dlg_w - total_w) // 2
for lbl, style, cmd in buttons:
p_n = btn_fire if style == "fire" else btn_norm
p_h = btn_fire if style == "fire" else btn_purp
b = ImageButton(
overlay, lbl, p_n, p_h, cmd,
sound_mgr=ctx.sounds, width=bw, height=38, style=style
)
overlay.create_window(cur_x + bw // 2, dlg_h - 46, window=b, anchor="center")
cur_x += bw + gap
return overlay

View File

@ -2,23 +2,25 @@
# games/solitaire/base/solitaire_stats_view.py
from __future__ import annotations
from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas
import tkinter as tk
from models.database import Database
from resources.code_res.game_constants import (
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
ACCENT_GOLD,
ACCENT_GOTH,
BG_COLOR,
BORDER_COLOR,
CELL_BG,
FG_COLOR,
MUTED_FG,
PANEL_BG,
STAT_FIELD_KEYS,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
# Kurze, prägnante Button-Labels für Varianten mit mehreren Modi
SHORT_VARIANT_TAB_KEYS: dict[str, str] = {
"klondike_1": "kl_draw_toggle_1",
"klondike_3": "kl_draw_toggle_3",
@ -29,7 +31,7 @@ SHORT_VARIANT_TAB_KEYS: dict[str, str] = {
class SolitaireStatsView:
"""Rahmenlose Solitaire-Statistik-Ansicht mit direktem Varianten-Umschalter."""
"""Kompakte Statistik-Ansicht mit direktem Varianten-Umschalter im selben Block."""
def __init__(self, context, game_folder: str, game_title_key: str, on_back):
self.ctx = context
@ -37,15 +39,12 @@ class SolitaireStatsView:
self.game_title_key = game_title_key
self.on_back = on_back
self._active_variant_id: int | None = None
self._photo_refs: list = []
def show(self, preselect_variant_id: int | None = None):
pid = self.ctx.profile["id"]
self._active_variant_id = preselect_variant_id
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
prog = Database.get_game_progress(pid, self.game_folder)
game_name = t(self.game_title_key)
@ -58,14 +57,43 @@ class SolitaireStatsView:
on_lang_refresh=lambda: self.show(preselect_variant_id=self._active_variant_id),
)
cv = create_menu_body_canvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=16)
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.86, relheight=0.80)
card = tk.Frame(
container,
bg=PANEL_BG,
padx=24,
pady=20,
highlightthickness=1,
highlightbackground=BORDER_COLOR,
)
card.pack(fill="both", expand=True)
# Kopfzeile: Links Rang/XP, rechts kompakter Umschalter (z. B. Gesamt | 1 Karte | 3 Karten)
header_row = tk.Frame(card, bg=PANEL_BG)
header_row.pack(fill="x", pady=(0, 14))
tk.Label(
header_row,
text=t(
"stats_game_rank_info",
game_name,
prog["title"],
prog["level"],
prog["current_xp"],
prog["needed_xp"],
),
font=("Georgia", 11, "bold"),
fg=ACCENT_GOLD,
bg=PANEL_BG,
).pack(side="left", anchor="w")
variants = Database.get_variants_for_filter(self.game_folder)
tab_btns: list[tuple[ImageButton, int]] = []
if len(variants) > 1:
toggle_bar = tk.Frame(header_row, bg=PANEL_BG)
toggle_bar.pack(side="right")
tabs: list[tuple[int | None, str]] = [(None, t("sol_stats_tab_all"))]
for v in variants:
v_key = v["variant_key"]
@ -77,137 +105,76 @@ class SolitaireStatsView:
tabs.append((v["id"], short_lbl))
for vid, tab_text in tabs:
is_sel = (self._active_variant_id == vid)
bw = 118 if vid is None else 156
b = ImageButton(
cv,
is_selected = self._active_variant_id == vid
raw_norm = self.ctx.assets.raw_btn_active if is_selected else self.ctx.assets.raw_sel
raw_act = self.ctx.assets.raw_btn_active if is_selected else self.ctx.assets.raw_sel_active
btn_w = 110 if vid is None else 150
ImageButton(
toggle_bar,
tab_text,
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
raw_norm,
raw_act,
lambda target_vid=vid: self._switch_tab(target_vid),
sound_mgr=self.ctx.sounds,
width=bw,
height=36,
style="fire" if is_sel else "amethyst",
)
tab_btns.append((b, bw))
width=btn_w,
height=32,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=(6, 0))
# Aktive Unterüberschrift des Blocks
active_title = t("stats_all_variants_of_game", game_name)
for v in variants:
if v["id"] == self._active_variant_id:
active_title = v["translated_name"]
break
tk.Label(
card,
text=t("stats_game_board_title", active_title),
font=("Georgia", 12, "bold"),
fg=ACCENT_GOTH,
bg=PANEL_BG,
).pack(anchor="w", pady=(0, 10))
grid_frame = tk.Frame(card, bg=PANEL_BG)
grid_frame.pack(fill="x", pady=(4, 0))
grid_frame.columnconfigure(0, weight=1, uniform="statcol")
grid_frame.columnconfigure(1, weight=1, uniform="statcol")
stats = Database.get_stats_overview(
pid,
variant_id=self._active_variant_id,
folder_path=self.game_folder if self._active_variant_id is None else None,
)
def draw_layout(w: int, h: int):
cv._sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
pad_x = max(56, int(w * 0.065))
content_w = min(1020, w - 2 * pad_x)
left_x = (w - content_w) // 2
# 1. Obere Rang- & Umschalter-Box in box_gold_double
hdr_h = 74
hdr_top = max(24, int(h * 0.05))
hdr_cy = hdr_top + hdr_h // 2
hdr_box = self.ctx.assets.get_box_photo("box_gold_double", (content_w, hdr_h))
if hdr_box:
self._photo_refs.append(hdr_box)
cv.create_image(w // 2, hdr_cy, image=hdr_box, anchor="center", tags="fg")
tabs_total_w = sum(bw + 8 for _, bw in tab_btns)
rank_ph = self.ctx.assets.get_goth_text_photo(
t(
"stats_game_rank_info",
game_name,
prog["title"],
prog["level"],
prog["current_xp"],
prog["needed_xp"],
),
size_px=FONT_SIZE_BODY + 1,
color=FONT_COLOR_TITLE_MAIN,
max_width=max(200, content_w - tabs_total_w - 64),
align="left",
)
self._photo_refs.append(rank_ph)
cv.create_image(left_x + 26, hdr_cy, image=rank_ph, anchor="w", tags="fg")
rx = left_x + content_w - 24
for b_wgt, bw in reversed(tab_btns):
cv.create_window(rx, hdr_cy, window=b_wgt, anchor="e", tags="fg")
rx -= (bw + 8)
# 2. Haupttafel in box_big mit 2x4 box_purple Zellen
board_top = hdr_top + hdr_h + 18
board_h = max(260, min(330, h - board_top - 32))
board_cy = board_top + board_h // 2
outer_box = self.ctx.assets.get_box_photo("box_big", (content_w, board_h))
if outer_box:
self._photo_refs.append(outer_box)
cv.create_image(w // 2, board_cy, image=outer_box, anchor="center", tags="fg")
sub_ph = self.ctx.assets.get_goth_text_photo(
t("stats_game_board_title", active_title),
size_px=FONT_SIZE_HEADING - 2,
color=FONT_COLOR_HEADING_SUB,
align="left",
)
self._photo_refs.append(sub_ph)
cv.create_image(left_x + 28, board_top + 34, image=sub_ph, anchor="w", tags="fg")
grid_top = board_top + 66
grid_h = board_h - 88
cols, rows = 4, 2
gap_x, gap_y = 14, 12
cell_w = (content_w - 56 - (cols - 1) * gap_x) // cols
cell_h = (grid_h - (rows - 1) * gap_y) // rows
cell_frame = self.ctx.assets.get_box_photo("box_purple", (cell_w, cell_h))
if cell_frame:
self._photo_refs.append(cell_frame)
for idx, (field_key, label_i18n_key) in enumerate(STAT_FIELD_KEYS):
r, c = divmod(idx, cols)
cx = left_x + 28 + c * (cell_w + gap_x) + cell_w // 2
cy = grid_top + r * (cell_h + gap_y) + cell_h // 2
if cell_frame:
cv.create_image(cx, cy, image=cell_frame, anchor="center", tags="fg")
lbl_ph = self.ctx.assets.get_goth_text_photo(
t(label_i18n_key), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
max_width=cell_w - 24, align="center",
r, c = divmod(idx, 2)
cell = tk.Frame(
grid_frame,
bg=CELL_BG,
padx=16,
pady=12,
highlightthickness=1,
highlightbackground=SUBTLE_BORDER,
)
if field_key == "won":
v_col = FONT_COLOR_STATUS_WIN
elif field_key == "lost":
v_col = FONT_COLOR_STATUS_LOSS
elif "streak" in field_key or field_key == "win_pct":
v_col = FONT_COLOR_HEADING_SUB
else:
v_col = FONT_COLOR_BODY_DEFAULT
cell.grid(row=r, column=c, sticky="ew", padx=(0, 8) if c == 0 else (8, 0), pady=6)
val_ph = self.ctx.assets.get_goth_text_photo(
str(stats.get(field_key, "--")), FONT_SIZE_HEADING - 2, v_col,
max_width=cell_w - 24, align="center",
)
self._photo_refs.extend([lbl_ph, val_ph])
cv.create_image(cx, cy - cell_h // 4 + 2, image=lbl_ph, anchor="center", tags="fg")
cv.create_image(cx, cy + cell_h // 5 + 2, image=val_ph, anchor="center", tags="fg")
tk.Label(
cell,
text=t(label_i18n_key),
font=("Helvetica", 10),
fg=MUTED_FG,
bg=CELL_BG,
).pack(side="left")
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(600, cv.winfo_height()))
tk.Label(
cell,
text=str(stats.get(field_key, "--")),
font=("Georgia", 12, "bold"),
fg=ACCENT_GOTH if "streak" in field_key else FG_COLOR,
bg=CELL_BG,
).pack(side="right")
def _switch_tab(self, variant_id: int | None):
if variant_id == self._active_variant_id:

View File

@ -4,29 +4,29 @@ from __future__ import annotations
import json
import tkinter as tk
from tkinter import ttk
from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas, open_goth_modal
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
from games.solitaire.freecell.views.freecell_table_view import FreeCellTableView
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
ACCENT_GOLD,
ACCENT_GOTH,
BG_COLOR,
BORDER_COLOR,
CELL_BG,
ERROR_FG,
FG_COLOR,
FREECELL_VARIANTS,
MODAL_BG,
MUTED_FG,
PANEL_BG,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "solitaire/freecell"
@ -37,9 +37,8 @@ DEFAULT_VARIANT_KEY = "freecell_std"
class FreeCellMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._modal_overlay: tk.Frame | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
def _clear_modal(self):
if self._return_bind_id is not None:
@ -65,7 +64,6 @@ class FreeCellMenuView:
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
prog = self.ctx.refresh_game_progress()
diff_setting_key = f"freecell_diff_{pid}"
@ -96,87 +94,72 @@ class FreeCellMenuView:
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
)
cv = create_menu_body_canvas(self.ctx)
btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14)
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.88, relheight=0.84)
main_card = tk.Frame(
container,
bg=PANEL_BG,
padx=26,
pady=20,
highlightthickness=1,
highlightbackground=BORDER_COLOR,
)
main_card.pack(fill="x")
tk.Label(
main_card,
text=t(GAME_TITLE_KEY),
font=("Georgia", 18, "bold"),
fg=ACCENT_GOLD,
bg=PANEL_BG,
).pack(anchor="w")
tk.Label(
main_card,
text=t("fc_menu_subtitle"),
font=("Helvetica", 10),
fg=MUTED_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(4, 14))
if status_msg:
tk.Label(
main_card,
text=status_msg,
font=("Helvetica", 10, "bold"),
fg="#7be08a" if status_is_ok else ERROR_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(0, 12))
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
saved_meta = self._parse_saved_meta(saved)
resume_btn = None
if saved and saved_meta is not None:
resume_btn = ImageButton(
cv, t("sol_resume_btn"), btn_fire, btn_fire,
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
sound_mgr=self.ctx.sounds, width=190, height=38, style="fire",
resume_box = tk.Frame(
main_card,
bg=CELL_BG,
padx=18,
pady=12,
highlightthickness=1,
highlightbackground=ACCENT_GOTH,
)
resume_box.pack(fill="x", pady=(0, 16))
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
left_info = tk.Frame(resume_box, bg=CELL_BG)
left_info.pack(side="left", fill="x", expand=True)
diff_dd = GothDropdown(
cv,
self.ctx.assets,
values=diff_labels,
textvariable=diff_var,
on_change=lambda val: Database.save_setting(diff_setting_key, str(diff_map.get(val, 1))),
sound_mgr=self.ctx.sounds,
width=420,
height=40,
)
tk.Label(
left_info,
text=t("sol_resume_box_title"),
font=("Georgia", 12, "bold"),
fg=ACCENT_GOTH,
bg=CELL_BG,
).pack(anchor="w")
start_btn = ImageButton(
cv, t("sol_start_btn"), btn_fire, btn_fire,
lambda: self._on_start_clicked(
DEFAULT_VARIANT_KEY, diff_map.get(diff_var.get(), 1), saved, saved_meta
),
sound_mgr=self.ctx.sounds, width=215, height=40, style="fire",
)
def draw_layout(w: int, h: int):
cv._sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
box_w = min(940, w - 120)
cx = w // 2
x_left = cx - box_w // 2
cur_y = max(26, int(h * 0.06))
title_ph = self.ctx.assets.get_goth_text_photo(t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left")
sub_ph = self.ctx.assets.get_goth_text_photo(
t("fc_menu_subtitle"), FONT_SIZE_BODY, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
)
self._photo_refs.extend([title_ph, sub_ph])
cv.create_image(x_left, cur_y, image=title_ph, anchor="nw", tags="fg")
cur_y += title_ph.height() + 4
cv.create_image(x_left, cur_y, image=sub_ph, anchor="nw", tags="fg")
cur_y += sub_ph.height() + 14
if status_msg:
st_ph = self.ctx.assets.get_goth_text_photo(
status_msg, FONT_SIZE_BODY,
FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS,
max_width=box_w, align="left",
)
self._photo_refs.append(st_ph)
cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg")
cur_y += st_ph.height() + 12
if saved and saved_meta is not None and resume_btn is not None:
res_h = 84
res_cy = cur_y + res_h // 2
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, res_h))
if r_box:
self._photo_refs.append(r_box)
cv.create_image(cx, res_cy, image=r_box, anchor="center", tags="fg")
rt_ph = self.ctx.assets.get_goth_text_photo(
t("sol_resume_box_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
)
ri_ph = self.ctx.assets.get_goth_text_photo(
t(
tk.Label(
left_info,
text=t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
@ -184,69 +167,130 @@ class FreeCellMenuView:
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
),
FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=box_w - 250, align="left",
font=("Helvetica", 10),
fg=FG_COLOR,
bg=CELL_BG,
).pack(anchor="w", pady=(4, 0))
ImageButton(
resume_box,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
sound_mgr=self.ctx.sounds,
width=185,
height=36,
font=("Helvetica", 10, "bold"),
).pack(side="right", padx=(12, 0))
tk.Label(
main_card,
text=t("sol_setup_sec_title"),
font=("Georgia", 12, "bold"),
fg=ACCENT_GOTH,
bg=PANEL_BG,
).pack(anchor="w", pady=(2, 8))
setup_box = tk.Frame(
main_card,
bg=CELL_BG,
padx=20,
pady=18,
highlightthickness=1,
highlightbackground=SUBTLE_BORDER,
)
self._photo_refs.extend([rt_ph, ri_ph])
cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg")
cv.create_image(x_left + 26, res_cy + 15, image=ri_ph, anchor="w", tags="fg")
cv.create_window(x_left + box_w - 26, res_cy, window=resume_btn, anchor="e", tags="fg")
cur_y += res_h + 18
setup_box.pack(fill="x")
sec_ph = self.ctx.assets.get_goth_text_photo(
t("sol_setup_sec_title"), FONT_SIZE_HEADING - 2, FONT_COLOR_HEADING_SUB, align="left"
)
self._photo_refs.append(sec_ph)
cv.create_image(x_left + 6, cur_y, image=sec_ph, anchor="nw", tags="fg")
cur_y += sec_ph.height() + 8
# Zeile 1: Modus-Info
mode_row = tk.Frame(setup_box, bg=CELL_BG)
mode_row.pack(fill="x", pady=(0, 12))
setup_h = 205
setup_cy = cur_y + setup_h // 2
s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h))
if s_box:
self._photo_refs.append(s_box)
cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg")
tk.Label(
mode_row,
text=t("fc_variant_info_lbl"),
width=16,
anchor="w",
font=("Helvetica", 10, "bold"),
fg=FG_COLOR,
bg=CELL_BG,
).pack(side="left")
lbl_col = x_left + 32
val_col = x_left + 225
tk.Label(
mode_row,
text=t("variant_freecell_std"),
font=("Georgia", 11, "bold"),
fg=ACCENT_GOLD,
bg=CELL_BG,
).pack(side="left", padx=(0, 14))
# Zeile 1: Modus
r1_y = cur_y + 44
m_lbl = self.ctx.assets.get_goth_text_photo(t("fc_variant_info_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left")
m_val = self.ctx.assets.get_goth_text_photo(t("variant_freecell_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left")
m_dsc = self.ctx.assets.get_goth_text_photo(
t("fc_desc_freecell_std"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
max_width=max(200, box_w - 260 - m_val.width()), align="left",
)
self._photo_refs.extend([m_lbl, m_val, m_dsc])
cv.create_image(lbl_col, r1_y, image=m_lbl, anchor="w", tags="fg")
cv.create_image(val_col, r1_y, image=m_val, anchor="w", tags="fg")
cv.create_image(val_col + m_val.width() + 18, r1_y, image=m_dsc, anchor="w", tags="fg")
tk.Label(
mode_row,
text=t("fc_desc_freecell_std"),
font=("Helvetica", 9),
fg=MUTED_FG,
bg=CELL_BG,
).pack(side="left")
# Zeile 2: Schwierigkeitsgrad
r2_y = cur_y + 102
d_lbl = self.ctx.assets.get_goth_text_photo(t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left")
self._photo_refs.append(d_lbl)
cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg")
diff_row = tk.Frame(setup_box, bg=CELL_BG)
diff_row.pack(fill="x", pady=(0, 16))
dd_w = max(240, box_w - 260)
if diff_dd._width != dd_w:
diff_dd._width = dd_w
diff_dd.configure(width=dd_w)
diff_dd._render_closed()
cv.create_window(val_col, r2_y, window=diff_dd, anchor="w", tags="fg")
tk.Label(
diff_row,
text=t("sol_diff_lbl"),
width=16,
anchor="w",
font=("Helvetica", 10, "bold"),
fg=FG_COLOR,
bg=CELL_BG,
).pack(side="left")
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
diff_cb = ttk.Combobox(
diff_row,
textvariable=diff_var,
values=diff_labels,
state="readonly",
font=("Helvetica", 10),
style="Goth.TCombobox",
)
diff_cb.pack(side="left", fill="x", expand=True, ipady=3)
def on_diff_changed(*_):
chosen = diff_map.get(diff_var.get(), 1)
Database.save_setting(diff_setting_key, str(chosen))
diff_cb.bind("<<ComboboxSelected>>", on_diff_changed)
# Zeile 3: Start
cv.create_window(x_left + box_w - 32, cur_y + setup_h - 38, window=start_btn, anchor="e", tags="fg")
action_row = tk.Frame(setup_box, bg=CELL_BG)
action_row.pack(fill="x")
hint_ph = self.ctx.assets.get_goth_text_photo(
t("fc_controls_hint"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
)
self._photo_refs.append(hint_ph)
cv.create_image(x_left + 6, cur_y + setup_h + 14, image=hint_ph, anchor="nw", tags="fg")
ImageButton(
action_row,
t("sol_start_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._on_start_clicked(
DEFAULT_VARIANT_KEY, diff_map.get(diff_var.get(), 1), saved, saved_meta
),
sound_mgr=self.ctx.sounds,
width=210,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="right")
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
tk.Label(
main_card,
text=t("fc_controls_hint"),
font=("Helvetica", 9),
fg=MUTED_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(14, 0))
if ask_resume_popup and saved and saved_meta is not None:
self._show_resume_prompt_modal(saved, saved_meta)
@ -273,6 +317,43 @@ class FreeCellMenuView:
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
self._clear_modal()
overlay = tk.Frame(
self.ctx.root,
bg=MODAL_BG,
padx=30,
pady=24,
highlightthickness=2,
highlightbackground=ACCENT_GOTH,
)
overlay.place(relx=0.5, rely=0.52, anchor="center")
self._modal_overlay = overlay
tk.Label(
overlay,
text=t("sol_resume_box_title"),
font=("Georgia", 16, "bold"),
fg=ACCENT_GOLD,
bg=MODAL_BG,
).pack(pady=(0, 10))
tk.Label(
overlay,
text=t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
saved_meta["moves"],
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
),
font=("Helvetica", 11),
fg=FG_COLOR,
bg=MODAL_BG,
justify="center",
).pack(pady=(0, 20))
btn_row = tk.Frame(overlay, bg=MODAL_BG)
btn_row.pack()
def resume_now(_event=None):
self._clear_modal()
@ -283,23 +364,29 @@ class FreeCellMenuView:
except tk.TclError:
self._return_bind_id = None
info_txt = t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
saved_meta["moves"],
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
)
self._modal_overlay = open_goth_modal(
self.ctx,
title_txt=t("sol_resume_box_title"),
body_txt=info_txt,
buttons=[
(t("sol_resume_btn"), "fire", resume_now),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
ImageButton(
btn_row,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
resume_now,
sound_mgr=self.ctx.sounds,
width=190,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="left", padx=6)
ImageButton(
btn_row,
t("bj_popup_to_menu_btn"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
self._clear_modal,
sound_mgr=self.ctx.sounds,
width=175,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="left", padx=6)
def _resume_saved(self, saved: dict, difficulty: int):
self._clear_modal()
@ -341,27 +428,87 @@ class FreeCellMenuView:
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
overlay = tk.Frame(
self.ctx.root,
bg=MODAL_BG,
padx=28,
pady=22,
highlightthickness=2,
highlightbackground=ERROR_FG,
)
overlay.place(relx=0.5, rely=0.52, anchor="center")
self._modal_overlay = overlay
tk.Label(
overlay,
text=t("sol_forfeit_title"),
font=("Georgia", 15, "bold"),
fg=ERROR_FG,
bg=MODAL_BG,
).pack(pady=(0, 8))
tk.Label(
overlay,
text=t("sol_forfeit_desc", penalty),
font=("Helvetica", 10),
fg=FG_COLOR,
bg=MODAL_BG,
wraplength=430,
justify="center",
).pack(pady=(0, 18))
row = tk.Frame(overlay, bg=MODAL_BG)
row.pack()
def forfeit_and_start():
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
Database.record_game_result(
pid, variant_key=old_v, won=False, duration_sec=saved_meta["elapsed_sec"], points_gained=0
pid,
variant_key=old_v,
won=False,
duration_sec=saved_meta["elapsed_sec"],
points_gained=0,
)
Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
self.ctx.refresh_game_progress()
self._clear_modal()
self._launch_fresh_game(new_variant_key, new_difficulty)
self._modal_overlay = open_goth_modal(
self.ctx,
title_txt=t("sol_forfeit_title"),
body_txt=t("sol_forfeit_desc", penalty),
is_danger=True,
buttons=[
(t("sol_resume_btn"), "fire", lambda: self._resume_saved(saved, old_diff)),
(t("sol_forfeit_confirm_new"), "amethyst", forfeit_and_start),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
ImageButton(
row,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._resume_saved(saved, old_diff),
sound_mgr=self.ctx.sounds,
width=165,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
ImageButton(
row,
t("sol_forfeit_confirm_new"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
forfeit_and_start,
sound_mgr=self.ctx.sounds,
width=175,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
ImageButton(
row,
t("bj_popup_to_menu_btn"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
self._clear_modal,
sound_mgr=self.ctx.sounds,
width=155,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
def _launch_fresh_game(self, variant_key: str, difficulty: int):
pid = self.ctx.profile["id"]

View File

@ -4,29 +4,29 @@ from __future__ import annotations
import json
import tkinter as tk
from tkinter import ttk
from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas, open_goth_modal
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
from games.solitaire.klondike.views.klondike_table_view import KlondikeTableView
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
ACCENT_GOLD,
ACCENT_GOTH,
BG_COLOR,
BORDER_COLOR,
CELL_BG,
ERROR_FG,
FG_COLOR,
KLONDIKE_VARIANTS,
MODAL_BG,
MUTED_FG,
PANEL_BG,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "solitaire/klondike"
@ -36,9 +36,8 @@ GAME_TITLE_KEY = "game_title_klondike"
class KlondikeMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._modal_overlay: tk.Frame | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
def _clear_modal(self):
if self._return_bind_id is not None:
@ -64,7 +63,6 @@ class KlondikeMenuView:
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
prog = self.ctx.refresh_game_progress()
diff_setting_key = f"klondike_diff_{pid}"
@ -103,110 +101,72 @@ class KlondikeMenuView:
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
)
cv = create_menu_body_canvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14)
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.88, relheight=0.84)
main_card = tk.Frame(
container,
bg=PANEL_BG,
padx=26,
pady=20,
highlightthickness=1,
highlightbackground=BORDER_COLOR,
)
main_card.pack(fill="x")
tk.Label(
main_card,
text=t(GAME_TITLE_KEY),
font=("Georgia", 18, "bold"),
fg=ACCENT_GOLD,
bg=PANEL_BG,
).pack(anchor="w")
tk.Label(
main_card,
text=t("sol_menu_subtitle"),
font=("Helvetica", 10),
fg=MUTED_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(4, 14))
if status_msg:
tk.Label(
main_card,
text=status_msg,
font=("Helvetica", 10, "bold"),
fg="#7be08a" if status_is_ok else ERROR_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(0, 12))
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
saved_meta = self._parse_saved_meta(saved)
resume_btn = None
if saved and saved_meta is not None:
resume_btn = ImageButton(
cv, t("sol_resume_btn"), btn_fire, btn_fire,
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
sound_mgr=self.ctx.sounds, width=190, height=38, style="fire",
resume_box = tk.Frame(
main_card,
bg=CELL_BG,
padx=18,
pady=12,
highlightthickness=1,
highlightbackground=ACCENT_GOTH,
)
resume_box.pack(fill="x", pady=(0, 16))
def switch_draw_mode(v_key: str):
if v_key == selected_variant or self._modal_overlay is not None:
return
Database.save_setting(draw_setting_key, v_key)
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
left_info = tk.Frame(resume_box, bg=CELL_BG)
left_info.pack(side="left", fill="x", expand=True)
draw_btns: list[ImageButton] = []
for v_key, toggle_lbl_key in (("klondike_1", "kl_draw_toggle_1"), ("klondike_3", "kl_draw_toggle_3")):
is_sel = (selected_variant == v_key)
b = ImageButton(
cv,
t(toggle_lbl_key),
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
lambda k=v_key: switch_draw_mode(k),
sound_mgr=self.ctx.sounds,
width=172,
height=36,
style="fire" if is_sel else "amethyst",
)
draw_btns.append(b)
tk.Label(
left_info,
text=t("sol_resume_box_title"),
font=("Georgia", 12, "bold"),
fg=ACCENT_GOTH,
bg=CELL_BG,
).pack(anchor="w")
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
diff_dd = GothDropdown(
cv,
self.ctx.assets,
values=diff_labels,
textvariable=diff_var,
on_change=lambda val: Database.save_setting(diff_setting_key, str(diff_map.get(val, 1))),
sound_mgr=self.ctx.sounds,
width=420,
height=40,
)
start_btn = ImageButton(
cv, t("sol_start_btn"), btn_fire, btn_fire,
lambda: self._on_start_clicked(
selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta
),
sound_mgr=self.ctx.sounds, width=215, height=40, style="fire",
)
def draw_layout(w: int, h: int):
cv._sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
box_w = min(940, w - 120)
cx = w // 2
x_left = cx - box_w // 2
cur_y = max(24, int(h * 0.055))
title_ph = self.ctx.assets.get_goth_text_photo(t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left")
sub_ph = self.ctx.assets.get_goth_text_photo(
t("sol_menu_subtitle"), FONT_SIZE_BODY, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
)
self._photo_refs.extend([title_ph, sub_ph])
cv.create_image(x_left, cur_y, image=title_ph, anchor="nw", tags="fg")
cur_y += title_ph.height() + 4
cv.create_image(x_left, cur_y, image=sub_ph, anchor="nw", tags="fg")
cur_y += sub_ph.height() + 14
if status_msg:
st_ph = self.ctx.assets.get_goth_text_photo(
status_msg, FONT_SIZE_BODY,
FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS,
max_width=box_w, align="left",
)
self._photo_refs.append(st_ph)
cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg")
cur_y += st_ph.height() + 12
if saved and saved_meta is not None and resume_btn is not None:
res_h = 84
res_cy = cur_y + res_h // 2
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, res_h))
if r_box:
self._photo_refs.append(r_box)
cv.create_image(cx, res_cy, image=r_box, anchor="center", tags="fg")
rt_ph = self.ctx.assets.get_goth_text_photo(
t("sol_resume_box_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
)
ri_ph = self.ctx.assets.get_goth_text_photo(
t(
tk.Label(
left_info,
text=t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
@ -214,72 +174,143 @@ class KlondikeMenuView:
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
),
FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=box_w - 250, align="left",
font=("Helvetica", 10),
fg=FG_COLOR,
bg=CELL_BG,
).pack(anchor="w", pady=(4, 0))
ImageButton(
resume_box,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
sound_mgr=self.ctx.sounds,
width=185,
height=36,
font=("Helvetica", 10, "bold"),
).pack(side="right", padx=(12, 0))
tk.Label(
main_card,
text=t("sol_setup_sec_title"),
font=("Georgia", 12, "bold"),
fg=ACCENT_GOTH,
bg=PANEL_BG,
).pack(anchor="w", pady=(2, 8))
setup_box = tk.Frame(
main_card,
bg=CELL_BG,
padx=20,
pady=18,
highlightthickness=1,
highlightbackground=SUBTLE_BORDER,
)
self._photo_refs.extend([rt_ph, ri_ph])
cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg")
cv.create_image(x_left + 26, res_cy + 15, image=ri_ph, anchor="w", tags="fg")
cv.create_window(x_left + box_w - 26, res_cy, window=resume_btn, anchor="e", tags="fg")
cur_y += res_h + 18
setup_box.pack(fill="x")
sec_ph = self.ctx.assets.get_goth_text_photo(
t("sol_setup_sec_title"), FONT_SIZE_HEADING - 2, FONT_COLOR_HEADING_SUB, align="left"
draw_row = tk.Frame(setup_box, bg=CELL_BG)
draw_row.pack(fill="x", pady=(0, 12))
tk.Label(
draw_row,
text=t("sol_draw_mode_lbl"),
width=16,
anchor="w",
font=("Helvetica", 10, "bold"),
fg=FG_COLOR,
bg=CELL_BG,
).pack(side="left")
def switch_draw_mode(v_key: str):
if v_key == selected_variant or self._modal_overlay is not None:
return
Database.save_setting(draw_setting_key, v_key)
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
for v_key, toggle_lbl_key in (("klondike_1", "kl_draw_toggle_1"), ("klondike_3", "kl_draw_toggle_3")):
is_sel = selected_variant == v_key
raw_norm = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel
raw_act = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
ImageButton(
draw_row,
t(toggle_lbl_key),
raw_norm,
raw_act,
lambda k=v_key: switch_draw_mode(k),
sound_mgr=self.ctx.sounds,
width=170,
height=34,
font=("Helvetica", 10, "bold"),
).pack(side="left", padx=(0, 10))
tk.Label(
draw_row,
text=t(f"kl_desc_{selected_variant}"),
font=("Helvetica", 9),
fg=MUTED_FG,
bg=CELL_BG,
).pack(side="left", padx=(8, 0))
diff_row = tk.Frame(setup_box, bg=CELL_BG)
diff_row.pack(fill="x", pady=(0, 16))
tk.Label(
diff_row,
text=t("sol_diff_lbl"),
width=16,
anchor="w",
font=("Helvetica", 10, "bold"),
fg=FG_COLOR,
bg=CELL_BG,
).pack(side="left")
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
diff_cb = ttk.Combobox(
diff_row,
textvariable=diff_var,
values=diff_labels,
state="readonly",
font=("Helvetica", 10),
style="Goth.TCombobox",
)
self._photo_refs.append(sec_ph)
cv.create_image(x_left + 6, cur_y, image=sec_ph, anchor="nw", tags="fg")
cur_y += sec_ph.height() + 8
diff_cb.pack(side="left", fill="x", expand=True, ipady=3)
setup_h = 215
setup_cy = cur_y + setup_h // 2
s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h))
if s_box:
self._photo_refs.append(s_box)
cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg")
def on_diff_changed(*_):
chosen = diff_map.get(diff_var.get(), 1)
Database.save_setting(diff_setting_key, str(chosen))
lbl_col = x_left + 32
val_col = x_left + 225
diff_cb.bind("<<ComboboxSelected>>", on_diff_changed)
# Zeile 1: Zieh-Modus Toggles + Beschreibung
r1_y = cur_y + 46
dm_lbl = self.ctx.assets.get_goth_text_photo(t("sol_draw_mode_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left")
self._photo_refs.append(dm_lbl)
cv.create_image(lbl_col, r1_y, image=dm_lbl, anchor="w", tags="fg")
cv.create_window(val_col, r1_y, window=draw_btns[0], anchor="w", tags="fg")
cv.create_window(val_col + 182, r1_y, window=draw_btns[1], anchor="w", tags="fg")
action_row = tk.Frame(setup_box, bg=CELL_BG)
action_row.pack(fill="x")
dsc_ph = self.ctx.assets.get_goth_text_photo(
t(f"kl_desc_{selected_variant}"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
max_width=max(150, box_w - 225 - 375), align="left",
)
self._photo_refs.append(dsc_ph)
cv.create_image(val_col + 366, r1_y, image=dsc_ph, anchor="w", tags="fg")
ImageButton(
action_row,
t("sol_start_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._on_start_clicked(
selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta
),
sound_mgr=self.ctx.sounds,
width=210,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="right")
# Zeile 2: Schwierigkeitsgrad
r2_y = cur_y + 108
d_lbl = self.ctx.assets.get_goth_text_photo(t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left")
self._photo_refs.append(d_lbl)
cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg")
dd_w = max(240, box_w - 260)
if diff_dd._width != dd_w:
diff_dd._width = dd_w
diff_dd.configure(width=dd_w)
diff_dd._render_closed()
cv.create_window(val_col, r2_y, window=diff_dd, anchor="w", tags="fg")
# Zeile 3: Start
cv.create_window(x_left + box_w - 32, cur_y + setup_h - 38, window=start_btn, anchor="e", tags="fg")
hint_ph = self.ctx.assets.get_goth_text_photo(
t("kl_controls_hint"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
)
self._photo_refs.append(hint_ph)
cv.create_image(x_left + 6, cur_y + setup_h + 14, image=hint_ph, anchor="nw", tags="fg")
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
tk.Label(
main_card,
text=t("kl_controls_hint"),
font=("Helvetica", 9),
fg=MUTED_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(14, 0))
# Direktes Wiederaufnahme-Popup beim Öffnen von Klondike (auch bei 0 Zügen nach Neustart)
if ask_resume_popup and saved and saved_meta is not None:
self._show_resume_prompt_modal(saved, saved_meta)
@ -305,6 +336,43 @@ class KlondikeMenuView:
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
self._clear_modal()
overlay = tk.Frame(
self.ctx.root,
bg=MODAL_BG,
padx=30,
pady=24,
highlightthickness=2,
highlightbackground=ACCENT_GOTH,
)
overlay.place(relx=0.5, rely=0.52, anchor="center")
self._modal_overlay = overlay
tk.Label(
overlay,
text=t("sol_resume_box_title"),
font=("Georgia", 16, "bold"),
fg=ACCENT_GOLD,
bg=MODAL_BG,
).pack(pady=(0, 10))
tk.Label(
overlay,
text=t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
saved_meta["moves"],
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
),
font=("Helvetica", 11),
fg=FG_COLOR,
bg=MODAL_BG,
justify="center",
).pack(pady=(0, 20))
btn_row = tk.Frame(overlay, bg=MODAL_BG)
btn_row.pack()
def resume_now(_event=None):
self._clear_modal()
@ -315,23 +383,29 @@ class KlondikeMenuView:
except tk.TclError:
self._return_bind_id = None
info_txt = t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
saved_meta["moves"],
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
)
self._modal_overlay = open_goth_modal(
self.ctx,
title_txt=t("sol_resume_box_title"),
body_txt=info_txt,
buttons=[
(t("sol_resume_btn"), "fire", resume_now),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
ImageButton(
btn_row,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
resume_now,
sound_mgr=self.ctx.sounds,
width=190,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="left", padx=6)
ImageButton(
btn_row,
t("bj_popup_to_menu_btn"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
self._clear_modal,
sound_mgr=self.ctx.sounds,
width=175,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="left", padx=6)
def _resume_saved(self, saved: dict, difficulty: int):
self._clear_modal()
@ -352,6 +426,7 @@ class KlondikeMenuView:
):
if self._modal_overlay is not None:
return
# Nur wenn bereits Züge gemacht wurden, kostet das Verwerfen XP -> Sicherheitsabfrage
if saved and saved_meta and saved_meta["moves"] > 0:
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
return
@ -373,27 +448,87 @@ class KlondikeMenuView:
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
overlay = tk.Frame(
self.ctx.root,
bg=MODAL_BG,
padx=28,
pady=22,
highlightthickness=2,
highlightbackground=ERROR_FG,
)
overlay.place(relx=0.5, rely=0.52, anchor="center")
self._modal_overlay = overlay
tk.Label(
overlay,
text=t("sol_forfeit_title"),
font=("Georgia", 15, "bold"),
fg=ERROR_FG,
bg=MODAL_BG,
).pack(pady=(0, 8))
tk.Label(
overlay,
text=t("sol_forfeit_desc", penalty),
font=("Helvetica", 10),
fg=FG_COLOR,
bg=MODAL_BG,
wraplength=430,
justify="center",
).pack(pady=(0, 18))
row = tk.Frame(overlay, bg=MODAL_BG)
row.pack()
def forfeit_and_start():
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
Database.record_game_result(
pid, variant_key=old_v, won=False, duration_sec=saved_meta["elapsed_sec"], points_gained=0
pid,
variant_key=old_v,
won=False,
duration_sec=saved_meta["elapsed_sec"],
points_gained=0,
)
Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
self.ctx.refresh_game_progress()
self._clear_modal()
self._launch_fresh_game(new_variant_key, new_difficulty)
self._modal_overlay = open_goth_modal(
self.ctx,
title_txt=t("sol_forfeit_title"),
body_txt=t("sol_forfeit_desc", penalty),
is_danger=True,
buttons=[
(t("sol_resume_btn"), "fire", lambda: self._resume_saved(saved, old_diff)),
(t("sol_forfeit_confirm_new"), "amethyst", forfeit_and_start),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
ImageButton(
row,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._resume_saved(saved, old_diff),
sound_mgr=self.ctx.sounds,
width=165,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
ImageButton(
row,
t("sol_forfeit_confirm_new"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
forfeit_and_start,
sound_mgr=self.ctx.sounds,
width=175,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
ImageButton(
row,
t("bj_popup_to_menu_btn"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
self._clear_modal,
sound_mgr=self.ctx.sounds,
width=155,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
def _launch_fresh_game(self, variant_key: str, difficulty: int):
pid = self.ctx.profile["id"]

View File

@ -4,29 +4,29 @@ from __future__ import annotations
import json
import tkinter as tk
from tkinter import ttk
from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas, open_goth_modal
from games.solitaire.base.solitaire_stats_view import SolitaireStatsView
from games.solitaire.spider_solitaire.views.spider_table_view import SpiderTableView
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
ACCENT_GOLD,
ACCENT_GOTH,
BG_COLOR,
BORDER_COLOR,
CELL_BG,
ERROR_FG,
FG_COLOR,
MODAL_BG,
MUTED_FG,
PANEL_BG,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
SPIDER_VARIANTS,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "solitaire/spider_solitaire"
@ -36,9 +36,8 @@ GAME_TITLE_KEY = "game_title_spider_solitaire"
class SpiderMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._modal_overlay: tk.Frame | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
def _clear_modal(self):
if self._return_bind_id is not None:
@ -64,7 +63,6 @@ class SpiderMenuView:
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
prog = self.ctx.refresh_game_progress()
diff_setting_key = f"spider_diff_{pid}"
@ -103,115 +101,72 @@ class SpiderMenuView:
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
)
cv = create_menu_body_canvas(self.ctx)
btn_norm = self.ctx.assets.raw_btn_default
btn_purp = self.ctx.assets.raw_btn_purple
btn_fire = self.ctx.assets.raw_btn_fire or btn_purp
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14)
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.88, relheight=0.84)
main_card = tk.Frame(
container,
bg=PANEL_BG,
padx=26,
pady=20,
highlightthickness=1,
highlightbackground=BORDER_COLOR,
)
main_card.pack(fill="x")
tk.Label(
main_card,
text=t(GAME_TITLE_KEY),
font=("Georgia", 18, "bold"),
fg=ACCENT_GOLD,
bg=PANEL_BG,
).pack(anchor="w")
tk.Label(
main_card,
text=t("sp_menu_subtitle"),
font=("Helvetica", 10),
fg=MUTED_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(4, 14))
if status_msg:
tk.Label(
main_card,
text=status_msg,
font=("Helvetica", 10, "bold"),
fg="#7be08a" if status_is_ok else ERROR_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(0, 12))
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
saved_meta = self._parse_saved_meta(saved)
resume_btn = None
if saved and saved_meta is not None:
resume_btn = ImageButton(
cv, t("sol_resume_btn"), btn_fire, btn_fire,
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
sound_mgr=self.ctx.sounds, width=190, height=38, style="fire",
resume_box = tk.Frame(
main_card,
bg=CELL_BG,
padx=18,
pady=12,
highlightthickness=1,
highlightbackground=ACCENT_GOTH,
)
resume_box.pack(fill="x", pady=(0, 16))
def switch_suit_mode(v_key: str):
if v_key == selected_variant or self._modal_overlay is not None:
return
Database.save_setting(var_setting_key, v_key)
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
left_info = tk.Frame(resume_box, bg=CELL_BG)
left_info.pack(side="left", fill="x", expand=True)
suit_btns: list[ImageButton] = []
suit_toggles = (
("spider_1suit", "sp_suit_toggle_1"),
("spider_2suit", "sp_suit_toggle_2"),
("spider_4suit", "sp_suit_toggle_4"),
)
for v_key, lbl_key in suit_toggles:
is_sel = (selected_variant == v_key)
b = ImageButton(
cv,
t(lbl_key),
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
lambda k=v_key: switch_suit_mode(k),
sound_mgr=self.ctx.sounds,
width=168,
height=36,
style="fire" if is_sel else "amethyst",
)
suit_btns.append(b)
tk.Label(
left_info,
text=t("sol_resume_box_title"),
font=("Georgia", 12, "bold"),
fg=ACCENT_GOTH,
bg=CELL_BG,
).pack(anchor="w")
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
diff_dd = GothDropdown(
cv,
self.ctx.assets,
values=diff_labels,
textvariable=diff_var,
on_change=lambda val: Database.save_setting(diff_setting_key, str(diff_map.get(val, 1))),
sound_mgr=self.ctx.sounds,
width=420,
height=40,
)
start_btn = ImageButton(
cv, t("sol_start_btn"), btn_fire, btn_fire,
lambda: self._on_start_clicked(
selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta
),
sound_mgr=self.ctx.sounds, width=215, height=40, style="fire",
)
def draw_layout(w: int, h: int):
cv._sync_bg(w, h) # type: ignore[attr-defined]
cv.delete("fg")
self._photo_refs.clear()
box_w = min(940, w - 120)
cx = w // 2
x_left = cx - box_w // 2
cur_y = max(22, int(h * 0.05))
title_ph = self.ctx.assets.get_goth_text_photo(t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left")
sub_ph = self.ctx.assets.get_goth_text_photo(
t("sp_menu_subtitle"), FONT_SIZE_BODY, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
)
self._photo_refs.extend([title_ph, sub_ph])
cv.create_image(x_left, cur_y, image=title_ph, anchor="nw", tags="fg")
cur_y += title_ph.height() + 4
cv.create_image(x_left, cur_y, image=sub_ph, anchor="nw", tags="fg")
cur_y += sub_ph.height() + 12
if status_msg:
st_ph = self.ctx.assets.get_goth_text_photo(
status_msg, FONT_SIZE_BODY,
FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS,
max_width=box_w, align="left",
)
self._photo_refs.append(st_ph)
cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg")
cur_y += st_ph.height() + 10
if saved and saved_meta is not None and resume_btn is not None:
res_h = 82
res_cy = cur_y + res_h // 2
r_box = self.ctx.assets.get_box_photo("box_gold_double", (box_w, res_h))
if r_box:
self._photo_refs.append(r_box)
cv.create_image(cx, res_cy, image=r_box, anchor="center", tags="fg")
rt_ph = self.ctx.assets.get_goth_text_photo(
t("sol_resume_box_title"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
)
ri_ph = self.ctx.assets.get_goth_text_photo(
t(
tk.Label(
left_info,
text=t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
@ -219,71 +174,153 @@ class SpiderMenuView:
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
),
FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=box_w - 250, align="left",
font=("Helvetica", 10),
fg=FG_COLOR,
bg=CELL_BG,
).pack(anchor="w", pady=(4, 0))
ImageButton(
resume_box,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._resume_saved(saved, saved_meta["difficulty"]),
sound_mgr=self.ctx.sounds,
width=185,
height=36,
font=("Helvetica", 10, "bold"),
).pack(side="right", padx=(12, 0))
tk.Label(
main_card,
text=t("sol_setup_sec_title"),
font=("Georgia", 12, "bold"),
fg=ACCENT_GOTH,
bg=PANEL_BG,
).pack(anchor="w", pady=(2, 8))
setup_box = tk.Frame(
main_card,
bg=CELL_BG,
padx=20,
pady=18,
highlightthickness=1,
highlightbackground=SUBTLE_BORDER,
)
self._photo_refs.extend([rt_ph, ri_ph])
cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg")
cv.create_image(x_left + 26, res_cy + 15, image=ri_ph, anchor="w", tags="fg")
cv.create_window(x_left + box_w - 26, res_cy, window=resume_btn, anchor="e", tags="fg")
cur_y += res_h + 16
setup_box.pack(fill="x")
sec_ph = self.ctx.assets.get_goth_text_photo(
t("sol_setup_sec_title"), FONT_SIZE_HEADING - 2, FONT_COLOR_HEADING_SUB, align="left"
# Zeile 1: 1 / 2 / 4 Farben Direkt-Umschalter
suit_row = tk.Frame(setup_box, bg=CELL_BG)
suit_row.pack(fill="x", pady=(0, 8))
tk.Label(
suit_row,
text=t("sp_suit_mode_lbl"),
width=16,
anchor="w",
font=("Helvetica", 10, "bold"),
fg=FG_COLOR,
bg=CELL_BG,
).pack(side="left")
def switch_suit_mode(v_key: str):
if v_key == selected_variant or self._modal_overlay is not None:
return
Database.save_setting(var_setting_key, v_key)
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
suit_toggles = (
("spider_1suit", "sp_suit_toggle_1"),
("spider_2suit", "sp_suit_toggle_2"),
("spider_4suit", "sp_suit_toggle_4"),
)
self._photo_refs.append(sec_ph)
cv.create_image(x_left + 6, cur_y, image=sec_ph, anchor="nw", tags="fg")
cur_y += sec_ph.height() + 8
for v_key, lbl_key in suit_toggles:
is_sel = selected_variant == v_key
raw_norm = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel
raw_act = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
ImageButton(
suit_row,
t(lbl_key),
raw_norm,
raw_act,
lambda k=v_key: switch_suit_mode(k),
sound_mgr=self.ctx.sounds,
width=165,
height=34,
font=("Helvetica", 10, "bold"),
).pack(side="left", padx=(0, 10))
setup_h = 240
setup_cy = cur_y + setup_h // 2
s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h))
if s_box:
self._photo_refs.append(s_box)
cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg")
lbl_col = x_left + 32
val_col = x_left + 225
# Zeile 1: 1 / 2 / 4 Farben Toggles + Kurzbeschreibung darunter
r1_y = cur_y + 44
sm_lbl = self.ctx.assets.get_goth_text_photo(t("sp_suit_mode_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left")
self._photo_refs.append(sm_lbl)
cv.create_image(lbl_col, r1_y, image=sm_lbl, anchor="w", tags="fg")
for idx, sb in enumerate(suit_btns):
cv.create_window(val_col + idx * 178, r1_y, window=sb, anchor="w", tags="fg")
dsc_ph = self.ctx.assets.get_goth_text_photo(
t(f"sp_desc_{selected_variant}"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
max_width=box_w - 260, align="left",
)
self._photo_refs.append(dsc_ph)
cv.create_image(val_col, r1_y + 34, image=dsc_ph, anchor="w", tags="fg")
# Kurze Infozeile zur gewählten Farb-Variante
desc_row = tk.Frame(setup_box, bg=CELL_BG)
desc_row.pack(fill="x", pady=(0, 12))
tk.Label(desc_row, text="", width=16, bg=CELL_BG).pack(side="left")
tk.Label(
desc_row,
text=t(f"sp_desc_{selected_variant}"),
font=("Helvetica", 9),
fg=MUTED_FG,
bg=CELL_BG,
).pack(side="left")
# Zeile 2: Schwierigkeitsgrad
r2_y = cur_y + 128
d_lbl = self.ctx.assets.get_goth_text_photo(t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left")
self._photo_refs.append(d_lbl)
cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg")
diff_row = tk.Frame(setup_box, bg=CELL_BG)
diff_row.pack(fill="x", pady=(0, 16))
dd_w = max(240, box_w - 260)
if diff_dd._width != dd_w:
diff_dd._width = dd_w
diff_dd.configure(width=dd_w)
diff_dd._render_closed()
cv.create_window(val_col, r2_y, window=diff_dd, anchor="w", tags="fg")
tk.Label(
diff_row,
text=t("sol_diff_lbl"),
width=16,
anchor="w",
font=("Helvetica", 10, "bold"),
fg=FG_COLOR,
bg=CELL_BG,
).pack(side="left")
diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())]
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())}
diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}"))
diff_cb = ttk.Combobox(
diff_row,
textvariable=diff_var,
values=diff_labels,
state="readonly",
font=("Helvetica", 10),
style="Goth.TCombobox",
)
diff_cb.pack(side="left", fill="x", expand=True, ipady=3)
def on_diff_changed(*_):
chosen = diff_map.get(diff_var.get(), 1)
Database.save_setting(diff_setting_key, str(chosen))
diff_cb.bind("<<ComboboxSelected>>", on_diff_changed)
# Zeile 3: Start
cv.create_window(x_left + box_w - 32, cur_y + setup_h - 38, window=start_btn, anchor="e", tags="fg")
action_row = tk.Frame(setup_box, bg=CELL_BG)
action_row.pack(fill="x")
hint_ph = self.ctx.assets.get_goth_text_photo(
t("sp_controls_hint"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left"
)
self._photo_refs.append(hint_ph)
cv.create_image(x_left + 6, cur_y + setup_h + 12, image=hint_ph, anchor="nw", tags="fg")
ImageButton(
action_row,
t("sol_start_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._on_start_clicked(
selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta
),
sound_mgr=self.ctx.sounds,
width=210,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="right")
cv.bind("<Configure>", lambda e: draw_layout(e.width, e.height) if e.width >= 200 else None)
self.ctx.root.update_idletasks()
draw_layout(max(900, cv.winfo_width()), max(620, cv.winfo_height()))
tk.Label(
main_card,
text=t("sp_controls_hint"),
font=("Helvetica", 9),
fg=MUTED_FG,
bg=PANEL_BG,
).pack(anchor="w", pady=(14, 0))
if ask_resume_popup and saved and saved_meta is not None:
self._show_resume_prompt_modal(saved, saved_meta)
@ -310,6 +347,43 @@ class SpiderMenuView:
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
self._clear_modal()
overlay = tk.Frame(
self.ctx.root,
bg=MODAL_BG,
padx=30,
pady=24,
highlightthickness=2,
highlightbackground=ACCENT_GOTH,
)
overlay.place(relx=0.5, rely=0.52, anchor="center")
self._modal_overlay = overlay
tk.Label(
overlay,
text=t("sol_resume_box_title"),
font=("Georgia", 16, "bold"),
fg=ACCENT_GOLD,
bg=MODAL_BG,
).pack(pady=(0, 10))
tk.Label(
overlay,
text=t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
saved_meta["moves"],
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
),
font=("Helvetica", 11),
fg=FG_COLOR,
bg=MODAL_BG,
justify="center",
).pack(pady=(0, 20))
btn_row = tk.Frame(overlay, bg=MODAL_BG)
btn_row.pack()
def resume_now(_event=None):
self._clear_modal()
@ -320,23 +394,29 @@ class SpiderMenuView:
except tk.TclError:
self._return_bind_id = None
info_txt = t(
"sol_resume_info",
t(f"variant_{saved['variant_key']}"),
t(f"sol_diff_short_{saved_meta['difficulty']}"),
saved_meta["moves"],
saved_meta["score"],
Database.format_seconds(saved_meta["elapsed_sec"]),
)
self._modal_overlay = open_goth_modal(
self.ctx,
title_txt=t("sol_resume_box_title"),
body_txt=info_txt,
buttons=[
(t("sol_resume_btn"), "fire", resume_now),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
ImageButton(
btn_row,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
resume_now,
sound_mgr=self.ctx.sounds,
width=190,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="left", padx=6)
ImageButton(
btn_row,
t("bj_popup_to_menu_btn"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
self._clear_modal,
sound_mgr=self.ctx.sounds,
width=175,
height=38,
font=("Helvetica", 10, "bold"),
).pack(side="left", padx=6)
def _resume_saved(self, saved: dict, difficulty: int):
self._clear_modal()
@ -378,27 +458,87 @@ class SpiderMenuView:
win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult)
penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
overlay = tk.Frame(
self.ctx.root,
bg=MODAL_BG,
padx=28,
pady=22,
highlightthickness=2,
highlightbackground=ERROR_FG,
)
overlay.place(relx=0.5, rely=0.52, anchor="center")
self._modal_overlay = overlay
tk.Label(
overlay,
text=t("sol_forfeit_title"),
font=("Georgia", 15, "bold"),
fg=ERROR_FG,
bg=MODAL_BG,
).pack(pady=(0, 8))
tk.Label(
overlay,
text=t("sol_forfeit_desc", penalty),
font=("Helvetica", 10),
fg=FG_COLOR,
bg=MODAL_BG,
wraplength=430,
justify="center",
).pack(pady=(0, 18))
row = tk.Frame(overlay, bg=MODAL_BG)
row.pack()
def forfeit_and_start():
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
Database.record_game_result(
pid, variant_key=old_v, won=False, duration_sec=saved_meta["elapsed_sec"], points_gained=0
pid,
variant_key=old_v,
won=False,
duration_sec=saved_meta["elapsed_sec"],
points_gained=0,
)
Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp)
self.ctx.refresh_game_progress()
self._clear_modal()
self._launch_fresh_game(new_variant_key, new_difficulty)
self._modal_overlay = open_goth_modal(
self.ctx,
title_txt=t("sol_forfeit_title"),
body_txt=t("sol_forfeit_desc", penalty),
is_danger=True,
buttons=[
(t("sol_resume_btn"), "fire", lambda: self._resume_saved(saved, old_diff)),
(t("sol_forfeit_confirm_new"), "amethyst", forfeit_and_start),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
ImageButton(
row,
t("sol_resume_btn"),
self.ctx.assets.raw_btn,
self.ctx.assets.raw_btn_active,
lambda: self._resume_saved(saved, old_diff),
sound_mgr=self.ctx.sounds,
width=165,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
ImageButton(
row,
t("sol_forfeit_confirm_new"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
forfeit_and_start,
sound_mgr=self.ctx.sounds,
width=175,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
ImageButton(
row,
t("bj_popup_to_menu_btn"),
self.ctx.assets.raw_sel,
self.ctx.assets.raw_sel_active,
self._clear_modal,
sound_mgr=self.ctx.sounds,
width=155,
height=34,
font=("Helvetica", 9, "bold"),
).pack(side="left", padx=5)
def _launch_fresh_game(self, variant_key: str, difficulty: int):
pid = self.ctx.profile["id"]

93
main.py
View File

@ -4,16 +4,12 @@ import signal
import subprocess
import sys
import tempfile
import tkinter as tk
import warnings
from pathlib import Path
from PIL import Image, ImageTk
# Unterdrückt die "Hello from the pygame community"-Konsole beim Start
os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
if sys.platform.startswith("linux"):
# Entspannt PulseAudio/CRAS-Pufferung unter Linux & ChromeOS (Crostini) gegen krakeligen Ton
os.environ.setdefault("PULSE_LATENCY_MSEC", "80")
import pygame
@ -24,33 +20,7 @@ from view.font_loader import FontLoader
from view.main_window import GothCardCollectionView
from view.window_state import WindowStatePersistence
# Oben in view/main_window.py:
APP_WM_CLASS = "TheGothCardgameCollection"
def _install_linux_label_descent_fix():
"""
Xft/FreeType unter Linux & Crostini meldet für Zierschriften (wie OldLondon) zu knappe
Unterlängen (descent), wodurch Buchstaben wie g, j, p, y unten abgeschnitten werden.
Sorgt bei reinen Text-Labels auf Linux automatisch für minimalen vertikalen Innenabstand.
"""
if not sys.platform.startswith("linux") or getattr(tk.Label, "_goth_descent_patched", False):
return
orig_init = tk.Label.__init__
def _patched_label_init(self, master=None, cnf={}, **kw):
has_image = ("image" in kw and kw["image"] is not None) or (isinstance(cnf, dict) and cnf.get("image"))
if not has_image:
cur_pady = kw.get("pady", cnf.get("pady") if isinstance(cnf, dict) else None)
if cur_pady is None:
kw["pady"] = 3
elif isinstance(cur_pady, int) and cur_pady < 3:
kw["pady"] = 3
orig_init(self, master, cnf, **kw)
tk.Label.__init__ = _patched_label_init
tk.Label._goth_descent_patched = True
APP_WM_CLASS = "goth-cardgame-collection"
def _prepare_os_app_identity():
@ -63,6 +33,7 @@ def _prepare_os_app_identity():
except Exception:
pass
elif sys.platform.startswith("linux"):
# Hilft X11/Tkinter bereits vor Fenstererstellung bei der Ressourcen-Zuordnung
os.environ.setdefault("RESOURCE_NAME", APP_WM_CLASS)
try:
import ctypes
@ -71,20 +42,6 @@ def _prepare_os_app_identity():
except Exception:
pass
# Audio-Pre-Init vor jeglicher Pygame-Initialisierung setzen
try:
is_linux = sys.platform.startswith("linux")
is_cros = is_linux and (
Path("/dev/.cros_milestone").exists()
or "sommelier" in os.environ.get("XDG_RUNTIME_DIR", "").lower()
or Path("/opt/google/cros-containers").exists()
)
freq = 48000 if is_linux else 44100
buf_size = 8192 if is_cros else (4096 if is_linux else 1024)
pygame.mixer.pre_init(frequency=freq, size=-16, channels=2, buffer=buf_size)
except Exception:
pass
def _extract_ico_frames(icon_path: Path) -> tuple[Image.Image | None, list[Image.Image]]:
"""Liest das größte Bild aus game_icon.ico (auch wenn es intern PNG/JPEG/BMP-codiert ist)."""
@ -134,8 +91,9 @@ def _extract_ico_frames(icon_path: Path) -> tuple[Image.Image | None, list[Image
def ensure_crostini_shelf_icon(icon_ico_path: Path, wm_class: str = APP_WM_CLASS) -> None:
"""
Registriert unter ChromeOS (Crostini) Icon & .desktop mit absolutem PNG-Pfad
und exakter Groß-/Kleinschreibung passend zu Tkinters X11 WM_CLASS.
Erzeugt unter ChromeOS (Crostini) vollautomatisch im User-Verzeichnis (~/.local)
ein PNG-Icon + .desktop-Zuordnung für den garcon-Daemon, damit das Shelf-Icon
ohne manuelle System-Installation statt eines grauen Kastens erscheint.
"""
if not sys.platform.startswith("linux"):
return
@ -151,59 +109,37 @@ def ensure_crostini_shelf_icon(icon_ico_path: Path, wm_class: str = APP_WM_CLASS
try:
data_home = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
apps_dir = data_home / "applications"
pixmaps_dir = data_home / "pixmaps"
desktop_id = wm_class.lower()
# Alte Fehlversuchs-Dateien aufräumen, damit garcon nicht verwirrt wird
for stale in ("goth-cardgame-collection.desktop", "thegothcardgamecollection.desktop"):
stale_p = apps_dir / stale
if stale != f"{desktop_id}.desktop" and stale_p.is_file():
stale_p.unlink(missing_ok=True)
desktop_file = apps_dir / f"{wm_class}.desktop"
best_pil, _ = _extract_ico_frames(icon_ico_path)
if best_pil is None:
return
# 1. Direkt in pixmaps + hicolor speichern & absoluten Pfad nutzen (umgeht fehlenden Icon-Cache!)
pixmaps_dir.mkdir(parents=True, exist_ok=True)
abs_icon_png = pixmaps_dir / f"{desktop_id}.png"
best_pil.resize((128, 128), Image.Resampling.LANCZOS).save(abs_icon_png, format="PNG")
if best_pil is not None:
for px in (128, 64, 48):
icon_dir = data_home / "icons" / "hicolor" / f"{px}x{px}" / "apps"
icon_png = icon_dir / f"{wm_class}.png"
if not icon_png.is_file():
icon_dir.mkdir(parents=True, exist_ok=True)
best_pil.resize((px, px), Image.Resampling.LANCZOS).save(
icon_dir / f"{desktop_id}.png", format="PNG"
)
best_pil.resize((px, px), Image.Resampling.LANCZOS).save(icon_png, format="PNG")
if getattr(sys, "frozen", False):
exec_cmd = f'"{Path(sys.executable).resolve()}"'
else:
exec_cmd = f'"{sys.executable}" "{Path(sys.argv[0]).resolve()}"'
# StartupWMClass MUSS exakt "TheGothCardgameCollection" sein (Tkinter großgeschrieben!)
desktop_content = (
"[Desktop Entry]\n"
"Version=1.0\n"
"Type=Application\n"
"Name=The Goth Cardgame Collection\n"
f"Exec={exec_cmd}\n"
f"Icon={abs_icon_png}\n"
f"Icon={wm_class}\n"
f"StartupWMClass={wm_class}\n"
"Categories=Game;CardGame;\n"
"Terminal=false\n"
)
apps_dir.mkdir(parents=True, exist_ok=True)
desktop_file = apps_dir / f"{desktop_id}.desktop"
if not desktop_file.is_file() or desktop_file.read_text(encoding="utf-8") != desktop_content:
apps_dir.mkdir(parents=True, exist_ok=True)
desktop_file.write_text(desktop_content, encoding="utf-8")
subprocess.run(
["update-desktop-database", str(apps_dir)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
except Exception:
pass
@ -285,6 +221,7 @@ def _apply_cross_platform_icon(app, root_path: Path):
app.tk.call("tk", "appname", APP_WM_CLASS)
except Exception:
pass
# Erzwingt die exakte X11 WM_CLASS am Top-Level-Fenster für Sommelier/Wayland
try:
app.update_idletasks()
subprocess.run(
@ -319,6 +256,7 @@ def _apply_cross_platform_icon(app, root_path: Path):
if cascade_pils:
try:
# Unter Linux/XWayland max. 128x128 übergeben, da 256x256 in _NET_WM_ICON oft grau wird
usable_pils = (
[im for im in cascade_pils if im.width <= 128]
if sys.platform.startswith("linux")
@ -436,10 +374,9 @@ def _install_clean_shutdown(app: GothCardCollectionView):
def main():
_prepare_os_app_identity()
_install_linux_label_descent_fix()
root_path = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
# Vor dem Erstellen des Tk-Fensters aufrufen, damit garcon das Icon bereits kennt!
ensure_crostini_shelf_icon((root_path / APP_ICON_REL_PATH).resolve(), APP_WM_CLASS)
FontLoader.register_fonts(root_path)

View File

@ -1,19 +1,12 @@
# -*- coding: utf-8 -*-
# models/sound_manager.py
import os
import sys
from pathlib import Path
from models.database import Database
from resources.code_res.game_constants import (
DEFAULT_VOL_AMBIANCE, DEFAULT_VOL_MENU,
INGAME_MUSIC_FILE, MENU_MUSIC_FILE, SOUND_MAP
)
if sys.platform.startswith("linux"):
# Verhindert Audio-Stottern / Knacksen in VM- & Container-Umgebungen (insb. ChromeOS Crostini)
os.environ.setdefault("PULSE_LATENCY_MSEC", "80")
try:
import pygame
PYGAME_AVAILABLE = True
@ -21,16 +14,6 @@ except ImportError:
PYGAME_AVAILABLE = False
def _is_crostini_env() -> bool:
if not sys.platform.startswith("linux"):
return False
return (
Path("/dev/.cros_milestone").exists()
or "sommelier" in os.environ.get("XDG_RUNTIME_DIR", "").lower()
or Path("/opt/google/cros-containers").exists()
)
class SoundManager:
def __init__(self, sounds_dir: Path):
self.ambiance_dir = sounds_dir / "ambiance"
@ -44,25 +27,8 @@ class SoundManager:
self._ready = False
if PYGAME_AVAILABLE:
self._init_mixer()
def _init_mixer(self):
is_linux = sys.platform.startswith("linux")
is_cros = _is_crostini_env()
# ChromeOS CRAS arbeitet nativ mit 48 kHz und benötigt über die VM-Grenze einen großen Puffer
freq = 48000 if is_linux else 44100
buf_size = 8192 if is_cros else (4096 if is_linux else 1024)
try:
if pygame.mixer.get_init():
pygame.mixer.quit()
pygame.mixer.pre_init(frequency=freq, size=-16, channels=2, buffer=buf_size)
pygame.mixer.init(frequency=freq, size=-16, channels=2, buffer=buf_size)
self._ready = True
except Exception:
try:
pygame.mixer.init()
pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=512)
self._ready = True
except Exception:
self._ready = False

View File

@ -1,59 +1,6 @@
# -*- coding: utf-8 -*-
# resources/code_res/game_constants.py
from resources.code_res.ui_typography import (
BTN_AMETHYST_TEXT_ACTIVE,
BTN_AMETHYST_TEXT_DISABLED,
BTN_AMETHYST_TEXT_HOVER,
BTN_AMETHYST_TEXT_NORMAL,
BTN_FIRE_TEXT_ACTIVE,
BTN_FIRE_TEXT_DISABLED,
BTN_FIRE_TEXT_HOVER,
BTN_FIRE_TEXT_NORMAL,
DROPDOWN_ITEM_TEXT_HOVER,
DROPDOWN_ITEM_TEXT_NORMAL,
DROPDOWN_ITEM_TEXT_SELECTED,
DROPDOWN_TEXT_CLOSED,
FONT_ANTIALIAS,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_DISABLED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WARN,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_FAMILY_ALTERNATE,
FONT_FAMILY_PRIMARY,
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_SHADOW_OFFSET_SMALL,
FONT_SIZE_BODY,
FONT_SIZE_BUTTON,
FONT_SIZE_DROPDOWN,
FONT_SIZE_HEADING,
FONT_SIZE_INPUT,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
FONT_SIZE_TITLE_XL,
FONT_VERTICAL_OFFSET_PX,
INPUT_CARET_COLOR,
INPUT_SELECTION_BG,
INPUT_TEXT_PLACEHOLDER,
INPUT_TEXT_VALUE,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
UI_BG_DARK,
)
# --- Dateien & Verzeichnisse ---
INTERNAL_DB_REL_PATH = "resources/code_res/internal_base.db"
USER_DB_FILENAME = "user_data.db"
@ -61,47 +8,15 @@ GAMES_ROOT_DIR = "games"
ENTRY_FILENAME = "start.py"
DEFAULT_CARD_THEME = "default"
# --- Neue UI-Grafiken in resources/images/ (inkl. abwärtskompatibler Aliase) ---
UI_IMAGES = {
# Hintergründe (Quer- & Hochformat)
"bg_horizontal": "background_horizontal.jpg",
"bg_vertical": "background_vertical.jpg",
"background": "background_horizontal.jpg", # Legacy-Alias
# Banner & Spieltische
"title": "title.png",
"background": "background.jpeg",
"title": "title.jpg",
"general_table": "general_table.jpg",
"poker_table": "poker_table.jpg",
"game_icon_art": "game_icon.jpg",
# Buttons (Normal, Amethyst-Hover, Feuer-Highlight)
"btn_default": "button.png",
"btn_purple": "button_highlighted_purple.png",
"btn_fire": "button_highlighted_fire.png",
# Legacy-Button-Aliase (zeigen direkt auf die neuen Button-Grafiken)
"btn_normal": "button_highlighted_fire.png",
"btn_active": "button_highlighted_fire.png",
"sel_inactive": "button.png",
"sel_active": "button_highlighted_purple.png",
# Transparente Zierrahmen (ersetzen selbst gezeichnete Frame-Ränder!)
"box_big": "box_big.png",
"box_gold_small": "box_gold_smal.png", # Dateiname exakt: box_gold_smal.png
"box_gold_double": "box_gold_small_double.png",
"box_purple": "box_small_purple.png",
"card_frame": "box_big.png", # Legacy-Alias
# Formular-Elemente (Input & geteiltes Dropdown)
"input_field": "input.png",
"dropdown_closed": "dropdown_closed.png",
"dropdown_closed_btn": "dropdown_closed_button.png",
"dropdown_open": "dropdown_box_hightlighted.png",
"dropdown_open_btn": "dropdown_box_hightlighted_button.png",
"dropdown_box": "dropdown_box.png",
"dropdown_selection": "dropdown_selection.png",
# Animationen
"btn_normal": "button1.png",
"btn_active": "button1_active.png",
"sel_inactive": "selection_inactive.png",
"sel_active": "selection_active.png",
"card_frame": "chat_window.png",
"win_gif": "win.gif",
"lose_gif": "lose.gif",
}
@ -115,22 +30,20 @@ GAME_ICON_MAP = {
"solitaire/klondike": "klondike_icon.ico",
"solitaire/freecell": "freecell_icon.ico",
"solitaire/spider_solitaire": "spider_icon.ico",
"solitaire/pyramid": "pyramid_icon.ico",
"solitaire/tripeaks": "tripeaks_icon.ico",
"romme": "romme_icon.ico",
"party/romme": "romme_icon.ico",
}
FONTS_REL_DIR = "resources/fonts"
CUSTOM_FONT_FILES = (
FONT_FILE_PRIMARY,
FONT_FILE_ALTERNATE,
"OldLondon.ttf",
"OldLondonAlternate.ttf",
)
# Einheitlich Old London für die gesamte UI
FONT_GOTH_TITLE = FONT_FAMILY_PRIMARY
FONT_GOTH_ALT = FONT_FAMILY_ALTERNATE
FONT_UI_BODY = FONT_FAMILY_PRIMARY
# Interne Familiennamen aus den TTF-Metadaten (+ Fallback)
FONT_GOTH_TITLE = "Old London"
FONT_GOTH_ALT = "Old London Alternate"
FONT_UI_BODY = "Helvetica"
# --- Flache Hauptkategorien (niemals Unterkategorien!) ---
CAT_LUCK = "luck"
@ -296,7 +209,7 @@ PK_VARIANTS = {
}
# --- Solitaire & Klondike ---
SOLO_FORFEIT_XP_RATIO = 0.40
SOLO_FORFEIT_XP_RATIO = 0.40 # XP-Abzug beim Aufgeben einer laufenden Solo-Runde
SOLITAIRE_DIFFICULTIES = {
0: {"key": "easy", "xp_mult": 0.85, "redeal_limit_d3": None},
@ -348,7 +261,7 @@ SPIDER_VARIANTS = {
},
}
# --- UI Geometrie ---
# --- UI Theme & Geometrie ---
DEFAULT_WINDOW_GEOM = "1150x800"
MIN_WINDOW_SIZE = (980, 700)
MENU_CARD_SIZE = (185, 245)
@ -359,21 +272,16 @@ PK_BOARD_CARD_SIZE = (88, 128)
PK_BOT_CARD_SIZE = (54, 80)
OUTCOME_GIF_SIZE = (170, 95)
# --- Farb-Aliase auf Basis von ui_typography.py ---
BG_COLOR = UI_BG_DARK
PANEL_BG = UI_BG_DARK # Keine grauen Kästen mehr über dem Hintergrund
CELL_BG = UI_BG_DARK
TABLE_BG = UI_BG_DARK
MODAL_BG = "#09070d"
INPUT_BG = "#120e1a"
BORDER_COLOR = UI_ACCENT_AMETHYST
SUBTLE_BORDER = "#2d243b"
FG_COLOR = FONT_COLOR_BODY_DEFAULT
MUTED_FG = FONT_COLOR_BODY_MUTED
SUCCESS_FG = FONT_COLOR_STATUS_WIN
WARN_FG = FONT_COLOR_STATUS_WARN
ERROR_FG = FONT_COLOR_STATUS_LOSS
DISABLED_FG = FONT_COLOR_DISABLED
ACCENT_GOTH = UI_ACCENT_AMETHYST
ACCENT_GOLD = UI_ACCENT_GOLD
TITLE_GOLD_FG = FONT_COLOR_TITLE_MAIN
BG_COLOR = "#0d0b12"
PANEL_BG = "#1b1821"
CELL_BG = "#24202c"
TABLE_BG = "#17141d"
MODAL_BG = "#0b090e"
INPUT_BG = "#1e1b24"
BORDER_COLOR = "#4a3f5c"
SUBTLE_BORDER = "#362f42"
FG_COLOR = "#e6e1ec"
MUTED_FG = "#aaa2b8"
ERROR_FG = "#ff7b7b"
ACCENT_GOTH = "#b388eb"
ACCENT_GOLD = "#d4af37"

View File

@ -1,77 +0,0 @@
# -*- coding: utf-8 -*-
# resources/code_res/ui_typography.py
# ==============================================================================
# GOTHIC UI TYPOGRAPHY & COLOR CONFIG (Old London)
# ==============================================================================
# --- Font Dateien & Familiennamen ---
FONT_FILE_PRIMARY = "OldLondon.ttf"
FONT_FILE_ALTERNATE = "OldLondonAlternate.ttf"
FONT_FAMILY_PRIMARY = "Old London"
FONT_FAMILY_ALTERNATE = "Old London Alternate"
# --- Basis- & Hintergrundfarben (Referenz für Kontrast & Schatten) ---
UI_BG_DARK = "#0d0b12"
UI_ACCENT_GOLD = "#d4af37"
UI_ACCENT_AMETHYST = "#8a4baf"
# --- Allgemeine Textfarben (Menüs, Fenster, Dialoge) ---
FONT_COLOR_TITLE_MAIN = "#e8c86b" # Helles Antikgold für große Haupttitel
FONT_COLOR_HEADING_SUB = "#d4af37" # Klassisches Gold für Unterüberschriften
FONT_COLOR_BODY_DEFAULT = "#cec7d8" # Kühles Altweiß für Fließtext & Labels
FONT_COLOR_BODY_MUTED = "#857c96" # Gedämpftes Lavendelgrau für sekundäre Infos
FONT_COLOR_DISABLED = "#524b5e" # Ausgegraut für gesperrte Optionen
# --- Button-Textfarben: Standard-Button (Amethyst) ---
BTN_AMETHYST_TEXT_NORMAL = "#b8b0c8" # Gedämpftes Silber-Lavendel (Ruhezustand)
BTN_AMETHYST_TEXT_HOVER = "#f6eeff" # Kristall-Fliederweiß (maximaler Kontrast auf Violett)
BTN_AMETHYST_TEXT_ACTIVE = "#ffffff" # Reines Lichtweiß im Klick-Moment
BTN_AMETHYST_TEXT_DISABLED = "#524b5e"
# --- Button-Textfarben: Hervorgehobener Button (Feuer / Rot-Gold) ---
BTN_FIRE_TEXT_NORMAL = "#c7bca8" # Warmes Steingrau-Pergament (Ruhezustand)
BTN_FIRE_TEXT_HOVER = "#fff3d1" # Helles Champagner-Gold (hebt sich von der Glut ab)
BTN_FIRE_TEXT_ACTIVE = "#ffffff" # Reines Weiß beim Klicken
BTN_FIRE_TEXT_DISABLED = "#5a504c"
# --- Formular-Elemente: Input-Felder & Dropdowns ---
INPUT_TEXT_VALUE = "#eae4f2" # Sehr klares Hell-Lavendel für aktive Eingaben
INPUT_TEXT_PLACEHOLDER = "#685f78" # Dunkles Violettgrau für Platzhalter-Text
INPUT_CARET_COLOR = "#d4af37" # Goldener Text-Cursor (Caret)
INPUT_SELECTION_BG = "#4a2566" # Markierungshintergrund bei selektiertem Text
DROPDOWN_TEXT_CLOSED = "#cec7d8" # Aktuell gewählter Eintrag (geschlossen)
DROPDOWN_ITEM_TEXT_NORMAL = "#b8b0c8" # Listen-Eintrag normal
DROPDOWN_ITEM_TEXT_HOVER = "#f6eeff" # Listen-Eintrag auf dem Amethyst-Auswahlbalken
DROPDOWN_ITEM_TEXT_SELECTED = "#e8c86b" # Aktuell aktiver Wert in der offenen Liste
# --- Status- & Spielmeldungen (Stats, Einsätze, Hinweise) ---
FONT_COLOR_STATUS_WIN = "#7bd88f" # Gedecktes Smaragdgrün (Gewinn / Positiv)
FONT_COLOR_STATUS_LOSS = "#e05a5a" # Gedecktes Karmesinrot (Verlust / Fehler)
FONT_COLOR_STATUS_WARN = "#e8b85a" # Bernstein (Warnung / Hinweis)
# --- Font-Größen (Abgestimmt auf Fraktur-Lesbarkeit bei 768p–1080p) ---
FONT_SIZE_TITLE_XL = 46
FONT_SIZE_TITLE_LG = 34
FONT_SIZE_BUTTON = 24
FONT_SIZE_HEADING = 26
FONT_SIZE_INPUT = 20
FONT_SIZE_DROPDOWN = 20
FONT_SIZE_BODY = 18
FONT_SIZE_SMALL_MIN = 16 # Unter 16px brechen die feinen Fraktur-Linien weg
# --- Schatten-, Outline- & Rendering-Regeln für Old London ---
FONT_SHADOW_ENABLED = True
FONT_SHADOW_COLOR = "#07050a" # Tiefer als UI_BG_DARK für saubere Trennung vom Damast
FONT_SHADOW_OFFSET_DEFAULT = (2, 2) # (x, y) in Pixeln für Buttons & Überschriften
FONT_SHADOW_OFFSET_SMALL = (1, 1) # (x, y) in Pixeln für Inputs & Dropdown-Listen
FONT_OUTLINE_COLOR = "#0d0b12" # Optionaler 1px-Rand um Text auf unruhigen Texturen
FONT_OUTLINE_THICKNESS_PX = 1
FONT_ANTIALIAS = True # Pflicht bei geschwungenen Fraktur-Kanten
FONT_FORCE_MIXED_CASE = True # Niemals .upper() nutzen (Fraktur-Versalien unlesbar!)
FONT_LETTER_SPACING_PX = 1 # Leichtes Tracking (+1px) verhindert Verschmelzen
FONT_LINE_HEIGHT_FACTOR = 1.25 # Etwas mehr Zeilenabstand für Unter-/Oberlängen
FONT_VERTICAL_OFFSET_PX = -4

Binary file not shown.

After

Width:  |  Height:  |  Size: 410 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 416 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 821 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 909 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 549 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 690 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 MiB

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 MiB

BIN
resources/images/title1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

View File

@ -1,435 +1,32 @@
# -*- coding: utf-8 -*-
# view/assets_manager.py
from __future__ import annotations
import re
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageTk
from PIL import Image, 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,
)
# Anteil der Ecke im hochauflösenden Quellbild (damit das komplette Eck-Ornament erfasst wird)
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,
}
# Ziel-Eckgröße im UI: skaliert relativ zur Boxgröße herunter und deckelt die maximale Rahmendicke!
BOX_TARGET_CORNER_SPEC = {
# box_key: (relativer_anteil_an_kleinerer_zielkante, min_px, max_px)
"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), # Sehr feiner Rahmen (10..18px statt ~82px!)
}
_ALL_CAPS_WORD_RE = re.compile(r"\b[A-ZÄÖÜ]{4,}\b")
from resources.code_res.game_constants import OUTCOME_GIF_SIZE, PLAYING_CARD_SIZE
class AssetManager:
def __init__(self, root_dir: Path):
self.root_dir = root_dir
self.res = ResourceManager(root_dir)
# --- Hintergründe & Spieltische ---
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 = self._load_ui_flexible("general_table", "general_table")
self.raw_poker_table = self._load_ui_flexible("poker_table", "poker_table")
# --- Neue Buttons (Default, Amethyst-Hover, Feuer-Highlight) ---
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")
# Abwärtskompatible Aliase für bestehende Views:
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
# --- Transparente Zierrahmen (9-Slice) ---
self.raw_boxes: dict[str, Image.Image | None] = {
"box_big": self._load_ui_flexible("box_big", "box_big"),
"box_gold_small": self._load_ui_flexible("box_gold_small", "box_gold_smal", "box_gold_small"),
"box_gold_double": self._load_ui_flexible("box_gold_double", "box_gold_small_double"),
"box_purple": self._load_ui_flexible("box_purple", "box_small_purple"),
"dropdown_box": self._load_ui_flexible("dropdown_box", "dropdown_box"),
}
self.raw_chat_frame = self.raw_boxes["box_big"]
# --- Formular-Assets (Input & geteiltes Dropdown) ---
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")
# --- Caches ---
self._tk_cache: dict = {}
self._pil_cache: dict = {}
self._font_cache: dict[tuple[bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
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 | None) -> Image.Image | None:
if path and path.is_file():
def _load_pil(path: Path):
if 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:
"""
Versucht zuerst den Pfad aus UI_IMAGES via ResourceManager zu laden und prüft
anschließend Fallback-Dateinamen mit .png / .jpg / .jpeg in resources/images/.
"""
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
# ------------------------------------------------------------------
# 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:
"""Verhindert unlesbare Fraktur-Versalienketten (z.B. 'GOLD-POT' -> 'Gold-Pot'), lässt Kürzel wie 'XP'/'DE' stehen."""
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
total = 0.0
for idx, ch in enumerate(line):
total += draw.textlength(ch, font=font)
if idx < len(line) - 1:
total += letter_spacing
return total
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,
):
cur_x = x
for ch in line:
if FONT_SHADOW_ENABLED and shadow_offset and (shadow_offset[0] or shadow_offset[1]):
draw.text(
(cur_x + shadow_offset[0], y + shadow_offset[1]),
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 += draw.textlength(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,
) -> Image.Image:
"""
Rendert Old-London-Text als scharfes, transparentes RGBA-PIL-Bild ohne jegliches
Plattform-/Xft-Clipping an Ober- oder Unterlängen.
"""
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 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)
# Automatischer Zeilenumbruch bei max_width
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
)
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,
)
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_img)
return self._tk_cache[tk_key]
# ------------------------------------------------------------------
# 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN (box_*.png)
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN (fein herunterskaliert!)
# ------------------------------------------------------------------
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:
"""
Skaliert einen hochauflösenden Zierrahmen per 9-Slice proportional zur Zielgröße
herunter, sodass Rahmen & Ecken fein bleiben statt klobig zu wirken.
"""
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
# 1. Quell-Ausschnitt der Ecke im Originalbild (erfasst das volle Eck-Ornament)
sc = max(12, int(round(min(sw, sh) * src_ratio)))
# 2. Ziel-Größe der Ecke im UI relativ zur Boxgröße klein halten (herunterskalieren!)
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.LANCZOS)
self._pil_cache[pil_key] = out
return out
out = Image.new("RGBA", (tw, th), (0, 0, 0, 0))
# 4 Ecken sauber mit LANCZOS herunterskalieren
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))
# Obere & untere Kante (Dicke = dc -> exakt passend zu den verkleinerten Ecken!)
mid_w = tw - 2 * dc
if mid_w > 0:
top_edge = src.crop((sc, 0, sw - sc, sc)).resize((mid_w, dc), Image.Resampling.LANCZOS)
bot_edge = src.crop((sc, sh - sc, sw - sc, sh)).resize((mid_w, dc), Image.Resampling.LANCZOS)
out.paste(top_edge, (dc, 0))
out.paste(bot_edge, (dc, th - dc))
# Linke & rechte Kante (Breite = 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.LANCZOS)
right_edge = src.crop((sw - sc, sc, sw, sh - sc)).resize((dc, mid_h), Image.Resampling.LANCZOS)
out.paste(left_edge, (0, dc))
out.paste(right_edge, (tw - dc, dc))
# Mittelstück bei dropdown_box.png füllen
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)
def get_box_photo(
self,
box_key: str,
size: tuple[int, int],
corner_ratio: float | None = None,
) -> ImageTk.PhotoImage | None:
tk_key = ("9slice_tk", box_key, size, corner_ratio)
if tk_key not in self._tk_cache:
pil_box = self.get_9slice_pil(box_key, size, corner_ratio=corner_ratio)
if pil_box is not None:
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_box)
return self._tk_cache.get(tk_key)
# ------------------------------------------------------------------
# KARTEN, BANNER & GIFS
# ------------------------------------------------------------------
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:
@ -446,7 +43,7 @@ class AssetManager:
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]) -> ImageTk.PhotoImage | None:
def get_scaled_photo(self, name: str, pil_img, size: tuple[int, int]):
if not pil_img:
return None
key = (name, size)

View File

@ -1,37 +1,14 @@
# -*- coding: utf-8 -*-
# view/dialogs/audio_settings_dialog.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
SUBTLE_BORDER,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, FG_COLOR,
MODAL_BG, MUTED_FG, PANEL_BG, SUBTLE_BORDER
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
class AudioSettingsDialog(tk.Canvas):
"""
Rahmenloses Gothic-Audio-Overlay auf Basis von background_vertical.jpg + box_big.png
mit eigenen Amethyst/Gold-Schiebereglern statt Standard-tk.Scale.
"""
DLG_W = 480
DLG_H = 440
class AudioSettingsDialog(tk.Frame):
@classmethod
def open(cls, root_window: tk.Tk, assets, sound_mgr):
existing = getattr(root_window, "_audio_overlay", None)
@ -44,180 +21,68 @@ class AudioSettingsDialog(tk.Canvas):
def __init__(self, root_window: tk.Tk, assets, sound_mgr):
super().__init__(
root_window,
width=self.DLG_W,
height=self.DLG_H,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
root_window, bg=MODAL_BG, highlightthickness=2,
highlightbackground=ACCENT_GOTH, padx=30, pady=24
)
self.root_window = root_window
self.assets = assets
self.sound_mgr = sound_mgr
self._photo_refs: list[ImageTk.PhotoImage] = []
self._pct_photos: dict[str, ImageTk.PhotoImage] = {}
self._dragging_key: str | None = None
self._sliders: dict[str, dict] = {}
self.place(relx=0.5, rely=0.5, anchor="center")
self._build_scene()
self._build()
def _build_scene(self):
self.delete("all")
self._photo_refs.clear()
def _build(self):
tk.Label(self, text=t("audio_title"), font=("Georgia", 17, "bold"), fg=ACCENT_GOTH, bg=MODAL_BG).pack(pady=(0, 6))
tk.Label(self, text=t("audio_subtitle"), font=("Helvetica", 9), fg=MUTED_FG, bg=MODAL_BG).pack(pady=(0, 18))
w, h = self.DLG_W, self.DLG_H
# 1. Hochformat-Hintergrund (background_vertical.jpg) + box_big.png Zierrahmen
bg_src = self.assets.raw_bg_vertical or self.assets.raw_bg_horizontal or self.assets.raw_bg
if bg_src is not None:
bg_scaled = bg_src.resize((w, h), Image.Resampling.LANCZOS)
bg_ph = ImageTk.PhotoImage(bg_scaled)
self._photo_refs.append(bg_ph)
self.create_image(0, 0, image=bg_ph, anchor="nw")
outer_box = self.assets.get_box_photo("box_big", (w - 6, h - 6))
if outer_box:
self._photo_refs.append(outer_box)
self.create_image(w // 2, h // 2, image=outer_box, anchor="center")
# 2. Titel & Untertitel
title_ph = self.assets.get_goth_text_photo(
t("audio_title"), size_px=FONT_SIZE_TITLE_LG - 2, color=FONT_COLOR_TITLE_MAIN, max_width=w - 60
)
sub_ph = self.assets.get_goth_text_photo(
t("audio_subtitle"), size_px=FONT_SIZE_SMALL_MIN, color=FONT_COLOR_BODY_MUTED, max_width=w - 70
)
self._photo_refs.extend([title_ph, sub_ph])
self.create_image(w // 2, 46, image=title_ph, anchor="center")
self.create_image(w // 2, 82, image=sub_ph, anchor="center")
# 3. Zwei Slider-Boxen in box_small_purple.png
self._create_goth_slider(
key="amb",
cy=162,
self._build_slider_row(
label_txt=t("audio_ambiance_label"),
desc_txt=t("audio_ambiance_desc"),
initial_vol=self.sound_mgr.ambiance_volume,
on_change=lambda v: self.sound_mgr.set_ambiance_volume(v, persist=True),
)
self._create_goth_slider(
key="sfx",
cy=284,
self._build_slider_row(
label_txt=t("audio_sfx_label"),
desc_txt=t("audio_sfx_desc"),
initial_vol=self.sound_mgr.menu_volume,
on_change=lambda v: self.sound_mgr.set_menu_volume(v, persist=True),
)
# 4. Untere Aktions-Buttons (Amethyst für Test, Feuer für Fertig)
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
btn_row = tk.Frame(self, bg=MODAL_BG)
btn_row.pack(fill="x", pady=(16, 0))
btn_test = ImageButton(
self, t("audio_test_btn"), btn_norm, btn_purp,
lambda: self.sound_mgr.play("deal"),
sound_mgr=None, width=168, height=40, style="amethyst"
ImageButton(
btn_row, t("audio_test_btn"), self.assets.raw_sel, self.assets.raw_sel_active,
lambda: self.sound_mgr.play("deal"), sound_mgr=None, width=150, height=38, font=("Helvetica", 10, "bold")
).pack(side="left")
ImageButton(
btn_row, t("audio_done_btn"), self.assets.raw_btn, self.assets.raw_btn_active,
self.close, sound_mgr=self.sound_mgr, width=150, height=38, font=("Helvetica", 10, "bold")
).pack(side="right")
def _build_slider_row(self, label_txt: str, desc_txt: str, initial_vol: float, on_change):
row = tk.Frame(self, bg=PANEL_BG, padx=16, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
row.pack(fill="x", pady=6)
top = tk.Frame(row, bg=PANEL_BG)
top.pack(fill="x")
tk.Label(top, text=label_txt, font=("Helvetica", 11, "bold"), fg=FG_COLOR, bg=PANEL_BG).pack(side="left")
pct_lbl = tk.Label(top, text=f"{int(round(initial_vol * 100))} %", font=("Helvetica", 11, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG)
pct_lbl.pack(side="right")
tk.Label(row, text=desc_txt, font=("Helvetica", 8), fg=MUTED_FG, bg=PANEL_BG).pack(anchor="w", pady=(2, 6))
def _handle(val_str):
pct_lbl.configure(text=f"{int(round(float(val_str)))} %")
on_change(float(val_str) / 100.0)
scale = tk.Scale(
row, from_=0, to=100, orient="horizontal", showvalue=False,
length=360, bg=PANEL_BG, fg=FG_COLOR, troughcolor=BG_COLOR,
activebackground=ACCENT_GOTH, highlightthickness=0, bd=0, command=_handle
)
btn_done = ImageButton(
self, t("audio_done_btn"), btn_fire, btn_fire,
self.close, sound_mgr=self.sound_mgr, width=168, height=40, style="fire"
)
self.create_window(42, h - 48, window=btn_test, anchor="w")
self.create_window(w - 42, h - 48, window=btn_done, anchor="e")
self.bind("<ButtonPress-1>", self._on_mouse_down)
self.bind("<B1-Motion>", self._on_mouse_drag)
self.bind("<ButtonRelease-1>", lambda _e: setattr(self, "_dragging_key", None))
def _create_goth_slider(self, key: str, cy: int, label_txt: str, desc_txt: str, initial_vol: float, on_change):
box_w, box_h = self.DLG_W - 72, 108
cx = self.DLG_W // 2
x_left = cx - box_w // 2 + 22
x_right = cx + box_w // 2 - 22
sec_box = self.assets.get_box_photo("box_purple", (box_w, box_h))
if sec_box:
self._photo_refs.append(sec_box)
self.create_image(cx, cy, image=sec_box, anchor="center")
lbl_ph = self.assets.get_goth_text_photo(
label_txt, size_px=FONT_SIZE_HEADING - 4, color=FONT_COLOR_BODY_DEFAULT, align="left"
)
desc_ph = self.assets.get_goth_text_photo(
desc_txt, size_px=FONT_SIZE_SMALL_MIN, color=FONT_COLOR_BODY_MUTED, max_width=box_w - 44, align="left"
)
self._photo_refs.extend([lbl_ph, desc_ph])
self.create_image(x_left, cy - 30, image=lbl_ph, anchor="w")
self.create_image(x_left, cy - 4, image=desc_ph, anchor="w")
pct_item = self.create_image(x_right, cy - 30, anchor="e")
track_y = cy + 28
track_x1 = x_left + 4
track_x2 = x_right - 4
self.create_rectangle(
track_x1, track_y - 4, track_x2, track_y + 4,
fill="#09070e", outline=SUBTLE_BORDER, width=1
)
fill_id = self.create_rectangle(
track_x1, track_y - 3, track_x1, track_y + 3,
fill=UI_ACCENT_AMETHYST, outline=""
)
knob_id = self.create_polygon(
0, 0, 0, 0, 0, 0, 0, 0,
fill=UI_ACCENT_GOLD, outline="#0d0b12", width=1
)
self._sliders[key] = {
"x1": track_x1,
"x2": track_x2,
"y": track_y,
"fill_id": fill_id,
"knob_id": knob_id,
"pct_item": pct_item,
"val": max(0.0, min(1.0, float(initial_vol))),
"on_change": on_change,
}
self._update_slider_visual(key, self._sliders[key]["val"], notify=False)
def _update_slider_visual(self, key: str, val: float, notify: bool = True):
s = self._sliders[key]
val = max(0.0, min(1.0, val))
s["val"] = val
kx = s["x1"] + (s["x2"] - s["x1"]) * val
ky = s["y"]
self.coords(s["fill_id"], s["x1"] + 1, ky - 3, kx, ky + 3)
# Rautenförmiger Gold-Reglergriff
r = 9
self.coords(s["knob_id"], kx, ky - r, kx + r, ky, kx, ky + r, kx - r, ky)
pct_txt = f"{int(round(val * 100))} %"
pct_ph = self.assets.get_goth_text_photo(
pct_txt, size_px=FONT_SIZE_BODY + 2, color=FONT_COLOR_HEADING_SUB, align="right"
)
self._pct_photos[key] = pct_ph
self.itemconfigure(s["pct_item"], image=pct_ph)
if notify:
s["on_change"](val)
def _on_mouse_down(self, event):
for key, s in self._sliders.items():
if (s["x1"] - 12) <= event.x <= (s["x2"] + 12) and abs(event.y - s["y"]) <= 18:
self._dragging_key = key
ratio = (event.x - s["x1"]) / max(1.0, float(s["x2"] - s["x1"]))
self._update_slider_visual(key, ratio, notify=True)
break
def _on_mouse_drag(self, event):
if self._dragging_key and self._dragging_key in self._sliders:
s = self._sliders[self._dragging_key]
ratio = (event.x - s["x1"]) / max(1.0, float(s["x2"] - s["x1"]))
self._update_slider_visual(self._dragging_key, ratio, notify=True)
scale.set(int(round(initial_vol * 100)))
scale.pack(fill="x")
def close(self):
self.destroy()

View File

@ -17,14 +17,12 @@ from view.menus.main_menu_view import MainMenuView
from view.menus.statistics_view import StatisticsView
from view.widgets.resizing_bg import ResizingBG
APP_WM_CLASS = "TheGothCardgameCollection"
APP_WM_CLASS = "goth-cardgame-collection"
class GothCardCollectionView(tk.Tk):
def __init__(self, ctrl, root_dir: Path):
super().__init__(baseName=APP_WM_CLASS, className=APP_WM_CLASS)
if sys.platform.startswith("linux"):
self.option_add("*Label.padY", 4)
self.ctrl = ctrl
self.title(t("app_title"))
self.configure(bg=BG_COLOR)
@ -133,18 +131,12 @@ class GothCardCollectionView(tk.Tk):
Database.close()
self.destroy()
# Unten in GothCardCollectionView (view/main_window.py):
def clear_window(self, apply_global_bg=True):
self.bg_widget = None
for widget in self.winfo_children():
widget.destroy()
if apply_global_bg and (self.assets.raw_bg_horizontal or self.assets.raw_bg):
self.bg_widget = ResizingBG(
self,
self.assets.raw_bg_horizontal or self.assets.raw_bg,
pil_vertical=self.assets.raw_bg_vertical,
bg=BG_COLOR,
)
if apply_global_bg and self.assets.raw_bg:
self.bg_widget = ResizingBG(self, self.assets.raw_bg, bg=BG_COLOR)
self.bg_widget.place(relx=0, rely=0, relwidth=1, relheight=1)
def show_login(self, profiles: list[str], preselect_name: str = ""):

View File

@ -1,21 +1,12 @@
# -*- coding: utf-8 -*-
# view/menus/login_view.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_TITLE_LG,
SUBTLE_BORDER,
ACCENT_GOTH, BG_COLOR, BORDER_COLOR, FG_COLOR, INPUT_BG, MUTED_FG, SUBTLE_BORDER
)
from resources.code_res.i18n import t
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
@ -25,175 +16,96 @@ class LoginView:
self.ctrl = root_view.ctrl
self.assets = root_view.assets
self.sounds = root_view.ctrl.sounds
self.profile_var: tk.StringVar | None = None
self.new_name_var: tk.StringVar | None = None
self._photo_refs: list = []
self._profiles: list[str] = []
self._dropdown: GothDropdown | None = None
self._entry: GothEntry | None = None
self.profile_var = None
self.new_name_var = None
def show(self, profiles: list[str], preselect_name: str = ""):
GothDropdown.close_any_open_popup()
self.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self._profiles = list(profiles)
cv = self.root.bg_widget
if not isinstance(cv, tk.Canvas):
cv = tk.Canvas(self.root, bg=BG_COLOR, highlightthickness=0, bd=0)
cv.place(relx=0, rely=0, relwidth=1, relheight=1)
self._cv = cv
# Weiter eingerückt, damit die Spinnennetze in der Ecke frei bleiben
top_controls = tk.Frame(self.root, bg=BG_COLOR)
top_controls.place(relx=0.93, rely=0.07, anchor="ne")
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
ImageButton(
top_controls, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active,
lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=115, height=36, font=("Helvetica", 10, "bold")
).pack(side="left", padx=(0, 8))
# Obere rechte Steuerung (Sprache & Audio) ohne Kasten
self._btn_lang = ImageButton(
cv, t("btn_lang"), btn_norm, btn_purp,
lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=116, height=36, style="amethyst"
)
self._btn_audio = ImageButton(
cv, t("btn_audio"), btn_norm, btn_purp,
ImageButton(
top_controls, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active,
lambda: AudioSettingsDialog.open(self.root, self.assets, self.sounds),
sound_mgr=self.sounds, width=102, height=36, style="amethyst"
sound_mgr=self.sounds, width=105, height=36, font=("Helvetica", 10, "bold")
).pack(side="left")
main_frame = tk.Frame(
self.root, bg=BG_COLOR, padx=36, pady=28,
highlightthickness=1, highlightbackground=SUBTLE_BORDER
)
main_frame.place(relx=0.5, rely=0.5, anchor="center")
# Vorhandenes Profil wählen (GothDropdown + Feuer-Button)
self._dropdown = None
self._btn_login = None
if self._profiles:
initial_prof = preselect_name if preselect_name in self._profiles else self._profiles[0]
self.profile_var = tk.StringVar(value=initial_prof)
self._dropdown = GothDropdown(
cv,
self.assets,
values=self._profiles,
textvariable=self.profile_var,
sound_mgr=self.sounds,
width=270,
height=42,
)
self._btn_login = ImageButton(
cv, t("login_btn"), btn_fire, btn_fire,
lambda: self.ctrl.do_login(self.profile_var.get()),
sound_mgr=self.sounds, width=168, height=42, style="fire"
)
# Neues Seelen-Profil anlegen (GothEntry + Button)
self.new_name_var = tk.StringVar()
self._entry = GothEntry(
cv,
self.assets,
width=270,
height=42,
textvariable=self.new_name_var,
)
self._entry.bind_return(lambda _e: self._submit_new_profile())
new_btn_pil = btn_fire if not self._profiles else btn_norm
new_btn_hov = btn_fire if not self._profiles else btn_purp
new_btn_style = "fire" if not self._profiles else "amethyst"
self._btn_create = ImageButton(
cv, t("new_profile_btn"), new_btn_pil, new_btn_hov,
self._submit_new_profile,
sound_mgr=self.sounds, width=168, height=42, style=new_btn_style
)
cv.bind("<Configure>", self._on_canvas_resize, add="+")
self.root.update_idletasks()
w = max(800, cv.winfo_width())
h = max(600, cv.winfo_height())
self._draw_scene(w, h)
if not self._profiles and self._entry is not None:
self._entry.entry.focus_set()
def _submit_new_profile(self):
if self._entry is None:
return
name = self._entry.get().strip()
if name:
self.ctrl.do_create_profile(name)
def _on_canvas_resize(self, event):
if event.widget != self._cv:
return
GothDropdown.close_any_open_popup()
w, h = max(1, event.width), max(1, event.height)
if w >= 100 and h >= 100:
self._draw_scene(w, h)
def _draw_scene(self, w: int, h: int):
cv = self._cv
cv.delete("login_fg")
self._photo_refs.clear()
pad_right = max(56, int(w * 0.07))
top_y = max(52, int(h * 0.08))
# 1. Sprach- & Audio-Buttons oben rechts (frei innerhalb der Spinnweben)
cv.create_window(w - pad_right, top_y, window=self._btn_audio, anchor="e", tags="login_fg")
cv.create_window(w - pad_right - 110, top_y, window=self._btn_lang, anchor="e", tags="login_fg")
cx = w // 2
compact = (h < 780)
# 2. Panorama-Titelbanner oben mittig (ohne künstlichen Rahmen)
banner_w = 460 if compact else 540
banner_h = 115
title_photo = self.assets.get_proportional_photo("title_login_banner", self.assets.raw_title, banner_w)
box_h = (255 if self._profiles else 160) if compact else (280 if self._profiles else 175)
total_block_h = banner_h + 24 + box_h
start_y = max(top_y + 36, (h - total_block_h) // 2)
# Breites Panorama-Banner title.jpg proportional (560px breit -> ~140px hoch) ohne Text-Overlay
title_photo = self.assets.get_proportional_photo("title_login_banner", self.assets.raw_title, 560)
if title_photo:
self._photo_refs.append(title_photo)
banner_cy = start_y + title_photo.height() // 2
cv.create_image(cx, banner_cy, image=title_photo, anchor="center", tags="login_fg")
box_top = start_y + title_photo.height() + (18 if compact else 26)
title_lbl = tk.Label(
main_frame,
image=title_photo,
bg=BG_COLOR,
bd=0,
highlightthickness=1,
highlightbackground=BORDER_COLOR,
)
title_lbl.image = title_photo
title_lbl.pack(pady=(0, 22))
else:
t_ph = self.assets.get_goth_text_photo(t("app_title"), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN)
self._photo_refs.append(t_ph)
cv.create_image(cx, start_y + 40, image=t_ph, anchor="center", tags="login_fg")
box_top = start_y + 92
tk.Label(
main_frame, text=t("app_title"),
font=("Georgia", 26, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR
).pack(pady=(0, 20))
# 3. Transparenter Zierrahmen box_big.png um die Anmelde-Elemente (ohne Hintergrund-Füllung!)
box_w = 530
box_cy = box_top + box_h // 2
frame_photo = self.assets.get_box_photo("box_big", (box_w, box_h))
if frame_photo:
self._photo_refs.append(frame_photo)
cv.create_image(cx, box_cy, image=frame_photo, anchor="center", tags="login_fg")
form_box = tk.Frame(main_frame, bg=BG_COLOR)
form_box.pack()
row_left = cx - 225
field_cx = row_left + 135
btn_cx = row_left + 270 + 14 + 84
if profiles:
tk.Label(
form_box, text=t("login_select_lbl"),
font=("Helvetica", 10), fg=MUTED_FG, bg=BG_COLOR
).pack(anchor="w", padx=4)
cur_y = box_top + (34 if compact else 40)
if self._profiles and self._dropdown is not None and self._btn_login is not None:
lbl1 = self.assets.get_goth_text_photo(
t("login_select_lbl"), size_px=FONT_SIZE_BODY, color=FONT_COLOR_HEADING_SUB, align="left"
frame = tk.Frame(form_box, bg=BG_COLOR)
frame.pack(pady=(4, 12))
initial_prof = preselect_name if preselect_name in profiles else profiles[0]
self.profile_var = tk.StringVar(value=initial_prof)
cb = ttk.Combobox(
frame, textvariable=self.profile_var, values=profiles,
state="readonly", font=("Helvetica", 12), width=19, style="Goth.TCombobox"
)
self._photo_refs.append(lbl1)
cv.create_image(row_left, cur_y, image=lbl1, anchor="w", tags="login_fg")
cb.grid(row=0, column=0, padx=(0, 12), ipady=3)
ImageButton(
frame, t("login_btn"), self.assets.raw_btn, self.assets.raw_btn_active,
lambda: self.ctrl.do_login(self.profile_var.get()), sound_mgr=self.sounds, width=155, height=40
).grid(row=0, column=1)
cur_y += 38
cv.create_window(field_cx, cur_y, window=self._dropdown, anchor="center", tags="login_fg")
cv.create_window(btn_cx, cur_y, window=self._btn_login, anchor="center", tags="login_fg")
tk.Frame(form_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", padx=4, pady=14)
sep_y = cur_y + (36 if compact else 42)
cv.create_line(cx - 215, sep_y, cx + 215, sep_y, fill=SUBTLE_BORDER, width=1, tags="login_fg")
cur_y = sep_y + (26 if compact else 30)
tk.Label(
form_box, text=t("login_create_lbl"),
font=("Helvetica", 10), fg=MUTED_FG, bg=BG_COLOR
).pack(anchor="w", padx=4)
lbl2 = self.assets.get_goth_text_photo(
t("login_create_lbl"), size_px=FONT_SIZE_BODY, color=FONT_COLOR_HEADING_SUB, align="left"
new_frame = tk.Frame(form_box, bg=BG_COLOR)
new_frame.pack(pady=(4, 4))
self.new_name_var = tk.StringVar()
entry = tk.Entry(
new_frame, textvariable=self.new_name_var, font=("Helvetica", 13),
bg=INPUT_BG, fg=FG_COLOR, bd=0, width=20,
highlightthickness=1, highlightbackground=BORDER_COLOR, insertbackground="white"
)
self._photo_refs.append(lbl2)
cv.create_image(row_left, cur_y, image=lbl2, anchor="w", tags="login_fg")
entry.grid(row=0, column=0, padx=(0, 12), ipady=6)
entry.bind("<Return>", lambda e: self.ctrl.do_create_profile(self.new_name_var.get().strip()))
if not profiles:
entry.focus_set()
cur_y += 38
cv.create_window(field_cx, cur_y, window=self._entry, anchor="center", tags="login_fg")
cv.create_window(btn_cx, cur_y, window=self._btn_create, anchor="center", tags="login_fg")
ImageButton(
new_frame, t("new_profile_btn"), self.assets.raw_btn, self.assets.raw_btn_active,
lambda: self.ctrl.do_create_profile(self.new_name_var.get().strip()), sound_mgr=self.sounds, width=155, height=40
).grid(row=0, column=1)

View File

@ -1,31 +1,16 @@
# -*- coding: utf-8 -*-
# view/menus/main_menu_view.py
from __future__ import annotations
import tkinter as tk
from games.solitaire.base.solitaire_theme import get_game_icon_photo
from models.database import Database
from resources.code_res.game_constants import (
BG_COLOR,
CAT_LUCK,
CAT_ONLINE,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
FONT_SIZE_TITLE_LG,
GAME_CATEGORIES,
SUBTLE_BORDER,
UI_ACCENT_AMETHYST,
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, CAT_LUCK,
CAT_ONLINE, ERROR_FG, FG_COLOR, GAME_CATEGORIES, MENU_CARD_SIZE,
MUTED_FG, PANEL_BG, SUBTLE_BORDER
)
from resources.code_res.i18n import t
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
@ -36,11 +21,7 @@ class MainMenuView:
self.assets = root_view.assets
self.sounds = root_view.ctrl.sounds
self.selected_category: str = CAT_LUCK
self._photo_refs: list = []
self._profile: dict = {}
self._available_games: list[dict] = []
self._devils_resume_only: bool = False
self._card_icon_refs: list = []
def show(
self,
@ -49,13 +30,8 @@ class MainMenuView:
devils_resume_only: bool = False,
category: str | None = None,
):
GothDropdown.close_any_open_popup()
self.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self._profile = profile
self._available_games = available_games
self._devils_resume_only = devils_resume_only
self._card_icon_refs.clear()
valid_cats = {c[0] for c in GAME_CATEGORIES}
if category in valid_cats:
@ -65,388 +41,283 @@ class MainMenuView:
saved_cat = Database.load_setting("last_menu_category", CAT_LUCK)
self.selected_category = saved_cat if saved_cat in valid_cats else CAT_LUCK
cv = self.root.bg_widget
if not isinstance(cv, tk.Canvas):
cv = tk.Canvas(self.root, bg=BG_COLOR, highlightthickness=0, bd=0)
cv.place(relx=0, rely=0, relwidth=1, relheight=1)
self._cv = cv
self._build_floating_buttons(cv)
cv.bind("<Configure>", self._on_canvas_layout, add="+")
self.root.update_idletasks()
w = max(800, cv.winfo_width())
h = max(600, cv.winfo_height())
self._draw_scene(w, h)
def _build_floating_buttons(self, cv: tk.Canvas):
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
self._top_left_btns: list[tuple[ImageButton, int]] = []
if not self._devils_resume_only:
b_prof = ImageButton(
cv, t("btn_switch_profile"), btn_norm, btn_purp,
self.ctrl.logout_to_login, sound_mgr=self.sounds, width=124, height=34, style="amethyst"
container = tk.Frame(
self.root, bg=BG_COLOR, padx=26, pady=14,
highlightthickness=1, highlightbackground=SUBTLE_BORDER
)
self._top_left_btns.append((b_prof, b_prof.pixel_width))
container.place(relx=0.5, rely=0.52, anchor="center", relwidth=0.92, relheight=0.88)
b_stats = ImageButton(
cv, t("btn_stats"), btn_norm, btn_purp,
self.ctrl.show_statistics, sound_mgr=self.sounds, width=96, height=34, style="amethyst"
)
self._top_left_btns.append((b_stats, b_stats.pixel_width))
# 3-Spalten-Topbar mit zentriertem title.jpg Banner in Spalte 1
top_bar = tk.Frame(container, bg=BG_COLOR)
top_bar.pack(fill="x", pady=(0, 10))
top_bar.columnconfigure(0, weight=1)
top_bar.columnconfigure(1, weight=1)
top_bar.columnconfigure(2, weight=1)
b_lang = ImageButton(
cv, t("btn_lang"), btn_norm, btn_purp,
lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=96, height=34, style="amethyst"
)
self._top_left_btns.append((b_lang, b_lang.pixel_width))
left_btns = tk.Frame(top_bar, bg=BG_COLOR)
left_btns.grid(row=0, column=0, sticky="w")
b_audio = ImageButton(
cv, t("btn_audio"), btn_norm, btn_purp,
if not devils_resume_only:
ImageButton(
left_btns, t("btn_switch_profile"), self.assets.raw_sel, self.assets.raw_sel_active,
self.ctrl.logout_to_login, sound_mgr=self.sounds, width=145, height=36, font=("Helvetica", 9, "bold")
).pack(side="left", padx=(0, 5))
ImageButton(
left_btns, t("btn_stats"), self.assets.raw_sel, self.assets.raw_sel_active,
self.ctrl.show_statistics, sound_mgr=self.sounds, width=110, height=36, font=("Helvetica", 9, "bold")
).pack(side="left", padx=(0, 5))
ImageButton(
left_btns, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active,
lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=105, height=36, font=("Helvetica", 9, "bold")
).pack(side="left", padx=(0, 5))
ImageButton(
left_btns, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active,
lambda: AudioSettingsDialog.open(self.root, self.assets, self.sounds),
sound_mgr=self.sounds, width=78, height=34, style="amethyst"
sound_mgr=self.sounds, width=85, height=36, font=("Helvetica", 9, "bold")
).pack(side="left")
header_banner = self.assets.get_proportional_photo("title_main_header", self.assets.raw_title, 320)
if header_banner:
hdr_lbl = tk.Label(
top_bar, image=header_banner, bg=BG_COLOR, bd=0,
highlightthickness=1, highlightbackground=SUBTLE_BORDER
)
self._top_left_btns.append((b_audio, b_audio.pixel_width))
hdr_lbl.image = header_banner
hdr_lbl.grid(row=0, column=1, padx=12)
else:
tk.Label(
top_bar, text=t("header_title"),
font=("Georgia", 20, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR
).grid(row=0, column=1, padx=12)
self._cat_btns: list[tuple[ImageButton, int]] = []
if not self._devils_resume_only:
for cat_id, title_key, _desc_key in GAME_CATEGORIES:
is_sel = (cat_id == self.selected_category)
pil_n = btn_fire if is_sel else btn_norm
pil_h = btn_fire if is_sel else btn_purp
b_style = "fire" if is_sel else "amethyst"
acc_box = tk.Frame(top_bar, bg=PANEL_BG, padx=16, pady=7, highlightthickness=1, highlightbackground=BORDER_COLOR)
acc_box.grid(row=0, column=2, sticky="e")
tk.Label(
acc_box,
text=t("main_acc_soul_only", profile["name"]),
font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
).pack()
b_cat = ImageButton(
cv,
t(title_key),
pil_n,
pil_h,
lambda cid=cat_id: self.show(
self._profile, self._available_games, devils_resume_only=False, category=cid
),
sound_mgr=self.sounds,
width=142,
height=38,
style=b_style,
tk.Frame(container, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(0, 10))
cards_section = tk.Frame(container, bg=BG_COLOR)
cards_section.pack(fill="both", expand=True)
# Im aktiven Devil's Deal sind alle Kategorien gesperrt -> nur Resume!
if devils_resume_only:
pakt_panel = tk.Frame(
cards_section, bg=PANEL_BG, padx=36, pady=28,
highlightthickness=2, highlightbackground=ERROR_FG
)
self._cat_btns.append((b_cat, b_cat.pixel_width))
pakt_panel.place(relx=0.5, rely=0.5, anchor="center")
def _on_canvas_layout(self, event):
if event.widget != self._cv:
return
w, h = max(1, event.width), max(1, event.height)
if w >= 100 and h >= 100:
self._draw_scene(w, h)
def _draw_scene(self, w: int, h: int):
cv = self._cv
cv.delete("ui_fg")
self._photo_refs.clear()
compact = (h < 800)
pad_x = max(112, int(w * 0.105))
top_y = max(72, int(h * 0.125))
# 1. Linke Menü-Buttons sauber innerhalb des Rahmens
cur_x = pad_x
for btn_wgt, bw in self._top_left_btns:
cv.create_window(cur_x, top_y, window=btn_wgt, anchor="w", tags=("ui_fg",))
cur_x += bw + 6
# 2. Seelen-Anzeige rechts oben
soul_photo = self.assets.get_goth_text_photo(
t("main_acc_soul_only", self._profile["name"]),
size_px=FONT_SIZE_BODY + 1,
color=FONT_COLOR_TITLE_MAIN,
align="center",
)
self._photo_refs.append(soul_photo)
soul_box_w = max(150, soul_photo.width() + 36)
soul_box_h = max(40, soul_photo.height() + 14)
soul_cx = w - pad_x - soul_box_w // 2
soul_frame = self.assets.get_box_photo("box_gold_small", (soul_box_w, soul_box_h))
if soul_frame:
self._photo_refs.append(soul_frame)
cv.create_image(soul_cx, top_y, image=soul_frame, anchor="center", tags=("ui_fg",))
cv.create_image(soul_cx, top_y, image=soul_photo, anchor="center", tags=("ui_fg",))
# 3. Titel-Banner klar rechts neben dem mittleren Rahmen-Ornament zentrieren!
# Das mittlere Dornen-Ornament von background_horizontal.jpg reicht bis ca. 56% der Breite;
# wir setzen das Banner daher gezielt mittig zwischen Ornament-Ende und Seelen-Box (~66% Breite).
banner_w = 230 if compact else 265
header_banner = self.assets.get_proportional_photo("title_main_header", self.assets.raw_title, banner_w)
ornament_right_edge = max(cur_x + 16, int(w * 0.565))
right_free = soul_cx - soul_box_w // 2 - 14
if header_banner and (right_free - ornament_right_edge) >= header_banner.width():
self._photo_refs.append(header_banner)
banner_cx = (ornament_right_edge + right_free) // 2
cv.create_image(banner_cx, top_y, image=header_banner, anchor="center", tags=("ui_fg",))
elif header_banner and (right_free - (cur_x + 12)) >= 170:
# Kompakt-Fallback für sehr schmale Fenster (< 1050px)
smaller = self.assets.get_proportional_photo("title_main_header_sm", self.assets.raw_title, 200)
if smaller:
self._photo_refs.append(smaller)
banner_cx = max(cur_x + 12 + smaller.width() // 2, right_free - smaller.width() // 2 - 8)
cv.create_image(banner_cx, top_y, image=smaller, anchor="center", tags=("ui_fg",))
elif not header_banner:
hdr_txt = self.assets.get_goth_text_photo(t("header_title"), FONT_SIZE_TITLE_LG - 4, FONT_COLOR_TITLE_MAIN)
self._photo_refs.append(hdr_txt)
cv.create_image((ornament_right_edge + right_free) // 2, top_y, image=hdr_txt, anchor="center", tags=("ui_fg",))
sep_y = top_y + (44 if compact else 52)
cv.create_line(pad_x, sep_y, w - pad_x, sep_y, fill=SUBTLE_BORDER, width=1, tags=("ui_fg",))
# 4. Devil's Deal Sperr-Ansicht
if self._devils_resume_only:
cy = (sep_y + h) // 2
pakt_frame = self.assets.get_box_photo("box_big", (600, 360))
if pakt_frame:
self._photo_refs.append(pakt_frame)
cv.create_image(w // 2, cy, image=pakt_frame, anchor="center", tags=("ui_fg",))
t_pakt = self.assets.get_goth_text_photo(
t("devils_deal_resume_title"), FONT_SIZE_TITLE_LG, FONT_COLOR_STATUS_LOSS
)
d_pakt = self.assets.get_goth_text_photo(
t("devils_deal_resume_desc"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=500
)
self._photo_refs.extend([t_pakt, d_pakt])
cv.create_image(w // 2, cy - 118, image=t_pakt, anchor="center", tags=("ui_fg",))
cv.create_image(w // 2, cy - 66, image=d_pakt, anchor="center", tags=("ui_fg",))
tk.Label(
pakt_panel, text=t("devils_deal_resume_title"),
font=("Georgia", 18, "bold"), fg=ERROR_FG, bg=PANEL_BG
).pack(pady=(0, 8))
tk.Label(
pakt_panel, text=t("devils_deal_resume_desc"),
font=("Helvetica", 11), fg=MUTED_FG, bg=PANEL_BG, wraplength=520, justify="center"
).pack(pady=(0, 22))
locked_folder = self.ctrl.get_locked_devils_game_folder() or ""
self._draw_framed_game_tile(
cv, w // 2, cy + 62,
tile_idx=0,
game_title=t("devils_deal_resume_card"),
rank_subtitle="",
on_click=self.ctrl.resume_devils_deal,
resume_card = self._create_game_card(
pakt_panel,
t("devils_deal_resume_card"),
"",
self.ctrl.resume_devils_deal,
game_folder=locked_folder,
bg_col=PANEL_BG,
is_online=True,
compact=True,
)
resume_card.pack()
return
# 5. Flache 4-Kategorien-Leiste
cat_y = sep_y + (28 if compact else 34)
total_tabs_w = sum(bw for _, bw in self._cat_btns) + max(0, len(self._cat_btns) - 1) * 10
tab_x = (w - total_tabs_w) // 2
for btn_wgt, bw in self._cat_btns:
cv.create_window(tab_x + bw // 2, cat_y, window=btn_wgt, anchor="center", tags=("ui_fg",))
tab_x += bw + 10
# --- FLACHE 4-KATEGORIEN-LEISTE ---
cat_bar = tk.Frame(
cards_section, bg=PANEL_BG, padx=16, pady=10,
highlightthickness=1, highlightbackground=BORDER_COLOR
)
cat_bar.pack(fill="x", pady=(0, 12))
tabs_wrap = tk.Frame(cat_bar, bg=PANEL_BG)
tabs_wrap.pack()
active_cat_title = ""
active_cat_desc = ""
for cat_id, title_key, desc_key in GAME_CATEGORIES:
if cat_id == self.selected_category:
active_cat_title = t(title_key)
c_title = t(title_key)
is_sel = (cat_id == self.selected_category)
if is_sel:
active_cat_title = c_title
active_cat_desc = t(desc_key)
break
pil_norm = self.assets.raw_btn if is_sel else self.assets.raw_sel
pil_hov = self.assets.raw_btn_active if is_sel else self.assets.raw_sel_active
btn_w = 205 if cat_id == "party_offline" else 155
ImageButton(
tabs_wrap, c_title, pil_norm, pil_hov,
lambda cid=cat_id: self.show(profile, available_games, devils_resume_only=False, category=cid),
sound_mgr=self.sounds, width=btn_w, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=6)
is_online_tab = (self.selected_category == CAT_ONLINE)
desc_y = cat_y + (32 if compact else 38)
desc_photo = self.assets.get_goth_text_photo(
active_cat_desc,
size_px=FONT_SIZE_BODY,
color=FONT_COLOR_STATUS_LOSS if is_online_tab else FONT_COLOR_BODY_MUTED,
max_width=min(880, w - 2 * pad_x),
align="center",
)
self._photo_refs.append(desc_photo)
cv.create_image(w // 2, desc_y, image=desc_photo, anchor="center", tags=("ui_fg",))
tk.Label(
cat_bar,
text=active_cat_desc,
font=("Helvetica", 10, "bold" if is_online_tab else "normal"),
fg=ERROR_FG if is_online_tab else MUTED_FG,
bg=PANEL_BG,
).pack(pady=(8, 2))
# 6. Gerahmte Spiel-Kacheln mit Lupeneffekt beim Hover
filtered_games = [
g for g in self._available_games if g.get("category", CAT_LUCK) == self.selected_category
]
# --- GEFILTERTES SPIELKARTEN-GRID ---
filtered_games = [g for g in available_games if g.get("category", CAT_LUCK) == self.selected_category]
area_top = desc_y + 28
area_bot = h - max(56, int(h * 0.085))
mid_y = (area_top + area_bot) // 2
cards_grid = tk.Frame(cards_section, bg=BG_COLOR)
cards_grid.pack(expand=True)
if not filtered_games:
empty_txt = self.assets.get_goth_text_photo(
t("no_games_in_category", active_cat_title),
size_px=FONT_SIZE_HEADING - 2,
color=FONT_COLOR_STATUS_LOSS if is_online_tab else FONT_COLOR_BODY_MUTED,
max_width=620,
empty_box = tk.Frame(
cards_grid, bg=PANEL_BG, padx=32, pady=22,
highlightthickness=1, highlightbackground=ERROR_FG if is_online_tab else SUBTLE_BORDER
)
self._photo_refs.append(empty_txt)
eb_w, eb_h = empty_txt.width() + 68, empty_txt.height() + 44
eb_frame = self.assets.get_box_photo("box_purple", (eb_w, eb_h))
if eb_frame:
self._photo_refs.append(eb_frame)
cv.create_image(w // 2, mid_y, image=eb_frame, anchor="center", tags=("ui_fg",))
cv.create_image(w // 2, mid_y, image=empty_txt, anchor="center", tags=("ui_fg",))
return
cols = min(4, len(filtered_games))
rows = (len(filtered_games) + cols - 1) // cols
tight = compact or rows > 1
col_step = min(248, max(195, (w - 2 * pad_x) // max(1, cols)))
row_step = 236 if tight else 268
start_y = mid_y - ((rows - 1) * row_step) // 2
empty_box.pack(pady=30)
tk.Label(
empty_box,
text=t("no_games_in_category", active_cat_title),
font=("Georgia", 12, "bold"),
fg=ERROR_FG if is_online_tab else MUTED_FG,
bg=PANEL_BG,
).pack()
else:
for idx, game in enumerate(filtered_games):
r, c = idx // 4, idx % 4
in_row = min(4, len(filtered_games) - r * 4)
cx = (w // 2) - ((in_row - 1) * col_step) // 2 + c * col_step
cy = start_y + r * row_step
prog = game.get("progress")
sub_txt = t("menu_card_rank_sub", prog["title"], prog["level"]) if prog else ""
self._draw_framed_game_tile(
cv, cx, cy,
tile_idx=idx,
game_title=game["title"],
rank_subtitle=sub_txt,
on_click=lambda g=game: self.ctrl.launch_game(g),
card_widget = self._create_game_card(
cards_grid,
game["title"],
sub_txt,
lambda g=game: self.ctrl.launch_game(g),
game_folder=game.get("folder", ""),
is_online=is_online_tab,
compact=tight,
)
card_widget.grid(row=idx // 4, column=idx % 4, padx=18, pady=10)
def _draw_framed_game_tile(
def _create_game_card(
self,
cv: tk.Canvas,
cx: int,
cy: int,
tile_idx: int,
parent,
game_title: str,
rank_subtitle: str,
on_click,
game_folder: str = "",
bg_col: str = BG_COLOR,
is_online: bool = False,
compact: bool = False,
):
"""
Zeichnet eine Spiel-Auswahlkachel mit transparentem Zierrahmen (ohne Trennlinie)
und echtem Lupeneffekt beim Hover (Rahmen + Icon + Titel + Rang wachsen synchron!).
"""
hit_tag = f"tile_hit_{tile_idx}"
tags = ("ui_fg", hit_tag)
) -> tk.Canvas:
card_w, card_h = MENU_CARD_SIZE
cv = tk.Canvas(parent, width=card_w, height=card_h, bg=bg_col, highlightthickness=0, cursor="hand2")
# Normal- vs. Lupen-Maße (ca. +9% Vergrößerung beim Hover)
card_w_n = 186 if compact else 204
card_h_n = 216 if compact else 242
card_w_h = card_w_n + 16
card_h_h = card_h_n + 18
base_outline = ERROR_FG if is_online else BORDER_COLOR
gem_color = ERROR_FG if is_online else ACCENT_GOTH
frame_norm = self.assets.get_box_photo("box_purple", (card_w_n, card_h_n))
frame_hov = self.assets.get_box_photo("box_gold_small", (card_w_h, card_h_h))
if frame_norm:
self._photo_refs.append(frame_norm)
if frame_hov:
self._photo_refs.append(frame_hov)
base_px = 92 if compact else 104
hover_px = base_px + 12
icon_norm = get_game_icon_photo(self.assets.res, game_folder, size_px=base_px) if game_folder else None
icon_hov = get_game_icon_photo(self.assets.res, game_folder, size_px=hover_px) if game_folder else None
title_px_n = (FONT_SIZE_HEADING - 3) if compact else (FONT_SIZE_HEADING - 1)
title_px_h = title_px_n + 3
title_norm = self.assets.get_goth_text_photo(
game_title, size_px=title_px_n, color=FONT_COLOR_BODY_DEFAULT, max_width=card_w_n - 26
outer_id = cv.create_rectangle(
4, 4, card_w - 4, card_h - 4,
fill=PANEL_BG, outline=base_outline, width=2
)
title_hov = self.assets.get_goth_text_photo(
game_title, size_px=title_px_h, color=FONT_COLOR_TITLE_MAIN, max_width=card_w_h - 24
inner_id = cv.create_rectangle(
11, 11, card_w - 11, card_h - 11,
fill="#16131c", outline=SUBTLE_BORDER, width=1
)
self._photo_refs.extend([title_norm, title_hov])
# Vertikale Positionen (Normal vs. leicht aufgefächert im Lupen-Zustand, ohne Trennlinie!)
icon_photo = get_game_icon_photo(self.assets.res, game_folder, size_px=92) if game_folder else None
top_gem = None
bot_gem = None
longest_word = max((len(w) for w in game_title.replace("\n", " ").split()), default=0)
if icon_photo is not None:
self._card_icon_refs.append(icon_photo)
# Dezenter Sockel-Schein hinter dem Spiel-Icon
icon_glow_id = cv.create_rectangle(
card_w // 2 - 48, 22, card_w // 2 + 48, 118,
outline=SUBTLE_BORDER, width=1
)
cv.create_image(card_w // 2, 70, image=icon_photo, anchor="center")
title_size = 13 if longest_word >= 10 else 15
title_y = 146 if rank_subtitle else 166
txt_id = cv.create_text(
card_w // 2, title_y,
text=game_title, width=card_w - 28, justify="center",
font=("Georgia", title_size, "bold"), fill=FG_COLOR
)
sub_id = None
if rank_subtitle:
icon_y_n = cy - (38 if compact else 44)
icon_y_h = icon_y_n - 3
title_y_n = icon_y_n + (base_px // 2) + (20 if compact else 23)
title_y_h = icon_y_h + (hover_px // 2) + (21 if compact else 24)
sub_y_n = title_y_n + (32 if compact else 36)
sub_y_h = title_y_h + (35 if compact else 39)
cv.create_line(
30, 174, card_w - 30, 174,
fill=SUBTLE_BORDER, width=1
)
sub_id = cv.create_text(
card_w // 2, 203,
text=rank_subtitle, width=card_w - 26, justify="center",
font=("Helvetica", 9, "bold"), fill=gem_color
)
else:
icon_y_n = cy - 20
icon_y_h = icon_y_n - 3
title_y_n = icon_y_n + (base_px // 2) + 24
title_y_h = icon_y_h + (hover_px // 2) + 25
sub_y_n = sub_y_h = cy
icon_glow_id = None
top_gem = cv.create_text(card_w // 2, 28, text="†" if is_online else "❖", font=("Helvetica", 11, "bold"), fill=gem_color)
bot_gem = cv.create_text(card_w // 2, card_h - 28, text="†" if is_online else "❖", font=("Helvetica", 11, "bold"), fill=gem_color)
frame_item = None
if frame_norm is not None:
frame_item = cv.create_image(cx, cy, image=frame_norm, anchor="center", tags=tags)
title_size = 15 if longest_word >= 11 else 17
title_y = (card_h // 2 - 22) if rank_subtitle else (card_h // 2)
txt_id = cv.create_text(
card_w // 2, title_y,
text=game_title, width=card_w - 32, justify="center",
font=("Georgia", title_size, "bold"), fill=FG_COLOR
)
img_item = None
if icon_norm is not None:
self._photo_refs.append(icon_norm)
if icon_hov is not None:
self._photo_refs.append(icon_hov)
img_item = cv.create_image(cx, icon_y_n, image=icon_norm, anchor="center", tags=tags)
else:
sym_col = FONT_COLOR_STATUS_LOSS if is_online else UI_ACCENT_AMETHYST
sym_n = self.assets.get_goth_text_photo("*", size_px=FONT_SIZE_TITLE_LG - 4, color=sym_col)
sym_h = self.assets.get_goth_text_photo("*", size_px=FONT_SIZE_TITLE_LG + 2, color=FONT_COLOR_TITLE_MAIN)
self._photo_refs.extend([sym_n, sym_h])
icon_norm, icon_hov = sym_n, sym_h
img_item = cv.create_image(cx, icon_y_n, image=icon_norm, anchor="center", tags=tags)
title_item = cv.create_image(cx, title_y_n, image=title_norm, anchor="center", tags=tags)
sub_item = None
sub_norm = None
sub_hov = None
sub_id = None
if rank_subtitle:
sub_col = FONT_COLOR_STATUS_LOSS if is_online else FONT_COLOR_HEADING_SUB
sub_px_n = FONT_SIZE_SMALL_MIN
sub_px_h = FONT_SIZE_SMALL_MIN + 2
sub_norm = self.assets.get_goth_text_photo(
rank_subtitle, size_px=sub_px_n, color=sub_col, max_width=card_w_n - 26
cv.create_line(
36, card_h // 2 + 4, card_w - 36, card_h // 2 + 4,
fill=SUBTLE_BORDER, width=1
)
sub_hov = self.assets.get_goth_text_photo(
rank_subtitle, size_px=sub_px_h, color="#ffffff", max_width=card_w_h - 24
sub_id = cv.create_text(
card_w // 2, card_h // 2 + 34,
text=rank_subtitle, width=card_w - 30, justify="center",
font=("Helvetica", 9, "bold"), fill=gem_color
)
self._photo_refs.extend([sub_norm, sub_hov])
sub_item = cv.create_image(cx, sub_y_n, image=sub_norm, anchor="center", tags=tags)
# Unsichtbare Hitbox über die volle vergrößerte Kachelfläche (verhindert Hover-Flackern am Rand)
hit_id = cv.create_rectangle(
cx - card_w_h // 2, cy - card_h_h // 2,
cx + card_w_h // 2, cy + card_h_h // 2,
fill="", outline="", width=0, tags=tags,
)
cv.tag_raise(hit_id)
def _on_enter(_e):
cv.configure(cursor="hand2")
if frame_item and frame_hov:
cv.itemconfigure(frame_item, image=frame_hov)
if img_item and icon_hov:
cv.coords(img_item, cx, icon_y_h)
cv.itemconfigure(img_item, image=icon_hov)
cv.coords(title_item, cx, title_y_h)
cv.itemconfigure(title_item, image=title_hov)
if sub_item and sub_hov:
cv.coords(sub_item, cx, sub_y_h)
cv.itemconfigure(sub_item, image=sub_hov)
cv.itemconfigure(outer_id, outline=ACCENT_GOLD)
cv.itemconfigure(inner_id, fill="#211c2a", outline=gem_color)
cv.itemconfigure(txt_id, fill=ACCENT_GOLD)
if icon_glow_id:
cv.itemconfigure(icon_glow_id, outline=ACCENT_GOLD)
if top_gem:
cv.itemconfigure(top_gem, fill=ACCENT_GOLD)
if bot_gem:
cv.itemconfigure(bot_gem, fill=ACCENT_GOLD)
if sub_id:
cv.itemconfigure(sub_id, fill="#ffffff")
def _on_leave(_e):
cv.configure(cursor="")
if frame_item and frame_norm:
cv.itemconfigure(frame_item, image=frame_norm)
if img_item and icon_norm:
cv.coords(img_item, cx, icon_y_n)
cv.itemconfigure(img_item, image=icon_norm)
cv.coords(title_item, cx, title_y_n)
cv.itemconfigure(title_item, image=title_norm)
if sub_item and sub_norm:
cv.coords(sub_item, cx, sub_y_n)
cv.itemconfigure(sub_item, image=sub_norm)
cv.itemconfigure(outer_id, outline=base_outline)
cv.itemconfigure(inner_id, fill="#16131c", outline=SUBTLE_BORDER)
cv.itemconfigure(txt_id, fill=FG_COLOR)
if icon_glow_id:
cv.itemconfigure(icon_glow_id, outline=SUBTLE_BORDER)
if top_gem:
cv.itemconfigure(top_gem, fill=gem_color)
if bot_gem:
cv.itemconfigure(bot_gem, fill=gem_color)
if sub_id:
cv.itemconfigure(sub_id, fill=gem_color)
cv.tag_bind(hit_tag, "<Enter>", _on_enter)
cv.tag_bind(hit_tag, "<Leave>", _on_leave)
cv.tag_bind(hit_tag, "<Button-1>", lambda _e: (self.sounds.play("click"), on_click()))
cv.bind("<Enter>", _on_enter)
cv.bind("<Leave>", _on_leave)
cv.bind("<Button-1>", lambda _e: (self.sounds.play("click"), on_click()))
return cv

View File

@ -1,25 +1,14 @@
# -*- coding: utf-8 -*-
# view/menus/statistics_view.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from models.database import Database
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_HEADING,
STAT_GAME_GROUPS,
SUBTLE_BORDER,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR,
FG_COLOR, PANEL_BG, STAT_GAME_GROUPS, SUBTLE_BORDER
)
from resources.code_res.i18n import t
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.stats_board_widget import StatsBoardWidget
@ -32,203 +21,100 @@ class StatisticsView:
self.sounds = root_view.ctrl.sounds
self.selected_folder = STAT_GAME_GROUPS[0][0]
self._photo_refs: list = []
self._profile: dict = {}
self._board: StatsBoardWidget | None = None
def show(self, profile: dict, folder_path: str | None = None):
GothDropdown.close_any_open_popup()
if folder_path is not None:
self.selected_folder = folder_path
self._profile = profile
self.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
cv = self.root.bg_widget
if not isinstance(cv, tk.Canvas):
cv = tk.Canvas(self.root, bg=BG_COLOR, highlightthickness=0, bd=0)
cv.place(relx=0, rely=0, relwidth=1, relheight=1)
self._cv = cv
topbar = tk.Frame(self.root, bg=PANEL_BG, padx=14, pady=8, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
topbar.pack(fill="x", side="top")
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
ImageButton(
topbar, t("btn_back_main"), self.assets.raw_sel, self.assets.raw_sel_active,
self.ctrl.show_main_menu, sound_mgr=self.sounds, width=145, height=36, font=("Helvetica", 10, "bold")
).pack(side="left")
# Obere Navigations-Buttons
self._btn_back = ImageButton(
cv, t("btn_back_main"), btn_norm, btn_purp,
self.ctrl.show_main_menu, sound_mgr=self.sounds, width=148, height=36, style="amethyst"
)
self._btn_lang = ImageButton(
cv, t("btn_lang"), btn_norm, btn_purp,
tk.Label(
topbar, text=t("stats_view_topbar", profile["name"]),
font=("Georgia", 15, "bold"), fg=FG_COLOR, bg=PANEL_BG
).pack(side="left", expand=True)
right_btns = tk.Frame(topbar, bg=PANEL_BG)
right_btns.pack(side="right")
ImageButton(
right_btns, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active,
lambda: self.ctrl.toggle_language(lambda: self.show(self.ctrl.active_profile, self.selected_folder)),
sound_mgr=self.sounds, width=112, height=36, style="amethyst"
)
self._btn_audio = ImageButton(
cv, t("btn_audio"), btn_norm, btn_purp,
lambda: AudioSettingsDialog.open(self.root, self.assets, self.sounds),
sound_mgr=self.sounds, width=92, height=36, style="amethyst"
)
sound_mgr=self.sounds, width=110, height=34, font=("Helvetica", 9, "bold")
).pack(side="left", padx=(0, 6))
# Spiel-Auswahl-Buttons
self._game_btns: list[tuple[tk.Widget, int]] = []
self._active_game_title = ""
ImageButton(
right_btns, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active,
lambda: AudioSettingsDialog.open(self.root, self.assets, self.sounds),
sound_mgr=self.sounds, width=92, height=34, font=("Helvetica", 9, "bold")
).pack(side="left")
container = tk.Frame(self.root, bg=BG_COLOR, padx=24, pady=18)
container.place(relx=0.5, rely=0.54, anchor="center", relwidth=0.88, relheight=0.82)
selector_panel = tk.Frame(
container, bg=PANEL_BG, padx=18, pady=14,
highlightthickness=1, highlightbackground=BORDER_COLOR
)
selector_panel.pack(fill="x", pady=(0, 14))
tk.Label(
selector_panel, text=t("stats_select_game_lbl"),
font=("Georgia", 13, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
).pack(anchor="w", pady=(0, 10))
tabs_row = tk.Frame(selector_panel, bg=PANEL_BG)
tabs_row.pack(fill="x")
active_game_title = ""
for folder, title_key in STAT_GAME_GROUPS:
g_title = t(title_key)
is_sel = (folder == self.selected_folder)
if is_sel:
self._active_game_title = g_title
p_n = btn_fire if is_sel else btn_norm
p_h = btn_fire if is_sel else btn_purp
st = "fire" if is_sel else "amethyst"
bw = 172
btn = ImageButton(
cv, g_title, p_n, p_h,
is_selected = (folder == self.selected_folder)
if is_selected:
active_game_title = g_title
pil_norm = self.assets.raw_btn if is_selected else self.assets.raw_sel
pil_hov = self.assets.raw_btn_active if is_selected else self.assets.raw_sel_active
ImageButton(
tabs_row, g_title, pil_norm, pil_hov,
lambda f=folder: self.show(profile, folder_path=f),
sound_mgr=self.sounds, width=bw, height=38, style=st
)
self._game_btns.append((btn, bw))
sound_mgr=self.sounds, width=165, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=(0, 8))
# Spielgebundene Rang- & XP-Leiste für das gewählte Spiel
g_prog = Database.get_game_progress(profile["id"], self.selected_folder)
rank_bar = tk.Frame(container, bg=PANEL_BG, padx=18, pady=10, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
rank_bar.pack(fill="x", pady=(0, 14))
tk.Label(
rank_bar,
text=t("stats_game_rank_info", active_game_title, g_prog["title"], g_prog["level"], g_prog["current_xp"], g_prog["needed_xp"]),
font=("Georgia", 11, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG
).pack(side="left")
ttk.Progressbar(
rank_bar, style="Goth.Horizontal.TProgressbar",
orient="horizontal", length=220, mode="determinate",
maximum=g_prog["needed_xp"], value=g_prog["current_xp"]
).pack(side="right")
# Statistik-Board für das aktive Spiel
game_variants = Database.get_variants_for_filter(folder_path=self.selected_folder)
filter_map = {t("stats_all_variants_of_game", self._active_game_title): None}
filter_map = {t("stats_all_variants_of_game", active_game_title): None}
for v in game_variants:
filter_map[v["translated_name"]] = v["id"]
self._board = StatsBoardWidget(
cv,
title=t("stats_game_board_title", self._active_game_title),
board = StatsBoardWidget(
container,
title=t("stats_game_board_title", active_game_title),
filter_map=filter_map,
fetch_callback=lambda vid: Database.get_stats_overview(
profile["id"], variant_id=vid, folder_path=self.selected_folder
),
)
cv.bind("<Configure>", self._on_canvas_layout, add="+")
self.root.update_idletasks()
w = max(800, cv.winfo_width())
h = max(600, cv.winfo_height())
self._draw_scene(w, h)
def _on_canvas_layout(self, event):
if event.widget != self._cv:
return
GothDropdown.close_any_open_popup()
w, h = max(1, event.width), max(1, event.height)
if w >= 120 and h >= 120:
self._draw_scene(w, h)
def _draw_scene(self, w: int, h: int):
cv = self._cv
cv.delete("stats_fg")
self._photo_refs.clear()
compact = (h < 780)
pad_x = max(56, int(w * 0.065))
top_y = max(52, int(h * 0.09))
# 1. Kopfbereich (frei über dem Hintergrund)
cv.create_window(pad_x, top_y, window=self._btn_back, anchor="w", tags="stats_fg")
cv.create_window(w - pad_x, top_y, window=self._btn_audio, anchor="e", tags="stats_fg")
cv.create_window(w - pad_x - 100, top_y, window=self._btn_lang, anchor="e", tags="stats_fg")
hdr_ph = self.assets.get_goth_text_photo(
t("stats_view_topbar", self._profile["name"]),
size_px=FONT_SIZE_HEADING + (0 if compact else 2),
color=FONT_COLOR_TITLE_MAIN,
max_width=max(200, w - 540),
)
self._photo_refs.append(hdr_ph)
cv.create_image(w // 2, top_y, image=hdr_ph, anchor="center", tags="stats_fg")
sep_y = top_y + (36 if compact else 44)
cv.create_line(pad_x, sep_y, w - pad_x, sep_y, fill=SUBTLE_BORDER, width=1, tags="stats_fg")
content_w = min(1060, w - 2 * pad_x)
left_edge = (w - content_w) // 2
# 2. Spiel-Auswahl im transparenten box_purple Rahmen
sel_h = 104 if compact else 116
sel_cy = sep_y + 18 + sel_h // 2
sel_box = self.assets.get_box_photo("box_purple", (content_w, sel_h))
if sel_box:
self._photo_refs.append(sel_box)
cv.create_image(w // 2, sel_cy, image=sel_box, anchor="center", tags="stats_fg")
sel_lbl = self.assets.get_goth_text_photo(
t("stats_select_game_lbl"), size_px=FONT_SIZE_BODY + 2, color=FONT_COLOR_HEADING_SUB, align="left"
)
self._photo_refs.append(sel_lbl)
cv.create_image(left_edge + 26, sel_cy - 26, image=sel_lbl, anchor="w", tags="stats_fg")
total_bw = sum(bw for _, bw in self._game_btns) + max(0, len(self._game_btns) - 1) * 10
bx = (w - total_bw) // 2
for btn_wgt, bw in self._game_btns:
cv.create_window(bx + bw // 2, sel_cy + 18, window=btn_wgt, anchor="center", tags="stats_fg")
bx += bw + 10
# 3. Spielgebundene Rang- & XP-Leiste in box_gold_double (box_gold_small_double.png)
g_prog = Database.get_game_progress(self._profile["id"], self.selected_folder)
rank_h = 66 if compact else 74
rank_cy = (sel_cy + sel_h // 2) + 14 + rank_h // 2
rank_box = self.assets.get_box_photo("box_gold_double", (content_w, rank_h))
if rank_box:
self._photo_refs.append(rank_box)
cv.create_image(w // 2, rank_cy, image=rank_box, anchor="center", tags="stats_fg")
rank_txt = t(
"stats_game_rank_info",
self._active_game_title,
g_prog["title"],
g_prog["level"],
g_prog["current_xp"],
g_prog["needed_xp"],
)
rank_ph = self.assets.get_goth_text_photo(
rank_txt,
size_px=FONT_SIZE_BODY + 1,
color=FONT_COLOR_BODY_DEFAULT,
max_width=content_w - 300,
align="left",
)
self._photo_refs.append(rank_ph)
cv.create_image(left_edge + 28, rank_cy, image=rank_ph, anchor="w", tags="stats_fg")
# Eigener Gothic-XP-Balken (ohne ttk-Kasten)
bar_w = 230
bar_h = 14
bar_x1 = left_edge + content_w - 28 - bar_w
bar_x2 = bar_x1 + bar_w
bar_y1 = rank_cy - bar_h // 2
bar_y2 = bar_y1 + bar_h
cv.create_rectangle(
bar_x1, bar_y1, bar_x2, bar_y2,
fill="#0b0810", outline=UI_ACCENT_GOLD, width=1, tags="stats_fg"
)
ratio = max(0.0, min(1.0, float(g_prog["current_xp"]) / max(1.0, float(g_prog["needed_xp"]))))
if ratio > 0.0:
fill_w = max(2, int((bar_w - 4) * ratio))
cv.create_rectangle(
bar_x1 + 2, bar_y1 + 2, bar_x1 + 2 + fill_w, bar_y2 - 2,
fill=UI_ACCENT_AMETHYST, outline="", tags="stats_fg"
)
# 4. Statistik-Board darunter einbetten
board_top = rank_cy + rank_h // 2 + 16
board_h = max(225, min(260, h - board_top - max(36, int(h * 0.06))))
if self._board is not None:
cv.create_window(
w // 2,
board_top + board_h // 2,
window=self._board,
width=content_w,
height=board_h,
anchor="center",
tags="stats_fg",
)
self._board.after(10, lambda: self._board._on_configure(
type("Evt", (), {"width": content_w, "height": board_h})()
))
board.pack(fill="x")

View File

@ -1,55 +1,19 @@
# -*- coding: utf-8 -*-
# view/widgets/bot_setup_widget.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from tkinter import ttk
from resources.code_res.game_constants import (
BG_COLOR,
BOT_LEVEL_COUNT,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_DISABLED,
FONT_SIZE_BODY,
BORDER_COLOR, BOT_LEVEL_COUNT, CELL_BG, FG_COLOR, INPUT_BG, MUTED_FG, SUBTLE_BORDER
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
class BotSetupWidget(tk.Canvas):
"""
Rahmenloses Gegner-Auswahl-Panel mit GothEntry (input.png) und GothDropdown
(dropdown_closed.png / dropdown_box.png / dropdown_selection.png).
"""
ROW_HEIGHT = 44
class BotSetupWidget(tk.Frame):
"""Wiederverwendbares Gegner-Auswahl-Panel mit Aktiv-/Inaktiv-Schaltung."""
def __init__(self, parent, saved_configs: dict[int, tuple[str, int]], max_bots: int = 3, enabled: bool = True):
total_h = max_bots * self.ROW_HEIGHT + 8
try:
parent_bg = parent.cget("bg")
except Exception:
parent_bg = BG_COLOR
super().__init__(
parent,
height=total_h,
bg=parent_bg,
bd=0,
highlightthickness=0,
)
top = self.winfo_toplevel()
self.assets = getattr(top, "assets", None)
ctrl = getattr(top, "ctrl", None)
self.sounds = getattr(ctrl, "sounds", None) if ctrl else None
self._enabled = bool(enabled)
self._max_bots = max_bots
self.rows_data: list[tuple[int, tk.StringVar, tk.StringVar, GothEntry, GothDropdown]] = []
self._bg_photo: ImageTk.PhotoImage | None = None
self._lbl_photos: list[ImageTk.PhotoImage] = []
super().__init__(parent, bg=CELL_BG, padx=14, pady=10, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
self.rows_data = []
self._labels = []
self.level_labels = [t("none_bot")] + [t(f"bot_level_{i}") for i in range(BOT_LEVEL_COUNT)]
self.label_to_lvl = {self.level_labels[0]: -1}
@ -62,111 +26,52 @@ class BotSetupWidget(tk.Canvas):
if not saved_name.strip():
saved_name = default_name
name_var = tk.StringVar(value=saved_name)
ent = GothEntry(
self,
self.assets,
width=148,
height=36,
textvariable=name_var,
enabled=self._enabled,
row = tk.Frame(self, bg=CELL_BG)
row.pack(fill="x", pady=3)
lbl = tk.Label(
row, text=t("opponent_label", slot + 1),
font=("Helvetica", 10, "bold"), fg=FG_COLOR, bg=CELL_BG, width=10, anchor="w"
)
lbl.pack(side="left")
self._labels.append(lbl)
name_var = tk.StringVar(value=saved_name)
ent = tk.Entry(
row, textvariable=name_var, font=("Helvetica", 10),
bg=INPUT_BG, fg=FG_COLOR, disabledbackground="#16141c", disabledforeground="#666070",
bd=0, width=16, highlightthickness=1, highlightbackground=BORDER_COLOR, insertbackground="white"
)
ent.pack(side="left", padx=(4, 10), ipady=4)
init_lbl = self.level_labels[0]
if 0 <= saved_lvl < BOT_LEVEL_COUNT:
init_lbl = t(f"bot_level_{saved_lvl}")
lvl_var = tk.StringVar(value=init_lbl)
dd = GothDropdown(
self,
self.assets,
values=self.level_labels,
textvariable=lvl_var,
sound_mgr=self.sounds,
width=245,
height=36,
enabled=self._enabled,
cb = ttk.Combobox(
row, textvariable=lvl_var, values=self.level_labels,
state="readonly", font=("Helvetica", 10), width=32, style="Goth.TCombobox"
)
cb.pack(side="left", fill="x", expand=True)
self.rows_data.append((slot, name_var, lvl_var, ent, dd))
self.rows_data.append((slot, name_var, lvl_var, ent, cb))
self.bind("<Configure>", self._on_configure)
def _slice_bg(self, w: int, h: int):
if self.assets is None:
return
top = self.winfo_toplevel()
rw = max(w, top.winfo_width())
rh = max(h, top.winfo_height())
src = (
self.assets.raw_bg_vertical
if (rh > rw and self.assets.raw_bg_vertical is not None)
else (self.assets.raw_bg_horizontal or self.assets.raw_bg)
)
if src is None:
return
ox = max(0, min(rw - w, self.winfo_rootx() - top.winfo_rootx()))
oy = max(0, min(rh - h, self.winfo_rooty() - top.winfo_rooty()))
scaled = src.resize((rw, rh), Image.Resampling.BILINEAR)
patch = scaled.crop((ox, oy, ox + w, oy + h))
self._bg_photo = ImageTk.PhotoImage(patch)
self.delete("bs_bg")
self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags="bs_bg")
self.tag_lower("bs_bg")
def _on_configure(self, event):
w, h = max(1, event.width), max(1, event.height)
if w < 150 or h < 30:
return
self._slice_bg(w, h)
self._layout_rows(w)
def _layout_rows(self, w: int):
self.delete("bs_fg")
self._lbl_photos.clear()
if self.assets is None:
return
lbl_col = FONT_COLOR_BODY_DEFAULT if self._enabled else FONT_COLOR_DISABLED
lbl_w = 96
ent_w = 148
gap = 8
dd_w = max(165, w - lbl_w - ent_w - 2 * gap - 6)
for idx, (slot, _nvar, _lvar, ent, dd) in enumerate(self.rows_data):
cy = 4 + idx * self.ROW_HEIGHT + self.ROW_HEIGHT // 2
lbl_ph = self.assets.get_goth_text_photo(
t("opponent_label", slot + 1),
size_px=FONT_SIZE_BODY,
color=lbl_col,
align="left",
)
self._lbl_photos.append(lbl_ph)
self.create_image(2, cy, image=lbl_ph, anchor="w", tags="bs_fg")
self.create_window(lbl_w, cy, window=ent, anchor="w", tags="bs_fg")
if dd._width != dd_w:
dd._width = dd_w
dd.configure(width=dd_w)
dd._render_closed()
self.create_window(lbl_w + ent_w + gap, cy, window=dd, anchor="w", tags="bs_fg")
self.set_enabled(enabled)
def set_enabled(self, enabled: bool):
self._enabled = bool(enabled)
for _slot, _nvar, _lvar, ent, dd in self.rows_data:
ent.set_enabled(self._enabled)
dd.set_enabled(self._enabled)
if self.winfo_exists() and self.winfo_width() >= 150:
self._layout_rows(self.winfo_width())
for lbl in self._labels:
lbl.configure(fg=FG_COLOR if enabled else MUTED_FG)
for _slot, _nvar, _lvar, ent, cb in self.rows_data:
ent.configure(state="normal" if enabled else "disabled")
cb.configure(state="readonly" if enabled else "disabled")
def collect_configs(self) -> tuple[list[tuple[int, str]], dict[int, tuple[str, int]]]:
active_bots: list[tuple[int, str]] = []
to_persist: dict[int, tuple[str, int]] = {}
for slot, _name_var, lvl_var, ent, _dd in self.rows_data:
clean_name = ent.get().strip() or t("bot_default_name", slot + 1)
for slot, name_var, lvl_var, _ent, _cb in self.rows_data:
clean_name = name_var.get().strip() or t("bot_default_name", slot + 1)
ai_lvl = self.label_to_lvl.get(lvl_var.get(), -1)
to_persist[slot] = (clean_name, ai_lvl)
if ai_lvl >= 0:

View File

@ -1,586 +0,0 @@
# -*- coding: utf-8 -*-
# view/widgets/goth_dropdown.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageDraw, ImageEnhance, ImageTk
from resources.code_res.game_constants import (
BG_COLOR,
DROPDOWN_ITEM_TEXT_HOVER,
DROPDOWN_ITEM_TEXT_NORMAL,
DROPDOWN_ITEM_TEXT_SELECTED,
DROPDOWN_TEXT_CLOSED,
FONT_COLOR_DISABLED,
FONT_LETTER_SPACING_PX,
FONT_OUTLINE_COLOR,
FONT_OUTLINE_THICKNESS_PX,
FONT_SHADOW_COLOR,
FONT_SHADOW_ENABLED,
FONT_SHADOW_OFFSET_SMALL,
FONT_SIZE_DROPDOWN,
FONT_SIZE_SMALL_MIN,
FONT_VERTICAL_OFFSET_PX,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
)
from view.widgets.image_button import _clean_outer_black_matte, _get_old_london
_TRIM_CACHE: dict[tuple[int, int, int], Image.Image] = {}
def _trim_outer_black_bbox(pil_img: Image.Image, threshold: int = 38) -> Image.Image:
"""
Schneidet äußere schwarze Leerränder exakt bis zur eigentlichen Rahmenkante ab,
damit linkes Hauptstück und rechtes Button-Stück ohne Höhenversatz nahtlos aneinanderpassen.
"""
key = (id(pil_img), pil_img.width, pil_img.height)
if key in _TRIM_CACHE:
return _TRIM_CACHE[key]
clean = _clean_outer_black_matte(pil_img)
rgb = clean.convert("RGB")
w, h = rgb.size
px = rgb.load()
min_x, min_y = w, h
max_x, max_y = -1, -1
for y in range(h):
for x in range(w):
r, g, b = px[x, y]
if r > threshold or g > threshold or b > threshold:
if x < min_x:
min_x = x
if x > max_x:
max_x = x
if y < min_y:
min_y = y
if y > max_y:
max_y = y
if max_x <= min_x or max_y <= min_y:
_TRIM_CACHE[key] = clean
return clean
cropped = clean.crop((min_x, min_y, max_x + 1, max_y + 1))
_TRIM_CACHE[key] = cropped
return cropped
class GothDropdown(tk.Canvas):
"""
Zweiteiliges Gothic-Dropdown:
- Rechts: Button-Kappe (dropdown_closed_button / dropdown_box_hightlighted_button),
skaliert NUR über die Höhe im festen Original-Seitenverhältnis (wird niemals breitgezogen!).
- Links: Hauptkörper (dropdown_closed / dropdown_box_hightlighted),
hält die linke Zierecke scharf und streckt den Rest exakt bis zur Button-Kappe.
- Aufklapp-Liste: Nutzt ausschließlich dropdown_box.png (bringt Rahmen & Hintergrund mit),
Einträge komplett ohne Auswahl-Kasten/Hintergrund (nur Text-Highlight),
inkl. Scroll-Pfeilen oben/unten und Mausrad-Support.
"""
_active_popup_owner: GothDropdown | None = None
ARROW_ZONE_H = 18
def __init__(
self,
parent,
assets,
values: list[str] | tuple[str, ...] = (),
textvariable: tk.StringVar | None = None,
on_change=None,
sound_mgr=None,
width: int = 250,
height: int = 40,
font_size: int = FONT_SIZE_DROPDOWN,
max_visible_items: int = 7,
enabled: bool = True,
):
try:
parent_bg = parent.cget("bg")
except Exception:
parent_bg = BG_COLOR
super().__init__(
parent,
width=width,
height=height,
bg=parent_bg,
bd=0,
highlightthickness=0,
cursor="hand2" if enabled else "arrow",
)
self.assets = assets
self.sounds = sound_mgr
self._on_change = on_change
self._width = max(110, int(width))
self._height = max(28, int(height))
self._font_px = max(FONT_SIZE_SMALL_MIN, min(int(font_size), int(self._height * 0.52)))
self._max_visible = max(3, int(max_visible_items))
self._values: list[str] = list(values)
self._var = textvariable if textvariable is not None else tk.StringVar()
self._enabled = bool(enabled)
self._hovered = False
self._popup: tk.Toplevel | None = None
self._closed_photo: ImageTk.PhotoImage | None = None
self._popup_refs: list[ImageTk.PhotoImage] = []
self._scroll_offset: int = 0
self._hover_idx: int = -1
self._hover_arrow: str | None = None # "up" | "down" | None
if not self._var.get() and self._values:
self._var.set(self._values[0])
self._var.trace_add("write", lambda *_: self._render_closed())
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<Button-1>", self._toggle_popup)
self.bind("<Destroy>", lambda _e: self.close_popup())
self._render_closed()
# --- Kompatibilitäts-Methoden ---
def get(self) -> str:
return self._var.get()
def set(self, value: str):
self._var.set(value)
self._render_closed()
def current(self, newindex: int | None = None) -> int:
if newindex is not None and 0 <= newindex < len(self._values):
self.set(self._values[newindex])
cur = self._var.get()
return self._values.index(cur) if cur in self._values else -1
def set_values(self, values: list[str] | tuple[str, ...], keep_current: bool = True):
self._values = list(values)
if not keep_current or self._var.get() not in self._values:
self._var.set(self._values[0] if self._values else "")
self._render_closed()
def set_enabled(self, enabled: bool):
self._enabled = bool(enabled)
if not self._enabled:
self.close_popup()
self.configure(cursor="hand2" if self._enabled else "arrow")
self._render_closed()
# --- Nahtloses Zusammensetzen aus gezerrtem Body + proportionalem Button ---
def _compose_bar_pil(self, is_highlighted: bool) -> tuple[Image.Image | None, int]:
if is_highlighted:
raw_body = getattr(self.assets, "raw_dropdown_open", None) or getattr(self.assets, "raw_dropdown_closed", None)
raw_btn = getattr(self.assets, "raw_dropdown_open_btn", None) or getattr(self.assets, "raw_dropdown_closed_btn", None)
else:
raw_body = getattr(self.assets, "raw_dropdown_closed", None)
raw_btn = getattr(self.assets, "raw_dropdown_closed_btn", None)
if raw_body is None:
raw_body = getattr(self.assets, "raw_btn_default", None)
if raw_body is None:
return None, 36
h = self._height
w = self._width
body_trim = _trim_outer_black_bbox(raw_body)
if raw_btn is None:
full = body_trim.resize((w, h), Image.Resampling.LANCZOS)
return full, max(34, h)
btn_trim = _trim_outer_black_bbox(raw_btn)
# Button-Breite strikt proportional zur Zielhöhe (niemals in die Breite ziehen!)
btn_aspect = btn_trim.width / max(1, btn_trim.height)
btn_w = max(24, min(w // 2, int(round(h * btn_aspect))))
body_w = max(24, w - btn_w)
btn_scaled = btn_trim.resize((btn_w, h), Image.Resampling.LANCZOS)
# Linke Zierecke des Hauptkörpers proportional halten, Rest bis zum Button strecken
left_cap_src_w = max(12, int(body_trim.height * 0.30))
left_cap_dst_w = min(body_w // 2, max(8, int(round(h * 0.30))))
stretch_dst_w = max(1, body_w - left_cap_dst_w)
left_cap = body_trim.crop((0, 0, left_cap_src_w, body_trim.height)).resize(
(left_cap_dst_w, h), Image.Resampling.LANCZOS
)
mid_stretch = body_trim.crop((left_cap_src_w, 0, body_trim.width, body_trim.height)).resize(
(stretch_dst_w, h), Image.Resampling.BILINEAR
)
combined = Image.new("RGBA", (w, h), (0, 0, 0, 0))
combined.paste(left_cap, (0, 0))
combined.paste(mid_stretch, (left_cap_dst_w, 0))
combined.paste(btn_scaled, (body_w, 0))
return combined, btn_w
def _draw_tracked_text_clipped(
self,
img: Image.Image,
text: str,
x_left: int,
x_right: int,
color: str,
font_px: int,
):
if not text:
return
draw = ImageDraw.Draw(img)
clean_txt = self.assets.sanitize_goth_case(str(text))
fnt = _get_old_london(font_px)
avail_w = max(20, x_right - x_left)
def _measure(s: str) -> float:
tot = 0.0
for i, ch in enumerate(s):
tot += draw.textlength(ch, font=fnt)
if i < len(s) - 1:
tot += FONT_LETTER_SPACING_PX
return tot
disp = clean_txt
if _measure(disp) > avail_w:
while len(disp) > 1 and _measure(disp + "...") > avail_w:
disp = disp[:-1]
disp = disp.rstrip() + "..."
try:
asc, desc = fnt.getmetrics() # type: ignore[attr-defined]
th = asc + desc
except Exception:
th = font_px
cy = (img.height - th) / 2.0 + FONT_VERTICAL_OFFSET_PX
cx = float(x_left)
sx, sy = FONT_SHADOW_OFFSET_SMALL
for ch in disp:
if FONT_SHADOW_ENABLED and self._enabled:
draw.text((cx + sx, cy + sy), ch, font=fnt, fill=FONT_SHADOW_COLOR)
if FONT_OUTLINE_THICKNESS_PX > 0 and self._enabled:
draw.text(
(cx, cy),
ch,
font=fnt,
fill=color,
stroke_width=FONT_OUTLINE_THICKNESS_PX,
stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((cx, cy), ch, font=fnt, fill=color)
cx += draw.textlength(ch, font=fnt) + FONT_LETTER_SPACING_PX
def _render_closed(self):
if not self.winfo_exists():
return
self.delete("all")
is_open = (self._popup is not None and self._popup.winfo_exists())
use_highlight_art = self._enabled and (is_open or self._hovered)
bar_pil, btn_w = self._compose_bar_pil(is_highlighted=use_highlight_art)
if bar_pil is None:
return
if not self._enabled:
alpha = bar_pil.getchannel("A")
rgb = ImageEnhance.Color(bar_pil.convert("RGB")).enhance(0.10)
rgb = ImageEnhance.Brightness(rgb).enhance(0.58)
bar_pil = rgb.convert("RGBA")
bar_pil.putalpha(alpha)
txt_col = (
FONT_COLOR_DISABLED
if not self._enabled
else (DROPDOWN_ITEM_TEXT_HOVER if use_highlight_art else DROPDOWN_TEXT_CLOSED)
)
pad_left = max(14, int(self._height * 0.36))
text_right_limit = self._width - btn_w - 8
self._draw_tracked_text_clipped(
bar_pil,
self._var.get(),
x_left=pad_left,
x_right=text_right_limit,
color=txt_col,
font_px=self._font_px,
)
self._closed_photo = ImageTk.PhotoImage(bar_pil)
self.create_image(0, 0, image=self._closed_photo, anchor="nw")
def _on_enter(self, _e):
if self._enabled:
self._hovered = True
self._render_closed()
def _on_leave(self, _e):
self._hovered = False
self._render_closed()
# --- Aufklapp-Liste (dropdown_box.png ohne inneren Auswahl-Hintergrund/Rahmen) ---
@classmethod
def close_any_open_popup(cls):
if cls._active_popup_owner is not None:
cls._active_popup_owner.close_popup()
def close_popup(self):
if GothDropdown._active_popup_owner is self:
GothDropdown._active_popup_owner = None
if self._popup is not None:
try:
if self._popup.winfo_exists():
self._popup.destroy()
except Exception:
pass
self._popup = None
self._popup_refs.clear()
self._hover_arrow = None
if self.winfo_exists():
self._render_closed()
def _toggle_popup(self, _event=None):
if not self._enabled or not self._values:
return
if self._popup is not None and self._popup.winfo_exists():
self.close_popup()
return
GothDropdown.close_any_open_popup()
if self.sounds:
self.sounds.play("click")
self._open_popup()
def _open_popup(self):
GothDropdown._active_popup_owner = self
scrollable = len(self._values) > self._max_visible
vis_count = min(len(self._values), self._max_visible)
row_h = max(30, self._height - 6)
border_pad = 12
arrow_h = self.ARROW_ZONE_H if scrollable else 0
top_offset = border_pad + arrow_h
pop_w = self._width
pop_h = vis_count * row_h + 2 * top_offset
cur_idx = self.current()
if cur_idx >= vis_count:
self._scroll_offset = min(cur_idx - vis_count + 1, max(0, len(self._values) - vis_count))
else:
self._scroll_offset = 0
self._hover_idx = -1
self._hover_arrow = None
self.update_idletasks()
rx = self.winfo_rootx()
ry = self.winfo_rooty() + self._height + 2
screen_h = self.winfo_screenheight()
if ry + pop_h > screen_h - 24:
ry = max(8, self.winfo_rooty() - pop_h - 2)
pop = tk.Toplevel(self)
pop.wm_overrideredirect(True)
pop.attributes("-topmost", True)
pop.geometry(f"{pop_w}x{pop_h}+{rx}+{ry}")
pop.configure(bg=BG_COLOR)
self._popup = pop
cv = tk.Canvas(pop, width=pop_w, height=pop_h, bg=BG_COLOR, bd=0, highlightthickness=0, cursor="hand2")
cv.pack(fill="both", expand=True)
self._pop_cv = cv
self._pop_geom = (pop_w, pop_h, row_h, top_offset, vis_count, scrollable, border_pad)
self._redraw_popup_list()
self._render_closed()
cv.bind("<Motion>", self._on_popup_motion)
cv.bind("<Leave>", self._on_popup_leave)
cv.bind("<Button-1>", self._on_popup_click)
# Mausrad auf Windows/macOS (<MouseWheel>) + Linux/Crostini (<Button-4>/<Button-5>)
for target in (pop, cv):
target.bind("<MouseWheel>", self._on_popup_wheel)
target.bind("<Button-4>", lambda _e: self._scroll_by(-1))
target.bind("<Button-5>", lambda _e: self._scroll_by(1))
pop.bind("<Up>", lambda _e: self._scroll_by(-1))
pop.bind("<Down>", lambda _e: self._scroll_by(1))
pop.bind("<Escape>", lambda _e: self.close_popup())
pop.bind("<FocusOut>", lambda _e: self.close_popup())
pop.focus_force()
@staticmethod
def _draw_scroll_arrow(
draw: ImageDraw.ImageDraw,
cx: int,
cy: int,
direction: str,
enabled: bool,
hovered: bool,
):
"""Zeichnet einen klaren generischen Pfeil (▲ / ▼) oben bzw. unten in die Liste."""
if not enabled:
fill_col = FONT_COLOR_DISABLED
outline_col = None
elif hovered:
fill_col = "#ffffff"
outline_col = UI_ACCENT_AMETHYST
else:
fill_col = UI_ACCENT_GOLD
outline_col = "#0d0b12"
half_w = 8
half_h = 5
if direction == "up":
pts = [(cx, cy - half_h), (cx - half_w, cy + half_h), (cx + half_w, cy + half_h)]
else:
pts = [(cx, cy + half_h), (cx - half_w, cy - half_h), (cx + half_w, cy - half_h)]
draw.polygon(pts, fill=fill_col, outline=outline_col)
def _redraw_popup_list(self):
if self._popup is None or not self._popup.winfo_exists():
return
cv = self._pop_cv
pop_w, pop_h, row_h, top_offset, vis_count, scrollable, border_pad = self._pop_geom
cv.delete("all")
self._popup_refs.clear()
# dropdown_box.png bringt Rahmen & Hintergrund bereits komplett mit
box_pil = self.assets.get_9slice_pil("dropdown_box", (pop_w, pop_h))
if box_pil is None:
box_pil = Image.new("RGBA", (pop_w, pop_h), (16, 13, 22, 255))
else:
box_pil = box_pil.copy()
cur_val = self._var.get()
# Einträge komplett ohne Extra-Rahmen und ohne Auswahl-Hintergrund rendern
for slot in range(vis_count):
val_idx = self._scroll_offset + slot
if val_idx >= len(self._values):
break
item_txt = self._values[val_idx]
y0 = top_offset + slot * row_h
is_hov = (val_idx == self._hover_idx)
is_sel = (item_txt == cur_val)
if is_hov:
t_col = DROPDOWN_ITEM_TEXT_HOVER
elif is_sel:
t_col = DROPDOWN_ITEM_TEXT_SELECTED
else:
t_col = DROPDOWN_ITEM_TEXT_NORMAL
row_img = Image.new("RGBA", (pop_w, row_h), (0, 0, 0, 0))
self._draw_tracked_text_clipped(
row_img,
item_txt,
x_left=18,
x_right=pop_w - 18,
color=t_col,
font_px=max(FONT_SIZE_SMALL_MIN, self._font_px - 1),
)
box_pil.alpha_composite(row_img, (0, y0))
# Generelle Scroll-Pfeile oben & unten einzeichnen, sobald gescrollt werden kann
if scrollable:
draw = ImageDraw.Draw(box_pil)
can_up = self._scroll_offset > 0
can_down = (self._scroll_offset + vis_count) < len(self._values)
up_cy = border_pad + self.ARROW_ZONE_H // 2
dn_cy = pop_h - border_pad - self.ARROW_ZONE_H // 2
self._draw_scroll_arrow(
draw, pop_w // 2, up_cy, "up",
enabled=can_up, hovered=(self._hover_arrow == "up"),
)
self._draw_scroll_arrow(
draw, pop_w // 2, dn_cy, "down",
enabled=can_down, hovered=(self._hover_arrow == "down"),
)
tk_pop = ImageTk.PhotoImage(box_pil)
self._popup_refs.append(tk_pop)
cv.create_image(0, 0, image=tk_pop, anchor="nw")
def _hit_arrow_zone(self, y: int) -> str | None:
_pop_w, pop_h, _row_h, top_offset, _vis_count, scrollable, _border_pad = self._pop_geom
if not scrollable:
return None
if 0 <= y < top_offset:
return "up"
if (pop_h - top_offset) < y <= pop_h:
return "down"
return None
def _slot_from_y(self, y: int) -> int:
_pop_w, _pop_h, row_h, top_offset, vis_count, _scrollable, _border_pad = self._pop_geom
rel = y - top_offset
if rel < 0:
return -1
slot = rel // row_h
if 0 <= slot < vis_count and (self._scroll_offset + slot) < len(self._values):
return self._scroll_offset + slot
return -1
def _on_popup_motion(self, event):
arr = self._hit_arrow_zone(event.y)
idx = -1 if arr is not None else self._slot_from_y(event.y)
if idx != self._hover_idx or arr != self._hover_arrow:
self._hover_idx = idx
self._hover_arrow = arr
self._redraw_popup_list()
def _on_popup_leave(self, _event):
if self._hover_idx != -1 or self._hover_arrow is not None:
self._hover_idx = -1
self._hover_arrow = None
self._redraw_popup_list()
def _on_popup_click(self, event):
arr = self._hit_arrow_zone(event.y)
if arr == "up":
self._scroll_by(-1)
return
if arr == "down":
self._scroll_by(1)
return
idx = self._slot_from_y(event.y)
if 0 <= idx < len(self._values):
chosen = self._values[idx]
changed = (chosen != self._var.get())
if self.sounds:
self.sounds.play("click")
self._var.set(chosen)
self.close_popup()
if changed and callable(self._on_change):
self._on_change(chosen)
else:
self.close_popup()
def _scroll_by(self, delta: int):
if self._popup is None or not self._popup.winfo_exists():
return
_pop_w, _pop_h, _row_h, _top_offset, vis_count, scrollable, _border_pad = self._pop_geom
if not scrollable:
return
max_off = max(0, len(self._values) - vis_count)
new_off = max(0, min(max_off, self._scroll_offset + delta))
if new_off != self._scroll_offset:
self._scroll_offset = new_off
self._redraw_popup_list()
def _on_popup_wheel(self, event):
if getattr(event, "delta", 0) == 0:
return
step = -1 if event.delta > 0 else 1
self._scroll_by(step)

View File

@ -1,162 +0,0 @@
# -*- coding: utf-8 -*-
# view/widgets/goth_entry.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_DISABLED,
FONT_FAMILY_PRIMARY,
FONT_SIZE_INPUT,
INPUT_BG,
INPUT_CARET_COLOR,
INPUT_SELECTION_BG,
INPUT_TEXT_PLACEHOLDER,
INPUT_TEXT_VALUE,
)
from view.widgets.image_button import _clean_outer_black_matte
class GothEntry(tk.Canvas):
"""
Rahmenloses Gothic-Texteingabefeld auf Basis von input.png:
Kein künstlicher Tkinter-Rahmen, goldener Cursor, Amethyst-Selektion & Platzhalter-Support.
"""
def __init__(
self,
parent,
assets,
width: int = 240,
height: int = 42,
textvariable: tk.StringVar | None = None,
placeholder: str = "",
font_size: int = FONT_SIZE_INPUT,
enabled: bool = True,
):
try:
parent_bg = parent.cget("bg")
except Exception:
parent_bg = BG_COLOR
super().__init__(
parent,
width=width,
height=height,
bg=parent_bg,
bd=0,
highlightthickness=0,
)
self.assets = assets
self._width = max(80, int(width))
self._height = max(30, int(height))
self._placeholder = placeholder
self._placeholder_active = False
self._enabled = bool(enabled)
self._var = textvariable if textvariable is not None else tk.StringVar()
self._bg_photo: ImageTk.PhotoImage | None = None
inner_fill = INPUT_BG
if getattr(self.assets, "raw_input", None) is not None:
clean_inp = _clean_outer_black_matte(self.assets.raw_input)
scaled = clean_inp.resize((self._width, self._height), Image.Resampling.LANCZOS)
# Exakte Innenfarbe aus der Grafikmitte abgreifen, damit das eingebettete Entry unsichtbar verschmilzt
cx, cy = self._width // 2, self._height // 2
r, g, b, a = scaled.getpixel((cx, cy))
if a > 200:
inner_fill = f"#{r:02x}{g:02x}{b:02x}"
self._bg_photo = ImageTk.PhotoImage(scaled)
self.create_image(0, 0, image=self._bg_photo, anchor="nw")
self._inner_bg = inner_fill
pad_x = max(16, int(self._width * 0.08))
eff_font_px = min(font_size, max(14, int(self._height * 0.46)))
self.entry = tk.Entry(
self,
textvariable=self._var,
font=(FONT_FAMILY_PRIMARY, eff_font_px),
fg=INPUT_TEXT_VALUE,
disabledforeground=FONT_COLOR_DISABLED,
disabledbackground=inner_fill,
readonlybackground=inner_fill,
bg=inner_fill,
insertbackground=INPUT_CARET_COLOR,
insertwidth=2,
selectbackground=INPUT_SELECTION_BG,
selectforeground="#ffffff",
bd=0,
relief="flat",
highlightthickness=0,
)
self.create_window(
self._width // 2,
self._height // 2,
window=self.entry,
width=max(40, self._width - 2 * pad_x),
height=max(18, self._height - 14),
anchor="center",
)
self.entry.bind("<FocusIn>", self._on_focus_in)
self.entry.bind("<FocusOut>", self._on_focus_out)
self.bind("<Button-1>", lambda _e: self.entry.focus_set() if self._enabled else None)
if not self._var.get() and self._placeholder:
self._show_placeholder()
self.set_enabled(self._enabled)
def _show_placeholder(self):
if self._placeholder and not self._var.get():
self._placeholder_active = True
self.entry.configure(fg=INPUT_TEXT_PLACEHOLDER)
self._var.set(self._placeholder)
def _clear_placeholder(self):
if self._placeholder_active:
self._placeholder_active = False
self._var.set("")
self.entry.configure(fg=INPUT_TEXT_VALUE)
def _on_focus_in(self, _event):
if self._enabled:
self._clear_placeholder()
def _on_focus_out(self, _event):
if not self._var.get().strip():
self._var.set("")
self._show_placeholder()
def get(self) -> str:
if self._placeholder_active:
return ""
return self._var.get()
def set(self, value: str):
self._placeholder_active = False
self._var.set(value)
if not value and self._placeholder and self.focus_get() != self.entry:
self._show_placeholder()
else:
self.entry.configure(fg=INPUT_TEXT_VALUE if self._enabled else FONT_COLOR_DISABLED)
def delete(self, first, last=None):
self._clear_placeholder()
self.entry.delete(first, last)
def insert(self, index, string: str):
self._clear_placeholder()
self.entry.insert(index, string)
def set_enabled(self, enabled: bool):
self._enabled = bool(enabled)
self.entry.configure(state="normal" if self._enabled else "disabled")
self.configure(cursor="xterm" if self._enabled else "arrow")
def bind_return(self, callback):
self.entry.bind("<Return>", callback)

View File

@ -1,148 +1,12 @@
# -*- coding: utf-8 -*-
# view/widgets/image_button.py
from __future__ import annotations
import re
from pathlib import Path
import tkinter as tk
from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageTk
from resources.code_res.game_constants import (
BG_COLOR,
BTN_AMETHYST_TEXT_ACTIVE,
BTN_AMETHYST_TEXT_DISABLED,
BTN_AMETHYST_TEXT_HOVER,
BTN_AMETHYST_TEXT_NORMAL,
BTN_FIRE_TEXT_ACTIVE,
BTN_FIRE_TEXT_DISABLED,
BTN_FIRE_TEXT_HOVER,
BTN_FIRE_TEXT_NORMAL,
FONTS_REL_DIR,
FONT_FILE_PRIMARY,
FONT_FORCE_MIXED_CASE,
FONT_LETTER_SPACING_PX,
FONT_OUTLINE_COLOR,
FONT_OUTLINE_THICKNESS_PX,
FONT_SHADOW_COLOR,
FONT_SHADOW_ENABLED,
FONT_SHADOW_OFFSET_DEFAULT,
FONT_SIZE_BUTTON,
FONT_SIZE_SMALL_MIN,
FONT_VERTICAL_OFFSET_PX,
)
_ROOT_DIR = Path(__file__).resolve().parents[2]
_FONT_CACHE: dict[int, ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
_ALPHA_CORNER_CACHE: dict[tuple[int, int, int], Image.Image] = {}
_TRIM_BTN_CACHE: dict[tuple[int, int, int], Image.Image] = {}
_LEADING_ICON_RE = re.compile(r"^(?:[←→↑↓↔❖†•✦★☆▶◀«»]+|\+(?=\s))\s*")
_TRAILING_ICON_RE = re.compile(r"\s*[←→↑↓↔❖†•✦★☆▶◀«»]+$")
# Geometrie-Anteil der seitlichen Zierkappen & oberen/unteren Rahmenleisten in button*.png
_SIDE_CAP_ASPECT = 0.46 # Breite einer Seitenkappe relativ zur Button-Höhe (inkl. Innenspitze)
_VERTICAL_FRAME_RATIO = 0.36 # Anteil oben + unten für Metallrahmen & Mittel-Ornament
def _get_old_london(size_px: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
size_px = max(13, int(size_px))
if size_px not in _FONT_CACHE:
fpath = _ROOT_DIR / FONTS_REL_DIR / FONT_FILE_PRIMARY
try:
_FONT_CACHE[size_px] = ImageFont.truetype(str(fpath), size_px)
except Exception:
_FONT_CACHE[size_px] = ImageFont.load_default()
return _FONT_CACHE[size_px]
def _clean_outer_black_matte(pil_img: Image.Image) -> Image.Image:
"""Macht rein schwarze Außenpixel außerhalb der Button-Zierspitzen transparent."""
key = (id(pil_img), pil_img.width, pil_img.height)
if key in _ALPHA_CORNER_CACHE:
return _ALPHA_CORNER_CACHE[key]
rgba = pil_img.convert("RGBA")
px = rgba.load()
w, h = rgba.size
if px[0, 0][3] > 240 and max(px[0, 0][:3]) < 14:
visited = bytearray(w * h)
stack = [
(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1),
(w // 2, 0), (w // 2, h - 1), (0, h // 2), (w - 1, h // 2),
]
while stack:
x, y = stack.pop()
idx = y * w + x
if visited[idx]:
continue
visited[idx] = 1
r, g, b, a = px[x, y]
mx = max(r, g, b)
if mx < 18:
new_a = 0 if mx < 8 else int((mx - 8) * 25.5)
px[x, y] = (r, g, b, min(a, new_a))
if x > 0:
stack.append((x - 1, y))
if x + 1 < w:
stack.append((x + 1, y))
if y > 0:
stack.append((x, y - 1))
if y + 1 < h:
stack.append((x, y + 1))
_ALPHA_CORNER_CACHE[key] = rgba
return rgba
def _trim_button_art(pil_img: Image.Image) -> Image.Image:
"""Entfernt leere transparente/schwarze Außenränder um die eigentliche Button-Grafik."""
key = (id(pil_img), pil_img.width, pil_img.height)
if key in _TRIM_BTN_CACHE:
return _TRIM_BTN_CACHE[key]
clean = _clean_outer_black_matte(pil_img)
bbox = clean.getbbox()
cropped = clean.crop(bbox) if bbox else clean
_TRIM_BTN_CACHE[key] = cropped
return cropped
def _scale_button_3slice(src_pil: Image.Image, target_w: int, target_h: int) -> tuple[Image.Image, int]:
"""
Skaliert die Button-Grafik verzerrungsfrei per 3-Slice:
- Linke & rechte Zierkappe skalieren proportional zur Zielhöhe (keine plattgezogenen Spitzen!).
- Das Mittelstück (Damast + Mittel-Ornament) übernimmt die restliche Breite.
Gibt (fertiges RGBA-Bild, effektive Seitenkappen-Breite in px) zurück.
"""
trimmed = _trim_button_art(src_pil)
sw, sh = trimmed.size
src_cap_w = max(16, int(round(sh * _SIDE_CAP_ASPECT)))
dst_cap_w = max(12, min(target_w // 3, int(round(target_h * _SIDE_CAP_ASPECT))))
mid_dst_w = max(4, target_w - 2 * dst_cap_w)
if sw <= 2 * src_cap_w + 8:
return trimmed.resize((target_w, target_h), Image.Resampling.LANCZOS), dst_cap_w
left_cap = trimmed.crop((0, 0, src_cap_w, sh)).resize((dst_cap_w, target_h), Image.Resampling.LANCZOS)
right_cap = trimmed.crop((sw - src_cap_w, 0, sw, sh)).resize((dst_cap_w, target_h), Image.Resampling.LANCZOS)
mid_piece = trimmed.crop((src_cap_w, 0, sw - src_cap_w, sh)).resize((mid_dst_w, target_h), Image.Resampling.LANCZOS)
out = Image.new("RGBA", (target_w, target_h), (0, 0, 0, 0))
out.paste(left_cap, (0, 0))
out.paste(mid_piece, (dst_cap_w, 0))
out.paste(right_cap, (dst_cap_w + mid_dst_w, 0))
return out, dst_cap_w
from PIL import Image, ImageEnhance, ImageTk
from resources.code_res.game_constants import BG_COLOR, FG_COLOR
class ImageButton(tk.Label):
"""
Gothic UI Button (Amethyst & Fire) mit echter Rahmen-Einberechnung:
Berechnet Seitenkappen + oberen/unteren Zierrahmen automatisch in die Button-Größe ein,
sodass Text niemals in die Eck-Spitzen oder Rahmenlinien ragt.
"""
"""Rahmenloser Alpha-PNG-Button mit echtem Graufilter für inaktive Zustände (enabled=False)."""
def __init__(
self,
parent,
@ -151,44 +15,47 @@ class ImageButton(tk.Label):
pil_hover,
command,
sound_mgr=None,
width: int = 150,
height: int = 36,
font=None,
width: int = 180,
height: int = 42,
font=("Helvetica", 11, "bold"),
enabled: bool = True,
style: str | None = None,
auto_expand: bool = True,
):
try:
parent_bg = parent.cget("bg")
except Exception:
parent_bg = BG_COLOR
self._requested_width = max(56, int(width))
self._height = max(28, int(height))
self._auto_expand = bool(auto_expand)
self._text = self._prepare_label_text(str(text or ""))
self._pil_normal = pil_normal
self._pil_hover = pil_hover or pil_normal
self._normal_photo = None
self._hover_photo = None
self._disabled_photo = None
if pil_normal:
resized_norm = pil_normal.resize((width, height), Image.Resampling.LANCZOS)
self._normal_photo = ImageTk.PhotoImage(resized_norm)
# Automatischer Grau- & Abdunklungsfilter für nicht klickbare Buttons
gray_base = ImageEnhance.Color(resized_norm).enhance(0.0)
dimmed = ImageEnhance.Brightness(gray_base).enhance(0.55)
self._disabled_photo = ImageTk.PhotoImage(dimmed)
if pil_hover:
resized_hov = pil_hover.resize((width, height), Image.Resampling.LANCZOS)
self._hover_photo = ImageTk.PhotoImage(resized_hov)
self._sound_mgr = sound_mgr
self._user_cmd = command
self._enabled = bool(enabled)
self._hovered = False
if style in ("fire", "amethyst"):
self._style = style
else:
self._style = self._detect_style(parent, pil_normal, pil_hover)
self._font_px = self._resolve_font_px(font, self._height)
self._width = self._compute_framed_width()
self._rebuild_state_photos()
init_photo = self._photo_normal if self._enabled else self._photo_disabled
init_img = self._normal_photo if self._enabled else self._disabled_photo
init_fg = FG_COLOR if self._enabled else "#777282"
super().__init__(
parent,
text="" if init_photo is not None else self._text,
image=init_photo if init_photo is not None else "",
text=text,
image=init_img if init_img else "",
compound="center",
font=font,
fg=init_fg,
bg=parent_bg,
bd=0,
padx=0,
@ -199,238 +66,42 @@ class ImageButton(tk.Label):
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<ButtonPress-1>", self._on_press)
self.bind("<ButtonRelease-1>", self._on_release)
@property
def pixel_width(self) -> int:
"""Tatsächliche Gesamtbreite des Buttons inklusive Rahmen-Aufschlag."""
return self._width
@property
def pixel_height(self) -> int:
return self._height
@staticmethod
def _measure_text_px(text: str, pil_font) -> float:
if not text:
return 0.0
dummy = Image.new("RGBA", (4, 4), (0, 0, 0, 0))
draw = ImageDraw.Draw(dummy)
total = 0.0
for i, ch in enumerate(text):
total += draw.textlength(ch, font=pil_font)
if i < len(text) - 1:
total += FONT_LETTER_SPACING_PX
return total
def _horizontal_frame_inset(self) -> int:
"""Breite EINER seitlichen Rahmenkappe + Sicherheitsabstand vor der Innenspitze."""
cap_px = max(13, int(round(self._height * _SIDE_CAP_ASPECT)))
return cap_px + 6
def _compute_framed_width(self) -> int:
"""Stellt sicher, dass width immer groß genug für Text + beide Seitenrahmen ist."""
if not self._text or not self._auto_expand:
return self._requested_width
pil_font = _get_old_london(self._font_px)
txt_w = self._measure_text_px(self._text, pil_font)
needed_w = int(round(txt_w + 2 * self._horizontal_frame_inset()))
return max(self._requested_width, needed_w)
@classmethod
def _prepare_label_text(cls, txt: str) -> str:
cleaned = _LEADING_ICON_RE.sub("", txt.strip())
cleaned = _TRAILING_ICON_RE.sub("", cleaned).strip()
cleaned = cleaned.replace("→", "-").replace("←", "-")
if not cleaned or not FONT_FORCE_MIXED_CASE:
return cleaned
parts = cleaned.split(" ")
fixed = []
for p in parts:
letters = [c for c in p if c.isalpha()]
if len(letters) >= 4 and all(c.isupper() for c in letters):
fixed.append(p.capitalize())
else:
fixed.append(p)
return " ".join(fixed)
@staticmethod
def _detect_style(parent, pil_normal, pil_hover) -> str:
try:
top = parent.winfo_toplevel()
assets = getattr(top, "assets", None)
if assets is not None and getattr(assets, "raw_btn_fire", None) is not None:
if pil_normal is assets.raw_btn_fire or pil_hover is assets.raw_btn_fire:
return "fire"
except Exception:
pass
return "amethyst"
@staticmethod
def _resolve_font_px(font_arg, btn_h: int) -> int:
# Nur das innere Feld abzüglich oberem/unterem Zierrahmen (_VERTICAL_FRAME_RATIO) für die Schrift nutzen!
inner_h = max(14.0, btn_h * (1.0 - _VERTICAL_FRAME_RATIO))
max_safe_px = max(14, min(FONT_SIZE_BUTTON, int(round(inner_h * 0.80))))
auto_px = max(FONT_SIZE_SMALL_MIN if btn_h >= 34 else 14, max_safe_px)
if isinstance(font_arg, (tuple, list)) and len(font_arg) >= 2:
try:
fam = str(font_arg[0]).lower()
raw_sz = int(font_arg[1])
if "london" in fam:
return max(14, min(max_safe_px, raw_sz))
scaled = int(round(raw_sz * 1.85))
return max(14, min(max_safe_px, scaled))
except Exception:
pass
return auto_px
def _palette(self) -> tuple[str, str, str, str]:
if self._style == "fire":
return (
BTN_FIRE_TEXT_NORMAL,
BTN_FIRE_TEXT_HOVER,
BTN_FIRE_TEXT_ACTIVE,
BTN_FIRE_TEXT_DISABLED,
)
return (
BTN_AMETHYST_TEXT_NORMAL,
BTN_AMETHYST_TEXT_HOVER,
BTN_AMETHYST_TEXT_ACTIVE,
BTN_AMETHYST_TEXT_DISABLED,
)
def _compose_button_photo(
self,
base_pil: Image.Image | None,
text_color: str,
dim_disabled: bool = False,
brighten_active: bool = False,
) -> ImageTk.PhotoImage | None:
if base_pil is None:
return None
bg, cap_w = _scale_button_3slice(base_pil, self._width, self._height)
if dim_disabled:
alpha = bg.getchannel("A")
rgb = ImageEnhance.Color(bg.convert("RGB")).enhance(0.10)
rgb = ImageEnhance.Brightness(rgb).enhance(0.55)
bg = rgb.convert("RGBA")
bg.putalpha(alpha)
elif brighten_active:
alpha = bg.getchannel("A")
rgb = ImageEnhance.Brightness(bg.convert("RGB")).enhance(1.12)
bg = rgb.convert("RGBA")
bg.putalpha(alpha)
if self._text:
draw = ImageDraw.Draw(bg)
# Verfügbare Innenbreite strikt zwischen linker und rechter Zierkappe!
side_inset = cap_w + 5
max_txt_w = max(20, self._width - 2 * side_inset)
f_px = self._font_px
pil_font = _get_old_london(f_px)
def _line_w(fnt) -> float:
total = 0.0
for i, ch in enumerate(self._text):
total += draw.textlength(ch, font=fnt)
if i < len(self._text) - 1:
total += FONT_LETTER_SPACING_PX
return total
while _line_w(pil_font) > max_txt_w and f_px > 13:
f_px -= 1
pil_font = _get_old_london(f_px)
tw = _line_w(pil_font)
try:
ascent, descent = pil_font.getmetrics() # type: ignore[attr-defined]
th = ascent + descent
except Exception:
th = f_px
cur_x = (self._width - tw) / 2.0
cur_y = (self._height - th) / 2.0 + FONT_VERTICAL_OFFSET_PX
sx, sy = FONT_SHADOW_OFFSET_DEFAULT
for ch in self._text:
if FONT_SHADOW_ENABLED and not dim_disabled:
draw.text((cur_x + sx, cur_y + sy), ch, font=pil_font, fill=FONT_SHADOW_COLOR)
if FONT_OUTLINE_THICKNESS_PX > 0 and not dim_disabled:
draw.text(
(cur_x, cur_y),
ch,
font=pil_font,
fill=text_color,
stroke_width=FONT_OUTLINE_THICKNESS_PX,
stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((cur_x, cur_y), ch, font=pil_font, fill=text_color)
cur_x += draw.textlength(ch, font=pil_font) + FONT_LETTER_SPACING_PX
return ImageTk.PhotoImage(bg)
def _rebuild_state_photos(self):
c_norm, c_hov, c_act, c_dis = self._palette()
self._photo_normal = self._compose_button_photo(self._pil_normal, c_norm)
self._photo_hover = self._compose_button_photo(self._pil_hover, c_hov)
self._photo_active = self._compose_button_photo(self._pil_hover, c_act, brighten_active=True)
self._photo_disabled = self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True)
def set_text(self, new_text: str):
self._text = self._prepare_label_text(str(new_text or ""))
self._width = self._compute_framed_width()
self._rebuild_state_photos()
self.set_enabled(self._enabled)
self.bind("<Button-1>", self._on_click)
def set_enabled(self, enabled: bool):
self._enabled = bool(enabled)
if not self._enabled:
self._hovered = False
if self._enabled:
self.configure(
image=self._photo_disabled if self._photo_disabled else "",
cursor="arrow",
image=self._normal_photo if self._normal_photo else "",
fg=FG_COLOR,
cursor="hand2",
)
else:
target = self._photo_hover if self._hovered else self._photo_normal
self.configure(
image=target if target else "",
cursor="hand2",
image=self._disabled_photo if self._disabled_photo else "",
fg="#777282",
cursor="arrow",
)
def _on_enter(self, _event):
if not self._enabled:
return
self._hovered = True
if self._photo_hover:
self.configure(image=self._photo_hover)
if self._hover_photo:
self.configure(image=self._hover_photo, fg="#ffffff")
else:
self.configure(fg="#ffffff")
def _on_leave(self, _event):
self._hovered = False
if not self._enabled:
return
if self._photo_normal:
self.configure(image=self._photo_normal)
if self._normal_photo:
self.configure(image=self._normal_photo, fg=FG_COLOR)
else:
self.configure(fg=FG_COLOR)
def _on_press(self, _event):
def _on_click(self, _event):
if not self._enabled:
return
if self._photo_active:
self.configure(image=self._photo_active)
def _on_release(self, event):
if not self._enabled:
return
inside = (0 <= event.x < self._width) and (0 <= event.y < self._height)
self._hovered = inside
target = self._photo_hover if inside else self._photo_normal
if target:
self.configure(image=target)
if inside:
if self._sound_mgr:
self._sound_mgr.play("click")
if self._user_cmd:

View File

@ -1,55 +1,23 @@
# -*- coding: utf-8 -*-
# view/widgets/resizing_bg.py
import tkinter as tk
from PIL import Image, ImageTk
class ResizingBG(tk.Canvas):
"""
Vollbild-Hintergrund-Canvas:
Wechselt je nach Seitenverhältnis automatisch zwischen background_horizontal.jpg (w >= h)
und background_vertical.jpg (h > w) und dient gleichzeitig als rahmenlose Zeichenfläche.
"""
def __init__(self, parent, pil_horizontal, pil_vertical=None, **kwargs):
kwargs.setdefault("highlightthickness", 0)
kwargs.setdefault("bd", 0)
super().__init__(parent, **kwargs)
self.raw_horiz = pil_horizontal
self.raw_vert = pil_vertical or pil_horizontal
class ResizingBG(tk.Label):
def __init__(self, parent, pil_image, **kwargs):
super().__init__(parent, bd=0, **kwargs)
self.raw_img = pil_image
self._photo = None
self._resize_job = None
self._last_size = (0, 0)
self.bind("<Configure>", self._on_resize, add="+")
def _pick_source_image(self, w: int, h: int):
if h > w and self.raw_vert is not None:
return self.raw_vert
return self.raw_horiz or self.raw_vert
self.bind("<Configure>", self._on_resize)
def _on_resize(self, event):
if event.widget != self:
return
w, h = max(1, event.width), max(1, event.height)
if (w, h) == self._last_size:
return
if self._resize_job:
try:
self.after_cancel(self._resize_job)
except Exception:
pass
if self._photo is None:
self._render(w, h)
else:
self._resize_job = self.after(45, lambda: self._render(w, h))
w, h = max(1, event.width), max(1, event.height)
self._resize_job = self.after(60, lambda: self._render(w, h))
def _render(self, w: int, h: int):
self._resize_job = None
src = self._pick_source_image(w, h)
if not self.winfo_exists() or src is None:
return
self._last_size = (w, h)
resized = src.resize((w, h), Image.Resampling.LANCZOS)
def _render(self, w, h):
resized = self.raw_img.resize((w, h), Image.Resampling.LANCZOS)
self._photo = ImageTk.PhotoImage(resized)
self.delete("bg_img")
self.create_image(0, 0, image=self._photo, anchor="nw", tags="bg_img")
self.tag_lower("bg_img")
self.configure(image=self._photo)

View File

@ -1,192 +1,60 @@
# -*- coding: utf-8 -*-
# view/widgets/stats_board_widget.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from tkinter import ttk
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_BODY_DEFAULT,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_HEADING_SUB,
FONT_COLOR_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_HEADING,
FONT_SIZE_SMALL_MIN,
STAT_FIELD_KEYS,
ACCENT_GOTH, BORDER_COLOR, CELL_BG, FG_COLOR,
MUTED_FG, PANEL_BG, STAT_FIELD_KEYS, SUBTLE_BORDER
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
class StatsBoardWidget(tk.Canvas):
"""
Rahmenloses Gothic-Statistik-Board:
Schneidet seinen Hintergrund live aus dem Hauptfenster-Hintergrundbild aus,
rahmt die Tafel mit box_big.png und jede der 8 Kennzahlen mit box_small_purple.png.
"""
BOARD_HEIGHT = 238
class StatsBoardWidget(tk.Frame):
def __init__(self, parent, title: str, filter_map: dict[str, int | None], fetch_callback):
super().__init__(
parent,
height=self.BOARD_HEIGHT,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
parent, bg=PANEL_BG, padx=16, pady=12,
highlightthickness=1, highlightbackground=BORDER_COLOR
)
top = self.winfo_toplevel()
self.assets = getattr(top, "assets", None)
ctrl = getattr(top, "ctrl", None)
self.sounds = getattr(ctrl, "sounds", None) if ctrl else None
self._title = str(title or "")
self.filter_map = dict(filter_map)
self.filter_map = filter_map
self.fetch_callback = fetch_callback
self._stats_data: dict = {}
self._bg_photo: ImageTk.PhotoImage | None = None
self._photo_refs: list[ImageTk.PhotoImage] = []
self._last_geom: tuple[int, int, int, int] = (0, 0, -1, -1)
header = tk.Frame(self, bg=PANEL_BG)
header.pack(fill="x", pady=(0, 8))
first_key = next(iter(self.filter_map.keys()), "")
self.title_lbl = tk.Label(header, text=title, font=("Georgia", 12, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG)
self.title_lbl.pack(side="left")
first_key = next(iter(filter_map.keys()))
self.filter_var = tk.StringVar(value=first_key)
self.filter_cb = GothDropdown(
self,
self.assets,
values=list(self.filter_map.keys()),
textvariable=self.filter_var,
on_change=lambda _val: self.refresh(),
sound_mgr=self.sounds,
width=290,
height=38,
self.filter_cb = ttk.Combobox(
header, textvariable=self.filter_var,
values=list(filter_map.keys()), state="readonly",
width=28, style="Goth.TCombobox"
)
self.filter_cb.pack(side="right")
self.bind("<Configure>", self._on_configure)
grid = tk.Frame(self, bg=PANEL_BG)
grid.pack(fill="x")
for col in range(4):
grid.columnconfigure(col, weight=1)
self.value_labels = {}
for i, (stat_key, i18n_key) in enumerate(STAT_FIELD_KEYS):
r, c = divmod(i, 4)
cell = tk.Frame(grid, bg=CELL_BG, padx=10, pady=6, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
cell.grid(row=r, column=c, padx=4, pady=3, sticky="nsew")
tk.Label(cell, text=t(i18n_key), font=("Helvetica", 9), fg=MUTED_FG, bg=CELL_BG).pack(anchor="w")
val_lbl = tk.Label(cell, text="0", font=("Helvetica", 12, "bold"), fg=FG_COLOR, bg=CELL_BG)
val_lbl.pack(anchor="w", pady=(1, 0))
self.value_labels[stat_key] = val_lbl
self.filter_cb.bind("<<ComboboxSelected>>", lambda e: self.refresh())
self.refresh()
def set_title(self, new_title: str):
self._title = str(new_title or "")
if self.winfo_exists() and self.winfo_width() >= 120:
self._redraw_contents(self.winfo_width(), self.winfo_height())
self.title_lbl.configure(text=new_title)
def refresh(self):
vid = self.filter_map.get(self.filter_var.get())
self._stats_data = self.fetch_callback(vid) or {}
if self.winfo_exists() and self.winfo_width() >= 120:
self._redraw_contents(self.winfo_width(), self.winfo_height())
def _slice_global_bg(self, w: int, h: int):
if self.assets is None:
return
top = self.winfo_toplevel()
rw = max(w, top.winfo_width())
rh = max(h, top.winfo_height())
src = (
self.assets.raw_bg_vertical
if (rh > rw and self.assets.raw_bg_vertical is not None)
else (self.assets.raw_bg_horizontal or self.assets.raw_bg)
)
if src is None:
return
ox = max(0, min(rw - w, self.winfo_rootx() - top.winfo_rootx()))
oy = max(0, min(rh - h, self.winfo_rooty() - top.winfo_rooty()))
scaled = src.resize((rw, rh), Image.Resampling.BILINEAR)
patch = scaled.crop((ox, oy, ox + w, oy + h))
self._bg_photo = ImageTk.PhotoImage(patch)
self.delete("sb_bg")
self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags="sb_bg")
self.tag_lower("sb_bg")
def _on_configure(self, event):
w, h = max(1, event.width), max(1, event.height)
if w < 120 or h < 80:
return
top = self.winfo_toplevel()
geom_key = (w, h, self.winfo_rootx() - top.winfo_rootx(), self.winfo_rooty() - top.winfo_rooty())
if geom_key != self._last_geom:
self._last_geom = geom_key
self._slice_global_bg(w, h)
self._redraw_contents(w, h)
def _redraw_contents(self, w: int, h: int):
self.delete("sb_fg")
self._photo_refs.clear()
if self.assets is None:
return
# Äußerer Zierrahmen box_big.png
outer_frame = self.assets.get_box_photo("box_big", (w - 4, h - 4))
if outer_frame:
self._photo_refs.append(outer_frame)
self.create_image(w // 2, h // 2, image=outer_frame, anchor="center", tags="sb_fg")
pad_x = 26
hdr_y = 34
# Titel links oben + GothDropdown rechts oben
title_ph = self.assets.get_goth_text_photo(
self._title,
size_px=FONT_SIZE_HEADING - 2,
color=FONT_COLOR_TITLE_MAIN,
max_width=max(160, w - 360),
align="left",
)
self._photo_refs.append(title_ph)
self.create_image(pad_x, hdr_y, image=title_ph, anchor="w", tags="sb_fg")
self.create_window(w - pad_x, hdr_y, window=self.filter_cb, anchor="e", tags="sb_fg")
# 2x4 Grid aus box_small_purple.png Kacheln
grid_top = 64
grid_h = h - grid_top - 18
cols = 4
rows = 2
gap_x = 12
gap_y = 10
cell_w = max(110, (w - 2 * pad_x - (cols - 1) * gap_x) // cols)
cell_h = max(56, (grid_h - (rows - 1) * gap_y) // rows)
cell_box_ph = self.assets.get_box_photo("box_purple", (cell_w, cell_h))
if cell_box_ph:
self._photo_refs.append(cell_box_ph)
for idx, (stat_key, i18n_key) in enumerate(STAT_FIELD_KEYS):
r, c = divmod(idx, cols)
cx = pad_x + c * (cell_w + gap_x) + cell_w // 2
cy = grid_top + r * (cell_h + gap_y) + cell_h // 2
if cell_box_ph:
self.create_image(cx, cy, image=cell_box_ph, anchor="center", tags="sb_fg")
lbl_ph = self.assets.get_goth_text_photo(
t(i18n_key),
size_px=FONT_SIZE_SMALL_MIN,
color=FONT_COLOR_BODY_MUTED,
max_width=cell_w - 24,
align="center",
)
val_str = str(self._stats_data.get(stat_key, "0"))
if stat_key == "won":
val_col = FONT_COLOR_STATUS_WIN
elif stat_key == "lost":
val_col = FONT_COLOR_STATUS_LOSS
elif stat_key in ("win_pct", "longest_streak"):
val_col = FONT_COLOR_HEADING_SUB
else:
val_col = FONT_COLOR_BODY_DEFAULT
val_ph = self.assets.get_goth_text_photo(
val_str,
size_px=FONT_SIZE_HEADING - 2,
color=val_col,
max_width=cell_w - 24,
align="center",
)
self._photo_refs.extend([lbl_ph, val_ph])
self.create_image(cx, cy - cell_h // 4 + 2, image=lbl_ph, anchor="center", tags="sb_fg")
self.create_image(cx, cy + cell_h // 5 + 2, image=val_ph, anchor="center", tags="sb_fg")
data = self.fetch_callback(vid)
for k, lbl in self.value_labels.items():
lbl.configure(text=str(data.get(k, "0")))