refactor(arch,ui,stats): modularize codebase (<500 LOC/file), unify stats hub & refine win FX

Großes Architektur-, Deduplizierungs- & UI-Release:
- Strikte Modularisierung (<500 Zeilen pro Datei, 1 Klasse pro Modul, pyscn Health Score 97/100).
- Gemeinsame Basis-Klassen extrahiert: SolitaireMenuBase, SolitaireTableController, SolitaireSessionGuard, SolitaireCanvasInput, SolitaireOutcomeFlow, LuckPouchMenuBase, CasinoArenaBase & CasinoResultDialogBase.
- UnifiedStatsView: kategorisierter Statistik-Hub (Glück, Solitaire, Bayerische Spiele, Gesellschaft) ohne Äpfel-mit-Birnen-Gesamtansicht.
- PokerResultDialog auf das Gothic-Canvas-Rahmendesign gehoben.
- EndgameFxOverlay: Feuerwerksraketen entfernt, direkter Spawn von Fledermaus- und Kürbis-Explosionen.
This commit is contained in:
thw 2026-11-22 23:07:57 +01:00
parent 42bf545b35
commit 9492b92e80
76 changed files with 8230 additions and 12827 deletions

View File

@ -255,18 +255,19 @@ class AppController:
self.view.show_main_menu(self.active_profile, games, devils_resume_only=False)
def show_statistics(self):
if self.has_active_devils_lock():
if self.has_active_devils_lock() or not self.active_profile:
return
self.sounds.play_menu_music()
if self.active_profile:
fresh = Database.get_profile_by_id(self.active_profile["id"])
if fresh:
if self.is_online_mode:
fresh = dict(fresh)
fresh["is_online"] = True
fresh["online_endpoint"] = self.online_session.endpoint_label
self.active_profile = fresh
self.view.show_statistics(self.active_profile)
fresh = Database.get_profile_by_id(self.active_profile["id"])
if fresh:
if self.is_online_mode:
fresh = dict(fresh)
fresh["is_online"] = True
fresh["online_endpoint"] = self.online_session.endpoint_label
self.active_profile = fresh
ctx = AppContext(self, game_folder="")
from view.unified_stats_view import UnifiedStatsView
UnifiedStatsView.open(ctx, game_endpoint=None, on_back=None)
def show_settings(
self,

View File

@ -0,0 +1,283 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_arena_renderer.py
from __future__ import annotations
from games.blackjack.models.hand_evaluator import HandEvaluator
from games.blackjack.models.player_hand import PlayerHand
from resources.code_res.game_constants import (
ACCENT_GOLD,
ACCENT_GOTH,
BJ_BOT_CARD_SIZE,
BJ_SPLIT_CARD_SIZE,
ERROR_FG,
FG_COLOR,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
PLAYING_CARD_SIZE,
)
from resources.code_res.i18n import t
BJ_DEALER_CARD_SIZE = (86, 125)
BJ_SEAT_LAYOUT_BY_COUNT = {
1: (2,),
2: (1, 2),
3: (1, 2, 3),
4: (0, 1, 2, 3),
}
class BlackjackArenaRenderer:
"""Zeichnet Dealer, Pot, Kultisten-Ecken und Spielerhände (inkl. Split) auf das Arena-Canvas."""
@staticmethod
def hand_state_suffix(hand: PlayerHand) -> str:
if hand.busted:
return t("bj_state_busted")
if hand.folded:
return t("bj_state_folded")
if hand.doubled or hand.cards_locked:
return t("bj_state_locked")
return ""
@staticmethod
def draw_dealer_and_pot(
view,
table_rect: tuple[int, int, int, int],
player_top_y: int,
reveal_dealer: bool,
) -> None:
tx1, ty1, tx2, ty2 = table_rect
t_cx = (tx1 + tx2) // 2
t_h = max(260, ty2 - ty1)
felt_top = ty1 + max(36, int(t_h * 0.15))
felt_bot = min(ty2 - max(28, int(t_h * 0.12)), player_top_y - 12)
_dc_w, dc_h = BJ_DEALER_CARD_SIZE
avail_felt_h = max(170, felt_bot - felt_top)
d_cards_cy = felt_top + min(dc_h // 2 + 12, int(avail_felt_h * 0.34))
d_photos = []
for c_idx, card in enumerate(view.engine.dealer_hand):
photo = (
view.ctx.assets.get_card_back_photo(color=view.cfg["back_color"], size=BJ_DEALER_CARD_SIZE)
if c_idx == 1 and not reveal_dealer
else view.ctx.assets.get_card_photo(card.image_filename, size=BJ_DEALER_CARD_SIZE)
)
if photo:
view._photo_refs.append(photo)
d_photos.append(photo)
if d_photos:
view._draw_fanned_cards_on_canvas(
t_cx, d_cards_cy, d_photos, BJ_DEALER_CARD_SIZE, visible_step=38, max_width=340
)
pot_txt = t("bj_pot_banner", view.engine.pot).split("|")[0].strip()
pot_cy = min(
felt_bot - 22,
max(d_cards_cy + dc_h // 2 + 34, (d_cards_cy + dc_h // 2 + felt_bot) // 2),
)
pot_size = max(16, FONT_SIZE_BODY + 1)
pot_ph = view._make_goth_photo(pot_txt, size_px=pot_size, color=FONT_COLOR_TITLE_MAIN)
if pot_ph is not None:
bw, bh = max(230, pot_ph.width() + 64), max(40, pot_ph.height() + 18)
view._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold")
view.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg")
else:
view._draw_framed_panel(t_cx, pot_cy, 240, 40, frame_style="gold")
view._place_goth_photo_or_fallback(t_cx, pot_cy, None, pot_txt, pot_size, ACCENT_GOLD)
@staticmethod
def draw_bots_at_corners(
view,
cw: int,
ch: int,
pad_x: int,
pad_top: int,
pad_bot: int,
table_rect: tuple[int, int, int, int],
reveal_opponents: bool,
) -> None:
if not view.bots:
return
tx1, ty1, tx2, ty2 = table_rect
bc_w, bc_h = BJ_BOT_CARD_SIZE
card_scale = 0.90 if ch < 560 else 1.0
cur_card_sz = (max(52, int(bc_w * card_scale)), max(76, int(bc_h * card_scale)))
base_box_w = max(198, cur_card_sz[0] + 114)
box_h = cur_card_sz[1] + 90
top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4)
bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22)
if bot_cy - top_cy < box_h + 14:
mid_y = (top_cy + bot_cy) // 2
top_cy, bot_cy = mid_y - (box_h + 14) // 2, mid_y + (box_h + 14) // 2
slot_indices = BJ_SEAT_LAYOUT_BY_COUNT.get(len(view.bots), (0, 1, 2, 3))
name_sz, sub_sz = max(14, FONT_SIZE_BODY - 1), max(13, FONT_SIZE_BODY - 2)
for bot_i, bot in enumerate(view.bots):
coord_idx = slot_indices[bot_i]
is_left_side = coord_idx in (0, 1)
by = bot_cy if coord_idx in (0, 3) else top_cy
is_turn = (bot_i == view.active_bot_idx)
is_out = (bot.folded or bot.busted)
frame_style = "gold" if is_turn else "purple"
status_border = ERROR_FG if is_out else None
disp_name = t("bj_bot_rebuy", bot.name) if bot.rebought else bot.name
name_col = ACCENT_GOLD if is_turn else ACCENT_GOTH
gold_txt = t("bj_bot_gold_lbl", bot.gold)
if reveal_opponents and bot.hand:
b_val, _ = HandEvaluator.evaluate(bot.hand)
if bot.folded:
info_txt = t("bj_rank_folded", b_val)
elif bot.busted:
info_txt = t("bj_rank_busted", b_val)
else:
info_txt = t("bj_bot_showdown_val", b_val, bot.bet_in_pot)
elif bot.status_text:
info_txt = bot.status_text
elif bot.hand:
info_txt = t("bj_bot_cards_hidden", len(bot.hand), bot.bet_in_pot)
else:
info_txt = ""
info_col = ERROR_FG if is_out else FG_COLOR
name_ph = view._make_goth_photo(disp_name, name_sz, name_col, max_width=220)
gold_ph = view._make_goth_photo(gold_txt, sub_sz, ACCENT_GOLD)
info_ph = view._make_goth_photo(info_txt, sub_sz, info_col, max_width=220)
widest_txt = max((ph.width() for ph in (name_ph, gold_ph, info_ph) if ph), default=140)
box_w = max(base_box_w, min(268, widest_txt + 54))
bx = (
max(pad_x + box_w // 2, tx1 + int(box_w * 0.36))
if is_left_side else min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36))
)
view._draw_framed_panel(bx, by, box_w, box_h, frame_style=frame_style, status_border=status_border)
top_y, bot_y = by - box_h // 2, by + box_h // 2
view._place_goth_photo_or_fallback(bx, top_y + 23, name_ph, disp_name, name_sz, name_col)
view._place_goth_photo_or_fallback(bx, top_y + 42, gold_ph, gold_txt, sub_sz, ACCENT_GOLD)
show_faces = reveal_opponents or bot.busted
bot_photos = []
for card in bot.hand:
photo = (
view.ctx.assets.get_card_photo(card.image_filename, size=cur_card_sz)
if show_faces else view.ctx.assets.get_card_back_photo(color=view.cfg["back_color"], size=cur_card_sz)
)
if photo:
view._photo_refs.append(photo)
bot_photos.append(photo)
if bot_photos:
view._draw_fanned_cards_on_canvas(
bx, by + 6, bot_photos, cur_card_sz, visible_step=25, max_width=box_w - 36
)
view._place_goth_photo_or_fallback(bx, bot_y - 21, info_ph, info_txt, sub_sz, info_col)
@classmethod
def draw_player_hands(cls, view, cw: int, player_zone_top: int, player_zone_bot: int) -> None:
hands = view.engine.player_hands
if not hands:
return
avail_h = max(140, player_zone_bot - player_zone_top)
zone_cy = (player_zone_top + player_zone_bot) // 2
if len(hands) == 1:
h = hands[0]
base_w, base_h = PLAYING_CARD_SIZE
scale = max(88, min(base_h, avail_h - 52)) / max(1, base_h)
card_sz = (max(60, int(round(base_w * scale))), int(round(base_h * scale)))
p_photos = []
for card in h.cards:
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
if photo:
view._photo_refs.append(photo)
p_photos.append(photo)
p_val, p_soft = HandEvaluator.evaluate(h.cards)
soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else ""
lbl_txt = t("bj_player_total", p_val, soft_hint, h.bet_in_pot, cls.hand_state_suffix(h))
is_player_turn = (view.engine.state == "ACTION_LOOP" and view.active_bot_idx == -1)
is_out = (h.busted or h.folded)
lbl_col = ERROR_FG if is_out else FONT_COLOR_TITLE_MAIN
lbl_sz = max(14, FONT_SIZE_BODY - 1)
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col)
step = 36
fan_w = card_sz[0] + max(0, len(p_photos) - 1) * step
txt_w = lbl_ph.width() if lbl_ph is not None else 240
box_w = max(300, min(560, max(fan_w + 96, txt_w + 72)))
box_h = min(avail_h, card_sz[1] + 52)
view._draw_framed_panel(
cw // 2, zone_cy, box_w, box_h,
frame_style="gold" if is_player_turn and not is_out else "purple",
status_border=ERROR_FG if is_out else None,
)
if p_photos:
view._draw_fanned_cards_on_canvas(
cw // 2, zone_cy - 11, p_photos, card_sz, visible_step=step, max_width=box_w - 44
)
view._place_goth_photo_or_fallback(cw // 2, zone_cy + box_h // 2 - 20, lbl_ph, lbl_txt, lbl_sz, lbl_col)
return
# Split-Hände nebeneinander
base_w, base_h = BJ_SPLIT_CARD_SIZE
scale = max(80, min(base_h, avail_h - 48)) / max(1, base_h)
card_sz = (max(54, int(round(base_w * scale))), int(round(base_h * scale)))
box_h = min(avail_h, card_sz[1] + 48)
lbl_sz = max(13, FONT_SIZE_BODY - 2)
prepared_splits = []
max_box_w = 228
for idx, h in enumerate(hands):
is_active = (
view.engine.state == "ACTION_LOOP"
and view.active_bot_idx == -1
and idx == view.active_hand_idx
)
is_out = (h.busted or h.folded)
p_val, p_soft = HandEvaluator.evaluate(h.cards)
soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else ""
lbl_txt = t("bj_hand_box_title", idx + 1, p_val, soft_hint, h.bet_in_pot, cls.hand_state_suffix(h))
lbl_col = ACCENT_GOLD if is_active else (ERROR_FG if is_out else FG_COLOR)
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col)
txt_w = lbl_ph.width() if lbl_ph is not None else 180
sp_fan_w = card_sz[0] + max(0, len(h.cards) - 1) * 28
max_box_w = max(max_box_w, max(228, min(320, max(sp_fan_w + 64, txt_w + 60))))
prepared_splits.append((h, is_active, is_out, lbl_txt, lbl_col, lbl_ph))
n_hands = len(hands)
slot_gap = max(max_box_w + 14, min(310, (cw - 360) // max(1, n_hands)))
start_cx = cw // 2 - ((n_hands - 1) * slot_gap) // 2
for idx, (h, is_active, is_out, lbl_txt, lbl_col, lbl_ph) in enumerate(prepared_splits):
h_cx = start_cx + idx * slot_gap
view._draw_framed_panel(
h_cx, zone_cy, max_box_w, box_h,
frame_style="gold" if is_active else "purple",
status_border=ERROR_FG if is_out else None,
)
sp_photos = []
for card in h.cards:
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
if photo:
view._photo_refs.append(photo)
sp_photos.append(photo)
if sp_photos:
view._draw_fanned_cards_on_canvas(
h_cx, zone_cy - 10, sp_photos, card_sz, visible_step=28, max_width=max_box_w - 36
)
view._place_goth_photo_or_fallback(h_cx, zone_cy + box_h // 2 - 18, lbl_ph, lbl_txt, lbl_sz, lbl_col)

View File

@ -2,514 +2,76 @@
# games/blackjack/views/blackjack_menu_view.py
from __future__ import annotations
import sqlite3
import tkinter as tk
from games.blackjack.views.blackjack_table_view import BlackjackTableView
from view.widgets.menu_body_canvas import MenuBodyCanvas
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,
)
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
from view.widgets.luck_pouch_menu_base import LuckPouchMenuBase
GAME_FOLDER_ID = "blackjack"
class BlackjackMenuView:
def __init__(self, context):
self.ctx = context
self.bot_widget: BotSetupWidget | None = None
self._photo_refs: list = []
class BlackjackMenuView(LuckPouchMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
LAST_ACC_SETTING_PREFIX = "last_bj_account"
STARTING_GOLD = BJ_STARTING_GOLD
MAX_BOTS = BJ_MAX_BOTS
REQUIRES_MIN_ONE_BOT = False
DEVILS_DEFAULT_VARIANT = "bj_classic"
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
pid = self.ctx.profile["id"]
KEY_TOPBAR = "bj_menu_topbar"
KEY_HEADER_GOLD = "bj_header_gold"
KEY_SEC1_TITLE = "bj_sec1_title"
KEY_BOTS_TITLE = "bj_bots_sec_title"
KEY_SEC3_TITLE = "bj_sec3_title"
KEY_GOLD_DISPLAY = "bj_gold_display_lbl"
KEY_DEFAULT_ACC_NAME = "bj_default_acc_name"
KEY_ERR_DUPLICATE = "bj_err_duplicate_name"
devils_acc = Database.get_active_devils_bj_account(pid)
if devils_acc is not None:
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
if saved is not None:
BlackjackTableView(
self.ctx,
variant_key=saved["variant_key"],
bj_account_id=devils_acc["id"],
bot_configs=[],
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
resume_state_json=saved["state_json"],
)
return
def _get_active_devils_account(self, pid: int):
return Database.get_active_devils_bj_account(pid)
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()
def _get_accounts(self, pid: int):
return Database.get_blackjack_accounts(pid)
dyn_xp_cost = bj_prog["xp_exchange_cost"]
is_divine = bj_prog["is_divine_punishment"]
at_floor = bj_prog["at_divine_floor"]
devils_deal_open = bj_prog["devils_deal_unlocked"]
def _get_account(self, acc_id: int):
return Database.get_blackjack_account(acc_id)
setting_key = f"last_bj_account_{pid}"
accounts = Database.get_blackjack_accounts(pid)
has_accounts = len(accounts) > 0
def _create_account(self, pid: int, name: str):
return Database.create_blackjack_account(pid, name)
if preselect_id is None and has_accounts:
saved_id_str = Database.load_setting(setting_key, "")
if saved_id_str.isdigit():
preselect_id = int(saved_id_str)
def _delete_account(self, acc_id: int):
Database.delete_blackjack_account(acc_id)
acc_by_name = {a["account_name"]: a for a in accounts}
acc_names = list(acc_by_name.keys())
def _exchange_xp(self, pid: int, acc_id: int):
return Database.exchange_xp_for_bj_gold(pid, acc_id)
active_acc = None
if has_accounts:
active_acc = accounts[0]
if preselect_id is not None:
for a in accounts:
if a["id"] == preselect_id:
active_acc = a
break
Database.save_setting(setting_key, str(active_acc["id"]))
def _variants_dict(self) -> dict[str, dict]:
return BJ_VARIANTS
selected_name_var = tk.StringVar(
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
def _min_entry_for_variant(self, _v_key: str, _cfg: dict) -> int:
return GOLD_MIN_TABLE_ENTRY
def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
return t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE)
def _format_limit_info(self, dyn_xp_cost: int) -> str:
return t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
BlackjackTableView(
self.ctx,
variant_key=variant_key,
bj_account_id=acc_id,
bot_configs=bots,
on_back_to_menu=lambda aid, msg="": self.show(preselect_id=aid, status_msg=msg),
resume_state_json=resume_json,
)
state_msg = {"text": status_msg, "ok": status_is_ok}
def get_current_acc() -> dict | None:
return acc_by_name.get(selected_name_var.get())
def open_bj_stats():
cur = get_current_acc()
if cur is None:
return
if self.bot_widget is not None and has_accounts:
_, to_save = self.bot_widget.collect_configs()
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),
).show(selected_acc_id=cur["id"])
def refresh_on_lang_switch():
cur = get_current_acc()
if self.bot_widget is not None and has_accounts:
_, to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
self.show(preselect_id=cur["id"] if cur else None)
topbar_gold_txt = (
t("bj_header_gold", active_acc["account_name"], active_acc["gold"])
if active_acc else ""
)
topbar = self.ctx.build_game_topbar(
self.ctx.root,
t("bj_menu_topbar"),
on_game_menu=None,
on_stats=open_bj_stats,
stats_enabled=has_accounts,
extra_right_text=topbar_gold_txt,
on_lang_refresh=refresh_on_lang_switch,
)
cv = MenuBodyCanvas(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
# --- 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,
)
def exchange_xp_action():
cur = get_current_acc()
if cur is None:
return
if self.bot_widget is not None:
_, to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
ok, msg = Database.exchange_xp_for_bj_gold(pid, cur["id"])
if ok and is_divine:
self.ctx.sounds.play("lose")
self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok)
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,
exchange_xp_action, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_exchange, style="amethyst",
)
def delete_selected_account():
cur = get_current_acc()
if cur is not None:
Database.delete_blackjack_account(cur["id"])
self.show()
delete_btn = ImageButton(
cv, t("bj_delete_acc_btn"), btn_norm, btn_purp,
delete_selected_account, sound_mgr=self.ctx.sounds,
width=136, height=32, enabled=has_accounts, style="amethyst",
)
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
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,
)
def create_new_account():
if not can_create_more:
return
name = new_entry.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())
return
try:
if self.bot_widget is not None and has_accounts:
_, to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
created = Database.create_blackjack_account(pid, name)
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())
if can_create_more:
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,
create_new_account, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_create_more, style=create_style,
)
# Optional Devil's Deal Controls
sac_dd = None
devil_btn = None
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 sac_candidates:
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,
)
def seal_devils_deal():
cur = get_current_acc()
victim_id = sac_map.get(sac_var.get())
if cur is None or victim_id is None:
return
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
ok, _msg = Database.execute_devils_deal(pid, GAME_FOLDER_ID, victim_id, cur["id"])
if ok:
self.ctx.sounds.play("end_battle")
BlackjackTableView(
self.ctx,
variant_key="bj_classic",
bj_account_id=cur["id"],
bot_configs=active_bots,
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",
)
# --- 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)
# --- Sektion 3: Varianten-Buttons ---
def enter_table(v_key: str):
cur = get_current_acc()
if not cur:
return
acc = Database.get_blackjack_account(cur["id"])
if not acc:
return
Database.save_setting(setting_key, str(acc["id"]))
active_bots, configs_to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, GAME_FOLDER_ID, configs_to_save)
cur_bj_prog = self.ctx.refresh_game_progress()
if acc["gold"] < GOLD_MIN_TABLE_ENTRY:
state_msg["text"] = 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())
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),
)
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:
t_btn = ImageButton(
cv, t("bj_enter_table_btn"), btn_fire, btn_fire,
lambda k=v_key: enter_table(k),
sound_mgr=self.ctx.sounds, width=168, height=38,
enabled=can_enter_now, style="fire",
)
table_buttons.append(t_btn)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
cv.delete("fg")
self._photo_refs.clear()
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()))

View File

@ -0,0 +1,307 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_showdown_presenter.py
from __future__ import annotations
import time
from games.blackjack.models.bot_seat import BlackjackBotSeat
from games.blackjack.models.hand_evaluator import HandEvaluator
from models.card import Card
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import GOLD_MIN_TABLE_ENTRY
from resources.code_res.i18n import t
class BlackjackShowdownPresenter:
"""Kapselt Showdown-Abrechnung, 7-7-7-Sofortsieg, XP-Vergabe und Popup-Aufbereitung."""
@staticmethod
def count_all_table_cards(view) -> None:
if len(view.engine.dealer_hand) >= 2:
for c in view.engine.dealer_hand[1:]:
view.bot_ai.observe_public_card(c)
for h in view.engine.player_hands:
for c in h.cards:
view.bot_ai.observe_public_card(c)
for b in view.bots:
for c in b.hand:
view.bot_ai.observe_public_card(c)
@staticmethod
def resolve_devils_lock(view, outcome_type: str) -> None:
if not view.devils_locked:
view._clear_persisted_state()
return
updated_acc = Database.get_blackjack_account(view.bj_account["id"])
if not (outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY):
Database.set_bj_devils_deal_active(view.bj_account["id"], False)
view.devils_locked = False
view._clear_persisted_state()
@staticmethod
def award_xp_and_record(view, outcome_type: str, won_stat: bool | None) -> tuple[int, int | None]:
duration = max(0.5, time.time() - view.round_start_time)
prog_before = view.ctx.refresh_game_progress()
opp_levels = [b.ai_level for b in view.bots]
xp_gained = Progression.calculate_match_xp(
player_level=prog_before["level"],
opponent_levels=opp_levels,
outcome_type=outcome_type,
variant_mult=view.cfg["xp_mult"],
)
if won_stat is None:
Database.add_game_points(view.ctx.profile["id"], view.GAME_FOLDER_ID, xp_gained)
prog_after = view.ctx.refresh_game_progress()
view.ctx.sounds.play("end_battle")
new_lvl = prog_after["level"] if prog_after["level"] > prog_before["level"] else None
return xp_gained, new_lvl
old_lvl, new_lvl = view.ctx.record_result(
view.variant_key,
won=won_stat,
duration_sec=duration,
points_gained=xp_gained,
bj_account_id=view.bj_account["id"],
)
return xp_gained, (new_lvl if new_lvl > old_lvl else None)
@staticmethod
def format_hand_rank_label(
cards, is_split: bool = False, busted: bool = False, folded: bool = False
) -> str:
val, _ = HandEvaluator.evaluate(cards)
if folded:
return t("bj_rank_folded", val)
if busted or val > 21:
return t("bj_rank_busted", val)
if HandEvaluator.is_triple_seven(cards):
return t("bj_rank_777")
if not is_split and HandEvaluator.is_natural_blackjack(cards):
return t("bj_rank_natural_bj")
if val == 21:
return t("bj_rank_split_21") if is_split else t("bj_rank_multi_21", len(cards))
return t("bj_rank_points", val, len(cards))
@staticmethod
def collect_showdown_snapshot(view, instant_777_winner: str | None = None) -> list[dict]:
snapshot: list[dict] = []
d_cards = view.engine.dealer_hand
d_val, _ = HandEvaluator.evaluate(d_cards)
d_rank = view.engine._hand_rank(d_cards)
snapshot.append({
"role": "DEALER", "name": "", "hand_no": 0,
"card_images": [c.image_filename for c in d_cards],
"cards_raw": [[c.suit, c.rank] for c in d_cards],
"is_split": False, "busted": d_val > 21, "folded": False,
"rank_tuple": list(d_rank),
})
multi_p = len(view.engine.player_hands) > 1
for idx, h in enumerate(view.engine.player_hands):
hr = view.engine._hand_rank(h.cards, is_split=h.is_split_hand) if h.is_active_in_pot else (0, 0)
snapshot.append({
"role": "PLAYER", "name": "", "hand_no": (idx + 1) if multi_p else 0,
"card_images": [c.image_filename for c in h.cards],
"cards_raw": [[c.suit, c.rank] for c in h.cards],
"is_split": h.is_split_hand, "busted": h.busted, "folded": h.folded,
"rank_tuple": list(hr),
})
for b in view.bots:
br = view.engine._hand_rank(b.hand) if b.is_active_in_pot else (0, 0)
snapshot.append({
"role": "BOT", "name": b.name, "hand_no": 0,
"card_images": [c.image_filename for c in b.hand],
"cards_raw": [[c.suit, c.rank] for c in b.hand],
"is_split": False, "busted": b.busted, "folded": b.folded,
"rank_tuple": list(br),
})
if instant_777_winner is not None:
for s in snapshot:
s["is_winner"] = bool(
(instant_777_winner == "PLAYER" and s["role"] == "PLAYER" and s["rank_tuple"] == [3, 21])
or (s["role"] == "BOT" and s["name"] == instant_777_winner and s["rank_tuple"] == [3, 21])
)
return snapshot
contenders = [s for s in snapshot[1:] if not s["busted"] and not s["folded"]]
dealer_entry = snapshot[0]
if not contenders:
dealer_entry["is_winner"] = True
for s in snapshot[1:]:
s["is_winner"] = False
return snapshot
best_contender = max(tuple(s["rank_tuple"]) for s in contenders)
d_rnk = tuple(dealer_entry["rank_tuple"])
dealer_entry["is_winner"] = (d_rnk >= best_contender)
for s in snapshot[1:]:
s["is_winner"] = (
d_rnk <= best_contender
and not s["busted"]
and not s["folded"]
and tuple(s["rank_tuple"]) == best_contender
)
return snapshot
@classmethod
def trigger_instant_777(
cls, view, winner_is_player: bool, winning_bot: BlackjackBotSeat | None
) -> dict:
view.engine.state = "SHOWDOWN"
cls.count_all_table_cards(view)
pot_total = view.engine.pot
total_p_bet = view.engine.total_player_bet
snap = cls.collect_showdown_snapshot(
view, instant_777_winner="PLAYER" if winner_is_player else winning_bot.name
)
if winner_is_player:
payout = pot_total + (total_p_bet if not view.bots else 0)
net = payout - total_p_bet
view.bj_account = Database.update_blackjack_gold(view.bj_account["id"], payout)
xp, leveled_to = cls.award_xp_and_record(view, "WIN_777", won_stat=True)
cls.resolve_devils_lock(view, "WIN_777")
return {
"winner_type": "PLAYER", "winner_names": [], "instant_777": "PLAYER",
"player_won": True, "player_net": net, "bank_gain": 0, "bot_gains": [],
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
}
winning_bot.gold += pot_total
bot_net = pot_total - winning_bot.bet_in_pot
xp, leveled_to = cls.award_xp_and_record(view, "LOSE", won_stat=False)
cls.resolve_devils_lock(view, "LOSE")
return {
"winner_type": "BOT", "winner_names": [winning_bot.name], "instant_777": winning_bot.name,
"player_won": False, "player_net": -total_p_bet, "bank_gain": 0,
"bot_gains": [(winning_bot.name, bot_net)] if bot_net > 0 else [],
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
}
@classmethod
def finalize_regular_showdown(cls, view) -> dict:
cls.count_all_table_cards(view)
res = view.engine.resolve_showdown(view.bots)
snap = cls.collect_showdown_snapshot(view, instant_777_winner=None)
if res["player_payout"] > 0:
view.bj_account = Database.update_blackjack_gold(view.bj_account["id"], res["player_payout"])
w_type = res["winner_type"]
if w_type == "PLAYER":
has_nat = any(
h.is_active_in_pot and not h.is_split_hand and HandEvaluator.is_natural_blackjack(h.cards)
for h in view.engine.player_hands
)
out_code, player_won_flag = ("WIN_BJ" if has_nat else "WIN"), True
xp, leveled_to = cls.award_xp_and_record(view, out_code, won_stat=True)
elif w_type == "TIE":
out_code, player_won_flag = "TIE", None
xp, leveled_to = cls.award_xp_and_record(view, "TIE", won_stat=None)
else:
out_code, player_won_flag = "LOSE", False
xp, leveled_to = cls.award_xp_and_record(view, "LOSE", won_stat=False)
cls.resolve_devils_lock(view, out_code)
return {
"winner_type": w_type, "winner_names": res["winner_names"], "instant_777": None,
"player_won": player_won_flag, "player_net": res["player_net"],
"bank_gain": res["bank_gain"], "bot_gains": res["bot_gains"],
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
}
@classmethod
def build_localized_popup_data(cls, view, payload: dict) -> dict:
w_type = payload["winner_type"]
headline = (
t("bj_popup_bank_won") if w_type == "BANK"
else (t("bj_popup_player_won") if w_type == "PLAYER"
else (t("bj_popup_bot_won", ", ".join(payload["winner_names"])) if w_type == "BOT" else t("bj_popup_tie")))
)
showdown_hands = []
for s in payload.get("showdown_snapshot", []):
cards_obj = [Card(sr[0], sr[1]) for sr in s.get("cards_raw", [])]
owner_lbl = (
t("bj_showdown_seat_dealer") if s["role"] == "DEALER"
else ((t("bj_showdown_seat_you_hand", s["hand_no"]) if s.get("hand_no") else t("bj_showdown_seat_you"))
if s["role"] == "PLAYER" else s["name"])
)
showdown_hands.append({
"owner_label": owner_lbl, "is_dealer": (s["role"] == "DEALER"),
"is_winner": s.get("is_winner", False), "busted": s.get("busted", False),
"folded": s.get("folded", False), "card_images": s.get("card_images", []),
"rank_label": cls.format_hand_rank_label(
cards_obj, s.get("is_split", False), s.get("busted", False), s.get("folded", False)
),
"rank_tuple": tuple(s.get("rank_tuple", [0, 0])), "role": s["role"],
})
other_gains = []
if payload["bank_gain"] > 0:
other_gains.append(t("bj_popup_bank_gain", payload["bank_gain"]))
for b_name, b_gain in payload["bot_gains"]:
if b_gain > 0:
other_gains.append(t("bj_popup_bot_gain", b_name, b_gain))
lvl_to = payload["leveled_to"]
lvl_str = t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to)) if lvl_to is not None else None
cur_gold = Database.get_blackjack_account(view.bj_account["id"])["gold"]
return {
"headline": headline,
"reason_text": cls._build_showdown_reason(payload, showdown_hands),
"showdown_hands": showdown_hands,
"player_won": payload["player_won"],
"player_net": payload["player_net"],
"other_gains": other_gains,
"xp_gained": payload["xp_gained"],
"new_level_title": lvl_str,
"can_continue": cur_gold >= GOLD_MIN_TABLE_ENTRY,
"can_leave_menu": not view.devils_locked,
}
@staticmethod
def _build_showdown_reason(payload: dict, showdown_hands: list[dict]) -> str:
if not showdown_hands:
return ""
inst = payload.get("instant_777")
if inst:
return t("bj_reason_777_win", t("bj_showdown_seat_you") if inst == "PLAYER" else inst)
dealer = showdown_hands[0]
if not [h for h in showdown_hands[1:] if not h["busted"] and not h["folded"]]:
return t("bj_reason_all_out")
winners = [h for h in showdown_hands if h["is_winner"]]
if not winners:
return ""
if dealer["is_winner"] and len(winners) > 1:
return t("bj_reason_dealer_tie_push", dealer["rank_label"])
top_rank = winners[0]["rank_tuple"]
winner_names_str = ", ".join(dict.fromkeys(w["owner_label"] for w in winners if not w["is_dealer"]))
win_label = dealer["owner_label"] if dealer["is_winner"] else winner_names_str
losers_21 = [
h for h in showdown_hands
if not h["is_winner"] and not h["busted"] and not h["folded"] and h["rank_tuple"][1] == 21
]
if top_rank == (3, 21) and losers_21:
return t("bj_reason_777_beats_21", win_label)
if top_rank == (2, 21) and losers_21:
return t("bj_reason_nat_beats_reg21", win_label)
non_dealer_winners = [w for w in winners if not w["is_dealer"]]
if len(non_dealer_winners) > 1:
return t("bj_reason_split_pot", non_dealer_winners[0]["rank_label"], winner_names_str)
if dealer["busted"] and not dealer["is_winner"]:
return t("bj_reason_dealer_bust", dealer["rank_label"], win_label, winners[0]["rank_label"])
others_alive = [h for h in showdown_hands if not h["is_winner"] and not h["busted"] and not h["folded"]]
runner = max(others_alive, key=lambda x: x["rank_tuple"]) if others_alive else dealer
return t("bj_reason_higher_score", win_label, winners[0]["rank_label"], f"{runner['owner_label']}: {runner['rank_label']}")

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,244 @@
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_turn_driver.py
from __future__ import annotations
from games.blackjack.models.bot_seat import BlackjackBotSeat
from games.blackjack.models.hand_evaluator import HandEvaluator
from games.blackjack.views.blackjack_showdown_presenter import BlackjackShowdownPresenter
from models.database import Database
from resources.code_res.game_constants import BJ_BOT_TURN_DELAY_MS
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
STEP_MITGEHEN = "MITGEHEN"
STEP_ZIEHEN = "ZIEHEN"
STEP_ERHOEHEN = "ERHOEHEN"
class BlackjackTurnDriver:
"""Steuert die Aktions-Buttons des Spielers und die KI-Zugschleife der Bots am Blackjack-Tisch."""
@staticmethod
def render_tree_step(view) -> None:
view.bj_account = Database.get_blackjack_account(view.bj_account["id"])
wallet = view.bj_account["gold"]
hand = view.engine.player_hands[view.active_hand_idx]
btn_norm = view.ctx.assets.raw_btn_default
btn_purp = view.ctx.assets.raw_btn_purple
btn_fire = view.ctx.assets.raw_btn_fire or btn_purp
primary_btns: list[ImageButton] = []
overflow_btns: list[ImageButton] = []
if view.turn_step == STEP_MITGEHEN:
to_call = min(wallet, max(0, view.engine.highest_bet - hand.bet_in_pot))
primary_btns.append(
ImageButton(
view.bottom_bar, t("bj_tree_btn_call_yes", to_call),
btn_fire, btn_fire, lambda: view._on_step1_call_yes(to_call),
sound_mgr=view.ctx.sounds, width=162, height=30, style="fire",
hover_text=lambda: t("bj_tip_call_yes"),
)
)
overflow_btns.append(
ImageButton(
view.bottom_bar, t("bj_tree_btn_call_no_lose"),
btn_norm, btn_purp, view._on_fold_hand,
sound_mgr=view.ctx.sounds, width=162, height=30, style="amethyst",
hover_text=lambda: t("bj_tip_fold"),
)
)
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
return
if view.turn_step == STEP_ZIEHEN:
primary_btns.append(
ImageButton(
view.bottom_bar, t("bj_tree_btn_draw_yes"),
btn_fire, btn_fire, view._on_step2_draw_yes,
sound_mgr=view.ctx.sounds, width=138, height=30, style="fire",
hover_text=lambda: t("bj_tip_draw_yes"),
)
)
if view.engine.can_double_down(view.active_hand_idx, wallet):
dd_cost = view.engine.get_double_down_cost(view.active_hand_idx)
primary_btns.append(
ImageButton(
view.bottom_bar, t("bj_double_btn", dd_cost),
btn_norm, btn_purp, view._on_step2_double_down,
sound_mgr=view.ctx.sounds, width=132, height=30,
style="amethyst", hover_text=lambda: t("bj_tip_double"),
)
)
if view.engine.can_split_hand(view.active_hand_idx, wallet):
primary_btns.append(
ImageButton(
view.bottom_bar, t("bj_split_btn", view.engine.highest_bet),
btn_norm, btn_purp, view._on_step2_split,
sound_mgr=view.ctx.sounds, width=124, height=30,
style="amethyst", hover_text=lambda: t("bj_tip_split"),
)
)
overflow_btns.append(
ImageButton(
view.bottom_bar, t("bj_tree_btn_draw_no"),
btn_norm, btn_purp, view._on_step2_draw_no,
sound_mgr=None, width=134, height=30, style="amethyst",
hover_text=lambda: t("bj_tip_draw_no"),
)
)
overflow_btns.append(
ImageButton(
view.bottom_bar, t("bj_fold_btn"),
btn_norm, btn_purp, view._on_fold_hand,
sound_mgr=view.ctx.sounds, width=110, height=30, style="amethyst",
hover_text=lambda: t("bj_tip_fold"),
)
)
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
return
if view.turn_step == STEP_ERHOEHEN:
for chip in [c for c in view._get_current_level_chips() if wallet >= c]:
primary_btns.append(
ImageButton(
view.bottom_bar, f"+{chip}g",
btn_fire, btn_fire, lambda c=chip: view._on_step3_raise_yes(c),
sound_mgr=view.ctx.sounds, width=76, height=30, style="fire",
hover_text=lambda: t("bj_tip_raise_chip"),
)
)
overflow_btns.append(
ImageButton(
view.bottom_bar, t("bj_tree_btn_raise_no"),
btn_norm, btn_purp, view._finish_current_hand_turn,
sound_mgr=view.ctx.sounds, width=162, height=30, style="amethyst",
hover_text=lambda: t("bj_tip_raise_no"),
)
)
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
@classmethod
def start_bots_cycle(cls, view) -> None:
view._set_bottom_buttons([])
if not view.bots or not view.engine.any_contender_alive(view.bots):
view._on_table_pass_completed()
return
view.active_bot_idx = 0
view._persist_state()
cls.step_next_bot(view)
@classmethod
def step_next_bot(cls, view) -> None:
if not view._canvas_alive():
return
while view.active_bot_idx < len(view.bots):
bot = view.bots[view.active_bot_idx]
if bot.is_active_in_pot and (
not view.settle_only_mode
or (bot.gold > 0 and bot.bet_in_pot < view.engine.highest_bet)
):
break
view.active_bot_idx += 1
if view.active_bot_idx >= len(view.bots):
view.active_bot_idx = -1
view._persist_state()
view._on_table_pass_completed()
return
bot = view.bots[view.active_bot_idx]
view._persist_state()
view._render_table(False, False)
view._turn_job = view.ctx.root.after(
BJ_BOT_TURN_DELAY_MS, lambda b=bot: cls.execute_bot_action(view, b)
)
@classmethod
def execute_bot_action(cls, view, bot: BlackjackBotSeat) -> None:
if not view._canvas_alive():
return
upcard = view.engine.dealer_hand[0]
dyn_chips = view._get_current_level_chips()
rem_cards = view.engine.deck.remaining()
to_call = min(bot.gold, max(0, view.engine.highest_bet - bot.bet_in_pot))
if to_call > 0:
if not view.bot_ai.decide_step1_mitgehen(
bot, view.engine.highest_bet, upcard, rem_cards
):
bot.folded = bot.cards_locked = True
bot.status_text = t("bj_bot_action_fold")
cls._finish_bot_step(view)
return
view.ctx.sounds.play("click")
view.engine.bot_add_gold_to_pot(bot, to_call)
if view.settle_only_mode:
bot.status_text = t("bj_bot_action_call", to_call)
cls._finish_bot_step(view)
return
drew_card = False
if not bot.cards_locked and not bot.doubled:
if view.bot_ai.wants_double_down(
bot, upcard, view.engine.highest_bet, rem_cards
):
dd_cost = (
max(view.engine.highest_bet, bot.bet_in_pot) * 2 - bot.bet_in_pot
)
paid = view.engine.bot_add_gold_to_pot(bot, dd_cost)
view.ctx.sounds.play("click")
view.engine.bot_draw_card(bot)
bot.doubled = bot.cards_locked = True
if HandEvaluator.is_triple_seven(bot.hand):
view._conclude_with_payload(
BlackjackShowdownPresenter.trigger_instant_777(view, False, bot)
)
return
b_val, _ = HandEvaluator.evaluate(bot.hand)
bot.status_text = (
t("bj_bot_action_bust", b_val)
if bot.busted
else t("bj_bot_action_double", paid)
)
cls._finish_bot_step(view)
return
if view.bot_ai.decide_step2_ziehen(bot, upcard, rem_cards):
view.ctx.sounds.play("click")
view.engine.bot_draw_card(bot)
drew_card = True
if HandEvaluator.is_triple_seven(bot.hand):
view._conclude_with_payload(
BlackjackShowdownPresenter.trigger_instant_777(view, False, bot)
)
return
if bot.busted:
b_val, _ = HandEvaluator.evaluate(bot.hand)
bot.status_text = t("bj_bot_action_bust", b_val)
cls._finish_bot_step(view)
return
raise_amt = view.bot_ai.decide_step3_erhoehen(
bot, dyn_chips, rem_cards, upcard
)
if raise_amt > 0:
view.ctx.sounds.play("click")
view.engine.bot_add_gold_to_pot(bot, raise_amt)
bot.status_text = t("bj_bot_action_bet", raise_amt)
elif drew_card:
bot.status_text = t("bj_bot_action_hit", len(bot.hand))
elif to_call > 0:
bot.status_text = t("bj_bot_action_call", to_call)
else:
bot.status_text = t("bj_bot_action_ready", len(bot.hand))
cls._finish_bot_step(view)
@classmethod
def _finish_bot_step(cls, view) -> None:
view.active_bot_idx += 1
view._persist_state()
view._render_table(False, False)
view._turn_job = view.ctx.root.after(
BJ_BOT_TURN_DELAY_MS, lambda: cls.step_next_bot(view)
)

View File

@ -2,53 +2,30 @@
# 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_SMALL_MIN,
FONT_SIZE_TITLE_LG,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.modal_veil import ModalVeil
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
SHOWDOWN_MINI_CARD_SIZE = (48, 70)
class BlackjackResultDialog(tk.Canvas):
"""
Rahmenloses Gothic-Showdown-Overlay für Blackjack (ohne eingebettetes GIF),
immer über allen UI-Leisten platziert und mit abgedunkeltem, gesperrtem Tisch.
"""
def __init__(
self,
parent,
assets,
sounds,
result_data: dict,
on_next_round,
on_back_to_menu,
):
GothDropdown.close_any_open_popup()
top_root = parent.winfo_toplevel()
class BlackjackResultDialog(CasinoResultDialogBase):
"""Gothic-Showdown-Overlay für Blackjack auf Basis von CasinoResultDialogBase."""
def __init__(self, parent, assets, sounds, result_data: dict, 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
extra_lines = len(result_data.get("other_gains", []))
dlg_w = max(560, min(830, cols * 250 + 64))
dlg_h = (
58
@ -58,65 +35,9 @@ class BlackjackResultDialog(tk.Canvas):
+ (24 if result_data.get("new_level_title") else 0)
+ 62
)
try:
max_h = max(420, top_root.winfo_height() - 60)
dlg_h = min(dlg_h, max_h)
except Exception:
pass
super().__init__(
top_root,
width=dlg_w,
height=dlg_h,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
)
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._photo_refs: list = []
self.place(relx=0.5, rely=0.5, anchor="center")
self._build_scene()
self._veil = ModalVeil(top_root, assets, modal_widget=self)
def _build_scene(self):
w, h = self._dlg_w, self._dlg_h
cx = w // 2
self._photo_refs.clear()
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")
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 = 26
p_won = self.data.get("player_won")
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)
)
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() + 8
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
reason_txt = self.data.get("reason_text", "")
if reason_txt:
r_ph = self.assets.get_goth_text_photo(
@ -133,163 +54,77 @@ class BlackjackResultDialog(tk.Canvas):
cur_y += rb_h + 8
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"
)
self._photo_refs.append(sec_ph)
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
cur_y += 22
if not hands_list:
return cur_y
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
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)
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
is_win = entry.get("is_winner", False)
is_dead = entry.get("busted", False) or entry.get("folded", False)
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)
)
o_ph = self.assets.get_goth_text_photo(
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
)
self._photo_refs.append(o_ph)
self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center")
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)
)
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
self.create_line(36, cur_y, w - 36, cur_y, fill=SUBTLE_BORDER, width=1)
cur_y += 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
elif p_net < 0:
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), FONT_COLOR_STATUS_LOSS
else:
own_txt, own_col = t("bj_popup_your_even"), FONT_COLOR_BODY_DEFAULT
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
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
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,
sec_ph = self.assets.get_goth_text_photo(
t("bj_showdown_section_title"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left"
)
self._photo_refs.append(xp_ph)
self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center")
self._photo_refs.append(sec_ph)
self.create_image(32, cur_y + 10, image=sec_ph, anchor="w")
cur_y += 22
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
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
btn_y = h - 34
can_next = self.data.get("can_continue", True)
can_menu = self.data.get("can_leave_menu", True)
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)
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"
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
is_win = entry.get("is_winner", False)
is_dead = entry.get("busted", False) or entry.get("folded", False)
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)
)
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"
o_ph = self.assets.get_goth_text_photo(
entry["owner_label"], FONT_SIZE_SMALL_MIN + 1, o_col, max_width=seat_w - 24
)
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._photo_refs.append(o_ph)
self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center")
c_photos = [
ph for img_name in entry.get("card_images", [])
if (ph := self.assets.get_card_photo(img_name, size=SHOWDOWN_MINI_CARD_SIZE)) is not None
]
self._photo_refs.extend(c_photos)
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, card_top = sx - fan_w // 2, 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)
)
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"
rk_ph = self.assets.get_goth_text_photo(
entry["rank_label"], FONT_SIZE_SMALL_MIN, rk_col, max_width=seat_w - 22
)
self.create_window(cx, btn_y, window=b_menu, anchor="center")
self._photo_refs.append(rk_ph)
self.create_image(sx, sy + seat_h // 2 - 18, image=rk_ph, anchor="center")
def close_dialog(self):
self._veil.release()
self._photo_refs.clear()
if self.winfo_exists():
self.destroy()
def _handle_next(self):
self.close_dialog()
self.on_next_round()
def _handle_menu(self):
self.close_dialog()
self.on_back_to_menu()
return cur_y + rows * (seat_h + 6) + 6

View File

@ -0,0 +1,324 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_arena_renderer.py
from __future__ import annotations
import tkinter as tk
from resources.code_res.game_constants import (
ACCENT_GOLD,
ACCENT_GOTH,
ERROR_FG,
FG_COLOR,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
MUTED_FG,
PLAYING_CARD_SIZE,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from games.poker.models.poker_evaluator import PokerEvaluator
from models.database import Database
from models.progression import Progression
PK_OVAL_BOARD_CARD = (78, 114)
PK_BOT_SHOWDOWN_CARD = (42, 62)
SEAT_LAYOUT_BY_COUNT = {
1: (2,),
2: (1, 3),
3: (1, 2, 3),
4: (0, 1, 3, 4),
5: (0, 1, 2, 3, 4),
}
class PokerArenaRenderer:
"""Zeichnet die 6-Max-Tischszene für Texas Hold'em auf das Arena-Canvas."""
@staticmethod
def role_badge(eng, seat_idx: int) -> str:
badges = []
if seat_idx == eng.dealer_pos:
badges.append(t("pk_role_dealer"))
if seat_idx == eng.sb_pos:
badges.append(t("pk_role_sb"))
if seat_idx == eng.bb_pos:
badges.append(t("pk_role_bb"))
return "".join(badges)
@classmethod
def draw_bots(
cls,
view,
cw: int,
ch: int,
pad_x: int,
pad_top: int,
pad_bot: int,
table_rect: tuple[int, int, int, int],
) -> int:
bot_seats = view.engine.seats[1:]
if not bot_seats:
return table_rect[1] + 24
tx1, ty1, tx2, ty2 = table_rect
is_showdown = (view.engine.street == "SHOWDOWN")
box_h = 98 if is_showdown else 88
base_box_w = 216 if is_showdown else 204
top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4)
bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22)
if bot_cy - top_cy < box_h + 16:
mid_y = (top_cy + bot_cy) // 2
top_cy, bot_cy = mid_y - (box_h + 16) // 2, mid_y + (box_h + 16) // 2
top_center_cy = max(pad_top + box_h // 2, ty1 + int(box_h * 0.42))
top_center_bottom = ty1 + 24
slot_indices = SEAT_LAYOUT_BY_COUNT.get(len(bot_seats), (0, 1, 2, 3, 4))
name_sz, sub_sz = max(14, FONT_SIZE_BODY - 1), max(13, FONT_SIZE_BODY - 2)
for bot_i, seat in enumerate(bot_seats):
coord_idx = slot_indices[bot_i]
is_turn = (not is_showdown and view.engine.turn_pos == seat.seat_id)
show_bot_cards = is_showdown and bool(seat.hole_cards) and (not seat.folded)
frame_style = "gold" if is_turn else "purple"
status_border = ERROR_FG if seat.folded else (ACCENT_GOTH if seat.all_in else None)
base_name = t("bj_bot_rebuy", seat.name) if seat.rebought else seat.name
title_txt = f"{base_name}{cls.role_badge(view.engine, seat.seat_id)}"
title_col = MUTED_FG if seat.folded else (ACCENT_GOLD if is_turn else ACCENT_GOTH)
stack_txt = t("pk_bot_stack_lbl", seat.stack, seat.street_bet)
st_txt = seat.status_text or "-"
st_col = ERROR_FG if seat.folded else (ACCENT_GOLD if is_turn else FG_COLOR)
max_txt_w = 176 if show_bot_cards else 230
title_ph = view._make_goth_photo(title_txt, name_sz, title_col, max_txt_w)
stack_ph = view._make_goth_photo(stack_txt, sub_sz, ACCENT_GOLD, max_txt_w)
st_ph = view._make_goth_photo(st_txt, sub_sz, st_col, max_txt_w)
widest_txt = max((ph.width() for ph in (title_ph, stack_ph, st_ph) if ph), default=140)
extra_cards_w = (PK_BOT_SHOWDOWN_CARD[0] + 38) if show_bot_cards else 0
box_w = max(base_box_w, min(296, widest_txt + extra_cards_w + 46))
if coord_idx == 2:
bx, by = cw // 2, top_center_cy
top_center_bottom = max(top_center_bottom, by + box_h // 2)
elif coord_idx in (0, 1):
bx = max(pad_x + box_w // 2, tx1 + int(box_w * 0.36))
by = bot_cy if coord_idx == 0 else top_cy
else:
bx = min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36))
by = top_cy if coord_idx == 3 else bot_cy
view._draw_framed_panel(bx, by, box_w, box_h, frame_style=frame_style, status_border=status_border)
if show_bot_cards:
c_w, c_h = PK_BOT_SHOWDOWN_CARD
step_x = 22
fan_left, fan_top = bx - box_w // 2 + 16, by - c_h // 2
for ci, c_obj in enumerate(seat.hole_cards[:2]):
c_ph = view.ctx.assets.get_card_photo(c_obj.image_filename, size=PK_BOT_SHOWDOWN_CARD)
if c_ph is not None:
view._photo_refs.append(c_ph)
view.arena_canvas.create_image(fan_left + ci * step_x, fan_top, image=c_ph, anchor="nw", tags="fg")
txt_cx = bx + (c_w + step_x) // 2 + 4
view._place_goth_photo_or_fallback(txt_cx, by - 24, title_ph, title_txt, name_sz, title_col)
view._place_goth_photo_or_fallback(txt_cx, by, stack_ph, stack_txt, sub_sz, ACCENT_GOLD)
view._place_goth_photo_or_fallback(txt_cx, by + 24, st_ph, st_txt, sub_sz, st_col)
else:
view._place_goth_photo_or_fallback(bx, by - 23, title_ph, title_txt, name_sz, title_col)
view._place_goth_photo_or_fallback(bx, by, stack_ph, stack_txt, sub_sz, ACCENT_GOLD)
view._place_goth_photo_or_fallback(bx, by + 23, st_ph, st_txt, sub_sz, st_col)
return top_center_bottom
@staticmethod
def draw_board_and_pot(
view, table_rect: tuple[int, int, int, int], top_obstacle_y: int, player_top_y: int
) -> None:
tx1, ty1, tx2, ty2 = table_rect
t_cx = (tx1 + tx2) // 2
t_h = max(260, ty2 - ty1)
felt_top = max(ty1 + max(32, int(t_h * 0.14)), top_obstacle_y + 12)
felt_bot = min(ty2 - max(24, int(t_h * 0.10)), player_top_y - 10)
avail_h = max(148, felt_bot - felt_top)
base_cw, base_ch = PK_OVAL_BOARD_CARD
scale = max(84, min(base_ch, avail_h - 58)) / max(1, base_ch)
card_w, card_h = max(58, int(round(base_cw * scale))), int(round(base_ch * scale))
card_sz = (card_w, card_h)
gap = max(8, int(card_w * 0.13))
start_x = t_cx - (5 * card_w + 4 * gap) // 2
board_cy = felt_top + card_h // 2 + max(4, (avail_h - card_h - 52) // 3)
card_top = board_cy - card_h // 2
for slot_i in range(5):
sx = start_x + slot_i * (card_w + gap)
if slot_i < len(view.engine.board):
photo = view.ctx.assets.get_card_photo(view.engine.board[slot_i].image_filename, size=card_sz)
if photo:
view._photo_refs.append(photo)
view.arena_canvas.create_image(sx, card_top, image=photo, anchor="nw", tags="fg")
continue
view.arena_canvas.create_rectangle(
sx, card_top, sx + card_w, card_top + card_h,
fill="#161220", outline=SUBTLE_BORDER, width=1, tags="fg",
)
pot_txt = t("pk_pot_banner", view.engine.total_pot).split("|")[0].strip()
pot_cy = min(felt_bot - 20, max(board_cy + card_h // 2 + 28, (board_cy + card_h // 2 + felt_bot) // 2))
pot_sz = max(15, FONT_SIZE_BODY)
pot_ph = view._make_goth_photo(pot_txt, pot_sz, FONT_COLOR_TITLE_MAIN)
if pot_ph is not None:
bw, bh = max(230, pot_ph.width() + 64), max(38, pot_ph.height() + 16)
view._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold")
view.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg")
else:
view._draw_framed_panel(t_cx, pot_cy, 240, 38, frame_style="gold")
view._place_goth_photo_or_fallback(t_cx, pot_cy, None, pot_txt, pot_sz, ACCENT_GOLD)
@classmethod
def draw_human_hand(cls, view, cw: int, pad_x: int, player_zone_top: int, player_zone_bot: int) -> None:
human = view.engine.human_seat
avail_h = max(140, player_zone_bot - player_zone_top)
zone_cy = (player_zone_top + player_zone_bot) // 2
base_w, base_h = PLAYING_CARD_SIZE
scale = max(88, min(base_h, avail_h - 52)) / max(1, base_h)
card_w, card_h = max(60, int(round(base_w * scale))), int(round(base_h * scale))
card_sz = (card_w, card_h)
p_photos = []
for card in human.hole_cards:
photo = view.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
if photo:
view._photo_refs.append(photo)
p_photos.append(photo)
state_tag = t("pk_state_folded") if human.folded else (t("pk_state_allin") if human.all_in else "")
role_str = cls.role_badge(view.engine, 0) or t("pk_role_player")
lbl_txt = t("pk_player_bet_only", role_str, human.street_bet, human.total_committed, state_tag)
is_my_turn = (view.engine.street != "SHOWDOWN" and view.engine.turn_pos == 0 and human.can_act)
lbl_col = ERROR_FG if human.folded else FONT_COLOR_TITLE_MAIN
lbl_sz = max(14, FONT_SIZE_BODY - 1)
lbl_ph = view._make_goth_photo(lbl_txt, lbl_sz, lbl_col)
cards_gap = 12
cards_span_w = len(p_photos) * card_w + max(0, len(p_photos) - 1) * cards_gap if p_photos else card_w * 2
txt_w = lbl_ph.width() if lbl_ph is not None else 250
box_w = max(300, min(540, max(cards_span_w + 96, txt_w + 72)))
box_h = min(avail_h, card_h + 52)
box_cx = cw // 2
status_bdr = ERROR_FG if human.folded else (ACCENT_GOTH if human.all_in else None)
view._draw_framed_panel(
box_cx, zone_cy, box_w, box_h,
frame_style="gold" if is_my_turn else "purple", status_border=status_bdr,
)
if p_photos:
c_start_x = box_cx - cards_span_w // 2
c_top_y = (zone_cy - 11) - card_h // 2
for idx, ph in enumerate(p_photos):
view.arena_canvas.create_image(
c_start_x + idx * (card_w + cards_gap), c_top_y, image=ph, anchor="nw", tags="fg"
)
view._place_goth_photo_or_fallback(box_cx, zone_cy + box_h // 2 - 20, lbl_ph, lbl_txt, lbl_sz, lbl_col)
ref_btn = view._card_ref_btn
if ref_btn is not None and ref_btn.winfo_exists():
if view._result_dialog is not None or view._fx_overlay is not None or view.engine.street == "SHOWDOWN":
ref_btn.place_forget()
else:
ref_bw, ref_bh = ref_btn.pixel_width, ref_btn.pixel_height
ref_x = box_cx + box_w // 2 + 16
if ref_x + ref_bw > cw - pad_x - 6:
ref_x = max(pad_x + 6, box_cx - box_w // 2 - ref_bw - 16)
ref_y = zone_cy + box_h // 2 - ref_bh - 6
ref_btn.place(x=ref_x, y=ref_y, width=ref_bw, height=ref_bh)
tk.Widget.tkraise(ref_btn)
@staticmethod
def collect_all_seats_reveal(eng, winner_names: list[str]) -> list[dict]:
win_set = set(winner_names)
entries = []
for s in eng.seats:
if s.hole_cards:
cat_id, _ = PokerEvaluator.evaluate_best(s.hole_cards + eng.board)
entries.append({
"name": s.name,
"cards": [[c.suit, c.rank] for c in s.hole_cards],
"folded": s.folded,
"cat_id": cat_id,
"is_winner": (s.name in win_set) and (not s.folded),
})
return entries
@staticmethod
def build_localized_popup_data(view, payload: dict) -> dict:
hand_desc = (
t("pk_popup_fold_win")
if payload["by_fold"]
else t(f"pk_hand_{payload['winning_hand_cat'] or 0}")
)
human_in_win = payload.get("human_in_winners", bool(payload.get("player_won")))
if human_in_win:
headline = (
t("pk_popup_split_won", hand_desc)
if payload["is_split"]
else t("pk_popup_player_won", hand_desc)
)
else:
headline = t(
"pk_popup_bot_won", ", ".join(payload["winner_names"]), hand_desc
)
other_gains = [
t("pk_popup_bot_gain", b_n, b_g)
for b_n, b_g in payload["bot_gains"]
if b_g > 0
]
lvl_to = payload["leveled_to"]
lvl_str = (
t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to))
if lvl_to is not None
else None
)
seat_showdown = []
for s_rev in payload.get("seats_reveal", []):
raw_c = t(f"pk_hand_{s_rev['cat_id']}").strip()
short_c = raw_c.split(" (")[0] if len(raw_c) > 20 else raw_c
seat_showdown.append({
"name": s_rev["name"],
"cards": s_rev["cards"],
"folded": s_rev["folded"],
"is_winner": s_rev["is_winner"],
"combo_text": (
f"{t('pk_bot_act_fold')} ({short_c})"
if s_rev["folded"]
else short_c
),
})
cur_gold = Database.get_poker_account(view.pk_account["id"])["gold"]
return {
"headline": headline,
"player_won": payload["player_won"],
"player_net": payload["player_net"],
"other_gains": other_gains,
"xp_gained": payload["xp_gained"],
"new_level_title": lvl_str,
"board_cards": payload.get("board_cards", []),
"seat_showdown": seat_showdown,
"can_continue": cur_gold >= view.cfg["min_entry"],
"can_leave_menu": not view.devils_locked,
}

View File

@ -2,25 +2,9 @@
# games/poker/views/poker_menu_view.py
from __future__ import annotations
import sqlite3
import tkinter as tk
from games.poker.views.poker_table_view import PokerTableView
from view.widgets.menu_body_canvas import MenuBodyCanvas
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,
@ -28,491 +12,71 @@ from resources.code_res.game_constants import (
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
from view.widgets.luck_pouch_menu_base import LuckPouchMenuBase
GAME_FOLDER_ID = "poker"
class PokerMenuView:
def __init__(self, context):
self.ctx = context
self.bot_widget: BotSetupWidget | None = None
self._photo_refs: list = []
class PokerMenuView(LuckPouchMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
LAST_ACC_SETTING_PREFIX = "last_pk_account"
STARTING_GOLD = PK_STARTING_GOLD
MAX_BOTS = PK_MAX_BOTS
REQUIRES_MIN_ONE_BOT = True
DEVILS_DEFAULT_VARIANT = "poker_holdem"
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
pid = self.ctx.profile["id"]
KEY_TOPBAR = "pk_menu_topbar"
KEY_HEADER_GOLD = "pk_header_gold"
KEY_SEC1_TITLE = "pk_sec1_title"
KEY_BOTS_TITLE = "pk_bots_sec_title"
KEY_SEC3_TITLE = "pk_sec3_title"
KEY_GOLD_DISPLAY = "pk_gold_display_lbl"
KEY_DEFAULT_ACC_NAME = "pk_default_acc_name"
KEY_ERR_DUPLICATE = "pk_err_duplicate_name"
devils_acc = Database.get_active_devils_pk_account(pid)
if devils_acc is not None:
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
if saved is not None:
PokerTableView(
self.ctx,
variant_key=saved["variant_key"],
pk_account_id=devils_acc["id"],
bot_configs=[],
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
resume_state_json=saved["state_json"],
)
return
def _default_bot_configs(self) -> dict[int, tuple[str, int]]:
return {
0: (t("bot_default_name", 1), 1),
1: (t("bot_default_name", 2), 2),
}
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()
def _get_active_devils_account(self, pid: int):
return Database.get_active_devils_pk_account(pid)
dyn_xp_cost = pk_prog["xp_exchange_cost"]
is_divine = pk_prog["is_divine_punishment"]
at_floor = pk_prog["at_divine_floor"]
devils_deal_open = pk_prog["devils_deal_unlocked"]
def _get_accounts(self, pid: int):
return Database.get_poker_accounts(pid)
setting_key = f"last_pk_account_{pid}"
accounts = Database.get_poker_accounts(pid)
has_accounts = len(accounts) > 0
def _get_account(self, acc_id: int):
return Database.get_poker_account(acc_id)
if preselect_id is None and has_accounts:
saved_id_str = Database.load_setting(setting_key, "")
if saved_id_str.isdigit():
preselect_id = int(saved_id_str)
def _create_account(self, pid: int, name: str):
return Database.create_poker_account(pid, name)
acc_by_name = {a["account_name"]: a for a in accounts}
acc_names = list(acc_by_name.keys())
def _delete_account(self, acc_id: int):
Database.delete_poker_account(acc_id)
active_acc = None
if has_accounts:
active_acc = accounts[0]
if preselect_id is not None:
for a in accounts:
if a["id"] == preselect_id:
active_acc = a
break
Database.save_setting(setting_key, str(active_acc["id"]))
def _exchange_xp(self, pid: int, acc_id: int):
return Database.exchange_xp_for_pk_gold(pid, acc_id)
selected_name_var = tk.StringVar(
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
def _variants_dict(self) -> dict[str, dict]:
return PK_VARIANTS
def _min_entry_for_variant(self, _v_key: str, cfg: dict) -> int:
return cfg["min_entry"]
def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
return t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"])
def _format_limit_info(self, dyn_xp_cost: int) -> str:
classic = PK_VARIANTS["poker_holdem"]
return t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic["sb"], classic["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
PokerTableView(
self.ctx,
variant_key=variant_key,
pk_account_id=acc_id,
bot_configs=bots,
on_back_to_menu=lambda aid, msg="": self.show(preselect_id=aid, status_msg=msg),
resume_state_json=resume_json,
)
state_msg = {"text": status_msg, "ok": status_is_ok}
def get_current_acc() -> dict | None:
return acc_by_name.get(selected_name_var.get())
def open_pk_stats():
cur = get_current_acc()
if cur is None:
return
if self.bot_widget is not None and has_accounts:
_, to_save = self.bot_widget.collect_configs()
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),
).show(selected_acc_id=cur["id"])
def refresh_on_lang_switch():
cur = get_current_acc()
if self.bot_widget is not None and has_accounts:
_, to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
self.show(preselect_id=cur["id"] if cur else None)
topbar_gold_txt = (
t("pk_header_gold", active_acc["account_name"], active_acc["gold"])
if active_acc else ""
)
topbar = self.ctx.build_game_topbar(
self.ctx.root,
t("pk_menu_topbar"),
on_game_menu=None,
on_stats=open_pk_stats,
stats_enabled=has_accounts,
extra_right_text=topbar_gold_txt,
on_lang_refresh=refresh_on_lang_switch,
)
cv = MenuBodyCanvas(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
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,
)
def exchange_xp_action():
cur = get_current_acc()
if cur is None:
return
if self.bot_widget is not None:
_, to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
ok, msg = Database.exchange_xp_for_pk_gold(pid, cur["id"])
if ok and is_divine:
self.ctx.sounds.play("lose")
self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok)
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,
exchange_xp_action, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_exchange, style="amethyst",
)
def delete_selected_account():
cur = get_current_acc()
if cur is not None:
Database.delete_poker_account(cur["id"])
self.show()
delete_btn = ImageButton(
cv, t("bj_delete_acc_btn"), btn_norm, btn_purp,
delete_selected_account, sound_mgr=self.ctx.sounds,
width=136, height=32, enabled=has_accounts, style="amethyst",
)
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
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,
)
def create_new_account():
if not can_create_more:
return
name = new_entry.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())
return
try:
if self.bot_widget is not None and has_accounts:
_, to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
created = Database.create_poker_account(pid, name)
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())
if can_create_more:
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,
create_new_account, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_create_more,
style="fire" if not has_accounts else "amethyst",
)
sac_dd = None
devil_btn = None
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 sac_candidates:
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,
)
def seal_devils_deal():
cur = get_current_acc()
victim_id = sac_map.get(sac_var.get())
if cur is None or victim_id is None:
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())
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"])
if ok:
self.ctx.sounds.play("end_battle")
PokerTableView(
self.ctx,
variant_key="poker_holdem",
pk_account_id=cur["id"],
bot_configs=active_bots,
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",
)
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
if not saved_bots:
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)
def enter_table(v_key: str):
cur = get_current_acc()
if not cur:
return
acc = Database.get_poker_account(cur["id"])
if not acc:
return
Database.save_setting(setting_key, str(acc["id"]))
active_bots, configs_to_save = self.bot_widget.collect_configs()
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())
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(
"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())
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),
)
variant_items = list(PK_VARIANTS.items())
for v_key, cfg in variant_items:
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,
lambda k=v_key: enter_table(k),
sound_mgr=self.ctx.sounds, width=168, height=38,
enabled=can_play_v, style="fire",
)
table_buttons.append((v_key, t_btn))
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
cv.delete("fg")
self._photo_refs.clear()
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()))

View File

@ -2,241 +2,128 @@
# games/poker/views/poker_result_dialog.py
from __future__ import annotations
import tkinter as tk
from models.card import Card
from resources.code_res.game_constants import (
ACCENT_GOLD,
ACCENT_GOTH,
CELL_BG,
ERROR_FG,
FG_COLOR,
MODAL_BG,
MUTED_FG,
SUBTLE_BORDER,
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_SMALL_MIN,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.modal_veil import ModalVeil
from view.widgets.casino_result_dialog_base import CasinoResultDialogBase
POPUP_HOLE_CARD_SIZE = (48, 70)
POPUP_HOLE_CARD_SIZE = (46, 68)
POPUP_BOARD_CARD_SIZE = (44, 64)
class PokerResultDialog(tk.Frame):
"""
Ergebnis-Overlay für Texas Hold'em (ohne eingebettetes GIF),
immer über allen UI-Leisten platziert und mit abgedunkeltem, gesperrtem Tisch.
"""
class PokerResultDialog(CasinoResultDialogBase):
"""Gothic-Showdown-Overlay für Texas Hold'em auf Basis von CasinoResultDialogBase."""
def __init__(
self,
parent,
assets,
sounds,
result_data: dict,
on_next_round,
on_back_to_menu,
):
GothDropdown.close_any_open_popup()
top_root = parent.winfo_toplevel()
def __init__(self, parent, assets, sounds, result_data: dict, on_next_round, on_back_to_menu):
seats = result_data.get("seat_showdown", [])
has_board = bool(result_data.get("board_cards"))
cols = min(3, max(1, len(seats)))
rows = (len(seats) + 2) // 3 if seats else 0
extra_lines = len(result_data.get("other_gains", []))
super().__init__(
top_root,
bg=MODAL_BG,
padx=26,
pady=18,
highlightthickness=2,
highlightbackground=ACCENT_GOTH,
dlg_w = max(580, min(840, cols * 252 + 64))
dlg_h = (
62
+ (86 if has_board else 8)
+ (rows * 134 + 14 if rows else 0)
+ 92 + min(2, extra_lines) * 20
+ (24 if result_data.get("new_level_title") else 0)
+ 62
)
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._card_photos = []
self.place(relx=0.5, rely=0.5, anchor="center")
self._build()
self._veil = ModalVeil(top_root, assets, modal_widget=self)
def _build(self):
p_won = self.data.get("player_won")
headline_color = ACCENT_GOLD if p_won else (
MUTED_FG if p_won is None else ERROR_FG
)
tk.Label(
self,
text=self.data["headline"],
font=("Georgia", 16, "bold"),
fg=headline_color,
bg=MODAL_BG,
wraplength=680,
justify="center",
).pack(pady=(2, 10))
reveal_box = tk.Frame(
self,
bg=CELL_BG,
padx=12,
pady=8,
highlightthickness=1,
highlightbackground=SUBTLE_BORDER,
)
reveal_box.pack(fill="x", pady=(0, 10))
super().__init__(parent, assets, sounds, result_data, dlg_w, dlg_h, on_next_round, on_back_to_menu)
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
board_raw = self.data.get("board_cards", [])
if board_raw:
b_row = tk.Frame(reveal_box, bg=CELL_BG)
b_row.pack(pady=(0, 6))
tk.Label(
b_row,
text=f"{t('pk_board_title')}:",
font=("Georgia", 9, "bold"),
fg=MUTED_FG,
bg=CELL_BG,
).pack(side="left", padx=(0, 8))
b_box_h = 76
b_cy = cur_y + b_box_h // 2
b_box = self.assets.get_box_photo("box_gold_double", (w - 56, b_box_h))
if b_box:
self._photo_refs.append(b_box)
self.create_image(cx, b_cy, image=b_box, anchor="center")
for s_suit, s_rank in board_raw:
c_obj = Card(s_suit, s_rank)
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_BOARD_CARD_SIZE)
if ph:
self._card_photos.append(ph)
tk.Label(b_row, image=ph, bg=CELL_BG, bd=0).pack(side="left", padx=2)
tk.Frame(reveal_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(2, 6))
seats_row = tk.Frame(reveal_box, bg=CELL_BG)
seats_row.pack()
for idx, entry in enumerate(self.data.get("seat_showdown", [])):
is_win = entry["is_winner"]
folded = entry["folded"]
border_c = ACCENT_GOLD if is_win else (SUBTLE_BORDER if not folded else "#3a252a")
s_card = tk.Frame(
seats_row,
bg="#191521",
padx=8,
pady=5,
highlightthickness=2 if is_win else 1,
highlightbackground=border_c,
lbl_ph = self.assets.get_goth_text_photo(
f"{t('pk_board_title')}:", FONT_SIZE_SMALL_MIN, FONT_COLOR_HEADING_SUB, align="left"
)
s_card.grid(row=idx // 6, column=idx % 6, padx=4, pady=2, sticky="nsew")
self._photo_refs.append(lbl_ph)
name_col = ACCENT_GOLD if is_win else (MUTED_FG if folded else ACCENT_GOTH)
tk.Label(
s_card,
text=entry["name"],
font=("Georgia", 9, "bold"),
fg=name_col,
bg="#191521",
).pack()
c_frame = tk.Frame(s_card, bg="#191521", height=POPUP_HOLE_CARD_SIZE[1] + 2)
c_frame.pack(pady=3)
for s_suit, s_rank in entry["cards"]:
c_obj = Card(s_suit, s_rank)
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_HOLE_CARD_SIZE)
b_photos = []
for s_suit, s_rank in board_raw:
ph = self.assets.get_card_photo(Card(s_suit, s_rank).image_filename, size=POPUP_BOARD_CARD_SIZE)
if ph:
self._card_photos.append(ph)
tk.Label(c_frame, image=ph, bg="#191521", bd=0).pack(side="left", padx=1)
self._photo_refs.append(ph)
b_photos.append(ph)
combo_col = "#7be08a" if is_win else (ERROR_FG if folded else FG_COLOR)
tk.Label(
s_card,
text=entry["combo_text"],
font=("Helvetica", 8, "bold"),
fg=combo_col,
bg="#191521",
wraplength=112,
justify="center",
).pack()
cw_b, ch_b = POPUP_BOARD_CARD_SIZE
cards_w = len(b_photos) * cw_b + max(0, len(b_photos) - 1) * 6
total_w = lbl_ph.width() + 14 + cards_w
start_x = cx - total_w // 2
info_box = tk.Frame(
self,
bg=CELL_BG,
padx=20,
pady=10,
highlightthickness=1,
highlightbackground=SUBTLE_BORDER,
)
info_box.pack(fill="x", pady=(0, 12))
self.create_image(start_x, b_cy, image=lbl_ph, anchor="w")
cx_card = start_x + lbl_ph.width() + 14
for bph in b_photos:
self.create_image(cx_card, b_cy - ch_b // 2, image=bph, anchor="nw")
cx_card += cw_b + 6
p_net = self.data["player_net"]
if p_net > 0:
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)), ERROR_FG
else:
own_txt, own_col = t("bj_popup_your_even"), FG_COLOR
cur_y += b_box_h + 8
tk.Label(info_box, text=own_txt, font=("Helvetica", 11, "bold"), fg=own_col, bg=CELL_BG).pack(pady=2)
seats = self.data.get("seat_showdown", [])
if not seats:
return cur_y
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)
max_cols = 3
rows = (len(seats) + max_cols - 1) // max_cols
seat_w = min(244, (w - 64 - (max_cols - 1) * 10) // max(1, min(max_cols, len(seats))))
seat_h = 126 if rows > 1 else 132
tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=8)
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)
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)
for idx, entry in enumerate(seats):
r_i, c_i = divmod(idx, max_cols)
in_row = min(max_cols, len(seats) - 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
if self.data.get("new_level_title"):
tk.Label(
info_box,
text=self.data["new_level_title"],
font=("Georgia", 11, "bold"),
fg=ACCENT_GOLD,
bg=CELL_BG,
).pack(pady=(3, 0))
is_win, folded = entry["is_winner"], entry["folded"]
frame_ph = win_box if is_win else std_box
if frame_ph:
self.create_image(sx, sy, image=frame_ph, anchor="center")
btn_row = tk.Frame(self, bg=MODAL_BG)
btn_row.pack(fill="x", pady=(4, 0))
n_col = FONT_COLOR_TITLE_MAIN if is_win else (FONT_COLOR_BODY_MUTED if folded else FONT_COLOR_HEADING_SUB)
n_ph = self.assets.get_goth_text_photo(entry["name"], FONT_SIZE_SMALL_MIN + 1, n_col, max_width=seat_w - 24)
self._photo_refs.append(n_ph)
self.create_image(sx, sy - seat_h // 2 + 19, image=n_ph, anchor="center")
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
cw_h, ch_h = POPUP_HOLE_CARD_SIZE
h_photos = [
ph for s_suit, s_rank in entry["cards"]
if (ph := self.assets.get_card_photo(Card(s_suit, s_rank).image_filename, size=POPUP_HOLE_CARD_SIZE))
]
self._photo_refs.extend(h_photos)
if h_photos:
span_w = len(h_photos) * cw_h + max(0, len(h_photos) - 1) * 6
hx = sx - span_w // 2
for hph in h_photos:
self.create_image(hx, sy - ch_h // 2 + 1, image=hph, anchor="nw")
hx += cw_h + 6
if self.data.get("can_continue", True):
ImageButton(
btn_row,
t("bj_popup_next_round_btn"),
btn_fire,
btn_fire,
self._handle_next,
sound_mgr=self.sounds,
width=200,
height=38,
style="fire",
).pack(side="left", padx=(0, 10))
cb_col = FONT_COLOR_STATUS_WIN if is_win else (FONT_COLOR_STATUS_LOSS if folded else FONT_COLOR_BODY_DEFAULT)
cb_ph = self.assets.get_goth_text_photo(entry["combo_text"], FONT_SIZE_SMALL_MIN, cb_col, max_width=seat_w - 20)
self._photo_refs.append(cb_ph)
self.create_image(sx, sy + seat_h // 2 - 18, image=cb_ph, anchor="center")
if self.data.get("can_leave_menu", True):
ImageButton(
btn_row,
t("bj_popup_to_menu_btn"),
btn_norm,
btn_purp,
self._handle_menu,
sound_mgr=self.sounds,
width=170,
height=38,
style="amethyst",
).pack(side="right")
def close_dialog(self):
self._veil.release()
if self.winfo_exists():
self.destroy()
def _handle_next(self):
self.close_dialog()
self.on_next_round()
def _handle_menu(self):
self.close_dialog()
self.on_back_to_menu()
return cur_y + rows * (seat_h + 6) + 6

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,270 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_turn_driver.py
from __future__ import annotations
import time
from games.poker.models.poker_seat import PokerSeat
from games.poker.views.poker_arena_renderer import PokerArenaRenderer
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
PK_BOT_TURN_DELAY_MS,
PK_STREET_DELAY_MS,
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
class PokerTurnDriver:
"""Steuert Setzrunden, Spieler-Aktionsleiste, KI-Züge und Showdown-Abrechnung beim Poker."""
@classmethod
def process_current_turn(cls, view) -> None:
if not view._canvas_alive():
return
if view.engine.only_one_left():
cls.finalize_hand(view)
return
if view.engine.is_betting_round_complete():
cls.advance_street_or_showdown(view)
return
if (
view.engine.turn_pos < 0
or not view.engine.seats[view.engine.turn_pos].can_act
):
view.engine.advance_turn_pointer()
if view.engine.turn_pos < 0:
cls.advance_street_or_showdown(view)
return
if view.engine.turn_pos == 0:
view._render_table()
cls.show_human_controls(view)
else:
view._set_bottom_buttons([])
bot = view.engine.seats[view.engine.turn_pos]
view._render_table()
view._turn_job = view.ctx.root.after(
PK_BOT_TURN_DELAY_MS, lambda b=bot: cls.execute_bot_turn(view, b)
)
@classmethod
def advance_street_or_showdown(cls, view) -> None:
view._set_bottom_buttons([])
if view.engine.street == "RIVER":
cls.finalize_hand(view)
return
view.ctx.sounds.play("click")
new_street = view.engine.advance_to_next_street()
view._persist_state()
view._render_table()
if new_street == "SHOWDOWN":
cls.finalize_hand(view)
elif view.engine.should_auto_runout_board():
view._turn_job = view.ctx.root.after(
PK_STREET_DELAY_MS, lambda: cls.advance_street_or_showdown(view)
)
else:
cls.process_current_turn(view)
@staticmethod
def show_human_controls(view) -> None:
if not hasattr(view, "bottom_bar") or not view.bottom_bar.winfo_exists():
return
human = view.engine.human_seat
to_call = max(0, view.engine.current_bet - human.street_bet)
dyn_chips = view._get_current_level_chips()
btn_norm = view.ctx.assets.raw_btn_default
btn_purp = view.ctx.assets.raw_btn_purple
btn_fire = view.ctx.assets.raw_btn_fire or btn_purp
primary_btns: list[ImageButton] = []
overflow_btns: list[ImageButton] = []
if to_call == 0:
primary_btns.append(
ImageButton(
view.bottom_bar, t("pk_btn_check"), btn_fire, btn_fire,
lambda: view._on_human_action("CHECK", 0), sound_mgr=None,
width=138, height=30, style="fire",
hover_text=lambda: t("pk_tip_check"),
)
)
elif human.stack > to_call:
primary_btns.append(
ImageButton(
view.bottom_bar, t("pk_btn_call", to_call), btn_fire, btn_fire,
lambda: view._on_human_action("CALL", 0),
sound_mgr=view.ctx.sounds, width=138, height=30, style="fire",
hover_text=lambda: t("pk_tip_call"),
)
)
avail_after_call = human.stack - to_call
min_r = view.engine.min_raise_delta
offered = sorted(
{max(min_r, c) for c in dyn_chips if max(min_r, c) < avail_after_call}
)[:4]
for r_delta in offered:
primary_btns.append(
ImageButton(
view.bottom_bar, f"+{r_delta}g", btn_norm, btn_purp,
lambda d=r_delta: view._on_human_action("RAISE", d),
sound_mgr=view.ctx.sounds, width=74, height=30, style="amethyst",
hover_text=lambda: t("pk_tip_raise"),
)
)
if human.stack > 0:
allin_fire = to_call > 0 and human.stack <= to_call
overflow_btns.append(
ImageButton(
view.bottom_bar, t("pk_btn_allin", human.stack),
btn_fire if allin_fire else btn_norm,
btn_fire if allin_fire else btn_purp,
lambda: view._on_human_action("ALLIN", 0),
sound_mgr=view.ctx.sounds, width=132, height=30,
style="fire" if allin_fire else "amethyst",
hover_text=lambda: t("pk_tip_allin"),
)
)
overflow_btns.append(
ImageButton(
view.bottom_bar, t("pk_btn_fold"), btn_norm, btn_purp,
lambda: view._on_human_action("FOLD", 0),
sound_mgr=view.ctx.sounds, width=122, height=30, style="amethyst",
hover_text=lambda: t("pk_tip_fold"),
)
)
view._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
@classmethod
def execute_bot_turn(cls, view, bot: PokerSeat) -> None:
if not view._canvas_alive():
return
active_opps = sum(
1 for s in view.engine.seats if s.is_in_hand and s.seat_id != bot.seat_id
)
act, r_delta = view.bot_ai.decide_action(
bot=bot,
board=view.engine.board,
current_bet=view.engine.current_bet,
pot=view.engine.total_pot,
min_raise_delta=view.engine.min_raise_delta,
chips=view._get_current_level_chips(),
active_opponents=active_opps,
)
paid = view.engine.apply_action(bot.seat_id, act, r_delta)
if act == "FOLD":
bot.status_text = t("pk_bot_act_fold")
elif act == "CHECK":
bot.status_text = t("pk_bot_act_check")
elif act == "ALLIN":
view.ctx.sounds.play("click")
bot.status_text = t("pk_bot_act_allin", bot.total_committed)
elif act == "RAISE":
view.ctx.sounds.play("click")
bot.status_text = t("pk_bot_act_raise", paid)
else:
view.ctx.sounds.play("click")
bot.status_text = t("pk_bot_act_call", paid)
view.engine.advance_turn_pointer()
view._persist_state()
view._render_table()
cls.process_current_turn(view)
@staticmethod
def finalize_hand(view) -> None:
ImageButton.close_active_hover_tip()
view._close_hands_overlay()
view._set_bottom_buttons([])
res = view.engine.resolve_hand()
if res["human_payout"] > 0:
view.pk_account = Database.update_poker_gold(
view.pk_account["id"], res["human_payout"]
)
duration = max(0.5, time.time() - view.round_start_time)
prog_before = view.ctx.refresh_game_progress()
opp_levels = [s.ai_level for s in view.engine.seats[1:]]
win_cat = res["winning_hand_cat"] or 0
if res["human_won"] and res["human_net"] > 0:
out_type = (
"WIN_777" if win_cat >= 8 else ("WIN_BJ" if win_cat >= 6 else "WIN")
)
won_stat: bool | None = True
elif res["human_net"] == 0 and res["human_payout"] > 0:
out_type, won_stat = "TIE", None
elif res["human_won"]:
out_type, won_stat = "WIN", True
else:
out_type, won_stat = "LOSE", False
xp_gained = Progression.calculate_match_xp(
prog_before["level"],
opp_levels,
out_type,
variant_mult=view.cfg["xp_mult"],
)
if won_stat is None:
Database.add_game_points(
view.ctx.profile["id"], view.GAME_FOLDER_ID, xp_gained
)
prog_after = view.ctx.refresh_game_progress()
view.ctx.sounds.play("end_battle")
leveled_to = (
prog_after["level"]
if prog_after["level"] > prog_before["level"]
else None
)
else:
old_lvl, new_lvl = view.ctx.record_result(
view.variant_key,
won=won_stat,
duration_sec=duration,
points_gained=xp_gained,
pk_account_id=view.pk_account["id"],
)
leveled_to = new_lvl if new_lvl > old_lvl else None
if view.devils_locked:
fresh_acc = Database.get_poker_account(view.pk_account["id"])
if not (out_type == "TIE" and fresh_acc["gold"] == 10):
Database.set_pk_devils_deal_active(view.pk_account["id"], False)
view.devils_locked = False
view._clear_persisted_state()
else:
view._clear_persisted_state()
payload = {
"by_fold": res["by_fold"],
"winner_names": res["winner_names"],
"winning_hand_cat": res["winning_hand_cat"],
"player_won": won_stat,
"human_in_winners": bool(res["human_won"]),
"is_split": res["is_split"],
"player_net": res["human_net"],
"bot_gains": res["bot_gains"],
"xp_gained": xp_gained,
"leveled_to": leveled_to,
"board_cards": [[c.suit, c.rank] for c in view.engine.board],
"seats_reveal": PokerArenaRenderer.collect_all_seats_reveal(
view.engine, res["winner_names"]
),
}
view._last_popup_payload = payload
if view.devils_locked:
view._persist_state()
elif view._canvas_alive():
view.topbar.set_locked_exit(False)
view._render_table()
view._open_result_popup(
PokerArenaRenderer.build_localized_popup_data(view, payload),
play_fx=True,
)

View File

@ -0,0 +1,374 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_canvas_input.py
from __future__ import annotations
import time
from games.solitaire.base.solitaire_core import SolitaireCard
from games.solitaire.base.solitaire_tap_prefs import (
SINGLE_TAP_MAX_HOLD_SEC,
is_single_tap_to_move_enabled,
)
from resources.code_res.game_constants import (
ACCENT_GOLD,
BORDER_COLOR,
CELL_BG,
ERROR_FG,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
MUTED_FG,
PLAYING_CARD_SIZE,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
class SolitaireCanvasInput:
"""
Kapselt für alle Solitaire-Tische das Canvas-Frame-Rendering, Slot-/Karten-Zeichnen,
Kartenflug-Animationen sowie Maus-, Drag-&-Drop- und Tap-/Doppelklick-Steuerung.
"""
DRAG_STACK_DY_FACTOR: float = 0.195
DRAG_THRESHOLD_PX: int = 5
DOUBLE_CLICK_SEC: float = 0.30
@staticmethod
def _card_key(card: SolitaireCard) -> tuple[str, str, int]:
return (card.suit, card.rank, card.deck_id)
def _get_card_aspect(self) -> float:
if self._card_aspect is None:
sample_pil = self.ctx.assets._load_pil(
self.ctx.assets.res.get_card_back_path(self.cfg["back_color"])
)
if sample_pil and sample_pil.size[0] > 0:
self._card_aspect = sample_pil.size[1] / sample_pil.size[0]
else:
self._card_aspect = PLAYING_CARD_SIZE[1] / PLAYING_CARD_SIZE[0]
return self._card_aspect
def _on_canvas_configure(self, _event=None):
if not self._canvas_alive() or self._fx_overlay is not None:
return
if self.hover_zoom is not None:
self.hover_zoom.cancel()
if self.animator:
self.animator.flush()
if self._resize_job is not None:
try:
self.ctx.root.after_cancel(self._resize_job)
except Exception:
pass
try:
self._resize_job = self.ctx.root.after(35, self._recompute_and_draw)
except Exception:
self._resize_job = None
def _prepare_canvas_frame(
self, min_w: int = 640, min_h: int = 420
) -> tuple[int, int]:
keep_ids = set(self.canvas.find_withtag("table_bg_slice")) | set(
self.canvas.find_withtag("modal_dim_veil")
)
for item_id in self.canvas.find_all():
if item_id not in keep_ids:
self.canvas.delete(item_id)
self._canvas_ui_refs.clear()
cw = max(min_w, self.canvas.winfo_width())
ch = max(min_h, self.canvas.winfo_height())
self._bg_renderer.draw_on_canvas(self.canvas, cw, ch)
return cw, ch
def _finish_canvas_frame(
self, canvas_w: int, canvas_h: int, exclude_source, hidden: set
):
if (
self.engine.has_timer_started
and not self._window_active
and not self.engine.won
and not self._game_concluded
and self._modal_overlay is None
and self._fx_overlay is None
):
p_ph = self.ctx.assets.get_goth_text_photo(
t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN
)
bw, bh = p_ph.width() + 56, max(44, p_ph.height() + 18)
box_ph = self.ctx.assets.get_box_photo("box_purple", (bw, bh))
self._canvas_ui_refs.extend([p_ph, box_ph] if box_ph else [p_ph])
pcx, pcy = canvas_w // 2, canvas_h - bh // 2 - 18
if box_ph:
self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center")
self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center")
if self.canvas.find_withtag("modal_dim_veil"):
self.canvas.tag_raise("modal_dim_veil")
if self.hover_zoom is not None and exclude_source is None and not hidden:
self.hover_zoom.refresh_after_redraw()
self._sync_buttons()
def _draw_slot(
self,
x: int,
y: int,
symbol: str = "",
symbol_color: str = MUTED_FG,
highlight_color: str | None = None,
draw_red_cross: bool = False,
):
cw, ch = self.card_size
outline = (
ERROR_FG
if draw_red_cross
else (highlight_color if highlight_color else BORDER_COLOR)
)
width = 2 if (highlight_color or draw_red_cross) else 1
self.canvas.create_rectangle(
x, y, x + cw, y + ch, fill=CELL_BG, outline=outline, width=width
)
if draw_red_cross:
px, py = max(14, int(cw * 0.22)), max(18, int(ch * 0.22))
self.canvas.create_line(
x + px, y + py, x + cw - px, y + ch - py,
fill="#ff4455", width=4, capstyle="round",
)
self.canvas.create_line(
x + cw - px, y + py, x + px, y + ch - py,
fill="#ff4455", width=4, capstyle="round",
)
elif symbol:
self.canvas.create_text(
x + cw // 2,
y + ch // 2,
text=symbol,
font=("Georgia", max(13, cw // 4), "bold"),
fill=symbol_color,
)
def _draw_card_at(
self,
card: SolitaireCard,
x: int,
y: int,
tags: tuple[str, ...] = (),
highlight_color: str | None = None,
dim_non_movable: bool = False,
):
cw, ch = self.card_size
photo = (
self.ctx.assets.get_card_photo(card.filename, size=self.card_size)
if card.face_up
else self.ctx.assets.get_card_back_photo(
self.cfg["back_color"], size=self.card_size
)
)
if photo is not None:
self.canvas.create_image(x, y, image=photo, anchor="nw", tags=tags)
else:
fill_c = "#f5f2f8" if card.face_up else "#201a2b"
self.canvas.create_rectangle(
x, y, x + cw, y + ch, fill=fill_c, outline=BORDER_COLOR, tags=tags
)
if card.face_up:
txt_c = "#c93b4b" if card.is_red else "#16131d"
self.canvas.create_text(
x + 9, y + 11, text=card.label, anchor="nw",
font=("Georgia", 10, "bold"), fill=txt_c, tags=tags,
)
if dim_non_movable and card.face_up and not highlight_color:
self.canvas.create_rectangle(
x, y, x + cw, y + ch, outline=SUBTLE_BORDER, width=1, tags=tags
)
if highlight_color:
self.canvas.create_rectangle(
x - 2, y - 2, x + cw + 2, y + ch + 2,
outline=highlight_color, width=2, tags=tags,
)
def _run_animated_action(
self, action_fn, override_starts=None, duration_ms: int = 115, after_cb=None
) -> bool:
if self.hover_zoom is not None:
self.hover_zoom.cancel()
if self.animator:
self.animator.flush()
before_pos = self._snapshot_card_positions()
if override_starts:
before_pos.update(override_starts)
if not action_fn():
return False
after_pos = self._snapshot_card_positions()
moved_keys = {
k
for k, end_xy in after_pos.items()
if k in before_pos
and (
abs(end_xy[0] - before_pos[k][0]) > 3
or abs(end_xy[1] - before_pos[k][1]) > 3
)
}
if not moved_keys or self.animator is None:
(after_cb if callable(after_cb) else self.redraw)()
return True
flights = [
{
"card": c,
"start": before_pos[self._card_key(c)],
"end": after_pos[self._card_key(c)],
}
for c in self._ordered_moved_cards(moved_keys)
]
self.redraw(hidden_card_keys=moved_keys)
def finish():
if self._canvas_alive():
(after_cb if callable(after_cb) else self.redraw)()
self.animator.start(
flights, self._draw_card_at, duration_ms=duration_ms, on_done=finish
)
return True
def _on_mouse_down(self, event):
if self.hover_zoom is not None:
self.hover_zoom.cancel()
if self._is_ui_locked():
return
if self.animator and self.animator.is_active:
self.animator.flush()
self._window_active = True
self._clear_hint()
hit = self._hit_test(event.x, event.y)
self._press_info = None
self._dragging = False
if not hit:
return
self.engine.start_timer_if_needed()
self._update_hud_text()
hit["start_xy"] = (event.x, event.y)
hit["press_ts"] = time.monotonic()
self._press_info = hit
def _on_mouse_move(self, event):
if (
not self._press_info
or not self._press_info.get("cards")
or self._fx_overlay is not None
):
return
sx, sy = self._press_info["start_xy"]
if not self._dragging:
if (
abs(event.x - sx) < self.DRAG_THRESHOLD_PX
and abs(event.y - sy) < self.DRAG_THRESHOLD_PX
):
return
if self.hover_zoom is not None:
self.hover_zoom.cancel()
self._dragging = True
self._drag_last_xy = (sx, sy)
self.redraw(exclude_source=self._press_info)
ox, oy = self._press_info["origin"]
drag_dy = max(15, int(self.card_size[1] * self.DRAG_STACK_DY_FACTOR))
for i, card in enumerate(self._press_info["cards"]):
self._draw_card_at(
card,
ox,
oy + i * drag_dy,
tags=("drag_ghost",),
highlight_color=ACCENT_GOLD if i == 0 else None,
)
dx = event.x - self._drag_last_xy[0]
dy = event.y - self._drag_last_xy[1]
self._drag_last_xy = (event.x, event.y)
self.canvas.move("drag_ghost", dx, dy)
def _on_drop_succeeded_sound(self):
self.ctx.sounds.play("click")
def _on_mouse_up(self, event):
info, was_dragging = self._press_info, self._dragging
self._press_info, self._dragging = None, False
if not info:
return
if not was_dragging:
self._handle_click(info)
return
ox, oy = info["origin"]
sx, sy = info["start_xy"]
drop_x, drop_y = ox + (event.x - sx), oy + (event.y - sy)
drag_dy = max(15, int(self.card_size[1] * self.DRAG_STACK_DY_FACTOR))
override = {
self._card_key(c): (drop_x, drop_y + i * drag_dy)
for i, c in enumerate(info["cards"])
}
if self._run_animated_action(
lambda: self._try_drop(info, drop_x, drop_y),
override_starts=override,
duration_ms=78,
after_cb=self._after_player_move,
):
self._on_drop_succeeded_sound()
else:
target_pos = self._snapshot_card_positions()
cards: list[SolitaireCard] = info["cards"]
hidden_keys = {self._card_key(c) for c in cards}
flights = [
{
"card": c,
"start": override[self._card_key(c)],
"end": target_pos.get(self._card_key(c), (ox, oy + i * drag_dy)),
}
for i, c in enumerate(cards)
]
self.redraw(hidden_card_keys=hidden_keys)
if self.animator:
self.animator.start(
flights, self._draw_card_at, duration_ms=85, on_done=self.redraw
)
else:
self.redraw()
def _dispatch_tap_or_double_click(self, info: dict):
now = time.monotonic()
if is_single_tap_to_move_enabled():
self._last_click_target = None
if (now - info.get("press_ts", now)) <= SINGLE_TAP_MAX_HOLD_SEC:
self._smart_auto_move(info)
return
target_id = (info["zone"], info.get("col", -1), info.get("idx", -1))
if (
self._last_click_target == target_id
and (now - self._last_click_ts) <= self.DOUBLE_CLICK_SEC
):
self._last_click_target = None
self._smart_auto_move(info)
else:
self._last_click_ts = now
self._last_click_target = target_id
def _on_right_click(self, event):
if self.hover_zoom is not None:
self.hover_zoom.cancel()
if self._is_ui_locked():
return
if self.animator and self.animator.is_active:
self.animator.flush()
self._window_active = True
self._clear_hint()
hit = self._hit_test(event.x, event.y)
if hit:
self.engine.start_timer_if_needed()
self._update_hud_text()
if hit.get("zone") == "stock":
self._handle_click(hit)
else:
self._smart_auto_move(hit)

View File

@ -0,0 +1,417 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_menu_base.py
from __future__ import annotations
import json
import tkinter as tk
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
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,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
class SolitaireMenuBase:
"""
Gemeinsame Vorauswahl-Menü-Basisklasse für alle Solitaire-Spiele
(Klondike, FreeCell, Spider, Pyramid, TriPeaks):
Kapselt Fortsetzen-Banner, Aufgabe-Bestätigung, Varianten-Toggles & Schwierigkeits-Auswahl.
"""
GAME_FOLDER_ID: str = ""
GAME_TITLE_KEY: str = ""
TOPBAR_KEY: str = ""
SUBTITLE_KEY: str = "sol_menu_subtitle"
CONTROLS_HINT_KEY: str = ""
DIFF_SETTING_PREFIX: str = ""
VARIANT_SETTING_PREFIX: str = ""
DEFAULT_VARIANT_KEY: str = ""
DEFAULT_SCORE: int = 0
REQUIRED_BOARD_KEYS: tuple[str, ...] = ("tableau",)
MODE_LABEL_KEY: str = ""
VARIANT_TOGGLES: tuple[tuple[str, str], ...] = ()
TOGGLE_BTN_WIDTH: int = 160
DESC_KEY_PREFIX: str = ""
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
def _variants_dict(self) -> dict[str, dict]:
raise NotImplementedError
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
raise NotImplementedError
def _clear_modal(self):
if self._return_bind_id is not None:
try:
self.ctx.root.unbind("<Return>", self._return_bind_id)
except Exception:
pass
self._return_bind_id = None
if self._modal_overlay is not None:
try:
self._modal_overlay.destroy()
except Exception:
pass
self._modal_overlay = None
def show(
self,
status_msg: str = "",
status_is_ok: bool = False,
ask_resume_popup: bool = False,
):
self._clear_modal()
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self.ctx.refresh_game_progress()
diff_setting_key = f"{self.DIFF_SETTING_PREFIX}_{pid}"
saved_diff_str = Database.load_setting(diff_setting_key, "1")
selected_diff = (
int(saved_diff_str)
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
else 1
)
variants_map = self._variants_dict()
if self.VARIANT_SETTING_PREFIX and len(variants_map) > 1:
var_setting_key = f"{self.VARIANT_SETTING_PREFIX}_{pid}"
selected_variant = Database.load_setting(var_setting_key, self.DEFAULT_VARIANT_KEY)
if selected_variant not in variants_map:
selected_variant = self.DEFAULT_VARIANT_KEY
else:
var_setting_key = ""
selected_variant = self.DEFAULT_VARIANT_KEY
self.ctx.build_game_topbar(
self.ctx.root,
t(self.TOPBAR_KEY),
stats_endpoint=self.GAME_FOLDER_ID,
on_game_menu=None,
on_stats_back=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
stats_enabled=True,
extra_right_text="",
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
)
cv = MenuBodyCanvas(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
saved = Database.load_game_state(pid, self.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=180, height=38, style="fire",
)
def switch_variant(v_key: str):
if v_key == selected_variant or self._modal_overlay is not None:
return
if var_setting_key:
Database.save_setting(var_setting_key, v_key)
self.show(status_msg=status_msg, status_is_ok=status_is_ok)
toggle_btns: list[ImageButton] = []
for v_key, lbl_key in self.VARIANT_TOGGLES:
is_sel = (selected_variant == v_key)
toggle_btns.append(
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_variant(k),
sound_mgr=self.ctx.sounds,
width=self.TOGGLE_BTN_WIDTH, height=36,
style="fire" if is_sel else "amethyst",
)
)
diff_levels = sorted(SOLITAIRE_DIFFICULTIES.keys())
diff_labels = [t(f"sol_diff_{lvl}") for lvl in diff_levels]
diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in diff_levels}
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=205, height=40, style="fire",
)
has_toggles = len(toggle_btns) > 0
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
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(self.GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left"
)
sub_ph = self.ctx.assets.get_goth_text_photo(
t(self.SUBTITLE_KEY), 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(
self._format_resume_info(saved, saved_meta),
FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT,
max_width=box_w - resume_btn.pixel_width - 70, align="left",
)
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
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
setup_h = 238 if has_toggles else 208
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, val_col = x_left + 32, x_left + 220
r1_y = cur_y + 44
m_lbl = self.ctx.assets.get_goth_text_photo(
t(self.MODE_LABEL_KEY), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left"
)
self._photo_refs.append(m_lbl)
cv.create_image(lbl_col, r1_y, image=m_lbl, anchor="w", tags="fg")
dsc_txt = t(f"{self.DESC_KEY_PREFIX}{selected_variant}")
if has_toggles:
bx_cur = val_col
for tb in toggle_btns:
cv.create_window(bx_cur, r1_y, window=tb, anchor="w", tags="fg")
bx_cur += tb.pixel_width + 10
dsc_ph = self.ctx.assets.get_goth_text_photo(
dsc_txt, 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")
r2_y = cur_y + 128
else:
m_val = self.ctx.assets.get_goth_text_photo(
t(f"variant_{selected_variant}"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left"
)
dsc_ph = self.ctx.assets.get_goth_text_photo(
dsc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
max_width=max(180, box_w - 275 - m_val.width()), align="left",
)
self._photo_refs.extend([m_val, dsc_ph])
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=dsc_ph, anchor="w", tags="fg")
r2_y = cur_y + 104
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")
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(self.CONTROLS_HINT_KEY), 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()))
if ask_resume_popup and saved and saved_meta is not None:
self._show_resume_prompt_modal(saved, saved_meta)
def _parse_saved_meta(self, saved: dict | None) -> dict | None:
if not saved:
return None
try:
data = json.loads(saved["state_json"])
if data.get("won"):
return None
board = data.get("board", {})
if not board or any(req_k not in board for req_k in self.REQUIRED_BOARD_KEYS):
return None
return {
"moves": max(0, int(data.get("moves", 0))),
"score": int(data.get("score", self.DEFAULT_SCORE)),
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
}
except Exception:
return None
@staticmethod
def _format_resume_info(saved: dict, saved_meta: dict) -> str:
return 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"]),
)
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
self._clear_modal()
def resume_now(_event=None):
self._clear_modal()
self._resume_saved(saved, saved_meta["difficulty"])
try:
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
except tk.TclError:
self._return_bind_id = None
self._modal_overlay = SolitaireModalDialog(
self.ctx,
title_txt=t("sol_resume_box_title"),
body_txt=self._format_resume_info(saved, saved_meta),
buttons=[
(t("sol_resume_btn"), "fire", resume_now),
(t("bj_popup_to_menu_btn"), "amethyst", self._clear_modal),
],
)
def _resume_saved(self, saved: dict, difficulty: int):
self._clear_modal()
self._launch_table_view(saved["variant_key"], difficulty, resume_state_json=saved["state_json"])
def _on_start_clicked(
self, variant_key: str, difficulty: int, saved: dict | None, saved_meta: dict | None
):
if self._modal_overlay is not None:
return
if saved and saved_meta and saved_meta["moves"] > 0:
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
return
self._launch_fresh_game(variant_key, difficulty)
def _show_overwrite_confirm_modal(
self, new_variant_key: str, new_difficulty: int, saved: dict, saved_meta: dict
):
pid = self.ctx.profile["id"]
old_v, old_diff = saved["variant_key"], saved_meta["difficulty"]
prog = Database.get_game_progress(pid, self.GAME_FOLDER_ID)
variants_map = self._variants_dict()
v_mult = variants_map.get(old_v, {"xp_mult": 1.0})["xp_mult"]
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
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)))
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
)
Database.adjust_game_points(pid, self.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 = SolitaireModalDialog(
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),
],
)
def _launch_fresh_game(self, variant_key: str, difficulty: int):
pid = self.ctx.profile["id"]
Database.save_setting(f"{self.DIFF_SETTING_PREFIX}_{pid}", str(difficulty))
if self.VARIANT_SETTING_PREFIX:
Database.save_setting(f"{self.VARIANT_SETTING_PREFIX}_{pid}", variant_key)
Database.delete_game_state(pid, self.GAME_FOLDER_ID)
self._launch_table_view(variant_key, difficulty, resume_state_json=None)

View File

@ -0,0 +1,253 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_outcome_flow.py
from __future__ import annotations
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import SOLO_FORFEIT_XP_RATIO
from resources.code_res.i18n import t
from view.widgets.endgame_fx_overlay import EndgameFxOverlay
class SolitaireOutcomeFlow:
"""Kapselt Sieg-, Niederlage-, Aufgabe- und Deadlock-Abläufe für alle Solitaire-Tische."""
@staticmethod
def _leave_to_menu(view, status_msg: str = "", ok: bool = False) -> None:
view._close_active_modal()
view._cleanup_timers()
if callable(view.on_back_to_menu):
if status_msg:
view.on_back_to_menu(status_msg, ok)
else:
view.on_back_to_menu()
@staticmethod
def _restart_from_modal(view) -> None:
view._close_active_modal()
view._start_fresh_deal()
@staticmethod
def compute_forfeit_penalty(view) -> int:
pid = view.ctx.profile["id"]
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
win_xp = Progression.calculate_match_xp(
prog["level"], [], "WIN", variant_mult=view._combined_xp_mult
)
return max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO)))
@classmethod
def show_deadlock_modal(cls, view) -> None:
if view.hover_zoom is not None:
view.hover_zoom.cancel()
view.engine.pause_timer()
view._save_progress()
penalty = cls.compute_forfeit_penalty(view)
def undo_step():
view._close_active_modal()
view._on_undo()
def undo_everything():
view._close_active_modal()
view._on_undo_all()
view._modal_overlay = SolitaireModalDialog(
view.ctx,
title_txt=t("sol_deadlock_title"),
body_txt=t("sol_deadlock_desc", penalty),
is_danger=True,
buttons=[
(t("sol_deadlock_btn_undo"), "fire", undo_step, view.engine.can_undo),
(t("sol_deadlock_btn_undo_all"), "fire", undo_everything, view.engine.can_undo_all),
(
t("sol_deadlock_btn_end", penalty),
"amethyst",
lambda: cls.execute_forfeit(view, penalty, go_menu=True),
True,
),
],
)
view._sync_buttons()
@classmethod
def show_forfeit_modal(cls, view) -> None:
if view.hover_zoom is not None:
view.hover_zoom.cancel()
view.engine.pause_timer()
view._save_progress()
penalty = cls.compute_forfeit_penalty(view)
view._modal_overlay = SolitaireModalDialog(
view.ctx,
title_txt=t("sol_forfeit_title"),
body_txt=t("sol_forfeit_desc", penalty),
is_danger=True,
buttons=[
(t("sol_btn_cancel"), "amethyst", view._close_active_modal),
(
t("sol_forfeit_confirm_new"),
"fire",
lambda: cls.execute_forfeit(view, penalty, go_menu=False),
),
(
t("sol_forfeit_confirm_menu"),
"amethyst",
lambda: cls.execute_forfeit(view, penalty, go_menu=True),
),
],
)
view._sync_buttons()
@classmethod
def execute_forfeit(cls, view, penalty: int, go_menu: bool) -> None:
if view.hover_zoom is not None:
view.hover_zoom.cancel()
pid = view.ctx.profile["id"]
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0
view._game_concluded = True
view.engine.pause_timer()
dur = view.engine.get_elapsed_seconds()
Database.delete_game_state(pid, view.GAME_FOLDER_ID)
Database.record_game_result(
pid, variant_key=view.variant_key, won=False, duration_sec=dur, points_gained=0
)
updated = Database.adjust_game_points(
pid, view.GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp
)
deducted = max(0, prog["total_points"] - updated["total_points"])
view.topbar.update_level_xp_text()
view.ctx.sounds.play("lose")
if view._modal_overlay is not None:
try:
view._modal_overlay.destroy()
except Exception:
pass
view._modal_overlay = None
view._sync_buttons()
def _after_lose_fx():
view._fx_overlay = None
if not view._canvas_alive():
return
cls._show_defeat_result_modal(view, deducted, dur, prefer_menu=go_menu)
view._fx_overlay = EndgameFxOverlay.play(
view.ctx.root,
view.ctx.assets,
outcome="lose",
on_continue=_after_lose_fx,
target_canvas=view.canvas,
)
view._sync_buttons()
@classmethod
def _show_defeat_result_modal(cls, view, deducted: int, dur: float, prefer_menu: bool) -> None:
lines = [
t(
"sol_win_summary",
view.engine.score,
view.engine.moves,
Database.format_seconds(dur),
t(f"sol_diff_short_{view.difficulty}"),
),
t("sol_loss_xp", deducted),
]
view._modal_overlay = SolitaireModalDialog(
view.ctx,
title_txt=t("sol_forfeit_title"),
body_txt="\n".join(lines),
is_danger=True,
buttons=[
(
t("sol_play_again_btn"),
"amethyst" if prefer_menu else "fire",
lambda: cls._restart_from_modal(view),
),
(
t("bj_popup_to_menu_btn"),
"fire" if prefer_menu else "amethyst",
lambda: cls._leave_to_menu(view, t("sol_loss_xp", deducted), False),
),
],
)
view._sync_buttons()
@classmethod
def handle_victory(cls, view) -> None:
if view.hover_zoom is not None:
view.hover_zoom.cancel()
view._game_concluded = True
view.engine.pause_timer()
pid = view.ctx.profile["id"]
Database.delete_game_state(pid, view.GAME_FOLDER_ID)
dur = view.engine.get_elapsed_seconds()
fast_t, mid_t = view.SPEED_THRESHOLDS_SEC
speed_bonus = 1.25 if dur <= fast_t else (1.12 if dur <= mid_t else 1.0)
prog = Database.get_game_progress(pid, view.GAME_FOLDER_ID)
xp_earned = Progression.calculate_match_xp(
prog["level"], [], "WIN", variant_mult=view._combined_xp_mult * speed_bonus
)
old_lvl, new_lvl = Database.record_game_result(
pid, variant_key=view.variant_key, won=True, duration_sec=dur, points_gained=xp_earned
)
view.topbar.update_level_xp_text()
view.ctx.sounds.play("win")
view._sync_buttons()
def _after_win_fx():
view._fx_overlay = None
if not view._canvas_alive():
return
cls._show_victory_modal(view, xp_earned, old_lvl, new_lvl, dur)
view._fx_overlay = EndgameFxOverlay.play(
view.ctx.root,
view.ctx.assets,
outcome="win",
on_continue=_after_win_fx,
target_canvas=view.canvas,
)
view._sync_buttons()
@classmethod
def _show_victory_modal(cls, view, xp_earned: int, old_lvl: int, new_lvl: int, dur: float) -> None:
lines = [
t(
"sol_win_summary",
view.engine.score,
view.engine.moves,
Database.format_seconds(dur),
t(f"sol_diff_short_{view.difficulty}"),
),
t("bj_popup_xp_earned", xp_earned),
]
if new_lvl > old_lvl:
lines.append(t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)))
view._modal_overlay = SolitaireModalDialog(
view.ctx,
title_txt=t("sol_win_title"),
body_txt="\n".join(lines),
buttons=[
(
t("sol_play_again_btn"),
"fire",
lambda: cls._restart_from_modal(view),
),
(
t("bj_popup_to_menu_btn"),
"amethyst",
lambda: cls._leave_to_menu(view),
),
],
)
view._sync_buttons()

View File

@ -0,0 +1,243 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_session_guard.py
from __future__ import annotations
import tkinter as tk
from games.solitaire.base.solitaire_canvas_input import SolitaireCanvasInput
from models.database import Database
from resources.code_res.i18n import t
class SolitaireSessionGuard(SolitaireCanvasInput):
"""
Verwaltet für alle Solitaire-Tische Fokus-Pause, 500ms-Uhr-Tick,
Savegame-Checkpoints, Root-Keybindings, Sprachwechsel und sauberes Timer-Cleanup.
"""
CHECKPOINT_TICKS: int = 30
def _is_ui_locked(self) -> bool:
return (
self.engine.won
or self._game_concluded
or self._auto_running
or (self._modal_overlay is not None)
or (self._fx_overlay is not None)
)
def _canvas_alive(self) -> bool:
if not self._alive:
return False
try:
return bool(self.canvas.winfo_exists())
except Exception:
return False
def _can_show_hover_zoom(self) -> bool:
return (
self._canvas_alive()
and not self._is_ui_locked()
and not self._dragging
and self._press_info is None
and self._window_active
and (self.animator is None or not self.animator.is_active)
)
def _play_table_music(self):
for method_name in ("play_ingame_music", "play_table_music"):
fn = getattr(self.ctx.sounds, method_name, None)
if callable(fn):
fn()
return
def _bind_root(self, seq: str, callback):
if seq and seq.startswith("<") and seq.endswith(">"):
try:
func_id = self.ctx.root.bind(seq, callback, add="+")
if func_id:
self._bind_ids.append((seq, func_id))
except tk.TclError:
pass
def _on_canvas_destroy(self, event=None):
if event is not None and event.widget is not self.canvas:
return
if not self._alive:
return
try:
self.engine.pause_timer()
if not self._game_concluded:
self._save_progress()
except Exception:
pass
self._cleanup_timers()
def _cleanup_timers(self):
self._alive = False
self.engine.pause_timer()
if self._fx_overlay is not None:
self._fx_overlay.cancel()
self._fx_overlay = None
if self.hover_zoom is not None:
self.hover_zoom.cancel()
if self.animator is not None:
self.animator.cancel()
for job in (
self._tick_job,
self._focus_job,
self._hint_job,
self._auto_job,
self._resize_job,
):
if job is not None:
try:
self.ctx.root.after_cancel(job)
except Exception:
pass
self._tick_job = self._focus_job = self._hint_job = None
self._auto_job = self._resize_job = None
for seq, func_id in self._bind_ids:
try:
self.ctx.root.unbind(seq, func_id)
except Exception:
pass
self._bind_ids.clear()
def _schedule_focus_check(self, _event=None):
if not self._canvas_alive():
return
if self._focus_job is not None:
try:
self.ctx.root.after_cancel(self._focus_job)
except Exception:
pass
try:
self._focus_job = self.ctx.root.after(60, self._check_window_focus)
except Exception:
self._focus_job = None
def _check_window_focus(self):
self._focus_job = None
if not self._canvas_alive():
return
try:
is_iconic = self.ctx.root.state() == "iconic"
has_focus = self.ctx.root.focus_displayof() is not None and not is_iconic
except Exception:
return
should_run = (
has_focus
and (self._modal_overlay is None)
and (self._fx_overlay is None)
and (not self._game_concluded)
and (not self.engine.won)
)
prev_paused = self.engine.is_timer_paused
self._window_active = has_focus
if should_run:
self.engine.resume_timer()
elif not prev_paused:
self.engine.pause_timer()
self._save_progress()
if prev_paused != self.engine.is_timer_paused:
self._update_hud_text()
if (
self.animator is None or not self.animator.is_active
) and self._fx_overlay is None:
self.redraw()
def _close_active_modal(self):
if self._modal_overlay is not None:
try:
self._modal_overlay.destroy()
except Exception:
pass
self._modal_overlay = None
self._check_window_focus()
self._sync_buttons()
def _refresh_lang(self):
if self.animator:
self.animator.flush()
self.engine.pause_timer()
self._save_progress()
state_json = self.engine.to_json()
self._cleanup_timers()
type(self)(
self.ctx,
variant_key=self.variant_key,
difficulty=self.difficulty,
on_back_to_menu=self.on_back_to_menu,
resume_state_json=state_json,
)
def _save_progress(self):
if self._game_concluded:
return
pid = self.ctx.profile["id"]
if self.engine.won:
Database.delete_game_state(pid, self.GAME_FOLDER_ID)
return
Database.save_game_state(
pid, self.GAME_FOLDER_ID, self.variant_key, self.engine.to_json()
)
def _start_clock(self):
if not self._canvas_alive():
return
self._check_window_focus()
self._update_hud_text()
if (
self.engine.has_timer_started
and not self.engine.is_timer_paused
and not self.engine.won
and not self._game_concluded
):
self._checkpoint_ticks += 1
if self._checkpoint_ticks >= self.CHECKPOINT_TICKS:
self._checkpoint_ticks = 0
self._save_progress()
try:
self._tick_job = self.ctx.root.after(500, self._start_clock)
except Exception:
self._tick_job = None
def _extra_hud_suffix(self) -> str:
return ""
def _update_hud_text(self):
if not self._alive:
return
try:
elapsed_str = Database.format_seconds(self.engine.get_elapsed_seconds())
paused_tag = (
t("sol_hud_paused_tag")
if (
self.engine.is_timer_paused
and not self.engine.won
and not self._game_concluded
)
else ""
)
diff_label = t(f"sol_diff_short_{self.difficulty}")
new_hud = (
t(
"sol_hud_stats",
self.engine.score,
self.engine.moves,
elapsed_str,
paused_tag,
diff_label,
)
+ self._extra_hud_suffix()
)
if self.hud_var.get() != new_hud:
self.hud_var.set(new_hud)
except Exception:
pass

View File

@ -0,0 +1,387 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_table_controller.py
from __future__ import annotations
import tkinter as tk
from games.solitaire.base.card_animator import CardFlightAnimator
from games.solitaire.base.card_hover_zoom import CardHoverZoom
from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar
from games.solitaire.base.solitaire_core import SolitaireCard
from games.solitaire.base.solitaire_outcome_flow import SolitaireOutcomeFlow
from games.solitaire.base.solitaire_session_guard import SolitaireSessionGuard
from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer
from resources.code_res.game_constants import (
PLAYING_CARD_SIZE,
SOLITAIRE_DIFFICULTIES,
TABLE_BG,
)
from resources.code_res.i18n import t
from view.widgets.endgame_fx_overlay import EndgameFxOverlay
from view.widgets.image_button import ImageButton
class SolitaireTableController(SolitaireSessionGuard):
"""
Gemeinsame Tisch-Basisklasse für alle Solitaire-Spiele:
Baut Topbar/BottomBar/Canvas auf und steuert Undo, Hint, Auto-Complete & Neu-Geben.
"""
GAME_FOLDER_ID: str = ""
HAS_AUTOCOMPLETE_BTN: bool = True
AUTO_STEP_DELAY_MS: int = 12
AUTO_FLIGHT_MS: int = 75
SPEED_THRESHOLDS_SEC: tuple[int, int] = (180, 330)
def _init_controller_state(
self, context, variant_key: str, cfg: dict, difficulty: int, on_back_to_menu
):
self.ctx = context
self.variant_key = variant_key
self.cfg = cfg
self.difficulty = max(0, min(3, int(difficulty)))
self.on_back_to_menu = on_back_to_menu
self._alive = True
self._game_concluded = False
self._window_active = True
self._checkpoint_ticks = 0
self._tick_job: str | None = None
self._focus_job: str | None = None
self._hint_job: str | None = None
self._auto_job: str | None = None
self._resize_job: str | None = None
self._bind_ids: list[tuple[str, str]] = []
self._auto_running = False
self.animator: CardFlightAnimator | None = None
self.hover_zoom: CardHoverZoom | None = None
self._fx_overlay: EndgameFxOverlay | None = None
self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res)
self._frame_bot_pad: int = 18
self._canvas_ui_refs: list = []
self._card_aspect: float | None = None
self.card_size: tuple[int, int] = PLAYING_CARD_SIZE
self._press_info: dict | None = None
self._dragging: bool = False
self._drag_last_xy: tuple[int, int] = (0, 0)
self._last_click_ts: float = 0.0
self._last_click_target: tuple | None = None
self._active_hint: dict | None = None
self._modal_overlay: tk.Widget | None = None
self.auto_btn: ImageButton | None = None
def _finish_startup(self, is_resumed: bool):
self._build_ui()
if not is_resumed:
self.ctx.sounds.play("deal")
self._check_window_focus()
self._save_progress()
self._start_clock()
@property
def _combined_xp_mult(self) -> float:
d_mult = SOLITAIRE_DIFFICULTIES.get(
self.difficulty, SOLITAIRE_DIFFICULTIES[1]
)["xp_mult"]
return self.cfg["xp_mult"] * d_mult
def _build_ui(self):
self._play_table_music()
self.ctx.root.clear_window(apply_global_bg=True)
self.ctx.refresh_game_progress()
self.topbar = self.ctx.build_game_topbar(
self.ctx.root,
stats_endpoint=self.GAME_FOLDER_ID,
stats_enabled=True,
on_lang_refresh=self._refresh_lang,
on_stats_back=self._schedule_focus_check,
)
self.hud_var = tk.StringVar(value="")
self.status_var = tk.StringVar(value="")
self.bottom_bar = SolitaireBottomBar(
self.ctx.root, self.ctx, self.hud_var, self.status_var
)
self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 10))
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
self.undo_btn = ImageButton(
self.bottom_bar, t("sol_btn_undo"), btn_norm, btn_purp,
self._on_undo, sound_mgr=self.ctx.sounds, width=136, height=32,
enabled=self.engine.can_undo, style="amethyst",
)
self.undo_all_btn = ImageButton(
self.bottom_bar, t("sol_btn_undo_all"), btn_norm, btn_purp,
self._on_undo_all, sound_mgr=self.ctx.sounds, width=92, height=32,
enabled=self.engine.can_undo_all, style="amethyst",
)
self.hint_btn = ImageButton(
self.bottom_bar, t("sol_btn_hint"), btn_norm, btn_purp,
self._on_hint, sound_mgr=self.ctx.sounds, width=92, height=32,
enabled=not self.engine.won, style="amethyst",
)
main_btns = [self.undo_btn, self.undo_all_btn, self.hint_btn]
if self.HAS_AUTOCOMPLETE_BTN:
self.auto_btn = ImageButton(
self.bottom_bar, t("sol_btn_autocomplete"), btn_fire, btn_fire,
self._start_auto_complete, sound_mgr=self.ctx.sounds,
width=112, height=32, enabled=self.engine.can_auto_complete(),
style="fire",
)
main_btns.append(self.auto_btn)
self.new_btn = ImageButton(
self.bottom_bar,
t("sol_btn_forfeit") if self.engine.moves > 0 else t("sol_btn_new_deal"),
btn_norm, btn_purp, self._on_new_or_forfeit_clicked,
sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst",
)
self.bottom_bar.set_buttons(main_btns, overflow_buttons=[self.new_btn])
self.canvas = tk.Canvas(
self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0
)
self.canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2))
self.animator = CardFlightAnimator(self.ctx.root, self.canvas)
self.hover_zoom = CardHoverZoom(
self.ctx.root,
self.canvas,
self.ctx.assets,
probe_fn=self._hover_card_probe,
can_show_fn=self._can_show_hover_zoom,
)
self.canvas.bind("<Configure>", self._on_canvas_configure)
self.canvas.bind("<Destroy>", self._on_canvas_destroy)
self.canvas.bind("<ButtonPress-1>", self._on_mouse_down)
self.canvas.bind("<B1-Motion>", self._on_mouse_move)
self.canvas.bind("<ButtonRelease-1>", self._on_mouse_up)
self.canvas.bind("<ButtonPress-3>", self._on_right_click)
self._bind_root("<Control-z>", lambda _e: self._run_undo_shortcut(False))
self._bind_root("<Control-Shift-Z>", lambda _e: self._run_undo_shortcut(True))
self._bind_root("<Control-Shift-z>", lambda _e: self._run_undo_shortcut(True))
self._bind_root("<KeyPress-h>", lambda _e: self._on_hint())
self._bind_root("<KeyPress-H>", lambda _e: self._on_hint())
self._bind_root("<FocusIn>", self._schedule_focus_check)
self._bind_root("<FocusOut>", self._schedule_focus_check)
self._update_hud_text()
def _run_undo_shortcut(self, all_moves: bool) -> str:
if self._fx_overlay is not None or self._game_concluded or self._auto_running:
return "break"
can_act = self.engine.can_undo_all if all_moves else self.engine.can_undo
if can_act:
if self._modal_overlay is not None:
self._close_active_modal()
self.ctx.sounds.play("click")
(self._on_undo_all if all_moves else self._on_undo)()
return "break"
def _sync_buttons(self):
if not self._canvas_alive():
return
locked = self._is_ui_locked()
self.undo_btn.set_enabled((not locked) and self.engine.can_undo)
self.undo_all_btn.set_enabled((not locked) and self.engine.can_undo_all)
self.hint_btn.set_enabled(not locked)
if self.auto_btn is not None:
self.auto_btn.set_enabled((not locked) and self.engine.can_auto_complete())
self.new_btn.set_enabled(
(not self._auto_running)
and (self._fx_overlay is None)
and (self._modal_overlay is None)
)
new_lbl = (
t("sol_btn_forfeit")
if (self.engine.moves > 0 and not self.engine.won and not self._game_concluded)
else t("sol_btn_new_deal")
)
prev_w = self.new_btn.pixel_width
self.new_btn.set_text(new_lbl)
if self.new_btn.pixel_width != prev_w:
self.bottom_bar.relayout()
self._update_hud_text()
def _status_after_move(self) -> str:
return ""
def _after_player_move(self):
self.status_var.set(self._status_after_move())
self._checkpoint_ticks = 0
self.redraw()
if self.engine.won:
SolitaireOutcomeFlow.handle_victory(self)
return
self._save_progress()
self._check_deadlock_and_prompt()
def _check_deadlock_and_prompt(self):
if not self._is_ui_locked() and not self.engine.has_any_meaningful_move():
SolitaireOutcomeFlow.show_deadlock_modal(self)
def _on_undo(self):
if self._is_ui_locked():
return
self._clear_hint()
def _done():
self.status_var.set("")
self._checkpoint_ticks = 0
self._save_progress()
self.redraw()
self._run_animated_action(self.engine.undo, duration_ms=105, after_cb=_done)
def _on_undo_all(self):
if self._is_ui_locked():
return
if self.animator:
self.animator.flush()
self._clear_hint()
if self.engine.undo_all():
self.status_var.set("")
self._checkpoint_ticks = 0
self._save_progress()
self.redraw()
def _clear_hint(self):
if self._hint_job is not None:
try:
self.ctx.root.after_cancel(self._hint_job)
except Exception:
pass
self._hint_job = None
self._active_hint = None
def _on_hint(self):
if self._is_ui_locked():
return
if self.animator:
self.animator.flush()
self._clear_hint()
self.engine.start_timer_if_needed()
self._update_hud_text()
hint = self.engine.get_hint()
if not hint:
self.status_var.set(t("sol_no_hint_msg"))
self._check_deadlock_and_prompt()
return
self.status_var.set("")
self._active_hint = hint
self.redraw()
self._hint_job = self.ctx.root.after(1600, self._expire_hint)
def _expire_hint(self):
self._hint_job = None
self._active_hint = None
if self._canvas_alive() and self._fx_overlay is None:
self.redraw()
def _start_auto_complete(self):
if (
not self.HAS_AUTOCOMPLETE_BTN
or not self.engine.can_auto_complete()
or self._is_ui_locked()
):
return
if self.animator:
self.animator.flush()
self._clear_hint()
self.engine.push_undo()
self._save_progress()
self._auto_running = True
self._sync_buttons()
self._step_auto_complete()
def _step_auto_complete(self):
if not self._canvas_alive():
return
def after_step():
if not self._canvas_alive():
return
self.redraw()
if not self.engine.won:
self._auto_job = self.ctx.root.after(
self.AUTO_STEP_DELAY_MS, self._step_auto_complete
)
else:
self._auto_running, self._auto_job = False, None
SolitaireOutcomeFlow.handle_victory(self)
if self._run_animated_action(
lambda: bool(self.engine.auto_complete_step(record_undo=False)),
duration_ms=self.AUTO_FLIGHT_MS,
after_cb=after_step,
):
self.ctx.sounds.play("click")
else:
self._auto_running, self._auto_job = False, None
self.redraw()
if self.engine.won:
SolitaireOutcomeFlow.handle_victory(self)
else:
self._save_progress()
def _start_fresh_deal(self):
self._game_concluded = False
self._reset_engine_for_new_deal()
self._check_window_focus()
self._save_progress()
self.status_var.set("")
self.ctx.sounds.play("deal")
self.redraw()
def _on_new_or_forfeit_clicked(self):
if (
self._auto_running
or self._modal_overlay is not None
or self._fx_overlay is not None
):
return
if self.animator:
self.animator.flush()
if self.engine.won or self._game_concluded or self.engine.moves == 0:
self._start_fresh_deal()
return
SolitaireOutcomeFlow.show_forfeit_modal(self)
def _reset_engine_for_new_deal(self):
raise NotImplementedError
def _recompute_and_draw(self):
raise NotImplementedError
def redraw(self, exclude_source=None, hidden_card_keys=None):
raise NotImplementedError
def _snapshot_card_positions(self) -> dict:
raise NotImplementedError
def _ordered_moved_cards(self, moved_keys: set) -> list[SolitaireCard]:
raise NotImplementedError
def _hover_card_probe(self, x: int, y: int) -> dict | None:
raise NotImplementedError
def _hit_test(self, x: int, y: int) -> dict | None:
raise NotImplementedError
def _handle_click(self, info: dict):
raise NotImplementedError
def _smart_auto_move(self, info: dict):
raise NotImplementedError
def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool:
raise NotImplementedError

View File

@ -2,110 +2,90 @@
# games/solitaire/base/solitaire_theme.py
from __future__ import annotations
import warnings
from pathlib import Path
import tkinter as tk
import warnings
from PIL import Image, ImageChops, ImageDraw, ImageTk
_ICON_PIL_CACHE: dict[Path, Image.Image] = {}
_ICON_TK_CACHE: dict[tuple[Path, int], ImageTk.PhotoImage] = {}
def _extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
def _pick_largest_rgba_frame(candidates, loader_fn) -> Image.Image | None:
best_img: Image.Image | None = None
best_area = -1
for item in candidates:
try:
frame = loader_fn(item).convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
return best_img
def extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
"""Liest den höchstauflösenden RGBA-Frame aus einer .ico-Datei."""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
with Image.open(icon_path) as ico:
best_img = None
best_area = -1
ico_helper = getattr(ico, "ico", None)
best_img = None
if ico_helper is not None and hasattr(ico_helper, "sizes"):
for sz in ico_helper.sizes():
try:
frame = ico_helper.getimage(sz).convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
best_img = _pick_largest_rgba_frame(ico_helper.sizes(), ico_helper.getimage)
if best_img is None:
for idx in range(getattr(ico, "n_frames", 1)):
try:
ico.seek(idx)
frame = ico.copy().convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
best_img = _pick_largest_rgba_frame(
range(getattr(ico, "n_frames", 1)),
lambda idx: (ico.seek(idx), ico.copy())[1],
)
return best_img if best_img is not None else ico.convert("RGBA")
except Exception:
return None
def _scan_badge_axis(primary_len: int, secondary_len: int, probe_pixel_fn) -> list[int]:
min_span = int(secondary_len * 0.38)
valid: list[int] = []
for p in range(primary_len):
cnt = sum(2 for s in range(0, secondary_len, 2) if probe_pixel_fn(p, s))
if cnt >= min_span:
valid.append(p)
return valid
def _auto_crop_and_round_badge(img: Image.Image) -> Image.Image:
"""
Schneidet weiße/transparente Außenränder (und eventuelle Text-Artefakte ganz oben)
ab und stanzt das quadratische App-Badge sauber mit abgerundeten Ecken aus.
"""
w, h = img.size
px = img.load()
def is_badge_pixel(r: int, g: int, b: int, a: int) -> bool:
if a < 40:
return False
# Helle/weiße Schachbrett- oder Hintergrundpixel ignorieren
if r > 228 and g > 228 and b > 228:
return False
return True
return a >= 40 and not (r > 228 and g > 228 and b > 228)
# Suche horizontale & vertikale Ausdehnung des eigentlichen breiten Icon-Blocks
# (Zeilen mit nur wenigen schmalen Buchstaben-Pixeln < 35% Breite werden oben übersprungen!)
min_row_span = int(w * 0.38)
valid_rows: list[int] = []
for y in range(h):
cnt = 0
for x in range(0, w, 2):
if is_badge_pixel(*px[x, y]):
cnt += 2
if cnt >= min_row_span:
valid_rows.append(y)
valid_rows = _scan_badge_axis(h, w, lambda y, x: is_badge_pixel(*px[x, y]))
valid_cols = _scan_badge_axis(w, h, lambda x, y: is_badge_pixel(*px[x, y]))
min_col_span = int(h * 0.38)
valid_cols: list[int] = []
for x in range(w):
cnt = 0
for y in range(0, h, 2):
if is_badge_pixel(*px[x, y]):
cnt += 2
if cnt >= min_col_span:
valid_cols.append(x)
cropped = (
img.crop((valid_cols[0], valid_rows[0], valid_cols[-1] + 1, valid_rows[-1] + 1))
if (valid_rows and valid_cols)
else img
)
if valid_rows and valid_cols:
top, bottom = valid_rows[0], valid_rows[-1] + 1
left, right = valid_cols[0], valid_cols[-1] + 1
cropped = img.crop((left, top, right, bottom))
else:
cropped = img
# Auf sauberes Quadrat bringen & mit 2x Supersampling rund maskieren
side = max(cropped.width, cropped.height)
square = cropped.resize((side, side), Image.Resampling.LANCZOS)
mask_big = Image.new("L", (side * 2, side * 2), 0)
draw = ImageDraw.Draw(mask_big)
radius = int(side * 2 * 0.195)
pad = int(side * 2 * 0.008)
draw.rounded_rectangle(
(pad, pad, side * 2 - 1 - pad, side * 2 - 1 - pad),
radius=radius,
radius=int(side * 2 * 0.195),
fill=255,
)
mask = mask_big.resize((side, side), Image.Resampling.LANCZOS)
r_ch, g_ch, b_ch, a_ch = square.split()
square.putalpha(ImageChops.multiply(a_ch, mask))
square.putalpha(ImageChops.multiply(square.getchannel("A"), mask))
return square
@ -119,24 +99,19 @@ def get_game_icon_photo(res_mgr, game_folder: str, size_px: int = 92) -> ImageTk
return _ICON_TK_CACHE[cache_key]
if icon_path not in _ICON_PIL_CACHE:
raw = _extract_best_ico_pil(icon_path)
raw = extract_best_ico_pil(icon_path)
if raw is None:
return None
_ICON_PIL_CACHE[icon_path] = _auto_crop_and_round_badge(raw)
resized = _ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(resized)
photo = ImageTk.PhotoImage(_ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS))
_ICON_TK_CACHE[cache_key] = photo
return photo
class SolitaireTableBgRenderer:
"""
Zeichnet und cached resources/images/general_table.jpg passgenau auf das Solitaire-Canvas
und liefert die Rahmen-Abstände, damit alle Stapel sauber innerhalb des Holzrahmens sitzen.
"""
"""Zeichnet den nahtlosen Fenster-Hintergrundausschnitt auf das Tisch-Canvas."""
# Prozentuale Rahmenstärke von general_table.jpg (Steinmauer + Kerzen + Holzrahmen)
FRAME_X_RATIO = 0.075
FRAME_TOP_RATIO = 0.095
FRAME_BOT_RATIO = 0.090
@ -145,8 +120,7 @@ class SolitaireTableBgRenderer:
self.res_mgr = res_mgr
self._raw_pil: Image.Image | None = None
self._loaded = False
self._cached_size: tuple[int, int] = (0, 0)
self._cached_photo: ImageTk.PhotoImage | None = None
self._slice_photo: ImageTk.PhotoImage | None = None
def _ensure_pil(self) -> Image.Image | None:
if not self._loaded:
@ -161,13 +135,13 @@ class SolitaireTableBgRenderer:
return self._raw_pil
def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]:
"""Gibt (inset_x, inset_top, inset_bottom) passend zum Zierrahmen zurück."""
if self._ensure_pil() is None:
return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16
ix = max(36, int(canvas_w * self.FRAME_X_RATIO))
itop = max(28, int(canvas_h * self.FRAME_TOP_RATIO))
ibot = max(26, int(canvas_h * self.FRAME_BOT_RATIO))
return ix, itop, ibot
return (
max(36, int(canvas_w * self.FRAME_X_RATIO)),
max(28, int(canvas_h * self.FRAME_TOP_RATIO)),
max(26, int(canvas_h * self.FRAME_BOT_RATIO)),
)
def draw_on_canvas(self, canvas: tk.Canvas, canvas_w: int, canvas_h: int):
if canvas_w < 80 or canvas_h < 80:
@ -177,8 +151,7 @@ class SolitaireTableBgRenderer:
if assets is None:
return
rw = max(canvas_w, root.winfo_width())
rh = max(canvas_h, root.winfo_height())
rw, rh = max(canvas_w, root.winfo_width()), max(canvas_h, root.winfo_height())
ox = max(0, min(rw - canvas_w, canvas.winfo_rootx() - root.winfo_rootx()))
oy = max(0, min(rh - canvas_h, canvas.winfo_rooty() - root.winfo_rooty()))
new_photo = assets.get_bg_patch_photo(rw, rh, ox, oy, canvas_w, canvas_h)

View File

@ -2,393 +2,38 @@
# games/solitaire/freecell/views/freecell_menu_view.py
from __future__ import annotations
import json
import tkinter as tk
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
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,
FREECELL_VARIANTS,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
from resources.code_res.game_constants import FREECELL_VARIANTS
GAME_FOLDER_ID = "solitaire/freecell"
GAME_TITLE_KEY = "game_title_freecell"
DEFAULT_VARIANT_KEY = "freecell_std"
class FreeCellMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
class FreeCellMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "fc_menu_topbar"
SUBTITLE_KEY = "fc_menu_subtitle"
CONTROLS_HINT_KEY = "fc_controls_hint"
def _clear_modal(self):
if self._return_bind_id is not None:
try:
self.ctx.root.unbind("<Return>", self._return_bind_id)
except Exception:
pass
self._return_bind_id = None
if self._modal_overlay is not None:
try:
self._modal_overlay.destroy()
except Exception:
pass
self._modal_overlay = None
DIFF_SETTING_PREFIX = "freecell_diff"
DEFAULT_VARIANT_KEY = "freecell_std"
REQUIRED_BOARD_KEYS = ("tableau", "freecells")
def show(
self,
status_msg: str = "",
status_is_ok: bool = False,
ask_resume_popup: bool = False,
):
self._clear_modal()
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self.ctx.refresh_game_progress()
MODE_LABEL_KEY = "fc_variant_info_lbl"
DESC_KEY_PREFIX = "fc_desc_"
diff_setting_key = f"freecell_diff_{pid}"
saved_diff_str = Database.load_setting(diff_setting_key, "1")
selected_diff = (
int(saved_diff_str)
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
else 1
)
def _variants_dict(self) -> dict[str, dict]:
return FREECELL_VARIANTS
self.ctx.build_game_topbar(
self.ctx.root,
t("fc_menu_topbar"),
on_game_menu=None,
on_stats_back=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
stats_enabled=True,
extra_right_text="",
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
)
cv = MenuBodyCanvas(self.ctx)
btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple
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=180,
height=38,
style="fire",
)
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(
DEFAULT_VARIANT_KEY, diff_map.get(diff_var.get(), 1), saved, saved_meta
),
sound_mgr=self.ctx.sounds,
width=205,
height=40,
style="fire",
)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
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(
"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_SIZE_BODY,
FONT_COLOR_BODY_DEFAULT,
max_width=box_w - resume_btn.pixel_width - 70,
align="left",
)
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
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
setup_h = 208
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: 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(180, box_w - 275 - 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")
# Zeile 2: Schwierigkeitsgrad
r2_y = cur_y + 104
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 - 265)
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("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")
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()))
if ask_resume_popup and saved and saved_meta is not None:
self._show_resume_prompt_modal(saved, saved_meta)
@staticmethod
def _parse_saved_meta(saved: dict | None) -> dict | None:
if not saved:
return None
try:
data = json.loads(saved["state_json"])
if data.get("won"):
return None
board = data.get("board", {})
if not board or "tableau" not in board or "freecells" not in board:
return None
return {
"moves": max(0, int(data.get("moves", 0))),
"score": int(data.get("score", 0)),
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
}
except Exception:
return None
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
self._clear_modal()
def resume_now(_event=None):
self._clear_modal()
self._resume_saved(saved, saved_meta["difficulty"])
try:
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
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 = SolitaireModalDialog(
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),
],
)
def _resume_saved(self, saved: dict, difficulty: int):
self._clear_modal()
FreeCellTableView(
self.ctx,
variant_key=saved["variant_key"],
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=saved["state_json"],
)
def _on_start_clicked(
self,
variant_key: str,
difficulty: int,
saved: dict | None,
saved_meta: dict | None,
):
if self._modal_overlay is not None:
return
if saved and saved_meta and saved_meta["moves"] > 0:
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
return
self._launch_fresh_game(variant_key, difficulty)
def _show_overwrite_confirm_modal(
self,
new_variant_key: str,
new_difficulty: int,
saved: dict,
saved_meta: dict,
):
pid = self.ctx.profile["id"]
old_v = saved["variant_key"]
old_diff = saved_meta["difficulty"]
prog = Database.get_game_progress(pid, GAME_FOLDER_ID)
v_mult = FREECELL_VARIANTS.get(old_v, {"xp_mult": 1.15})["xp_mult"]
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
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)))
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
)
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 = SolitaireModalDialog(
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),
],
)
def _launch_fresh_game(self, variant_key: str, difficulty: int):
pid = self.ctx.profile["id"]
Database.save_setting(f"freecell_diff_{pid}", str(difficulty))
Database.delete_game_state(pid, GAME_FOLDER_ID)
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
FreeCellTableView(
self.ctx,
variant_key=variant_key,
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=resume_state_json,
)

File diff suppressed because it is too large Load Diff

View File

@ -7,17 +7,13 @@ from games.solitaire.base.solitaire_core import (
SolitaireCard,
is_alternating_descending,
)
from games.solitaire.klondike.models.klondike_hint_analyzer import KlondikeHintAnalyzer
from games.solitaire.klondike.models.klondike_solver import generate_solvable_klondike_deck
from resources.code_res.game_constants import SOLITAIRE_DIFFICULTIES, SUITS
class KlondikeEngine(SolitaireBaseEngine):
"""
Klondike-Spiellogik (Draw 1 & Draw 3) mit:
- garantierter Lösbarkeit
- 3-Zyklen-Stagnationssperre auf dem Stock (rotes X, per Undo auflösbar)
- automatischer Sackgassen-Erkennung (has_any_meaningful_move)
"""
"""Klondike-Spiellogik (Draw 1 & Draw 3) mit garantierter Lösbarkeit & Stagnationssperre."""
NUM_TABLEAU = 7
NUM_FOUNDATIONS = 4
@ -37,8 +33,6 @@ class KlondikeEngine(SolitaireBaseEngine):
self.seed: int | None = seed
self.redeals_used: int = 0
self.redeal_limit: int | None = None
# Zählt volle Stock-Durchläufe ohne jeglichen Spielfortschritt
self.stagnant_cycles: int = 0
self.progress_in_current_cycle: bool = False
@ -96,7 +90,6 @@ class KlondikeEngine(SolitaireBaseEngine):
self.capture_initial_state()
def _mark_board_progress(self):
"""Sobald eine Karte auf dem Spielfeld bewegt wird, wird der Stagnationszähler zurückgesetzt."""
self.stagnant_cycles = 0
self.progress_in_current_cycle = True
@ -117,20 +110,16 @@ class KlondikeEngine(SolitaireBaseEngine):
return True
return False
# --- Regel-Prüfungen ---
def foundation_index_for_suit(self, suit: str) -> int:
return SUITS.index(suit)
def can_move_to_foundation(self, card: SolitaireCard, found_idx: int) -> bool:
if not card.face_up or not (0 <= found_idx < self.NUM_FOUNDATIONS):
return False
target_suit = SUITS[found_idx]
if card.suit != target_suit:
if card.suit != SUITS[found_idx]:
return False
pile = self.foundations[found_idx]
if not pile:
return card.value == 1
return card.value == pile[-1].value + 1
return (card.value == 1) if not pile else (card.value == pile[-1].value + 1)
def can_move_to_tableau(self, moving_cards: list[SolitaireCard], dst_col: int) -> bool:
if not moving_cards or not (0 <= dst_col < self.NUM_TABLEAU):
@ -144,9 +133,7 @@ class KlondikeEngine(SolitaireBaseEngine):
top = dst[-1]
return top.face_up and (top.is_red != head.is_red) and (top.value == head.value + 1)
# --- Stock, Redeal-Limit & 3-Zyklen-Stagnationssperre ---
def is_stagnation_locked(self) -> bool:
"""True, wenn 3 volle Durchläufe des Decks ohne jede Änderung erfolgt sind."""
return (
not self.stock
and bool(self.waste)
@ -162,15 +149,10 @@ class KlondikeEngine(SolitaireBaseEngine):
)
def is_stock_locked(self) -> bool:
"""True, wenn der Stapel nicht mehr neu umgedreht werden darf (Rotes X)."""
return self.is_stagnation_locked() or self.is_redeal_exhausted()
def can_draw_or_recycle(self) -> bool:
if self.stock:
return True
if self.waste and not self.is_stock_locked():
return True
return False
return bool(self.stock) or (bool(self.waste) and not self.is_stock_locked())
def draw_from_stock(self) -> bool:
if self.won:
@ -183,9 +165,6 @@ class KlondikeEngine(SolitaireBaseEngine):
card.face_up = True
self.waste.append(card)
self.moves += 1
# Wenn gerade die letzte Karte eines kompletten ereignislosen Durchlaufs aufgedeckt wurde,
# zählt dieser Zyklus als abgeschlossen -> beim 3. Mal erscheint sofort das rote X!
if not self.stock and not self.progress_in_current_cycle:
self.stagnant_cycles += 1
return True
@ -204,10 +183,8 @@ class KlondikeEngine(SolitaireBaseEngine):
elif self.redeals_used > 3:
self._add_score(self.SCORE_RECYCLE_DRAW3)
return True
return False
# --- Aktionen: Kartenverschiebungen ---
def move_waste_to_foundation(self, found_idx: int | None = None) -> bool:
if self.won or not self.waste:
return False
@ -283,21 +260,17 @@ class KlondikeEngine(SolitaireBaseEngine):
if self.won or not (0 <= found_idx < self.NUM_FOUNDATIONS):
return False
f_pile = self.foundations[found_idx]
if not f_pile:
return False
card = f_pile[-1]
if not self.can_move_to_tableau([card], dst_col):
if not f_pile or not self.can_move_to_tableau([f_pile[-1]], dst_col):
return False
self.push_undo()
f_pile.pop()
card = f_pile.pop()
self.tableau[dst_col].append(card)
self.moves += 1
self._mark_board_progress()
self._add_score(self.SCORE_FOUNDATION_TO_TABLEAU)
return True
# --- Komfort: Auto-Complete, Hinweise & Sackgassen-Prüfung ---
def can_auto_complete(self) -> bool:
if self.won or self.stock or self.waste:
return False
@ -306,7 +279,6 @@ class KlondikeEngine(SolitaireBaseEngine):
def auto_complete_step(self, record_undo: bool = False) -> tuple[int, int] | None:
if self.won:
return None
candidates: list[tuple[int, int, int]] = []
for col_idx, col in enumerate(self.tableau):
if not col:
@ -315,7 +287,6 @@ class KlondikeEngine(SolitaireBaseEngine):
f_idx = self.foundation_index_for_suit(card.suit)
if self.can_move_to_foundation(card, f_idx):
candidates.append((card.value, col_idx, f_idx))
if not candidates:
return None
@ -332,166 +303,12 @@ class KlondikeEngine(SolitaireBaseEngine):
self._check_victory()
return best_col, best_f_idx
def _card_can_play_anywhere(self, card: SolitaireCard) -> bool:
probe = SolitaireCard(suit=card.suit, rank=card.rank, face_up=True, deck_id=card.deck_id)
if self.can_move_to_foundation(probe, self.foundation_index_for_suit(probe.suit)):
return True
return any(self.can_move_to_tableau([probe], dst_col) for dst_col in range(self.NUM_TABLEAU))
def _reachable_stock_waste_cards(self) -> list[SolitaireCard]:
"""Ermittelt alle Karten, die durch Ziehen/Recyclen aktuell noch oben auf dem Waste landen können."""
reachable: list[SolitaireCard] = []
if self.waste:
reachable.append(self.waste[-1])
# 1. Restlichen aktuellen Stock in draw_count-Schritten simulieren
if self.stock:
sim_stk = list(self.stock)
while sim_stk:
step = min(self.draw_count, len(sim_stk))
top_drawn = None
for _ in range(step):
top_drawn = sim_stk.pop()
if top_drawn is not None:
reachable.append(top_drawn)
# 2. Falls danach noch ein Recycle erlaubt wäre, auch den nächsten Zyklus prüfen
will_lock_after_stock = (
bool(self.stock)
and (not self.progress_in_current_cycle)
and (self.stagnant_cycles + 1 >= self.MAX_STAGNANT_CYCLES)
)
can_recycle_next = (
not self.is_stock_locked()
and not will_lock_after_stock
and (self.redeal_limit is None or self.redeals_used < self.redeal_limit)
)
if can_recycle_next and (self.stock or self.waste):
full_cycle = list(self.waste) + list(reversed(self.stock))
sim_stk2 = list(reversed(full_cycle))
while sim_stk2:
step = min(self.draw_count, len(sim_stk2))
top_drawn = None
for _ in range(step):
top_drawn = sim_stk2.pop()
if top_drawn is not None:
reachable.append(top_drawn)
return reachable
def has_any_meaningful_move(self) -> bool:
"""
Prüft, ob noch irgendein sinnvoller Zug existiert.
Reine Endlos-Züge (König von leerer Spalte zu leerer Spalte, grundloses Hin-und-Her-Schieben
von Teil-Runs ohne Freilegung einer verdeckten oder Foundation-fähigen Karte) zählen NICHT.
"""
if self.won:
return True
# 1. Tableau-Spitze -> Foundation
for col_idx, col in enumerate(self.tableau):
if col:
top = col[-1]
if self.can_move_to_foundation(top, self.foundation_index_for_suit(top.suit)):
return True
# 2. Sinnvolle Tableau -> Tableau Züge
for src_col, col in enumerate(self.tableau):
if not col:
continue
first_up = next((i for i, c in enumerate(col) if c.face_up), len(col))
if first_up >= len(col):
continue
# a) Ganzen offenen Stapel bewegen (legt verdeckte Karte frei oder räumt Spalte für anderen König)
whole_run = col[first_up:]
if not (first_up == 0 and whole_run[0].value == 13):
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.can_move_to_tableau(whole_run, dst_col):
# Leert es nur eine Spalte (first_up == 0, Karte != K), ist das immer produktiv
return True
# b) Teil-Run splitten, falls die freigelegte Karte darunter direkt auf die Foundation passt
for split_idx in range(first_up + 1, len(col)):
exposed = col[split_idx - 1]
if self.can_move_to_foundation(exposed, self.foundation_index_for_suit(exposed.suit)):
sub_run = col[split_idx:]
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.can_move_to_tableau(sub_run, dst_col):
return True
# 3. Erreichbare Karten aus Waste / Stock prüfen
for r_card in self._reachable_stock_waste_cards():
if self._card_can_play_anywhere(r_card):
return True
# 4. Falls der Stock noch ungezogene / recyclebare Karten hat, die der Spieler noch selbst aufdecken darf,
# erst dann als Deadlock melden, wenn entweder gar keine spielbare Karte drin steckt ODER das rote X aktiv ist.
# (Schritt 3 hat bereits geprüft, ob im erreichbaren Stock überhaupt noch eine spielbare Karte liegt!)
# 5. Seltener Rettungszug: Karte von Foundation aufs Tableau holen, um damit sofort eine Tableau-Spitze aufzunehmen
for f_idx, f_pile in enumerate(self.foundations):
if not f_pile or f_pile[-1].value <= 2:
continue
f_card = f_pile[-1]
for dst_col in range(self.NUM_TABLEAU):
if not self.can_move_to_tableau([f_card], dst_col):
continue
# Bringt dieser Rückzug einer anderen Tableau-Karte sofort ein neues Ziel?
for other_col, o_pile in enumerate(self.tableau):
if other_col == dst_col or not o_pile:
continue
o_first_up = next((i for i, c in enumerate(o_pile) if c.face_up), len(o_pile))
head = o_pile[o_first_up]
if head.is_red != f_card.is_red and head.value + 1 == f_card.value:
return True
return False
return KlondikeHintAnalyzer.has_any_meaningful_move(self)
def get_hint(self) -> dict | None:
if self.waste:
w_card = self.waste[-1]
f_idx = self.foundation_index_for_suit(w_card.suit)
if self.can_move_to_foundation(w_card, f_idx):
return {"type": "waste_to_foundation", "dst": f_idx}
return KlondikeHintAnalyzer.get_hint(self)
for col_idx, col in enumerate(self.tableau):
if col:
t_card = col[-1]
f_idx = self.foundation_index_for_suit(t_card.suit)
if self.can_move_to_foundation(t_card, f_idx):
return {"type": "tableau_to_foundation", "src_col": col_idx, "dst": f_idx}
for src_col, col in enumerate(self.tableau):
if not col:
continue
first_up_idx = next((i for i, c in enumerate(col) if c.face_up), len(col))
if first_up_idx >= len(col):
continue
moving = col[first_up_idx:]
if first_up_idx == 0 and moving[0].value == 13:
continue
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.can_move_to_tableau(moving, dst_col):
return {
"type": "tableau_to_tableau",
"src_col": src_col,
"card_idx": first_up_idx,
"dst_col": dst_col,
}
if self.waste:
w_card = self.waste[-1]
for dst_col in range(self.NUM_TABLEAU):
if self.can_move_to_tableau([w_card], dst_col):
return {"type": "waste_to_tableau", "dst_col": dst_col}
if self.can_draw_or_recycle():
return {"type": "draw_stock"}
return None
# --- Persistenz ---
def serialize_board(self) -> dict:
return {
"draw_count": self.draw_count,
@ -516,9 +333,5 @@ class KlondikeEngine(SolitaireBaseEngine):
self.progress_in_current_cycle = bool(board.get("progress_in_cycle", 0))
self.stock = [SolitaireCard.from_dict(d) for d in board["stock"]]
self.waste = [SolitaireCard.from_dict(d) for d in board["waste"]]
self.foundations = [
[SolitaireCard.from_dict(d) for d in f] for f in board["foundations"]
]
self.tableau = [
[SolitaireCard.from_dict(d) for d in col] for col in board["tableau"]
]
self.foundations = [[SolitaireCard.from_dict(d) for d in f] for f in board["foundations"]]
self.tableau = [[SolitaireCard.from_dict(d) for d in col] for col in board["tableau"]]

View File

@ -0,0 +1,152 @@
# -*- coding: utf-8 -*-
# games/solitaire/klondike/models/klondike_hint_analyzer.py
from __future__ import annotations
from games.solitaire.base.solitaire_core import SolitaireCard
class KlondikeHintAnalyzer:
"""Kapselt Erreichbarkeits-Analyse, Deadlock-Prüfung und Zug-Tipps für KlondikeEngine."""
@staticmethod
def card_can_play_anywhere(eng, card: SolitaireCard) -> bool:
probe = SolitaireCard(suit=card.suit, rank=card.rank, face_up=True, deck_id=card.deck_id)
if eng.can_move_to_foundation(probe, eng.foundation_index_for_suit(probe.suit)):
return True
return any(eng.can_move_to_tableau([probe], dst_col) for dst_col in range(eng.NUM_TABLEAU))
@staticmethod
def reachable_stock_waste_cards(eng) -> list[SolitaireCard]:
reachable: list[SolitaireCard] = []
if eng.waste:
reachable.append(eng.waste[-1])
if eng.stock:
sim_stk = list(eng.stock)
while sim_stk:
step = min(eng.draw_count, len(sim_stk))
top_drawn = None
for _ in range(step):
top_drawn = sim_stk.pop()
if top_drawn is not None:
reachable.append(top_drawn)
will_lock_after_stock = (
bool(eng.stock)
and (not eng.progress_in_current_cycle)
and (eng.stagnant_cycles + 1 >= eng.MAX_STAGNANT_CYCLES)
)
can_recycle_next = (
not eng.is_stock_locked()
and not will_lock_after_stock
and (eng.redeal_limit is None or eng.redeals_used < eng.redeal_limit)
)
if can_recycle_next and (eng.stock or eng.waste):
full_cycle = list(eng.waste) + list(reversed(eng.stock))
sim_stk2 = list(reversed(full_cycle))
while sim_stk2:
step = min(eng.draw_count, len(sim_stk2))
top_drawn = None
for _ in range(step):
top_drawn = sim_stk2.pop()
if top_drawn is not None:
reachable.append(top_drawn)
return reachable
@classmethod
def has_any_meaningful_move(cls, eng) -> bool:
if eng.won:
return True
for col in eng.tableau:
if col:
top = col[-1]
if eng.can_move_to_foundation(top, eng.foundation_index_for_suit(top.suit)):
return True
for src_col, col in enumerate(eng.tableau):
if not col:
continue
first_up = next((i for i, c in enumerate(col) if c.face_up), len(col))
if first_up >= len(col):
continue
whole_run = col[first_up:]
if not (first_up == 0 and whole_run[0].value == 13):
for dst_col in range(eng.NUM_TABLEAU):
if src_col != dst_col and eng.can_move_to_tableau(whole_run, dst_col):
return True
for split_idx in range(first_up + 1, len(col)):
exposed = col[split_idx - 1]
if eng.can_move_to_foundation(exposed, eng.foundation_index_for_suit(exposed.suit)):
sub_run = col[split_idx:]
for dst_col in range(eng.NUM_TABLEAU):
if src_col != dst_col and eng.can_move_to_tableau(sub_run, dst_col):
return True
for r_card in cls.reachable_stock_waste_cards(eng):
if cls.card_can_play_anywhere(eng, r_card):
return True
for f_pile in eng.foundations:
if not f_pile or f_pile[-1].value <= 2:
continue
f_card = f_pile[-1]
for dst_col in range(eng.NUM_TABLEAU):
if not eng.can_move_to_tableau([f_card], dst_col):
continue
for other_col, o_pile in enumerate(eng.tableau):
if other_col == dst_col or not o_pile:
continue
o_first_up = next((i for i, c in enumerate(o_pile) if c.face_up), len(o_pile))
head = o_pile[o_first_up]
if head.is_red != f_card.is_red and head.value + 1 == f_card.value:
return True
return False
@staticmethod
def get_hint(eng) -> dict | None:
if eng.waste:
w_card = eng.waste[-1]
f_idx = eng.foundation_index_for_suit(w_card.suit)
if eng.can_move_to_foundation(w_card, f_idx):
return {"type": "waste_to_foundation", "dst": f_idx}
for col_idx, col in enumerate(eng.tableau):
if col:
t_card = col[-1]
f_idx = eng.foundation_index_for_suit(t_card.suit)
if eng.can_move_to_foundation(t_card, f_idx):
return {"type": "tableau_to_foundation", "src_col": col_idx, "dst": f_idx}
for src_col, col in enumerate(eng.tableau):
if not col:
continue
first_up_idx = next((i for i, c in enumerate(col) if c.face_up), len(col))
if first_up_idx >= len(col):
continue
moving = col[first_up_idx:]
if first_up_idx == 0 and moving[0].value == 13:
continue
for dst_col in range(eng.NUM_TABLEAU):
if src_col != dst_col and eng.can_move_to_tableau(moving, dst_col):
return {
"type": "tableau_to_tableau",
"src_col": src_col,
"card_idx": first_up_idx,
"dst_col": dst_col,
}
if eng.waste:
w_card = eng.waste[-1]
for dst_col in range(eng.NUM_TABLEAU):
if eng.can_move_to_tableau([w_card], dst_col):
return {"type": "waste_to_tableau", "dst_col": dst_col}
if eng.can_draw_or_recycle():
return {"type": "draw_stock"}
return None

View File

@ -2,425 +2,44 @@
# games/solitaire/klondike/views/klondike_menu_view.py
from __future__ import annotations
import json
import tkinter as tk
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
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,
KLONDIKE_VARIANTS,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
from resources.code_res.game_constants import KLONDIKE_VARIANTS
GAME_FOLDER_ID = "solitaire/klondike"
GAME_TITLE_KEY = "game_title_klondike"
class KlondikeMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
class KlondikeMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "kl_menu_topbar"
SUBTITLE_KEY = "sol_menu_subtitle"
CONTROLS_HINT_KEY = "kl_controls_hint"
def _clear_modal(self):
if self._return_bind_id is not None:
try:
self.ctx.root.unbind("<Return>", self._return_bind_id)
except Exception:
pass
self._return_bind_id = None
if self._modal_overlay is not None:
try:
self._modal_overlay.destroy()
except Exception:
pass
self._modal_overlay = None
DIFF_SETTING_PREFIX = "klondike_diff"
VARIANT_SETTING_PREFIX = "klondike_variant"
DEFAULT_VARIANT_KEY = "klondike_1"
REQUIRED_BOARD_KEYS = ("tableau",)
def show(
self,
status_msg: str = "",
status_is_ok: bool = False,
ask_resume_popup: bool = False,
):
self._clear_modal()
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self.ctx.refresh_game_progress()
MODE_LABEL_KEY = "sol_draw_mode_lbl"
VARIANT_TOGGLES = (
("klondike_1", "kl_draw_toggle_1"),
("klondike_3", "kl_draw_toggle_3"),
)
TOGGLE_BTN_WIDTH = 162
DESC_KEY_PREFIX = "kl_desc_"
diff_setting_key = f"klondike_diff_{pid}"
draw_setting_key = f"klondike_variant_{pid}"
def _variants_dict(self) -> dict[str, dict]:
return KLONDIKE_VARIANTS
saved_diff_str = Database.load_setting(diff_setting_key, "1")
selected_diff = (
int(saved_diff_str)
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
else 1
)
selected_variant = Database.load_setting(draw_setting_key, "klondike_1")
if selected_variant not in KLONDIKE_VARIANTS:
selected_variant = "klondike_1"
self.ctx.build_game_topbar(
self.ctx.root,
t("kl_menu_topbar"),
on_game_menu=None,
on_stats_back=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
stats_enabled=True,
extra_right_text="",
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
)
cv = MenuBodyCanvas(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
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=180,
height=38,
style="fire",
)
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)
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=162,
height=36,
style="fire" if is_sel else "amethyst",
)
draw_btns.append(b)
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=205,
height=40,
style="fire",
)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
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(
"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_SIZE_BODY,
FONT_COLOR_BODY_DEFAULT,
max_width=box_w - resume_btn.pixel_width - 70,
align="left",
)
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
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
setup_h = 238
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 + 220
# Zeile 1: Zieh-Modus Toggles + Beschreibung sauber darunter (kein Anstoßen an den rechten Rahmen!)
r1_y = cur_y + 44
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")
bx_cur = val_col
for db in draw_btns:
cv.create_window(bx_cur, r1_y, window=db, anchor="w", tags="fg")
bx_cur += db.pixel_width + 10
dsc_txt = t(f"kl_desc_{selected_variant}").replace("•", "-")
dsc_ph = self.ctx.assets.get_goth_text_photo(
dsc_txt,
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")
# 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")
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()))
if ask_resume_popup and saved and saved_meta is not None:
self._show_resume_prompt_modal(saved, saved_meta)
@staticmethod
def _parse_saved_meta(saved: dict | None) -> dict | None:
if not saved:
return None
try:
data = json.loads(saved["state_json"])
if data.get("won"):
return None
board = data.get("board", {})
if not board or "tableau" not in board:
return None
return {
"moves": max(0, int(data.get("moves", 0))),
"score": int(data.get("score", 0)),
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
}
except Exception:
return None
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
self._clear_modal()
def resume_now(_event=None):
self._clear_modal()
self._resume_saved(saved, saved_meta["difficulty"])
try:
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
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 = SolitaireModalDialog(
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),
],
)
def _resume_saved(self, saved: dict, difficulty: int):
self._clear_modal()
KlondikeTableView(
self.ctx,
variant_key=saved["variant_key"],
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=saved["state_json"],
)
def _on_start_clicked(
self,
variant_key: str,
difficulty: int,
saved: dict | None,
saved_meta: dict | None,
):
if self._modal_overlay is not None:
return
if saved and saved_meta and saved_meta["moves"] > 0:
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
return
self._launch_fresh_game(variant_key, difficulty)
def _show_overwrite_confirm_modal(
self,
new_variant_key: str,
new_difficulty: int,
saved: dict,
saved_meta: dict,
):
pid = self.ctx.profile["id"]
old_v = saved["variant_key"]
old_diff = saved_meta["difficulty"]
prog = Database.get_game_progress(pid, GAME_FOLDER_ID)
v_mult = KLONDIKE_VARIANTS.get(old_v, {"xp_mult": 1.0})["xp_mult"]
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
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)))
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
)
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 = SolitaireModalDialog(
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),
],
)
def _launch_fresh_game(self, variant_key: str, difficulty: int):
pid = self.ctx.profile["id"]
Database.save_setting(f"klondike_diff_{pid}", str(difficulty))
Database.save_setting(f"klondike_variant_{pid}", variant_key)
Database.delete_game_state(pid, GAME_FOLDER_ID)
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
KlondikeTableView(
self.ctx,
variant_key=variant_key,
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=resume_state_json,
)

File diff suppressed because it is too large Load Diff

View File

@ -2,426 +2,46 @@
# games/solitaire/spider_solitaire/views/spider_menu_view.py
from __future__ import annotations
import json
import tkinter as tk
from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
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,
SOLITAIRE_DIFFICULTIES,
SOLO_FORFEIT_XP_RATIO,
SPIDER_VARIANTS,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.menu_body_canvas import MenuBodyCanvas
from resources.code_res.game_constants import SPIDER_VARIANTS
GAME_FOLDER_ID = "solitaire/spider_solitaire"
GAME_TITLE_KEY = "game_title_spider_solitaire"
class SpiderMenuView:
def __init__(self, context):
self.ctx = context
self._modal_overlay: tk.Widget | None = None
self._return_bind_id: str | None = None
self._photo_refs: list = []
class SpiderMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "sp_menu_topbar"
SUBTITLE_KEY = "sp_menu_subtitle"
CONTROLS_HINT_KEY = "sp_controls_hint"
def _clear_modal(self):
if self._return_bind_id is not None:
try:
self.ctx.root.unbind("<Return>", self._return_bind_id)
except Exception:
pass
self._return_bind_id = None
if self._modal_overlay is not None:
try:
self._modal_overlay.destroy()
except Exception:
pass
self._modal_overlay = None
DIFF_SETTING_PREFIX = "spider_diff"
VARIANT_SETTING_PREFIX = "spider_variant"
DEFAULT_VARIANT_KEY = "spider_1suit"
DEFAULT_SCORE = 500
REQUIRED_BOARD_KEYS = ("tableau", "stock_deals")
def show(
self,
status_msg: str = "",
status_is_ok: bool = False,
ask_resume_popup: bool = False,
):
self._clear_modal()
pid = self.ctx.profile["id"]
self.ctx.sounds.play_menu_music()
self.ctx.root.clear_window(apply_global_bg=True)
self._photo_refs.clear()
self.ctx.refresh_game_progress()
MODE_LABEL_KEY = "sp_suit_mode_lbl"
VARIANT_TOGGLES = (
("spider_1suit", "sp_suit_toggle_1"),
("spider_2suit", "sp_suit_toggle_2"),
("spider_4suit", "sp_suit_toggle_4"),
)
TOGGLE_BTN_WIDTH = 158
DESC_KEY_PREFIX = "sp_desc_"
diff_setting_key = f"spider_diff_{pid}"
var_setting_key = f"spider_variant_{pid}"
def _variants_dict(self) -> dict[str, dict]:
return SPIDER_VARIANTS
saved_diff_str = Database.load_setting(diff_setting_key, "1")
selected_diff = (
int(saved_diff_str)
if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES
else 1
)
selected_variant = Database.load_setting(var_setting_key, "spider_1suit")
if selected_variant not in SPIDER_VARIANTS:
selected_variant = "spider_1suit"
self.ctx.build_game_topbar(
self.ctx.root,
t("sp_menu_topbar"),
on_game_menu=None,
on_stats_back=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
stats_enabled=True,
extra_right_text="",
on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok),
)
cv = MenuBodyCanvas(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
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=180,
height=38,
style="fire",
)
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_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=158,
height=36,
style="fire" if is_sel else "amethyst",
)
suit_btns.append(b)
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=205,
height=40,
style="fire",
)
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
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(
"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_SIZE_BODY,
FONT_COLOR_BODY_DEFAULT,
max_width=box_w - resume_btn.pixel_width - 70,
align="left",
)
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
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
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 + 220
# 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")
bx_cur = val_col
for sb in suit_btns:
cv.create_window(bx_cur, r1_y, window=sb, anchor="w", tags="fg")
bx_cur += sb.pixel_width + 10
dsc_txt = t(f"sp_desc_{selected_variant}").replace("•", "-")
dsc_ph = self.ctx.assets.get_goth_text_photo(
dsc_txt, 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")
# 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")
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("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")
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()))
if ask_resume_popup and saved and saved_meta is not None:
self._show_resume_prompt_modal(saved, saved_meta)
@staticmethod
def _parse_saved_meta(saved: dict | None) -> dict | None:
if not saved:
return None
try:
data = json.loads(saved["state_json"])
if data.get("won"):
return None
board = data.get("board", {})
if not board or "tableau" not in board or "stock_deals" not in board:
return None
return {
"moves": max(0, int(data.get("moves", 0))),
"score": int(data.get("score", 500)),
"elapsed_sec": float(data.get("elapsed_sec", 0.0)),
"difficulty": max(0, min(3, int(board.get("difficulty", 1)))),
}
except Exception:
return None
def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict):
self._clear_modal()
def resume_now(_event=None):
self._clear_modal()
self._resume_saved(saved, saved_meta["difficulty"])
try:
self._return_bind_id = self.ctx.root.bind("<Return>", resume_now, add="+")
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 = SolitaireModalDialog(
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),
],
)
def _resume_saved(self, saved: dict, difficulty: int):
self._clear_modal()
SpiderTableView(
self.ctx,
variant_key=saved["variant_key"],
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=saved["state_json"],
)
def _on_start_clicked(
self,
variant_key: str,
difficulty: int,
saved: dict | None,
saved_meta: dict | None,
):
if self._modal_overlay is not None:
return
if saved and saved_meta and saved_meta["moves"] > 0:
self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta)
return
self._launch_fresh_game(variant_key, difficulty)
def _show_overwrite_confirm_modal(
self,
new_variant_key: str,
new_difficulty: int,
saved: dict,
saved_meta: dict,
):
pid = self.ctx.profile["id"]
old_v = saved["variant_key"]
old_diff = saved_meta["difficulty"]
prog = Database.get_game_progress(pid, GAME_FOLDER_ID)
v_mult = SPIDER_VARIANTS.get(old_v, {"xp_mult": 1.10})["xp_mult"]
d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"]
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)))
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
)
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 = SolitaireModalDialog(
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),
],
)
def _launch_fresh_game(self, variant_key: str, difficulty: int):
pid = self.ctx.profile["id"]
Database.save_setting(f"spider_diff_{pid}", str(difficulty))
Database.save_setting(f"spider_variant_{pid}", variant_key)
Database.delete_game_state(pid, GAME_FOLDER_ID)
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
SpiderTableView(
self.ctx,
variant_key=variant_key,
difficulty=difficulty,
on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok),
resume_state_json=resume_state_json,
)

File diff suppressed because it is too large Load Diff

51
main.py
View File

@ -23,6 +23,7 @@ from resources.code_res.game_constants import APP_ICON_REL_PATH
from view.font_loader import FontLoader
from view.main_window import GothCardCollectionView
from view.widgets.error_report_overlay import ErrorReportOverlay
from games.solitaire.base.solitaire_theme import extract_best_ico_pil
# Oben in view/main_window.py:
APP_WM_CLASS = "TheGothCardgameCollection"
@ -87,49 +88,15 @@ def _prepare_os_app_identity():
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)."""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
with Image.open(icon_path) as ico:
best_img = None
best_area = -1
ico_helper = getattr(ico, "ico", None)
if ico_helper is not None and hasattr(ico_helper, "sizes"):
for sz in ico_helper.sizes():
try:
frame = ico_helper.getimage(sz).convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
if best_img is None:
n_frames = getattr(ico, "n_frames", 1)
for idx in range(n_frames):
try:
ico.seek(idx)
frame = ico.copy().convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
if best_img is None:
best_img = ico.convert("RGBA")
cascade = [
best_img.resize((px, px), Image.Resampling.LANCZOS)
for px in (256, 128, 64, 48, 32, 16)
]
return best_img, cascade
except Exception:
"""Nutzt den zentralen ICO-Frame-Reader und erzeugt die Fenster-Icon-Kaskade."""
best_img = extract_best_ico_pil(icon_path)
if best_img is None:
return None, []
cascade = [
best_img.resize((px, px), Image.Resampling.LANCZOS)
for px in (256, 128, 64, 48, 32, 16)
]
return best_img, cascade
def ensure_crostini_shelf_icon(icon_ico_path: Path, wm_class: str = APP_WM_CLASS) -> None:

View File

@ -9,16 +9,9 @@ from pathlib import Path
import resources.code_res.sql_queries as sql
from models.db_locator import DbLocator
from resources.code_res.game_constants import (
BJ_DEFAULT_BET,
BJ_STARTING_GOLD,
DEVILS_DEAL_GOLD_REWARD,
GOLD_MAX_ACCOUNTS,
INTERNAL_DB_REL_PATH,
PK_STARTING_GOLD,
USER_DB_FILENAME,
XP_TO_GOLD_AMOUNT,
)
from models.db_pouch_repo import DbPouchRepo
from models.db_stats_repo import DbStatsRepo
from resources.code_res.game_constants import INTERNAL_DB_REL_PATH, USER_DB_FILENAME
def _resolve_bundle_root() -> Path:
@ -48,6 +41,11 @@ USER_DB_PATH = DbLocator.resolve_initial_db_path(USER_DATA_DIR)
class Database:
"""
Zentrale SQLite-Fassade für Verbindung, DB-Speicherort/Umzug, Einstellungen,
Profile und Savegames; delegiert Goldbeutel und Statistiken an Sub-Repositories.
"""
_connection: sqlite3.Connection | None = None
_active_user_db_path: Path = USER_DB_PATH
@ -124,7 +122,6 @@ class Database:
@classmethod
def _persist_self_location_in_db(cls, previous_path: Path | None = None) -> None:
"""Speichert den aktuellen kanonischen Dateipfad direkt in der DB selbst + im OS-Locator."""
cur_p = cls._active_user_db_path.resolve()
cls.save_setting("user_db_path", str(cur_p))
cls.save_setting("user_db_dir", str(cur_p.parent))
@ -141,9 +138,7 @@ class Database:
cls.conn().commit()
cls._persist_self_location_in_db()
# ------------------------------------------------------------------
# NUTZERDATEN-PFAD WÄHLEN (ERST-START), LADEN & ATOMAR UMZIEHEN
# ------------------------------------------------------------------
# --- DB-Speicherort, Live-Wechsel & Atomarer Umzug ---
@staticmethod
def validate_sqlite_file(candidate_file: Path) -> bool:
if not candidate_file.is_file():
@ -154,22 +149,16 @@ class Database:
if not res or str(res[0]).lower() != "ok":
return False
tables = {
r[0]
for r in test_c.execute(
r[0] for r in test_c.execute(
"SELECT name FROM sqlite_master WHERE type='table';"
).fetchall()
}
# Entweder frisch/leer oder gültige Goth-Cardgame-Nutzerdatenbank
return (not tables) or ("profiles" in tables and "settings" in tables)
except Exception:
return False
@classmethod
def relocate_for_first_user(cls, target_dir_or_file: Path) -> Path:
"""
Wird beim Anlegen des allerersten lokalen Profils genutzt, falls der Nutzer
einen eigenen Zielordner gewählt hat. Entfernt eine leere Platzhalter-DB am alten Ort.
"""
target = target_dir_or_file.expanduser().resolve()
if target.is_dir() or target.suffix.lower() != ".db":
target = target / USER_DB_FILENAME
@ -196,7 +185,6 @@ class Database:
@classmethod
def switch_user_database(cls, existing_db_file: Path) -> tuple[bool, str]:
"""Lädt eine bestehende user_data.db von beliebigem Pfad und merkt sie in DB & Locator."""
cand = existing_db_file.expanduser().resolve()
if not cls.validate_sqlite_file(cand):
return False, "invalid_file"
@ -220,10 +208,6 @@ class Database:
@classmethod
def move_user_database(cls, destination_dir: Path) -> tuple[bool, str]:
"""
Zieht die aktive user_data.db per konsistentem SQLite-Online-Backup in einen neuen
Ordner um, speichert den neuen Pfad in der DB + im Locator und räumt die alte Datei auf.
"""
dst_dir = destination_dir.expanduser().resolve()
dst_dir.mkdir(parents=True, exist_ok=True)
dst_file = (dst_dir / cls._active_user_db_path.name).resolve()
@ -236,7 +220,6 @@ class Database:
tmp_file = dst_dir / f".{dst_file.name}.moving_tmp"
try:
tmp_file.unlink(missing_ok=True)
# Konsistentes Backup der laufenden Haupt-DB (inkl. ungeschriebener WAL-Seiten)
src_conn = cls.conn()
src_conn.commit()
with sqlite3.connect(str(tmp_file)) as backup_conn:
@ -255,13 +238,11 @@ class Database:
cls.init_db()
cls._persist_self_location_in_db(previous_path=old_file)
# Alte DB-Dateien erst löschen, nachdem die neue DB aktiv & verifiziert ist
for suffix in ("", "-wal", "-shm"):
try:
Path(f"{old_file}{suffix}").unlink(missing_ok=True)
except Exception:
pass
return True, str(dst_file)
except Exception as exc:
try:
@ -273,9 +254,7 @@ class Database:
cls.init_db()
return False, str(exc)
# ------------------------------------------------------------------
# ÜBERSETZUNGEN, PRESTIGE & SETTINGS
# ------------------------------------------------------------------
# --- Stammdaten, Settings, Profile & Savegames ---
@classmethod
def load_all_translations(cls) -> dict[str, dict[str, str]]:
out: dict[str, dict[str, str]] = {"DE": {}, "EN": {}}
@ -295,7 +274,6 @@ class Database:
def save_setting(cls, key: str, value: str):
cls.execute(sql.UPSERT_SETTING, (key, str(value)))
# --- Profile ---
@classmethod
def get_profiles(cls) -> list[str]:
return [r["name"] for r in cls.fetch_all(sql.SELECT_ALL_PROFILES)]
@ -309,117 +287,6 @@ class Database:
def get_profile_by_id(cls, profile_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_PROFILE_BY_ID, (profile_id,))
# --- Spielgebundene Progression ---
@classmethod
def get_game_progress(cls, profile_id: int, game_folder: str) -> dict:
from models.progression import Progression
cls.execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
row = cls.fetch_one(sql.SELECT_GAME_PROGRESS, (profile_id, game_folder))
info = Progression.get_level_info(
row["points"],
profile_id=profile_id,
game_folder=game_folder,
ever_deity=bool(row["ever_reached_deity"]),
)
if info["ever_reached_deity"] and not row["ever_reached_deity"]:
cls.execute(sql.MARK_GAME_EVER_DEITY, (profile_id, game_folder))
return info
@classmethod
def get_recorded_game_level_avg_xp(cls, profile_id: int, game_folder: str, level_num: int) -> int:
row = cls.fetch_one(sql.SELECT_GAME_LEVEL_AVG_XP, (profile_id, game_folder, int(level_num)))
if not row or row["games_count"] <= 0:
return 0
return int(row["total_xp_earned"] // row["games_count"])
@classmethod
def _record_game_xp_with_history(cls, profile_id: int, game_folder: str, current_level: int, xp_gained: int):
from models.progression import Progression
if xp_gained <= 0:
return
cls.conn().execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
cls.conn().execute(sql.ADD_GAME_POINTS, (int(xp_gained), profile_id, game_folder))
if current_level >= Progression.get_creator_spirit_v_level():
cls.conn().execute(
sql.UPSERT_GAME_LEVEL_XP_HISTORY,
(profile_id, game_folder, int(current_level), int(xp_gained))
)
@classmethod
def add_game_points(cls, profile_id: int, game_folder: str, points: int):
if points <= 0:
return
cur_prog = cls.get_game_progress(profile_id, game_folder)
with cls.conn():
cls._record_game_xp_with_history(profile_id, game_folder, cur_prog["level"], int(points))
cls.get_game_progress(profile_id, game_folder)
@classmethod
def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict:
cur = cls.get_game_progress(profile_id, game_folder)
new_pts = max(min_floor_xp, cur["total_points"] + int(delta_points))
cls.execute(sql.SET_GAME_POINTS, (new_pts, profile_id, game_folder))
return cls.get_game_progress(profile_id, game_folder)
# --- Spielgebundener THE DEVIL'S DEAL (Blackjack & Poker jeweils autark!) ---
@classmethod
def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]:
from models.progression import Progression
min_lvl = Progression.get_devils_deal_min_level()
eligible = []
for row in cls.fetch_all(sql.SELECT_CANDIDATES_FOR_GAME_SACRIFICE, (game_folder, active_profile_id)):
info = Progression.get_level_info(row["points"])
if info["level"] >= min_lvl:
eligible.append({
"id": row["id"],
"name": row["name"],
"level": info["level"],
"title": info["title"],
})
return eligible
@classmethod
def execute_devils_deal(
cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, account_id: int
) -> tuple[bool, str]:
from resources.code_res.i18n import t
candidates = {c["id"]: c for c in cls.get_sacrificeable_profiles(active_profile_id, game_folder)}
victim = candidates.get(sacrifice_profile_id)
if not victim:
return False, ""
if game_folder == "poker":
with cls.conn():
cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
cls.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
cls.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1, account_id))
acc = cls.get_poker_account(account_id)
else:
with cls.conn():
cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1, account_id))
acc = cls.get_blackjack_account(account_id)
return True, t("bj_devils_deal_success", victim["name"], DEVILS_DEAL_GOLD_REWARD, acc["account_name"])
@classmethod
def get_active_devils_bj_account(cls, profile_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_BJ_ACCOUNT, (profile_id,))
@classmethod
def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool):
cls.execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1 if active else 0, bj_account_id))
@classmethod
def get_active_devils_pk_account(cls, profile_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_PK_ACCOUNT, (profile_id,))
@classmethod
def set_pk_devils_deal_active(cls, pk_account_id: int, active: bool):
cls.execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1 if active else 0, pk_account_id))
# --- Savegames ---
@classmethod
def save_game_state(cls, profile_id: int, game_folder: str, variant_key: str, state_json: str):
cls.execute(sql.UPSERT_SAVEGAME, (profile_id, game_folder, variant_key, state_json))
@ -432,263 +299,131 @@ class Database:
def delete_game_state(cls, profile_id: int, game_folder: str):
cls.execute(sql.DELETE_SAVEGAME, (profile_id, game_folder))
# --- Blackjack Gold-Konten ---
# --- Delegatoren an DbStatsRepo ---
@classmethod
def get_blackjack_accounts(cls, profile_id: int) -> list[dict]:
return cls.fetch_all(sql.SELECT_BJ_ACCOUNTS_BY_PROFILE, (profile_id,))
def get_game_progress(cls, profile_id: int, game_folder: str) -> dict:
return DbStatsRepo.get_game_progress(cls, profile_id, game_folder)
@classmethod
def get_blackjack_account(cls, bj_account_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_ID, (bj_account_id,))
def get_recorded_game_level_avg_xp(cls, profile_id: int, game_folder: str, level_num: int) -> int:
return DbStatsRepo.get_recorded_game_level_avg_xp(cls, profile_id, game_folder, level_num)
@classmethod
def create_blackjack_account(cls, profile_id: int, account_name: str) -> dict:
from resources.code_res.i18n import t
clean_name = account_name.strip()
if not clean_name:
raise ValueError(t("bj_err_empty_name"))
if len(cls.get_blackjack_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS:
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
cls.execute(sql.INSERT_BJ_ACCOUNT, (profile_id, clean_name, BJ_STARTING_GOLD, BJ_DEFAULT_BET))
return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_NAME, (profile_id, clean_name))
def add_game_points(cls, profile_id: int, game_folder: str, points: int):
DbStatsRepo.add_game_points(cls, profile_id, game_folder, points)
@classmethod
def update_blackjack_gold(cls, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict:
if last_bet is not None:
cls.execute(sql.UPDATE_BJ_GOLD_AND_BET, (int(gold_delta), int(last_bet), bj_account_id))
else:
cls.execute(sql.UPDATE_BJ_GOLD_ONLY, (int(gold_delta), bj_account_id))
return cls.get_blackjack_account(bj_account_id)
def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict:
return DbStatsRepo.adjust_game_points(cls, profile_id, game_folder, delta_points, min_floor_xp)
@classmethod
def save_blackjack_last_bet(cls, bj_account_id: int, bet: int):
cls.execute(sql.UPDATE_BJ_LAST_BET, (int(bet), bj_account_id))
@classmethod
def delete_blackjack_account(cls, bj_account_id: int):
cls.execute(sql.DELETE_BJ_ACCOUNT, (bj_account_id,))
@classmethod
def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]:
return cls._exchange_game_xp_for_gold(profile_id, "blackjack", bj_account_id)
# --- Poker Gold-Konten (autarke Bankroll + eigener XP-Tausch!) ---
@classmethod
def get_poker_accounts(cls, profile_id: int) -> list[dict]:
return cls.fetch_all(sql.SELECT_PK_ACCOUNTS_BY_PROFILE, (profile_id,))
@classmethod
def get_poker_account(cls, pk_account_id: int) -> dict | None:
return cls.fetch_one(sql.SELECT_PK_ACCOUNT_BY_ID, (pk_account_id,))
@classmethod
def create_poker_account(cls, profile_id: int, account_name: str) -> dict:
from resources.code_res.i18n import t
clean_name = account_name.strip()
if not clean_name:
raise ValueError(t("bj_err_empty_name"))
if len(cls.get_poker_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS:
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
cls.execute(sql.INSERT_PK_ACCOUNT, (profile_id, clean_name, PK_STARTING_GOLD))
return cls.fetch_one(sql.SELECT_PK_ACCOUNT_BY_NAME, (profile_id, clean_name))
@classmethod
def update_poker_gold(cls, pk_account_id: int, gold_delta: int) -> dict:
cls.execute(sql.UPDATE_PK_GOLD_ONLY, (int(gold_delta), pk_account_id))
return cls.get_poker_account(pk_account_id)
@classmethod
def delete_poker_account(cls, pk_account_id: int):
cls.execute(sql.DELETE_PK_ACCOUNT, (pk_account_id,))
@classmethod
def exchange_xp_for_pk_gold(cls, profile_id: int, pk_account_id: int) -> tuple[bool, str]:
return cls._exchange_game_xp_for_gold(profile_id, "poker", pk_account_id)
@classmethod
def _exchange_game_xp_for_gold(cls, profile_id: int, game_folder: str, account_id: int) -> tuple[bool, str]:
from models.progression import Progression
from resources.code_res.i18n import t
prog = cls.get_game_progress(profile_id, game_folder)
if prog.get("at_divine_floor"):
return False, t("bj_err_floor_reached")
cost = prog["xp_exchange_cost"]
is_divine = prog["is_divine_punishment"]
if not is_divine and prog["total_points"] < cost:
return False, t("bj_err_not_enough_xp", prog["total_points"], cost)
if is_divine:
floor_xp = Progression.get_creator_spirit_v_floor_xp()
new_points = max(floor_xp, prog["total_points"] - cost)
actual_deducted = prog["total_points"] - new_points
if actual_deducted <= 0:
return False, t("bj_err_floor_reached")
else:
new_points = max(0, prog["total_points"] - cost)
actual_deducted = cost
with cls.conn():
cls.conn().execute(sql.SET_GAME_POINTS, (new_points, profile_id, game_folder))
if game_folder == "poker":
cls.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
cls.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (0, account_id))
acc = cls.get_poker_account(account_id)
else:
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (0, account_id))
acc = cls.get_blackjack_account(account_id)
updated_prog = cls.get_game_progress(profile_id, game_folder)
if is_divine:
return True, t(
"bj_exchange_divine_success",
XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted, updated_prog["title"]
)
return True, t("bj_exchange_success", XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted)
# --- Bot Configs & Statistiken ---
@classmethod
def load_bot_configs(cls, profile_id: int, game_folder: str) -> dict[int, tuple[str, int]]:
rows = cls.fetch_all(sql.SELECT_BOT_CONFIGS, (profile_id, game_folder))
return {r["slot_idx"]: (r["bot_name"], r["ai_level"]) for r in rows}
return DbStatsRepo.load_bot_configs(cls, profile_id, game_folder)
@classmethod
def save_bot_configs(cls, profile_id: int, game_folder: str, configs: dict[int, tuple[str, int]]):
data = [(profile_id, game_folder, int(idx), name, int(lvl)) for idx, (name, lvl) in configs.items()]
cls.execute_many(sql.UPSERT_BOT_CONFIG, data)
@classmethod
def _upsert_stat(cls, scope: str, owner_id: int, variant_id: int, won: bool, duration_sec: float):
q = sql.STATS_SQL[scope]
cur = cls.fetch_one(q["select_one"], (owner_id, variant_id))
dur = max(0.0, duration_sec)
if not cur:
cls.conn().execute(q["insert"], (
owner_id, variant_id,
1 if won else 0, 0 if won else 1,
1 if won else 0, 1 if won else 0,
dur if won else None, dur,
))
else:
c_streak = (cur["current_streak"] + 1) if won else 0
best_t = cur["best_time_sec"]
if won:
best_t = dur if best_t is None else min(best_t, dur)
cls.conn().execute(q["update"], (
cur["games_played"] + 1,
cur["games_won"] + (1 if won else 0),
cur["games_lost"] + (0 if won else 1),
c_streak,
max(cur["longest_streak"], c_streak),
best_t,
cur["total_time_sec"] + dur,
owner_id, variant_id,
))
DbStatsRepo.save_bot_configs(cls, profile_id, game_folder, configs)
@classmethod
def record_game_result(
cls,
profile_id: int,
variant_key: str,
won: bool,
duration_sec: float,
points_gained: int = 0,
bj_account_id: int | None = None,
pk_account_id: int | None = None,
cls, profile_id: int, variant_key: str, won: bool, duration_sec: float,
points_gained: int = 0, bj_account_id: int | None = None, pk_account_id: int | None = None,
) -> tuple[int, int]:
var_info = cls.fetch_one(sql.SELECT_VARIANT_INFO_BY_KEY, (variant_key,))
if not var_info:
raise ValueError(f"Unbekannte Spielvariante in internal_base.db: {variant_key}")
variant_id = var_info["id"]
game_folder = var_info["folder_path"]
prog_before = cls.get_game_progress(profile_id, game_folder)
old_lvl = prog_before["level"]
with cls.conn():
if points_gained > 0:
cls._record_game_xp_with_history(profile_id, game_folder, old_lvl, int(points_gained))
cls._upsert_stat("profile", profile_id, variant_id, won, duration_sec)
if bj_account_id is not None:
cls._upsert_stat("bj_account", bj_account_id, variant_id, won, duration_sec)
if pk_account_id is not None:
cls._upsert_stat("pk_account", pk_account_id, variant_id, won, duration_sec)
new_lvl = cls.get_game_progress(profile_id, game_folder)["level"]
return old_lvl, new_lvl
return DbStatsRepo.record_game_result(
cls, profile_id, variant_key, won, duration_sec, points_gained, bj_account_id, pk_account_id
)
@classmethod
def get_variants_for_filter(cls, folder_path: str | None = None) -> list[dict]:
from resources.code_res.i18n import t
rows = (
cls.fetch_all(sql.SELECT_VARIANTS_BY_FOLDER, (folder_path,))
if folder_path else cls.fetch_all(sql.SELECT_ALL_VARIANTS)
)
for d in rows:
d["translated_name"] = t(f"variant_{d['variant_key']}")
return rows
@classmethod
def _query_stats(cls, scope: str, owner_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict:
q = sql.STATS_SQL[scope]
if variant_id is not None:
row = cls.fetch_one(q["select_one"], (owner_id, variant_id))
if not row or row["games_played"] == 0:
return cls._empty_stats()
played, won, lost = row["games_played"], row["games_won"], row["games_lost"]
c_streak, l_streak, best_t, total_t = row["current_streak"], row["longest_streak"], row["best_time_sec"], row["total_time_sec"]
else:
row = (
cls.fetch_one(q["aggregate_folder"], (owner_id, folder_path))
if folder_path is not None
else cls.fetch_one(q["aggregate_all"], (owner_id,))
)
if not row or row["played"] == 0:
return cls._empty_stats()
played, won, lost = row["played"], row["won"], row["lost"]
c_streak, l_streak, best_t, total_t = row["c_streak"], row["l_streak"], row["best_time"], row["total_time"]
return {
"played": played,
"won": won,
"lost": lost,
"win_pct": f"{(won / played * 100.0):.1f} %",
"current_streak": c_streak,
"longest_streak": l_streak,
"best_time": cls.format_seconds(best_t),
"avg_time": cls.format_seconds(total_t / played),
}
return DbStatsRepo.get_variants_for_filter(cls, folder_path)
@classmethod
def get_stats_overview(cls, profile_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict:
return cls._query_stats("profile", profile_id, variant_id=variant_id, folder_path=folder_path)
return DbStatsRepo.query_stats(cls, "profile", profile_id, variant_id=variant_id, folder_path=folder_path)
@classmethod
def get_bj_account_stats_overview(cls, bj_account_id: int, variant_id: int | None = None) -> dict:
return cls._query_stats("bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack")
return DbStatsRepo.query_stats(cls, "bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack")
@classmethod
def get_pk_account_stats_overview(cls, pk_account_id: int, variant_id: int | None = None) -> dict:
return cls._query_stats("pk_account", pk_account_id, variant_id=variant_id, folder_path="poker")
return DbStatsRepo.query_stats(cls, "pk_account", pk_account_id, variant_id=variant_id, folder_path="poker")
@staticmethod
def format_seconds(sec: float | None) -> str:
if sec is None:
return "--:--"
mins, secs = divmod(int(round(sec)), 60)
if mins >= 60:
hrs, mins = divmod(mins, 60)
return f"{hrs:02d}:{mins:02d}:{secs:02d}"
return f"{mins:02d}:{secs:02d}"
format_seconds = staticmethod(DbStatsRepo.format_seconds)
@staticmethod
def _empty_stats() -> dict:
return {
"played": 0, "won": 0, "lost": 0, "win_pct": "0.0 %",
"current_streak": 0, "longest_streak": 0, "best_time": "--:--", "avg_time": "--:--",
}
# --- Delegatoren an DbPouchRepo ---
@classmethod
def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]:
return DbPouchRepo.get_sacrificeable_profiles(cls, active_profile_id, game_folder)
@classmethod
def execute_devils_deal(cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, account_id: int) -> tuple[bool, str]:
return DbPouchRepo.execute_devils_deal(cls, active_profile_id, game_folder, sacrifice_profile_id, account_id)
@classmethod
def get_active_devils_bj_account(cls, profile_id: int) -> dict | None:
return DbPouchRepo.get_active_devils_bj_account(cls, profile_id)
@classmethod
def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool):
DbPouchRepo.set_bj_devils_deal_active(cls, bj_account_id, active)
@classmethod
def get_active_devils_pk_account(cls, profile_id: int) -> dict | None:
return DbPouchRepo.get_active_devils_pk_account(cls, profile_id)
@classmethod
def set_pk_devils_deal_active(cls, pk_account_id: int, active: bool):
DbPouchRepo.set_pk_devils_deal_active(cls, pk_account_id, active)
@classmethod
def get_blackjack_accounts(cls, profile_id: int) -> list[dict]:
return DbPouchRepo.get_blackjack_accounts(cls, profile_id)
@classmethod
def get_blackjack_account(cls, bj_account_id: int) -> dict | None:
return DbPouchRepo.get_blackjack_account(cls, bj_account_id)
@classmethod
def create_blackjack_account(cls, profile_id: int, account_name: str) -> dict:
return DbPouchRepo.create_blackjack_account(cls, profile_id, account_name)
@classmethod
def update_blackjack_gold(cls, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict:
return DbPouchRepo.update_blackjack_gold(cls, bj_account_id, gold_delta, last_bet)
@classmethod
def save_blackjack_last_bet(cls, bj_account_id: int, bet: int):
DbPouchRepo.save_blackjack_last_bet(cls, bj_account_id, bet)
@classmethod
def delete_blackjack_account(cls, bj_account_id: int):
DbPouchRepo.delete_blackjack_account(cls, bj_account_id)
@classmethod
def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]:
return DbPouchRepo.exchange_game_xp_for_gold(cls, profile_id, "blackjack", bj_account_id)
@classmethod
def get_poker_accounts(cls, profile_id: int) -> list[dict]:
return DbPouchRepo.get_poker_accounts(cls, profile_id)
@classmethod
def get_poker_account(cls, pk_account_id: int) -> dict | None:
return DbPouchRepo.get_poker_account(cls, pk_account_id)
@classmethod
def create_poker_account(cls, profile_id: int, account_name: str) -> dict:
return DbPouchRepo.create_poker_account(cls, profile_id, account_name)
@classmethod
def update_poker_gold(cls, pk_account_id: int, gold_delta: int) -> dict:
return DbPouchRepo.update_poker_gold(cls, pk_account_id, gold_delta)
@classmethod
def delete_poker_account(cls, pk_account_id: int):
DbPouchRepo.delete_poker_account(cls, pk_account_id)
@classmethod
def exchange_xp_for_pk_gold(cls, profile_id: int, pk_account_id: int) -> tuple[bool, str]:
return DbPouchRepo.exchange_game_xp_for_gold(cls, profile_id, "poker", pk_account_id)

194
models/db_pouch_repo.py Normal file
View File

@ -0,0 +1,194 @@
# -*- coding: utf-8 -*-
# models/db_pouch_repo.py
from __future__ import annotations
import resources.code_res.sql_queries as sql
from resources.code_res.game_constants import (
BJ_DEFAULT_BET,
BJ_STARTING_GOLD,
DEVILS_DEAL_GOLD_REWARD,
GOLD_MAX_ACCOUNTS,
PK_STARTING_GOLD,
XP_TO_GOLD_AMOUNT,
)
class DbPouchRepo:
"""
Kapselt alle Operationen für Blackjack- & Poker-Goldbeutel,
XP->Gold-Umtausch (inkl. Divine Punishment) sowie The Devil's Deal.
"""
@staticmethod
def get_sacrificeable_profiles(db, active_profile_id: int, game_folder: str) -> list[dict]:
from models.progression import Progression
min_lvl = Progression.get_devils_deal_min_level()
eligible = []
for row in db.fetch_all(sql.SELECT_CANDIDATES_FOR_GAME_SACRIFICE, (game_folder, active_profile_id)):
info = Progression.get_level_info(row["points"])
if info["level"] >= min_lvl:
eligible.append({
"id": row["id"],
"name": row["name"],
"level": info["level"],
"title": info["title"],
})
return eligible
@classmethod
def execute_devils_deal(
cls,
db,
active_profile_id: int,
game_folder: str,
sacrifice_profile_id: int,
account_id: int,
) -> tuple[bool, str]:
from resources.code_res.i18n import t
candidates = {c["id"]: c for c in cls.get_sacrificeable_profiles(db, active_profile_id, game_folder)}
victim = candidates.get(sacrifice_profile_id)
if not victim:
return False, ""
if game_folder == "poker":
with db.conn():
db.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
db.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
db.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1, account_id))
acc = cls.get_poker_account(db, account_id)
else:
with db.conn():
db.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
db.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
db.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1, account_id))
acc = cls.get_blackjack_account(db, account_id)
return True, t("bj_devils_deal_success", victim["name"], DEVILS_DEAL_GOLD_REWARD, acc["account_name"])
@staticmethod
def get_active_devils_bj_account(db, profile_id: int) -> dict | None:
return db.fetch_one(sql.SELECT_ACTIVE_DEVILS_BJ_ACCOUNT, (profile_id,))
@staticmethod
def set_bj_devils_deal_active(db, bj_account_id: int, active: bool) -> None:
db.execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1 if active else 0, bj_account_id))
@staticmethod
def get_active_devils_pk_account(db, profile_id: int) -> dict | None:
return db.fetch_one(sql.SELECT_ACTIVE_DEVILS_PK_ACCOUNT, (profile_id,))
@staticmethod
def set_pk_devils_deal_active(db, pk_account_id: int, active: bool) -> None:
db.execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1 if active else 0, pk_account_id))
# --- Blackjack Gold-Konten ---
@staticmethod
def get_blackjack_accounts(db, profile_id: int) -> list[dict]:
return db.fetch_all(sql.SELECT_BJ_ACCOUNTS_BY_PROFILE, (profile_id,))
@staticmethod
def get_blackjack_account(db, bj_account_id: int) -> dict | None:
return db.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_ID, (bj_account_id,))
@classmethod
def create_blackjack_account(cls, db, profile_id: int, account_name: str) -> dict:
from resources.code_res.i18n import t
clean_name = account_name.strip()
if not clean_name:
raise ValueError(t("bj_err_empty_name"))
if len(cls.get_blackjack_accounts(db, profile_id)) >= GOLD_MAX_ACCOUNTS:
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
db.execute(sql.INSERT_BJ_ACCOUNT, (profile_id, clean_name, BJ_STARTING_GOLD, BJ_DEFAULT_BET))
return db.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_NAME, (profile_id, clean_name))
@classmethod
def update_blackjack_gold(cls, db, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict:
if last_bet is not None:
db.execute(sql.UPDATE_BJ_GOLD_AND_BET, (int(gold_delta), int(last_bet), bj_account_id))
else:
db.execute(sql.UPDATE_BJ_GOLD_ONLY, (int(gold_delta), bj_account_id))
return cls.get_blackjack_account(db, bj_account_id)
@staticmethod
def save_blackjack_last_bet(db, bj_account_id: int, bet: int) -> None:
db.execute(sql.UPDATE_BJ_LAST_BET, (int(bet), bj_account_id))
@staticmethod
def delete_blackjack_account(db, bj_account_id: int) -> None:
db.execute(sql.DELETE_BJ_ACCOUNT, (bj_account_id,))
# --- Poker Gold-Konten ---
@staticmethod
def get_poker_accounts(db, profile_id: int) -> list[dict]:
return db.fetch_all(sql.SELECT_PK_ACCOUNTS_BY_PROFILE, (profile_id,))
@staticmethod
def get_poker_account(db, pk_account_id: int) -> dict | None:
return db.fetch_one(sql.SELECT_PK_ACCOUNT_BY_ID, (pk_account_id,))
@classmethod
def create_poker_account(cls, db, profile_id: int, account_name: str) -> dict:
from resources.code_res.i18n import t
clean_name = account_name.strip()
if not clean_name:
raise ValueError(t("bj_err_empty_name"))
if len(cls.get_poker_accounts(db, profile_id)) >= GOLD_MAX_ACCOUNTS:
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
db.execute(sql.INSERT_PK_ACCOUNT, (profile_id, clean_name, PK_STARTING_GOLD))
return db.fetch_one(sql.SELECT_PK_ACCOUNT_BY_NAME, (profile_id, clean_name))
@classmethod
def update_poker_gold(cls, db, pk_account_id: int, gold_delta: int) -> dict:
db.execute(sql.UPDATE_PK_GOLD_ONLY, (int(gold_delta), pk_account_id))
return cls.get_poker_account(db, pk_account_id)
@staticmethod
def delete_poker_account(db, pk_account_id: int) -> None:
db.execute(sql.DELETE_PK_ACCOUNT, (pk_account_id,))
# --- Gemeinsamer XP->Gold-Tausch ---
@classmethod
def exchange_game_xp_for_gold(
cls, db, profile_id: int, game_folder: str, account_id: int
) -> tuple[bool, str]:
from models.progression import Progression
from resources.code_res.i18n import t
prog = db.get_game_progress(profile_id, game_folder)
if prog.get("at_divine_floor"):
return False, t("bj_err_floor_reached")
cost = prog["xp_exchange_cost"]
is_divine = prog["is_divine_punishment"]
if not is_divine and prog["total_points"] < cost:
return False, t("bj_err_not_enough_xp", prog["total_points"], cost)
if is_divine:
floor_xp = Progression.get_creator_spirit_v_floor_xp()
new_points = max(floor_xp, prog["total_points"] - cost)
actual_deducted = prog["total_points"] - new_points
if actual_deducted <= 0:
return False, t("bj_err_floor_reached")
else:
new_points = max(0, prog["total_points"] - cost)
actual_deducted = cost
with db.conn():
db.conn().execute(sql.SET_GAME_POINTS, (new_points, profile_id, game_folder))
if game_folder == "poker":
db.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
db.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (0, account_id))
acc = cls.get_poker_account(db, account_id)
else:
db.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
db.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (0, account_id))
acc = cls.get_blackjack_account(db, account_id)
updated_prog = db.get_game_progress(profile_id, game_folder)
if is_divine:
return True, t(
"bj_exchange_divine_success",
XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted, updated_prog["title"],
)
return True, t("bj_exchange_success", XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted)

214
models/db_stats_repo.py Normal file
View File

@ -0,0 +1,214 @@
# -*- coding: utf-8 -*-
# models/db_stats_repo.py
from __future__ import annotations
import resources.code_res.sql_queries as sql
class DbStatsRepo:
"""
Kapselt spielgebundene Progression, Level-XP-Historie, Bot-Konfigurationen
sowie Varianten- & Goldbeutel-Statistiken.
"""
@staticmethod
def get_game_progress(db, profile_id: int, game_folder: str) -> dict:
from models.progression import Progression
db.execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
row = db.fetch_one(sql.SELECT_GAME_PROGRESS, (profile_id, game_folder))
info = Progression.get_level_info(
row["points"],
profile_id=profile_id,
game_folder=game_folder,
ever_deity=bool(row["ever_reached_deity"]),
)
if info["ever_reached_deity"] and not row["ever_reached_deity"]:
db.execute(sql.MARK_GAME_EVER_DEITY, (profile_id, game_folder))
return info
@staticmethod
def get_recorded_game_level_avg_xp(
db, profile_id: int, game_folder: str, level_num: int
) -> int:
row = db.fetch_one(sql.SELECT_GAME_LEVEL_AVG_XP, (profile_id, game_folder, int(level_num)))
if not row or row["games_count"] <= 0:
return 0
return int(row["total_xp_earned"] // row["games_count"])
@staticmethod
def record_game_xp_with_history(
db, profile_id: int, game_folder: str, current_level: int, xp_gained: int
) -> None:
from models.progression import Progression
if xp_gained <= 0:
return
db.conn().execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder))
db.conn().execute(sql.ADD_GAME_POINTS, (int(xp_gained), profile_id, game_folder))
if current_level >= Progression.get_creator_spirit_v_level():
db.conn().execute(
sql.UPSERT_GAME_LEVEL_XP_HISTORY,
(profile_id, game_folder, int(current_level), int(xp_gained)),
)
@classmethod
def add_game_points(cls, db, profile_id: int, game_folder: str, points: int) -> None:
if points <= 0:
return
cur_prog = cls.get_game_progress(db, profile_id, game_folder)
with db.conn():
cls.record_game_xp_with_history(db, profile_id, game_folder, cur_prog["level"], int(points))
cls.get_game_progress(db, profile_id, game_folder)
@classmethod
def adjust_game_points(
cls, db, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0
) -> dict:
cur = cls.get_game_progress(db, profile_id, game_folder)
new_pts = max(min_floor_xp, cur["total_points"] + int(delta_points))
db.execute(sql.SET_GAME_POINTS, (new_pts, profile_id, game_folder))
return cls.get_game_progress(db, profile_id, game_folder)
# --- Bot Configs ---
@staticmethod
def load_bot_configs(db, profile_id: int, game_folder: str) -> dict[int, tuple[str, int]]:
rows = db.fetch_all(sql.SELECT_BOT_CONFIGS, (profile_id, game_folder))
return {r["slot_idx"]: (r["bot_name"], r["ai_level"]) for r in rows}
@staticmethod
def save_bot_configs(
db, profile_id: int, game_folder: str, configs: dict[int, tuple[str, int]]
) -> None:
data = [(profile_id, game_folder, int(idx), name, int(lvl)) for idx, (name, lvl) in configs.items()]
db.execute_many(sql.UPSERT_BOT_CONFIG, data)
# --- Spielergebnisse & Varianten-Statistiken ---
@staticmethod
def upsert_stat(db, scope: str, owner_id: int, variant_id: int, won: bool, duration_sec: float) -> None:
q = sql.STATS_SQL[scope]
cur = db.fetch_one(q["select_one"], (owner_id, variant_id))
dur = max(0.0, duration_sec)
if not cur:
db.conn().execute(q["insert"], (
owner_id, variant_id,
1 if won else 0, 0 if won else 1,
1 if won else 0, 1 if won else 0,
dur if won else None, dur,
))
else:
c_streak = (cur["current_streak"] + 1) if won else 0
best_t = cur["best_time_sec"]
if won:
best_t = dur if best_t is None else min(best_t, dur)
db.conn().execute(q["update"], (
cur["games_played"] + 1,
cur["games_won"] + (1 if won else 0),
cur["games_lost"] + (0 if won else 1),
c_streak,
max(cur["longest_streak"], c_streak),
best_t,
cur["total_time_sec"] + dur,
owner_id, variant_id,
))
@classmethod
def record_game_result(
cls,
db,
profile_id: int,
variant_key: str,
won: bool,
duration_sec: float,
points_gained: int = 0,
bj_account_id: int | None = None,
pk_account_id: int | None = None,
) -> tuple[int, int]:
var_info = db.fetch_one(sql.SELECT_VARIANT_INFO_BY_KEY, (variant_key,))
if not var_info:
raise ValueError(f"Unbekannte Spielvariante in internal_base.db: {variant_key}")
variant_id = var_info["id"]
game_folder = var_info["folder_path"]
prog_before = cls.get_game_progress(db, profile_id, game_folder)
old_lvl = prog_before["level"]
with db.conn():
if points_gained > 0:
cls.record_game_xp_with_history(db, profile_id, game_folder, old_lvl, int(points_gained))
cls.upsert_stat(db, "profile", profile_id, variant_id, won, duration_sec)
if bj_account_id is not None:
cls.upsert_stat(db, "bj_account", bj_account_id, variant_id, won, duration_sec)
if pk_account_id is not None:
cls.upsert_stat(db, "pk_account", pk_account_id, variant_id, won, duration_sec)
new_lvl = cls.get_game_progress(db, profile_id, game_folder)["level"]
return old_lvl, new_lvl
@staticmethod
def get_variants_for_filter(db, folder_path: str | None = None) -> list[dict]:
from resources.code_res.i18n import t
rows = (
db.fetch_all(sql.SELECT_VARIANTS_BY_FOLDER, (folder_path,))
if folder_path else db.fetch_all(sql.SELECT_ALL_VARIANTS)
)
for d in rows:
d["translated_name"] = t(f"variant_{d['variant_key']}")
return rows
@classmethod
def query_stats(
cls,
db,
scope: str,
owner_id: int,
variant_id: int | None = None,
folder_path: str | None = None,
) -> dict:
q = sql.STATS_SQL[scope]
if variant_id is not None:
row = db.fetch_one(q["select_one"], (owner_id, variant_id))
if not row or row["games_played"] == 0:
return cls.empty_stats()
played, won, lost = row["games_played"], row["games_won"], row["games_lost"]
c_streak, l_streak = row["current_streak"], row["longest_streak"]
best_t, total_t = row["best_time_sec"], row["total_time_sec"]
else:
row = (
db.fetch_one(q["aggregate_folder"], (owner_id, folder_path))
if folder_path is not None
else db.fetch_one(q["aggregate_all"], (owner_id,))
)
if not row or row["played"] == 0:
return cls.empty_stats()
played, won, lost = row["played"], row["won"], row["lost"]
c_streak, l_streak = row["c_streak"], row["l_streak"]
best_t, total_t = row["best_time"], row["total_time"]
return {
"played": played,
"won": won,
"lost": lost,
"win_pct": f"{(won / played * 100.0):.1f} %",
"current_streak": c_streak,
"longest_streak": l_streak,
"best_time": cls.format_seconds(best_t),
"avg_time": cls.format_seconds(total_t / played),
}
@staticmethod
def format_seconds(sec: float | None) -> str:
if sec is None:
return "--:--"
mins, secs = divmod(int(round(sec)), 60)
if mins >= 60:
hrs, mins = divmod(mins, 60)
return f"{hrs:02d}:{mins:02d}:{secs:02d}"
return f"{mins:02d}:{secs:02d}"
@staticmethod
def empty_stats() -> dict:
return {
"played": 0, "won": 0, "lost": 0, "win_pct": "0.0 %",
"current_streak": 0, "longest_streak": 0, "best_time": "--:--", "avg_time": "--:--",
}

View File

@ -162,6 +162,19 @@ FOLDER_CATEGORY_MAP = {
"solitaire/spider_solitaire": CAT_SOLO,
}
# --- Statistik-Kategorien & Spiel-Zuordnung (keine "Gesamt"-Statistik!) ---
STAT_CAT_LUCK = "luck"
STAT_CAT_SOLITAIRE = "solitaire"
STAT_CAT_BAVARIAN = "bavarian"
STAT_CAT_PARTY = "party_offline"
STAT_CATEGORIES = (
(STAT_CAT_LUCK, "cat_luck", "cat_desc_luck"),
(STAT_CAT_SOLITAIRE, "cat_solitaire", "cat_desc_solitaire"),
(STAT_CAT_BAVARIAN, "cat_bavarian", "cat_desc_bavarian"),
(STAT_CAT_PARTY, "cat_party_offline", "cat_desc_party_offline"),
)
STAT_GAME_GROUPS = (
("blackjack", "game_title_blackjack"),
("poker", "game_title_poker"),
@ -170,6 +183,16 @@ STAT_GAME_GROUPS = (
("solitaire/spider_solitaire", "game_title_spider_solitaire"),
)
STAT_FOLDER_CATEGORY_MAP = {
"blackjack": STAT_CAT_LUCK,
"poker": STAT_CAT_LUCK,
"solitaire/klondike": STAT_CAT_SOLITAIRE,
"solitaire/freecell": STAT_CAT_SOLITAIRE,
"solitaire/spider_solitaire": STAT_CAT_SOLITAIRE,
"solitaire/pyramid": STAT_CAT_SOLITAIRE,
"solitaire/tripeaks": STAT_CAT_SOLITAIRE,
}
# --- Karten-Definitionen ---
SUITS = ("C", "D", "H", "S")
RED_SUITS = ("D", "H")

Binary file not shown.

View File

@ -0,0 +1,293 @@
-- 00_schema_and_ranks.sql
-- Basis-Tabellen & Prestige-Ränge (0..259)
DROP TABLE IF EXISTS base_i18n;
DROP TABLE IF EXISTS base_prestige_ranks;
DROP TABLE IF EXISTS game_variants;
CREATE TABLE base_i18n (
key TEXT NOT NULL,
lang TEXT NOT NULL,
val TEXT NOT NULL,
PRIMARY KEY (key, lang)
);
CREATE TABLE base_prestige_ranks (
rank_idx INTEGER PRIMARY KEY,
title_de TEXT NOT NULL,
title_en TEXT NOT NULL
);
CREATE TABLE game_variants (
id INTEGER PRIMARY KEY,
folder_path TEXT NOT NULL,
game_name TEXT NOT NULL,
variant_key TEXT UNIQUE NOT NULL,
display_name TEXT NOT NULL
);
-- =========================================================================
-- PRESTIGE-RÄNGE (0..258 in I-V, 259 = Gottheit)
-- =========================================================================
INSERT INTO base_prestige_ranks (rank_idx, title_de, title_en) VALUES
(0, 'Erst-Starter', 'First-Starter'),
(1, 'Küken', 'Hatchling'),
(2, 'Frischling', 'Fledgling'),
(3, 'Grünschnabel', 'Greenhorn'),
(4, 'Ahnungsloser', 'Clueless'),
(5, 'Zuschauer', 'Spectator'),
(6, 'Zaungast', 'Bystander'),
(7, 'Mitläufer', 'Follower'),
(8, 'Stolperer', 'Stumbler'),
(9, 'Tapsiger', 'Fumbler'),
(10, 'Schnupperer', 'Dabbler'),
(11, 'Probierer', 'Taster'),
(12, 'Neugieriger', 'Curious'),
(13, 'Sucher', 'Seeker'),
(14, 'Tastender', 'Feeler'),
(15, 'Lerner', 'Learner'),
(16, 'Anfänger', 'Beginner'),
(17, 'Neuling', 'Newcomer'),
(18, 'Einsteiger', 'Entrant'),
(19, 'Debütant', 'Debutant'),
(20, 'Auszubildender', 'Trainee'),
(21, 'Praktikant', 'Intern'),
(22, 'Lehrling', 'Apprentice'),
(23, 'Schüler', 'Pupil'),
(24, 'Jungspund', 'Youngster'),
(25, 'Zögling', 'Protege'),
(26, 'Anwärter', 'Candidate'),
(27, 'Aspirant', 'Aspirant'),
(28, 'Novize', 'Novice'),
(29, 'Initiand', 'Initiate'),
(30, 'Hilfskraft', 'Helper'),
(31, 'Handlanger', 'Henchman'),
(32, 'Zuarbeiter', 'Assistant'),
(33, 'Gehilfe', 'Aide'),
(34, 'Knappe', 'Squire'),
(35, 'Läufer', 'Runner'),
(36, 'Späher', 'Scout'),
(37, 'Kundschafter', 'Pathfinder'),
(38, 'Rekrut', 'Recruit'),
(39, 'Kadett', 'Cadet'),
(40, 'Aufsteiger', 'Riser'),
(41, 'Fortgeschrittener', 'Intermediate'),
(42, 'Geübter', 'Practiced'),
(43, 'Erprobter', 'Tested'),
(44, 'Bewährter', 'Proven'),
(45, 'Tauglicher', 'Capable'),
(46, 'Fähiger', 'Able'),
(47, 'Geschickter', 'Skillful'),
(48, 'Gewandter', 'Adroit'),
(49, 'Behender', 'Nimble'),
(50, 'Geselle', 'Journeyman'),
(51, 'Handwerker', 'Craftsman'),
(52, 'Schaffender', 'Creator'),
(53, 'Macher', 'Maker'),
(54, 'Praktiker', 'Practitioner'),
(55, 'Anwender', 'Applier'),
(56, 'Umsetzer', 'Implementer'),
(57, 'Ausführender', 'Executor'),
(58, 'Routinier', 'Regular'),
(59, 'Stammkraft', 'Mainstay'),
(60, 'Kenner', 'Connoisseur'),
(61, 'Wissender', 'Knower'),
(62, 'Kundiger', 'Versed'),
(63, 'Belesener', 'Erudite'),
(64, 'Gelehrter', 'Scholar'),
(65, 'Denker', 'Thinker'),
(66, 'Planer', 'Planner'),
(67, 'Rechner', 'Calculator'),
(68, 'Prüfer', 'Examiner'),
(69, 'Analytiker', 'Analyst'),
(70, 'Könner', 'Adept'),
(71, 'Fachkraft', 'Skilled Pro'),
(72, 'Fachmann', 'Professionalist'),
(73, 'Sachverständiger', 'Surveyor'),
(74, 'Berater', 'Advisor'),
(75, 'Spezialist', 'Specialist'),
(76, 'Techniker', 'Technician'),
(77, 'Methodiker', 'Methodist'),
(78, 'Systematiker', 'Systematist'),
(79, 'Präzisionsarbeiter', 'Precisionist'),
(80, 'Profi', 'Pro'),
(81, 'Berufsspieler', 'Pro Gambler'),
(82, 'Vollprofi', 'Full Pro'),
(83, 'Leistungsträger', 'Key Player'),
(84, 'Stütze', 'Support'),
(85, 'Säule', 'Pillar'),
(86, 'Garant', 'Guarantor'),
(87, 'Fels', 'Rock'),
(88, 'Anker', 'Anchor'),
(89, 'Rückgrat', 'Backbone'),
(90, 'Taktiker', 'Tactician'),
(91, 'Stratege', 'Strategist'),
(92, 'Fuchs', 'Fox'),
(93, 'Schlitzohr', 'Sharpster'),
(94, 'Stratege der Tiefe', 'Deep Strategist'),
(95, 'Drahtzieher', 'Mastermind'),
(96, 'Lenker', 'Steersman'),
(97, 'Leiter', 'Director'),
(98, 'Koordinator', 'Coordinator'),
(99, 'Regisseur', 'Conductor'),
(100, 'Experte', 'Expert'),
(101, 'Koryphäe', 'Luminary'),
(102, 'Kapazität', 'Capacity'),
(103, 'Autorität', 'Authority'),
(104, 'Instanz', 'Instance'),
(105, 'Referenz', 'Reference'),
(106, 'Maßstab', 'Benchmark'),
(107, 'Vorbild', 'Role Model'),
(108, 'Wegweiser', 'Guidepost'),
(109, 'Pionier', 'Pioneer'),
(110, 'Veteran', 'Veteran'),
(111, 'Altgedienter', 'Old Hand'),
(112, 'Haudegen', 'Warhorse'),
(113, 'Schlachtross', 'Battle Charger'),
(114, 'Überlebender', 'Survivor'),
(115, 'Abgehärteter', 'Hardened'),
(116, 'Unerschütterlicher', 'Unshakable'),
(117, 'Standhafter', 'Steadfast'),
(118, 'Eiserner', 'Ironclad'),
(119, 'Unbeugsamer', 'Indomitable'),
(120, 'Meister', 'Master'),
(121, 'Lehrmeister', 'Grand Tutor'),
(122, 'Zuchtmeister', 'Taskmaster'),
(123, 'Schulmeister', 'Schoolmaster'),
(124, 'Werkmeister', 'Guild Craftsman'),
(125, 'Gildenmeister', 'Guildmaster'),
(126, 'Ordensmeister', 'Order Master'),
(127, 'Logenmeister', 'Lodge Master'),
(128, 'Ratsmeister', 'Council Master'),
(129, 'Ehrenmeister', 'Honorary Master'),
(130, 'Virtuose', 'Virtuoso'),
(131, 'Künstler', 'Artist'),
(132, 'Feingeist', 'Refined Spirit'),
(133, 'Ästhet', 'Aesthete'),
(134, 'Perfektionist', 'Perfectionist'),
(135, 'Vollender', 'Completer'),
(136, 'Meisterhand', 'Master Hand'),
(137, 'Wunderkind', 'Prodigy'),
(138, 'Ausnahmetalent', 'Exceptional Talent'),
(139, 'Jahrhunderttalent', 'Century Talent'),
(140, 'Elite', 'Elite'),
(141, 'Auserwählter', 'Chosen'),
(142, 'Berufener', 'Destined'),
(143, 'Herausragender', 'Preeminent'),
(144, 'Überlegener', 'Superior'),
(145, 'Spitzenreiter', 'Frontrunner'),
(146, 'Vorreiter', 'Trailblazer'),
(147, 'Anführer', 'Leader'),
(148, 'Kommandant', 'Commander'),
(149, 'Feldherr', 'Warlord'),
(150, 'Großmeister', 'Grandmaster'),
(151, 'Erzmeister', 'Archmaster'),
(152, 'Hochmeister', 'High Master'),
(153, 'Oberhaupt', 'Chief'),
(154, 'Patriarch', 'Patriarch'),
(155, 'Doyen', 'Doyen'),
(156, 'Altmeister', 'Old Master'),
(157, 'Übermeister', 'Overmaster'),
(158, 'Großstratege', 'Grand Strategist'),
(159, 'Meisterdenker', 'Master Thinker'),
(160, 'Champion', 'Champion'),
(161, 'Titelträger', 'Titleholder'),
(162, 'Sieger', 'Victor'),
(163, 'Triumphator', 'Triumphator'),
(164, 'Gewinner', 'Winner'),
(165, 'Überwinder', 'Overcomer'),
(166, 'Bezwinger', 'Vanquisher'),
(167, 'Eroberer', 'Conqueror'),
(168, 'Unterwerfer', 'Subjugator'),
(169, 'Herrscher', 'Ruler'),
(170, 'Held', 'Hero'),
(171, 'Volksheld', 'Folk Hero'),
(172, 'Retter', 'Savior'),
(173, 'Beschützer', 'Protector'),
(174, 'Wächter', 'Guardian'),
(175, 'Hüter', 'Keeper'),
(176, 'Schildträger', 'Shieldbearer'),
(177, 'Schwertträger', 'Swordbearer'),
(178, 'Bannerträger', 'Bannerbearer'),
(179, 'Lichtbringer', 'Lightbringer'),
(180, 'Ikone', 'Icon'),
(181, 'Idol', 'Idol'),
(182, 'Vorzeigefigur', 'Figurehead'),
(183, 'Ruhmesträger', 'Glorybearer'),
(184, 'Ehrenträger', 'Honorbearer'),
(185, 'Würdenträger', 'Dignitary'),
(186, 'Gekröntes Haupt', 'Crowned Head'),
(187, 'Hoheit', 'Highness'),
(188, 'Majestät', 'Majesty'),
(189, 'Souverän', 'Sovereign'),
(190, 'Legende', 'Legend'),
(191, 'Lebende Legende', 'Living Legend'),
(192, 'Unvergessener', 'Unforgotten'),
(193, 'Verewigter', 'Immortalized'),
(194, 'Ruhmreicher', 'Glorious'),
(195, 'Glorreicher', 'Illustrious'),
(196, 'Strahlender', 'Radiant'),
(197, 'Erleuchteter', 'Enlightened'),
(198, 'Weiser', 'Sage'),
(199, 'Orakel', 'Oracle'),
(200, 'Mythos', 'Myth'),
(201, 'Fabelwesen', 'Mythic Being'),
(202, 'Sagenfigur', 'Fabled Figure'),
(203, 'Phantom', 'Phantom'),
(204, 'Schattenläufer', 'Shadowwalker'),
(205, 'Schicksalsweber', 'Fateweaver'),
(206, 'Weltenwanderer', 'Worldwalker'),
(207, 'Zeitloser', 'Timeless'),
(208, 'Ewiger', 'Eternal'),
(209, 'Unendlicher', 'Infinite'),
(210, 'Unbesiegbarer', 'Invincible'),
(211, 'Unbezwingbarer', 'Unconquerable'),
(212, 'Unantastbarer', 'Untouchable'),
(213, 'Unfehlbarer', 'Infallible'),
(214, 'Allwissender', 'Omniscient'),
(215, 'Allsehender', 'All-Seeing'),
(216, 'Allmächtiger', 'Almighty'),
(217, 'Schöpfer', 'Maker of Realms'),
(218, 'Weltenformer', 'Worldshaper'),
(219, 'Kosmoswächter', 'Cosmos Warden'),
(220, 'Titan', 'Titan'),
(221, 'Gigant', 'Giant'),
(222, 'Koloss', 'Colossus'),
(223, 'Urgewalt', 'Primal Force'),
(224, 'Naturgewalt', 'Force of Nature'),
(225, 'Sturmbringer', 'Stormbringer'),
(226, 'Weltenbrecher', 'Worldbreaker'),
(227, 'Sternengucker', 'Stargazer'),
(228, 'Sternenwanderer', 'Starwalker'),
(229, 'Sternenschmied', 'Starforger'),
(230, 'Halbgott', 'Demigod'),
(231, 'Götterbote', 'Herald of Gods'),
(232, 'Götterliebling', 'Gods'' Favored'),
(233, 'Göttergleicher', 'Godlike'),
(234, 'Himmelsstürmer', 'Skybreaker'),
(235, 'Sphärenwandler', 'Spherewalker'),
(236, 'Ätherweber', 'Aetherweaver'),
(237, 'Astralreisender', 'Astral Traveler'),
(238, 'Lichtgestalt', 'Light Being'),
(239, 'Transzendenter', 'Transcendent'),
(240, 'Unsterblicher', 'Immortal'),
(241, 'Erhabener', 'Exalted'),
(242, 'Geweihter', 'Consecrated'),
(243, 'Gesegneter', 'Blessed'),
(244, 'Heiliger', 'Saint'),
(245, 'Prophet', 'Prophet'),
(246, 'Erlöser', 'Redeemer'),
(247, 'Avatar', 'Avatar'),
(248, 'Inkarnation', 'Incarnation'),
(249, 'Manifestation', 'Manifestation'),
(250, 'Ursprung', 'Origin'),
(251, 'Anfang und Ende', 'Beginning and End'),
(252, 'Alpha', 'Alpha'),
(253, 'Omega', 'Omega'),
(254, 'Paradoxon', 'Paradox'),
(255, 'Singularität', 'Singularity'),
(256, 'Absolutum', 'Absolute'),
(257, 'Übergott', 'Overgod'),
(258, 'Schöpfergeist', 'Creator Spirit'),
(259, 'Gottheit', 'Deity');

View File

@ -1,300 +1,5 @@
-- 01_allgemein.sql
-- Basis-Tabellen, Prestige-Ränge (0..259) & globale Übersetzungen (DE/EN)
DROP TABLE IF EXISTS base_i18n;
DROP TABLE IF EXISTS base_prestige_ranks;
DROP TABLE IF EXISTS game_variants;
CREATE TABLE base_i18n (
key TEXT NOT NULL,
lang TEXT NOT NULL,
val TEXT NOT NULL,
PRIMARY KEY (key, lang)
);
CREATE TABLE base_prestige_ranks (
rank_idx INTEGER PRIMARY KEY,
title_de TEXT NOT NULL,
title_en TEXT NOT NULL
);
CREATE TABLE game_variants (
id INTEGER PRIMARY KEY,
folder_path TEXT NOT NULL,
game_name TEXT NOT NULL,
variant_key TEXT UNIQUE NOT NULL,
display_name TEXT NOT NULL
);
-- =========================================================================
-- PRESTIGE-RÄNGE (0..258 in I-V, 259 = Gottheit)
-- =========================================================================
INSERT INTO base_prestige_ranks (rank_idx, title_de, title_en) VALUES
(0, 'Erst-Starter', 'First-Starter'),
(1, 'Küken', 'Hatchling'),
(2, 'Frischling', 'Fledgling'),
(3, 'Grünschnabel', 'Greenhorn'),
(4, 'Ahnungsloser', 'Clueless'),
(5, 'Zuschauer', 'Spectator'),
(6, 'Zaungast', 'Bystander'),
(7, 'Mitläufer', 'Follower'),
(8, 'Stolperer', 'Stumbler'),
(9, 'Tapsiger', 'Fumbler'),
(10, 'Schnupperer', 'Dabbler'),
(11, 'Probierer', 'Taster'),
(12, 'Neugieriger', 'Curious'),
(13, 'Sucher', 'Seeker'),
(14, 'Tastender', 'Feeler'),
(15, 'Lerner', 'Learner'),
(16, 'Anfänger', 'Beginner'),
(17, 'Neuling', 'Newcomer'),
(18, 'Einsteiger', 'Entrant'),
(19, 'Debütant', 'Debutant'),
(20, 'Auszubildender', 'Trainee'),
(21, 'Praktikant', 'Intern'),
(22, 'Lehrling', 'Apprentice'),
(23, 'Schüler', 'Pupil'),
(24, 'Jungspund', 'Youngster'),
(25, 'Zögling', 'Protege'),
(26, 'Anwärter', 'Candidate'),
(27, 'Aspirant', 'Aspirant'),
(28, 'Novize', 'Novice'),
(29, 'Initiand', 'Initiate'),
(30, 'Hilfskraft', 'Helper'),
(31, 'Handlanger', 'Henchman'),
(32, 'Zuarbeiter', 'Assistant'),
(33, 'Gehilfe', 'Aide'),
(34, 'Knappe', 'Squire'),
(35, 'Läufer', 'Runner'),
(36, 'Späher', 'Scout'),
(37, 'Kundschafter', 'Pathfinder'),
(38, 'Rekrut', 'Recruit'),
(39, 'Kadett', 'Cadet'),
(40, 'Aufsteiger', 'Riser'),
(41, 'Fortgeschrittener', 'Intermediate'),
(42, 'Geübter', 'Practiced'),
(43, 'Erprobter', 'Tested'),
(44, 'Bewährter', 'Proven'),
(45, 'Tauglicher', 'Capable'),
(46, 'Fähiger', 'Able'),
(47, 'Geschickter', 'Skillful'),
(48, 'Gewandter', 'Adroit'),
(49, 'Behender', 'Nimble'),
(50, 'Geselle', 'Journeyman'),
(51, 'Handwerker', 'Craftsman'),
(52, 'Schaffender', 'Creator'),
(53, 'Macher', 'Maker'),
(54, 'Praktiker', 'Practitioner'),
(55, 'Anwender', 'Applier'),
(56, 'Umsetzer', 'Implementer'),
(57, 'Ausführender', 'Executor'),
(58, 'Routinier', 'Regular'),
(59, 'Stammkraft', 'Mainstay'),
(60, 'Kenner', 'Connoisseur'),
(61, 'Wissender', 'Knower'),
(62, 'Kundiger', 'Versed'),
(63, 'Belesener', 'Erudite'),
(64, 'Gelehrter', 'Scholar'),
(65, 'Denker', 'Thinker'),
(66, 'Planer', 'Planner'),
(67, 'Rechner', 'Calculator'),
(68, 'Prüfer', 'Examiner'),
(69, 'Analytiker', 'Analyst'),
(70, 'Könner', 'Adept'),
(71, 'Fachkraft', 'Skilled Pro'),
(72, 'Fachmann', 'Professionalist'),
(73, 'Sachverständiger', 'Surveyor'),
(74, 'Berater', 'Advisor'),
(75, 'Spezialist', 'Specialist'),
(76, 'Techniker', 'Technician'),
(77, 'Methodiker', 'Methodist'),
(78, 'Systematiker', 'Systematist'),
(79, 'Präzisionsarbeiter', 'Precisionist'),
(80, 'Profi', 'Pro'),
(81, 'Berufsspieler', 'Pro Gambler'),
(82, 'Vollprofi', 'Full Pro'),
(83, 'Leistungsträger', 'Key Player'),
(84, 'Stütze', 'Support'),
(85, 'Säule', 'Pillar'),
(86, 'Garant', 'Guarantor'),
(87, 'Fels', 'Rock'),
(88, 'Anker', 'Anchor'),
(89, 'Rückgrat', 'Backbone'),
(90, 'Taktiker', 'Tactician'),
(91, 'Stratege', 'Strategist'),
(92, 'Fuchs', 'Fox'),
(93, 'Schlitzohr', 'Sharpster'),
(94, 'Stratege der Tiefe', 'Deep Strategist'),
(95, 'Drahtzieher', 'Mastermind'),
(96, 'Lenker', 'Steersman'),
(97, 'Leiter', 'Director'),
(98, 'Koordinator', 'Coordinator'),
(99, 'Regisseur', 'Conductor'),
(100, 'Experte', 'Expert'),
(101, 'Koryphäe', 'Luminary'),
(102, 'Kapazität', 'Capacity'),
(103, 'Autorität', 'Authority'),
(104, 'Instanz', 'Instance'),
(105, 'Referenz', 'Reference'),
(106, 'Maßstab', 'Benchmark'),
(107, 'Vorbild', 'Role Model'),
(108, 'Wegweiser', 'Guidepost'),
(109, 'Pionier', 'Pioneer'),
(110, 'Veteran', 'Veteran'),
(111, 'Altgedienter', 'Old Hand'),
(112, 'Haudegen', 'Warhorse'),
(113, 'Schlachtross', 'Battle Charger'),
(114, 'Überlebender', 'Survivor'),
(115, 'Abgehärteter', 'Hardened'),
(116, 'Unerschütterlicher', 'Unshakable'),
(117, 'Standhafter', 'Steadfast'),
(118, 'Eiserner', 'Ironclad'),
(119, 'Unbeugsamer', 'Indomitable'),
(120, 'Meister', 'Master'),
(121, 'Lehrmeister', 'Grand Tutor'),
(122, 'Zuchtmeister', 'Taskmaster'),
(123, 'Schulmeister', 'Schoolmaster'),
(124, 'Werkmeister', 'Guild Craftsman'),
(125, 'Gildenmeister', 'Guildmaster'),
(126, 'Ordensmeister', 'Order Master'),
(127, 'Logenmeister', 'Lodge Master'),
(128, 'Ratsmeister', 'Council Master'),
(129, 'Ehrenmeister', 'Honorary Master'),
(130, 'Virtuose', 'Virtuoso'),
(131, 'Künstler', 'Artist'),
(132, 'Feingeist', 'Refined Spirit'),
(133, 'Ästhet', 'Aesthete'),
(134, 'Perfektionist', 'Perfectionist'),
(135, 'Vollender', 'Completer'),
(136, 'Meisterhand', 'Master Hand'),
(137, 'Wunderkind', 'Prodigy'),
(138, 'Ausnahmetalent', 'Exceptional Talent'),
(139, 'Jahrhunderttalent', 'Century Talent'),
(140, 'Elite', 'Elite'),
(141, 'Auserwählter', 'Chosen'),
(142, 'Berufener', 'Destined'),
(143, 'Herausragender', 'Preeminent'),
(144, 'Überlegener', 'Superior'),
(145, 'Spitzenreiter', 'Frontrunner'),
(146, 'Vorreiter', 'Trailblazer'),
(147, 'Anführer', 'Leader'),
(148, 'Kommandant', 'Commander'),
(149, 'Feldherr', 'Warlord'),
(150, 'Großmeister', 'Grandmaster'),
(151, 'Erzmeister', 'Archmaster'),
(152, 'Hochmeister', 'High Master'),
(153, 'Oberhaupt', 'Chief'),
(154, 'Patriarch', 'Patriarch'),
(155, 'Doyen', 'Doyen'),
(156, 'Altmeister', 'Old Master'),
(157, 'Übermeister', 'Overmaster'),
(158, 'Großstratege', 'Grand Strategist'),
(159, 'Meisterdenker', 'Master Thinker'),
(160, 'Champion', 'Champion'),
(161, 'Titelträger', 'Titleholder'),
(162, 'Sieger', 'Victor'),
(163, 'Triumphator', 'Triumphator'),
(164, 'Gewinner', 'Winner'),
(165, 'Überwinder', 'Overcomer'),
(166, 'Bezwinger', 'Vanquisher'),
(167, 'Eroberer', 'Conqueror'),
(168, 'Unterwerfer', 'Subjugator'),
(169, 'Herrscher', 'Ruler'),
(170, 'Held', 'Hero'),
(171, 'Volksheld', 'Folk Hero'),
(172, 'Retter', 'Savior'),
(173, 'Beschützer', 'Protector'),
(174, 'Wächter', 'Guardian'),
(175, 'Hüter', 'Keeper'),
(176, 'Schildträger', 'Shieldbearer'),
(177, 'Schwertträger', 'Swordbearer'),
(178, 'Bannerträger', 'Bannerbearer'),
(179, 'Lichtbringer', 'Lightbringer'),
(180, 'Ikone', 'Icon'),
(181, 'Idol', 'Idol'),
(182, 'Vorzeigefigur', 'Figurehead'),
(183, 'Ruhmesträger', 'Glorybearer'),
(184, 'Ehrenträger', 'Honorbearer'),
(185, 'Würdenträger', 'Dignitary'),
(186, 'Gekröntes Haupt', 'Crowned Head'),
(187, 'Hoheit', 'Highness'),
(188, 'Majestät', 'Majesty'),
(189, 'Souverän', 'Sovereign'),
(190, 'Legende', 'Legend'),
(191, 'Lebende Legende', 'Living Legend'),
(192, 'Unvergessener', 'Unforgotten'),
(193, 'Verewigter', 'Immortalized'),
(194, 'Ruhmreicher', 'Glorious'),
(195, 'Glorreicher', 'Illustrious'),
(196, 'Strahlender', 'Radiant'),
(197, 'Erleuchteter', 'Enlightened'),
(198, 'Weiser', 'Sage'),
(199, 'Orakel', 'Oracle'),
(200, 'Mythos', 'Myth'),
(201, 'Fabelwesen', 'Mythic Being'),
(202, 'Sagenfigur', 'Fabled Figure'),
(203, 'Phantom', 'Phantom'),
(204, 'Schattenläufer', 'Shadowwalker'),
(205, 'Schicksalsweber', 'Fateweaver'),
(206, 'Weltenwanderer', 'Worldwalker'),
(207, 'Zeitloser', 'Timeless'),
(208, 'Ewiger', 'Eternal'),
(209, 'Unendlicher', 'Infinite'),
(210, 'Unbesiegbarer', 'Invincible'),
(211, 'Unbezwingbarer', 'Unconquerable'),
(212, 'Unantastbarer', 'Untouchable'),
(213, 'Unfehlbarer', 'Infallible'),
(214, 'Allwissender', 'Omniscient'),
(215, 'Allsehender', 'All-Seeing'),
(216, 'Allmächtiger', 'Almighty'),
(217, 'Schöpfer', 'Maker of Realms'),
(218, 'Weltenformer', 'Worldshaper'),
(219, 'Kosmoswächter', 'Cosmos Warden'),
(220, 'Titan', 'Titan'),
(221, 'Gigant', 'Giant'),
(222, 'Koloss', 'Colossus'),
(223, 'Urgewalt', 'Primal Force'),
(224, 'Naturgewalt', 'Force of Nature'),
(225, 'Sturmbringer', 'Stormbringer'),
(226, 'Weltenbrecher', 'Worldbreaker'),
(227, 'Sternengucker', 'Stargazer'),
(228, 'Sternenwanderer', 'Starwalker'),
(229, 'Sternenschmied', 'Starforger'),
(230, 'Halbgott', 'Demigod'),
(231, 'Götterbote', 'Herald of Gods'),
(232, 'Götterliebling', 'Gods'' Favored'),
(233, 'Göttergleicher', 'Godlike'),
(234, 'Himmelsstürmer', 'Skybreaker'),
(235, 'Sphärenwandler', 'Spherewalker'),
(236, 'Ätherweber', 'Aetherweaver'),
(237, 'Astralreisender', 'Astral Traveler'),
(238, 'Lichtgestalt', 'Light Being'),
(239, 'Transzendenter', 'Transcendent'),
(240, 'Unsterblicher', 'Immortal'),
(241, 'Erhabener', 'Exalted'),
(242, 'Geweihter', 'Consecrated'),
(243, 'Gesegneter', 'Blessed'),
(244, 'Heiliger', 'Saint'),
(245, 'Prophet', 'Prophet'),
(246, 'Erlöser', 'Redeemer'),
(247, 'Avatar', 'Avatar'),
(248, 'Inkarnation', 'Incarnation'),
(249, 'Manifestation', 'Manifestation'),
(250, 'Ursprung', 'Origin'),
(251, 'Anfang und Ende', 'Beginning and End'),
(252, 'Alpha', 'Alpha'),
(253, 'Omega', 'Omega'),
(254, 'Paradoxon', 'Paradox'),
(255, 'Singularität', 'Singularity'),
(256, 'Absolutum', 'Absolute'),
(257, 'Übergott', 'Overgod'),
(258, 'Schöpfergeist', 'Creator Spirit'),
(259, 'Gottheit', 'Deity');
-- =========================================================================
-- ALLGEMEINE ÜBERSETZUNGEN (Menüs, Kategorien, Einstellungen, Bots, Statistik)
-- =========================================================================
-- Globale Übersetzungen (Menüs, Kategorien, Einstellungen, Bots, Statistik, Online & Fehler)
INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('app_title', 'DE', 'The Goth Cardgame Collection'),
@ -341,6 +46,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('btn_back_game_menu', 'EN', 'Game Menu'),
('btn_back_main', 'DE', 'Hauptmenü'),
('btn_back_main', 'EN', 'Main Menu'),
('btn_back_stats_hub', 'DE', 'Spielauswahl'),
('btn_back_stats_hub', 'EN', 'Game Selection'),
('btn_lang', 'DE', 'Sprache: DE'),
('btn_lang', 'EN', 'Lang: EN'),
('btn_settings', 'DE', 'Einstellungen'),
@ -349,12 +56,18 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('btn_stats', 'EN', 'Statistics'),
('btn_switch_profile', 'DE', 'Profil wechseln'),
('btn_switch_profile', 'EN', 'Switch Profile'),
('cat_bavarian', 'DE', 'Bayerische Spiele'),
('cat_bavarian', 'EN', 'Bavarian Games'),
('cat_desc_bavarian', 'DE', 'Traditionelle Stich- und Wirtshausspiele mit dem 36er Bayerischen Blatt.'),
('cat_desc_bavarian', 'EN', 'Traditional trick-taking & tavern card games played with the 36-card Bavarian deck.'),
('cat_desc_luck', 'DE', 'Harte Konsequenzen: Goldbeutel, Tischeinsätze, Divine Punishment & The Devil''s Deal.'),
('cat_desc_luck', 'EN', 'Harsh consequences: Gold pouches, table stakes, Divine Punishment & The Devil''s Deal.'),
('cat_desc_online', 'DE', 'Kein Welpenschutz: Echte Gegner & entfesselte Bots auf Gottheit-Niveau!'),
('cat_desc_online', 'EN', 'No hand-holding: Real opponents & unleashed bots operating at Deity rank!'),
('cat_desc_party_offline', 'DE', 'Klassische Gesellschaftsrunden am lokalen Tisch gegen KI-Charaktere.'),
('cat_desc_party_offline', 'EN', 'Classic parlor card games at the local table against AI personalities.'),
('cat_desc_solitaire', 'DE', 'Garantiert lösbare Solitaire-Varianten - Bestzeiten, Serien und spielgebundene Ränge.'),
('cat_desc_solitaire', 'EN', 'Guaranteed solvable Solitaire variants - best times, streaks, and per-game ranks.'),
('cat_desc_solo', 'DE', 'Reines Kalkül gegen das Deck - eigene Fortschritts- und Rückstufungsregeln ohne Gold-Zwang.'),
('cat_desc_solo', 'EN', 'Pure calculation against the deck - dedicated progression & demotion rules without Gold.'),
('cat_luck', 'DE', 'Glück'),
@ -363,6 +76,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('cat_online', 'EN', 'Online'),
('cat_party_offline', 'DE', 'Gesellschaft - Offline'),
('cat_party_offline', 'EN', 'Party - Offline'),
('cat_solitaire', 'DE', 'Solitaire'),
('cat_solitaire', 'EN', 'Solitaire'),
('cat_solo', 'DE', 'Solo'),
('cat_solo', 'EN', 'Solo'),
('choose_cardgame', 'DE', 'Wähle ein Kartenspiel'),
@ -375,8 +90,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('devils_deal_resume_desc', 'EN', 'Your soul is bound to the table. Other games are locked until the pact is resolved!'),
('devils_deal_resume_title', 'DE', 'THE DEVIL''S DEAL AKTIV'),
('devils_deal_resume_title', 'EN', 'THE DEVIL''S DEAL ACTIVE'),
('filter_all_games', 'DE', 'Alle Spiele'),
('filter_all_games', 'EN', 'All Games'),
('filter_all_games', 'DE', 'Alle Varianten'),
('filter_all_games', 'EN', 'All Variants'),
('header_title', 'DE', 'GOTH CARD COLLECTION'),
('header_title', 'EN', 'GOTH CARD COLLECTION'),
('level_badge', 'DE', '{0} | {1} (Lv. {2} | {3}/{4} XP)'),
@ -419,24 +134,26 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('stat_win_pct', 'EN', 'Win Rate %'),
('stat_won', 'DE', 'Gewonnene Spiele'),
('stat_won', 'EN', 'Games Won'),
('stats_account_title', 'DE', 'Profil-Statistik: {0}'),
('stats_account_title', 'EN', 'Profile Statistics: {0}'),
('stats_all_variants_of_game', 'DE', 'Alle {0}-Spiele (Gesamt)'),
('stats_all_variants_of_game', 'EN', 'All {0} Games (Total)'),
('stats_account_title', 'DE', 'Spiel-Statistik: {0}'),
('stats_account_title', 'EN', 'Game Statistics: {0}'),
('stats_all_variants_of_game', 'DE', 'Alle {0}-Varianten (Gesamt)'),
('stats_all_variants_of_game', 'EN', 'All {0} Variants (Total)'),
('stats_game_board_title', 'DE', 'Statistik für {0}'),
('stats_game_board_title', 'EN', 'Statistics for {0}'),
('stats_game_rank_info', 'DE', 'Dein Rang in {0}: {1} - Stufe {2} ({3} / {4} XP)'),
('stats_game_rank_info', 'EN', 'Your Rank in {0}: {1} - Level {2} ({3} / {4} XP)'),
('stats_overall_summary', 'DE', 'Gesamtübersicht für Profil ''{0}'' (Alle Spiele)'),
('stats_overall_summary', 'EN', 'Overall Summary for Profile ''{0}'' (All Games)'),
('stats_hub_subtitle', 'DE', 'Wähle eine Spielgruppe und anschließend das gewünschte Kartenspiel zur Detail-Auswertung.'),
('stats_hub_subtitle', 'EN', 'Select a game group and pick a card game to inspect its dedicated statistics.'),
('stats_overall_summary', 'DE', 'Spielauswahl Statistik ({0})'),
('stats_overall_summary', 'EN', 'Statistics Game Selection ({0})'),
('stats_pouch_lbl', 'DE', 'Konto:'),
('stats_pouch_lbl', 'EN', 'Pouch:'),
('stats_profile_total_tab', 'DE', 'Profil (Gesamt)'),
('stats_profile_total_tab', 'EN', 'Profile (Total)'),
('stats_profile_total_tab', 'DE', 'Profil (Spiel)'),
('stats_profile_total_tab', 'EN', 'Profile (Game)'),
('stats_select_game_lbl', 'DE', 'Spiel auswählen:'),
('stats_select_game_lbl', 'EN', 'Select Game:'),
('stats_view_topbar', 'DE', 'Spiel-Statistiken ({0})'),
('stats_view_topbar', 'EN', 'Game Statistics ({0})'),
('stats_view_topbar', 'DE', 'Statistiken - {0}'),
('stats_view_topbar', 'EN', 'Statistics - {0}'),
('xp_next_level', 'DE', '{0} / {1} XP bis Lv. {2}'),
('xp_next_level', 'EN', '{0} / {1} XP to Lv. {2}'),
('settings_hover_help_desc', 'DE', 'Erklärungen beim Überfahren von Aktions-Buttons'),

Binary file not shown.

Before

Width:  |  Height:  |  Size: 182 KiB

View File

@ -2,29 +2,21 @@
# view/assets_manager.py
from __future__ import annotations
import re
import tkinter as tk
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageFont, ImageTk
import tkinter as tk
from PIL import Image, ImageChops, ImageDraw, ImageTk
from models.resource_manager import ResourceManager
from resources.code_res.game_constants import (
FONTS_REL_DIR,
CARD_FILE_PATTERN,
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,
)
from view.goth_text_renderer import GothTextRenderer
BOX_SOURCE_CORNER_RATIO = {
"box_big": 0.16,
@ -42,8 +34,6 @@ BOX_TARGET_CORNER_SPEC = {
"dropdown_box": (0.10, 10, 18),
}
_ALL_CAPS_WORD_RE = re.compile(r"\b[A-ZÄÖÜ]{4,}\b")
def _clean_box_matte_fast(pil_img: Image.Image | None, hollow_center: bool = True) -> Image.Image | None:
if pil_img is None:
@ -70,7 +60,6 @@ def _clean_box_matte_fast(pil_img: Image.Image | None, hollow_center: bool = Tru
if changed:
ext_alpha = seed_img.point(lambda p: 0 if p == 128 else 255)
rgba.putalpha(ImageChops.darker(a, ext_alpha))
return rgba
@ -82,9 +71,9 @@ class AssetManager:
self._tk_cache: dict = {}
self._pil_cache: dict = {}
self._raw_card_cache: dict[str, Image.Image | None] = {}
self._font_cache: dict[tuple[bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
self._bg_scaled_key: tuple[bool, int, int] | None = None
self._bg_scaled_pil: Image.Image | None = None
self._text_renderer = GothTextRenderer(root_dir, self._pil_cache, self._tk_cache)
self.raw_bg_horizontal = self._load_ui_flexible("bg_horizontal", "background_horizontal")
self.raw_bg_vertical = self._load_ui_flexible("bg_vertical", "background_vertical")
@ -175,26 +164,21 @@ class AssetManager:
for attr in ("raw_btn_default", "raw_btn_purple", "raw_btn_fire"):
img = getattr(self, attr, None)
if img is not None and img.height > btn_cap_h:
ratio = btn_cap_h / img.height
nw = max(1, int(round(img.width * ratio)))
nw = max(1, int(round(img.width * (btn_cap_h / img.height))))
setattr(self, attr, img.resize((nw, btn_cap_h), Image.Resampling.LANCZOS))
if max(sw, sh) >= 2500:
return
max_bg_w = int(sw * 1.15)
max_bg_h = int(sh * 1.15)
max_bg_w, max_bg_h = int(sw * 1.15), int(sh * 1.15)
for attr in ("raw_bg_horizontal", "raw_bg_vertical", "raw_bg", "raw_poker_table"):
img = getattr(self, attr, None)
if img is not None and (img.width > max_bg_w or img.height > max_bg_h):
ratio = min(max_bg_w / img.width, max_bg_h / img.height)
nw = max(1, int(round(img.width * ratio)))
nh = max(1, int(round(img.height * ratio)))
nw, nh = max(1, int(round(img.width * ratio))), max(1, int(round(img.height * ratio)))
setattr(self, attr, img.resize((nw, nh), Image.Resampling.LANCZOS))
# ------------------------------------------------------------------
# ZENTRALER HINTERGRUND-CACHE & MODAL-ABDUNKLUNG
# ------------------------------------------------------------------
# --- Hintergrund-Cache & Modal-Abdunklung ---
def get_window_bg_pil(self, rw: int, rh: int) -> Image.Image | None:
rw, rh = max(64, int(rw)), max(64, int(rh))
is_vert = bool(rh > rw and self.raw_bg_vertical is not None)
@ -211,13 +195,10 @@ class AssetManager:
self._bg_scaled_key = key
return self._bg_scaled_pil
def get_bg_patch_photo(
self, rw: int, rh: int, ox: int, oy: int, w: int, h: int
) -> ImageTk.PhotoImage | None:
def get_bg_patch_photo(self, rw: int, rh: int, ox: int, oy: int, w: int, h: int) -> ImageTk.PhotoImage | None:
w, h = max(1, int(w)), max(1, int(h))
rw, rh = max(w, int(rw)), max(h, int(rh))
ox = max(0, min(rw - w, int(ox)))
oy = max(0, min(rh - h, int(oy)))
ox, oy = max(0, min(rw - w, int(ox))), max(0, min(rh - h, int(oy)))
tk_key = ("bg_patch", rw, rh, ox, oy, w, h)
if tk_key in self._tk_cache:
@ -232,18 +213,11 @@ class AssetManager:
for k in stale[:-12]:
self._tk_cache.pop(k, None)
cropped = base.crop((ox, oy, ox + w, oy + h))
photo = ImageTk.PhotoImage(cropped)
photo = ImageTk.PhotoImage(base.crop((ox, oy, ox + w, oy + h)))
self._tk_cache[tk_key] = photo
return photo
def get_dim_veil_photo(
self, width: int, height: int, alpha: int = 148
) -> ImageTk.PhotoImage:
"""
Erzeugt einen halbtransparenten RGBA-Abdunklungsschleier für gesperrte Spieltische,
sodass Karten und Tischdetails darunter gedimmt/ausgegraut sichtbar bleiben.
"""
def get_dim_veil_photo(self, width: int, height: int, alpha: int = 148) -> ImageTk.PhotoImage:
w, h = max(8, int(width)), max(8, int(height))
a = max(0, min(240, int(alpha)))
tk_key = ("dim_veil", w, h, a)
@ -251,94 +225,14 @@ class AssetManager:
stale = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "dim_veil"]
for k in stale[:-6]:
self._tk_cache.pop(k, None)
veil_pil = Image.new("RGBA", (w, h), (10, 8, 16, a))
self._tk_cache[tk_key] = ImageTk.PhotoImage(veil_pil)
self._tk_cache[tk_key] = ImageTk.PhotoImage(Image.new("RGBA", (w, h), (10, 8, 16, a)))
return self._tk_cache[tk_key]
# ------------------------------------------------------------------
# FONT-LOADER & OLD-LONDON TEXT-RENDERER (PIL RGBA)
# ------------------------------------------------------------------
def get_pil_font(self, size_px: int, alternate: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
size_px = max(12, int(size_px))
key = (alternate, size_px)
if key not in self._font_cache:
fname = FONT_FILE_ALTERNATE if alternate else FONT_FILE_PRIMARY
fpath = self.root_dir / FONTS_REL_DIR / fname
if not fpath.is_file():
fpath = self.root_dir / FONTS_REL_DIR / FONT_FILE_PRIMARY
try:
self._font_cache[key] = ImageFont.truetype(str(fpath), size_px)
except Exception:
self._font_cache[key] = ImageFont.load_default()
return self._font_cache[key]
# --- Delegatoren an GothTextRenderer ---
sanitize_goth_case = staticmethod(GothTextRenderer.sanitize_goth_case)
@staticmethod
def sanitize_goth_case(text: str) -> str:
if not text or not FONT_FORCE_MIXED_CASE:
return text
return _ALL_CAPS_WORD_RE.sub(lambda m: m.group(0).capitalize(), text)
def _measure_tracked_line(
self,
draw: ImageDraw.ImageDraw,
line: str,
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
letter_spacing: int,
) -> float:
if not line:
return 0.0
if letter_spacing == 0:
return float(draw.textlength(line, font=font))
adv_fn = draw.textlength
total = 0.0
for ch in line:
total += adv_fn(ch, font=font)
return total + letter_spacing * (len(line) - 1)
def _draw_tracked_line(
self,
draw: ImageDraw.ImageDraw,
x: float,
y: float,
line: str,
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
fill: str,
letter_spacing: int,
shadow_offset: tuple[int, int] | None,
outline_px: int,
):
if not line:
return
has_shadow = bool(FONT_SHADOW_ENABLED and shadow_offset and (shadow_offset[0] or shadow_offset[1]))
sx = shadow_offset[0] if (has_shadow and shadow_offset) else 0
sy = shadow_offset[1] if (has_shadow and shadow_offset) else 0
if letter_spacing == 0:
if has_shadow:
draw.text((x + sx, y + sy), line, font=font, fill=FONT_SHADOW_COLOR)
if outline_px > 0:
draw.text((x, y), line, font=font, fill=fill, stroke_width=outline_px, stroke_fill=FONT_OUTLINE_COLOR)
else:
draw.text((x, y), line, font=font, fill=fill)
return
adv_fn = draw.textlength
cur_x = x
for ch in line:
if has_shadow:
draw.text((cur_x + sx, y + sy), ch, font=font, fill=FONT_SHADOW_COLOR)
if outline_px > 0:
draw.text(
(cur_x, y),
ch,
font=font,
fill=fill,
stroke_width=outline_px,
stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((cur_x, y), ch, font=font, fill=fill)
cur_x += adv_fn(ch, font=font) + letter_spacing
def get_pil_font(self, size_px: int, alternate: bool = False):
return self._text_renderer.get_pil_font(size_px, alternate=alternate)
def render_goth_text_pil(
self,
@ -353,76 +247,9 @@ class AssetManager:
alternate: bool = False,
uncached: bool = False,
) -> Image.Image:
clean_text = self.sanitize_goth_case(str(text or ""))
cache_key = (
"goth_txt_pil", clean_text, size_px, color, max_width,
align, shadow_offset, outline_px, letter_spacing, alternate,
return self._text_renderer.render_pil(
text, size_px, color, max_width, align, shadow_offset, outline_px, letter_spacing, alternate, uncached
)
if not uncached and cache_key in self._pil_cache:
return self._pil_cache[cache_key]
font = self.get_pil_font(size_px, alternate=alternate)
dummy = Image.new("RGBA", (8, 8), (0, 0, 0, 0))
d_draw = ImageDraw.Draw(dummy)
raw_paragraphs = clean_text.split("\n")
lines: list[str] = []
for para in raw_paragraphs:
if not max_width or max_width <= 20 or not para.strip():
lines.append(para)
continue
words = para.split(" ")
cur = ""
for w in words:
cand = f"{cur} {w}".strip() if cur else w
if self._measure_tracked_line(d_draw, cand, font, letter_spacing) <= max_width or not cur:
cur = cand
else:
lines.append(cur)
cur = w
lines.append(cur)
if not lines:
lines = [""]
try:
ascent, descent = font.getmetrics() # type: ignore[attr-defined]
except Exception:
ascent, descent = size_px, max(6, size_px // 3)
base_line_h = max(size_px + 4, ascent + descent)
step_y = int(round(base_line_h * FONT_LINE_HEIGHT_FACTOR))
pad_x = max(6, outline_px * 2 + (abs(shadow_offset[0]) if shadow_offset else 0) + 4)
pad_top = max(6, outline_px * 2 + 4)
pad_bot = max(8, descent // 2 + outline_px * 2 + (abs(shadow_offset[1]) if shadow_offset else 0) + 6)
line_widths = [self._measure_tracked_line(d_draw, ln, font, letter_spacing) for ln in lines]
content_w = int(round(max(line_widths, default=1.0)))
img_w = max(4, content_w + pad_x * 2)
img_h = max(4, pad_top + base_line_h + max(0, len(lines) - 1) * step_y + pad_bot)
canvas_img = Image.new("RGBA", (img_w, img_h), (0, 0, 0, 0))
draw = ImageDraw.Draw(canvas_img)
for idx, (ln, lw) in enumerate(zip(lines, line_widths)):
if align == "left":
lx = float(pad_x)
elif align == "right":
lx = float(img_w - pad_x) - lw
else:
lx = (img_w - lw) / 2.0
ly = float(pad_top + idx * step_y + FONT_VERTICAL_OFFSET_PX)
self._draw_tracked_line(
draw, lx, ly, ln, font, color, letter_spacing, shadow_offset, outline_px
)
if not uncached:
if len(self._pil_cache) > 500:
txt_keys = [k for k in self._pil_cache if isinstance(k, tuple) and k and k[0] == "goth_txt_pil"]
for k in txt_keys[:150]:
self._pil_cache.pop(k, None)
self._pil_cache[cache_key] = canvas_img
return canvas_img
def get_goth_text_photo(
self,
@ -436,32 +263,11 @@ class AssetManager:
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,
return self._text_renderer.get_photo(
text, size_px, color, max_width, align, shadow_offset, outline_px, letter_spacing, alternate
)
if tk_key not in self._tk_cache:
pil_img = self.render_goth_text_pil(
text=text,
size_px=size_px,
color=color,
max_width=max_width,
align=align,
shadow_offset=shadow_offset,
outline_px=outline_px,
letter_spacing=letter_spacing,
alternate=alternate,
)
if len(self._tk_cache) > 500:
txt_keys = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "goth_txt_tk"]
for k in txt_keys[:150]:
self._tk_cache.pop(k, None)
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_img)
return self._tk_cache[tk_key]
# ------------------------------------------------------------------
# 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN
# ------------------------------------------------------------------
# --- 9-Slice Rahmen-Scaler ---
def get_9slice_pil(
self,
box_key: str,
@ -481,10 +287,8 @@ class AssetManager:
sw, sh = src.size
sc = max(12, int(round(min(sw, sh) * src_ratio)))
rel_target, min_dc, max_dc = BOX_TARGET_CORNER_SPEC.get(box_key, (0.14, 12, 36))
scaled_dc = int(round(min(tw, th) * rel_target * border_scale))
dc = max(min_dc, min(max_dc, scaled_dc))
dc = max(min_dc, min(max_dc, int(round(min(tw, th) * rel_target * border_scale))))
dc = min(dc, sc, tw // 2 - 1, th // 2 - 1)
if dc < 6:
@ -493,57 +297,35 @@ class AssetManager:
return out
out = Image.new("RGBA", (tw, th), (0, 0, 0, 0))
out.paste(src.crop((0, 0, sc, sc)).resize((dc, dc), Image.Resampling.LANCZOS), (0, 0))
out.paste(src.crop((sw - sc, 0, sw, sc)).resize((dc, dc), Image.Resampling.LANCZOS), (tw - dc, 0))
out.paste(src.crop((0, sh - sc, sc, sh)).resize((dc, dc), Image.Resampling.LANCZOS), (0, th - dc))
out.paste(src.crop((sw - sc, sh - sc, sw, sh)).resize((dc, dc), Image.Resampling.LANCZOS), (tw - dc, th - dc))
tl = src.crop((0, 0, sc, sc)).resize((dc, dc), Image.Resampling.LANCZOS)
tr = src.crop((sw - sc, 0, sw, sc)).resize((dc, dc), Image.Resampling.LANCZOS)
bl = src.crop((0, sh - sc, sc, sh)).resize((dc, dc), Image.Resampling.LANCZOS)
br = src.crop((sw - sc, sh - sc, sw, sh)).resize((dc, dc), Image.Resampling.LANCZOS)
out.paste(tl, (0, 0))
out.paste(tr, (tw - dc, 0))
out.paste(bl, (0, th - dc))
out.paste(br, (tw - dc, th - dc))
mid_w = tw - 2 * dc
mid_w, mid_h = tw - 2 * dc, th - 2 * dc
if mid_w > 0:
top_edge = src.crop((sc, 0, sw - sc, sc)).resize((mid_w, dc), Image.Resampling.BILINEAR)
bot_edge = src.crop((sc, sh - sc, sw - sc, sh)).resize((mid_w, dc), Image.Resampling.BILINEAR)
out.paste(top_edge, (dc, 0))
out.paste(bot_edge, (dc, th - dc))
mid_h = th - 2 * dc
out.paste(src.crop((sc, 0, sw - sc, sc)).resize((mid_w, dc), Image.Resampling.BILINEAR), (dc, 0))
out.paste(src.crop((sc, sh - sc, sw - sc, sh)).resize((mid_w, dc), Image.Resampling.BILINEAR), (dc, th - dc))
if mid_h > 0:
left_edge = src.crop((0, sc, sc, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR)
right_edge = src.crop((sw - sc, sc, sw, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR)
out.paste(left_edge, (0, dc))
out.paste(right_edge, (tw - dc, dc))
out.paste(src.crop((0, sc, sc, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR), (0, dc))
out.paste(src.crop((sw - sc, sc, sw, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR), (tw - dc, dc))
if mid_w > 0 and mid_h > 0 and box_key == "dropdown_box":
center_patch = src.crop((sc, sc, sw - sc, sh - sc)).resize((mid_w, mid_h), Image.Resampling.BILINEAR)
out.paste(center_patch, (dc, dc))
out.paste(src.crop((sc, sc, sw - sc, sh - sc)).resize((mid_w, mid_h), Image.Resampling.BILINEAR), (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,
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
)
pil_box = self.get_9slice_pil(box_key, size, corner_ratio=corner_ratio, border_scale=border_scale)
if pil_box is not None:
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_box)
return self._tk_cache.get(tk_key)
# ------------------------------------------------------------------
# KARTEN, BANNER & WIN/LOSE-GIFS MIT ALPHA-KANAL
# ------------------------------------------------------------------
# --- Karten, Banner & Animationen ---
def _get_raw_card_pil(self, path: Path | None) -> Image.Image | None:
if not path:
return None
@ -584,8 +366,7 @@ class AssetManager:
if not pil_img or target_width <= 10:
return None
src_w, src_h = pil_img.size
target_height = max(1, int(round(target_width * (src_h / src_w))))
return self.get_scaled_photo(name, pil_img, (target_width, target_height))
return self.get_scaled_photo(name, pil_img, (target_width, max(1, int(round(target_width * (src_h / src_w))))))
def get_gif_frames(self, key_or_filename: str, size=OUTCOME_GIF_SIZE) -> list[ImageTk.PhotoImage]:
cache_key = ("gif", key_or_filename, size)
@ -597,8 +378,7 @@ class AssetManager:
with Image.open(path) as gif:
idx = 0
while True:
frame = gif.copy().convert("RGBA").resize(size, Image.Resampling.BILINEAR)
frames.append(ImageTk.PhotoImage(frame))
frames.append(ImageTk.PhotoImage(gif.copy().convert("RGBA").resize(size, Image.Resampling.BILINEAR)))
idx += 1
gif.seek(idx)
except EOFError:
@ -611,10 +391,6 @@ class AssetManager:
def get_win_lose_gif_sequence(
self, stem_or_filename: str, size: tuple[int, int]
) -> tuple[list[ImageTk.PhotoImage], list[int]]:
"""
Lädt transparente RGBA-GIFs aus resources/images/win_lose/ inklusive ihrer
echten Frame-Dauern (ms) und cacht sie für verzögerungsfreie Partikel-Spawns.
"""
tw, th = max(24, int(size[0])), max(24, int(size[1]))
cache_key = ("win_lose_gif", stem_or_filename, (tw, th))
if cache_key in self._tk_cache:
@ -630,8 +406,7 @@ class AssetManager:
with Image.open(path) as gif:
idx = 0
while True:
dur = int(gif.info.get("duration", 65) or 65)
dur = max(35, min(200, dur))
dur = max(35, min(200, int(gif.info.get("duration", 65) or 65)))
raw_frames.append(gif.copy().convert("RGBA"))
raw_durs.append(dur)
idx += 1
@ -643,74 +418,62 @@ class AssetManager:
self._pil_cache[raw_pil_key] = (raw_frames, raw_durs)
src_frames, src_durs = self._pil_cache[raw_pil_key]
tk_frames = [
ImageTk.PhotoImage(fr.resize((tw, th), Image.Resampling.LANCZOS))
for fr in src_frames
]
result = (tk_frames, list(src_durs))
self._tk_cache[cache_key] = result
return result
tk_frames = [ImageTk.PhotoImage(fr.resize((tw, th), Image.Resampling.LANCZOS)) for fr in src_frames]
self._tk_cache[cache_key] = (tk_frames, list(src_durs))
return self._tk_cache[cache_key]
# ------------------------------------------------------------------
# STARTUP-PRELOADER
# ------------------------------------------------------------------
def preload_startup_assets(self, init_win_size: tuple[int, int] = (1280, 760), on_step=None):
from resources.code_res.game_constants import SUITS, RANKS
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton, _trim_button_art
from view.widgets.goth_dropdown import _trim_outer_black_bbox
def _notify(msg: str):
if callable(on_step):
on_step(msg)
_notify("Fonts...")
if callable(on_step):
on_step("Fonts...")
for px in (14, 15, 16, 18, 20, 22, 24, 26, 30, 34, 38):
self.get_pil_font(px, alternate=False)
_notify("Background...")
if callable(on_step):
on_step("Background...")
w, h = max(800, init_win_size[0]), max(600, init_win_size[1])
self.get_bg_patch_photo(w, h, 0, 0, w, h)
if self.raw_title is not None:
self.get_proportional_photo("title_main_header", self.raw_title, 265)
_notify("UI Controls...")
if callable(on_step):
on_step("UI Controls...")
for raw_b in (self.raw_btn_default, self.raw_btn_purple, self.raw_btn_fire):
if raw_b is not None:
_trim_button_art(raw_b)
for raw_dd in (
self.raw_dropdown_closed,
self.raw_dropdown_closed_btn,
self.raw_dropdown_open,
self.raw_dropdown_open_btn,
self.raw_dropdown_closed, self.raw_dropdown_closed_btn,
self.raw_dropdown_open, self.raw_dropdown_open_btn,
):
if raw_dd is not None:
_trim_outer_black_bbox(raw_dd)
dummy_root = tk._default_root
if dummy_root is not None and self.raw_btn_default is not None:
common_specs = [
for lbl, bw, bh in (
(t("btn_back_main"), 110, 32),
(t("btn_back_game_menu"), 108, 32),
(t("btn_stats"), 96, 32),
(t("btn_lang"), 96, 32),
(t("btn_settings"), 122, 32),
(t("btn_switch_profile"), 124, 34),
]
for lbl, bw, bh in common_specs:
):
tmp = ImageButton(
dummy_root, lbl, self.raw_btn_default, self.raw_btn_purple,
None, width=bw, height=bh, style="amethyst"
None, width=bw, height=bh, style="amethyst",
)
tmp._ensure_hover()
tmp.destroy()
_notify("Cards...")
if callable(on_step):
on_step("Cards...")
for suit in SUITS:
for rank in RANKS:
fname = f"{rank}_of_{suit}.png"
p = self.res.get_card_path(fname)
p = self.res.get_card_path(CARD_FILE_PATTERN.format(suit=suit, rank=rank))
if p and p.is_file():
self._get_raw_card_pil(p)
for back_col in ("Black", "Red", "Blue", "Purple", "Gold"):
@ -718,6 +481,5 @@ class AssetManager:
if bp and bp.is_file():
self._get_raw_card_pil(bp)
_notify("Animations...")
for wl_name in ("firework_start", "bat_explosion", "pumpkin_explosion", "foul_pumpkin"):
self.get_win_lose_gif_sequence(wl_name, (170, 170))
if callable(on_step):
on_step("Animations...")

235
view/goth_text_renderer.py Normal file
View File

@ -0,0 +1,235 @@
# -*- coding: utf-8 -*-
# view/goth_text_renderer.py
from __future__ import annotations
import re
from pathlib import Path
import tkinter as tk
from PIL import Image, ImageDraw, ImageFont, ImageTk
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,
)
_ALL_CAPS_WORD_RE = re.compile(r"\b[A-ZÄÖÜ]{4,}\b")
class GothTextRenderer:
"""Rendert mehrzeilige Old-London-Texte mit Tracking, Kontur und Schlagschatten als PIL/Tk-Grafik."""
def __init__(self, root_dir: Path, pil_cache: dict, tk_cache: dict):
self.root_dir = root_dir
self._pil_cache = pil_cache
self._tk_cache = tk_cache
self._font_cache: dict[tuple[bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
def get_pil_font(self, size_px: int, alternate: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
size_px = max(12, int(size_px))
key = (alternate, size_px)
if key not in self._font_cache:
fname = FONT_FILE_ALTERNATE if alternate else FONT_FILE_PRIMARY
fpath = self.root_dir / FONTS_REL_DIR / fname
if not fpath.is_file():
fpath = self.root_dir / FONTS_REL_DIR / FONT_FILE_PRIMARY
try:
self._font_cache[key] = ImageFont.truetype(str(fpath), size_px)
except Exception:
self._font_cache[key] = ImageFont.load_default()
return self._font_cache[key]
@staticmethod
def sanitize_goth_case(text: str) -> str:
if not text or not FONT_FORCE_MIXED_CASE:
return text
return _ALL_CAPS_WORD_RE.sub(lambda m: m.group(0).capitalize(), text)
@staticmethod
def measure_tracked_line(
draw: ImageDraw.ImageDraw,
line: str,
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
letter_spacing: int,
) -> float:
if not line:
return 0.0
if letter_spacing == 0:
return float(draw.textlength(line, font=font))
adv_fn = draw.textlength
total = 0.0
for ch in line:
total += adv_fn(ch, font=font)
return total + letter_spacing * (len(line) - 1)
@staticmethod
def draw_tracked_line(
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,
) -> None:
if not line:
return
has_shadow = bool(FONT_SHADOW_ENABLED and shadow_offset and (shadow_offset[0] or shadow_offset[1]))
sx = shadow_offset[0] if (has_shadow and shadow_offset) else 0
sy = shadow_offset[1] if (has_shadow and shadow_offset) else 0
if letter_spacing == 0:
if has_shadow:
draw.text((x + sx, y + sy), line, font=font, fill=FONT_SHADOW_COLOR)
if outline_px > 0:
draw.text((x, y), line, font=font, fill=fill, stroke_width=outline_px, stroke_fill=FONT_OUTLINE_COLOR)
else:
draw.text((x, y), line, font=font, fill=fill)
return
adv_fn = draw.textlength
cur_x = x
for ch in line:
if has_shadow:
draw.text((cur_x + sx, y + sy), ch, font=font, fill=FONT_SHADOW_COLOR)
if outline_px > 0:
draw.text(
(cur_x, y),
ch,
font=font,
fill=fill,
stroke_width=outline_px,
stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((cur_x, y), ch, font=font, fill=fill)
cur_x += adv_fn(ch, font=font) + letter_spacing
def render_pil(
self,
text: str,
size_px: int,
color: str = FONT_COLOR_BODY_DEFAULT,
max_width: int | None = None,
align: str = "center",
shadow_offset: tuple[int, int] | None = FONT_SHADOW_OFFSET_DEFAULT,
outline_px: int = FONT_OUTLINE_THICKNESS_PX,
letter_spacing: int = FONT_LETTER_SPACING_PX,
alternate: bool = False,
uncached: bool = False,
) -> Image.Image:
clean_text = self.sanitize_goth_case(str(text or ""))
cache_key = (
"goth_txt_pil", clean_text, size_px, color, max_width,
align, shadow_offset, outline_px, letter_spacing, alternate,
)
if not uncached and cache_key in self._pil_cache:
return self._pil_cache[cache_key]
font = self.get_pil_font(size_px, alternate=alternate)
dummy = Image.new("RGBA", (8, 8), (0, 0, 0, 0))
d_draw = ImageDraw.Draw(dummy)
lines: list[str] = []
for para in clean_text.split("\n"):
if not max_width or max_width <= 20 or not para.strip():
lines.append(para)
continue
cur = ""
for w in para.split(" "):
cand = f"{cur} {w}".strip() if cur else w
if self.measure_tracked_line(d_draw, cand, font, letter_spacing) <= max_width or not cur:
cur = cand
else:
lines.append(cur)
cur = w
lines.append(cur)
if not lines:
lines = [""]
try:
ascent, descent = font.getmetrics() # type: ignore[attr-defined]
except Exception:
ascent, descent = size_px, max(6, size_px // 3)
base_line_h = max(size_px + 4, ascent + descent)
step_y = int(round(base_line_h * FONT_LINE_HEIGHT_FACTOR))
pad_x = max(6, outline_px * 2 + (abs(shadow_offset[0]) if shadow_offset else 0) + 4)
pad_top = max(6, outline_px * 2 + 4)
pad_bot = max(8, descent // 2 + outline_px * 2 + (abs(shadow_offset[1]) if shadow_offset else 0) + 6)
line_widths = [self.measure_tracked_line(d_draw, ln, font, letter_spacing) for ln in lines]
content_w = int(round(max(line_widths, default=1.0)))
img_w = max(4, content_w + pad_x * 2)
img_h = max(4, pad_top + base_line_h + max(0, len(lines) - 1) * step_y + pad_bot)
canvas_img = Image.new("RGBA", (img_w, img_h), (0, 0, 0, 0))
draw = ImageDraw.Draw(canvas_img)
for idx, (ln, lw) in enumerate(zip(lines, line_widths)):
if align == "left":
lx = float(pad_x)
elif align == "right":
lx = float(img_w - pad_x) - lw
else:
lx = (img_w - lw) / 2.0
ly = float(pad_top + idx * step_y + FONT_VERTICAL_OFFSET_PX)
self.draw_tracked_line(
draw, lx, ly, ln, font, color, letter_spacing, shadow_offset, outline_px
)
if not uncached:
if len(self._pil_cache) > 500:
txt_keys = [k for k in self._pil_cache if isinstance(k, tuple) and k and k[0] == "goth_txt_pil"]
for k in txt_keys[:150]:
self._pil_cache.pop(k, None)
self._pil_cache[cache_key] = canvas_img
return canvas_img
def get_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_pil(
text=text,
size_px=size_px,
color=color,
max_width=max_width,
align=align,
shadow_offset=shadow_offset,
outline_px=outline_px,
letter_spacing=letter_spacing,
alternate=alternate,
)
if len(self._tk_cache) > 500:
txt_keys = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "goth_txt_tk"]
for k in txt_keys[:150]:
self._tk_cache.pop(k, None)
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_img)
return self._tk_cache[tk_key]

View File

@ -14,7 +14,6 @@ from resources.code_res.i18n import t
from view.assets_manager import AssetManager
from view.menus.login_view import LoginView
from view.menus.main_menu_view import MainMenuView
from view.menus.statistics_view import StatisticsView
from view.menus.settings_view import SettingsView
APP_WM_CLASS = "TheGothCardgameCollection"
@ -43,7 +42,6 @@ class GothCardCollectionView(tk.Tk):
self.bg_widget = None
self.login_view = LoginView(self)
self.main_menu_view = MainMenuView(self)
self.statistics_view = StatisticsView(self)
self.settings_view = SettingsView(self)
def _setup_global_ttk_styles(self):
@ -178,9 +176,6 @@ class GothCardCollectionView(tk.Tk):
def show_main_menu(self, profile: dict, available_games: list[dict], devils_resume_only: bool = False):
self.main_menu_view.show(profile, available_games, devils_resume_only=devils_resume_only)
def show_statistics(self, profile: dict):
self.statistics_view.show(profile)
def show_settings(
self,
on_back=None,

View File

@ -7,7 +7,6 @@ import tkinter as tk
from tkinter import filedialog
from models.database import Database
from models.db_locator import DbLocator
from resources.code_res.game_constants import (
BG_COLOR,
FONT_COLOR_BODY_MUTED,
@ -22,6 +21,7 @@ from resources.code_res.game_constants import (
USER_DB_FILENAME,
)
from resources.code_res.i18n import t
from view.menus.online_login_panel import OnlineLoginPanel
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
@ -36,14 +36,7 @@ class LoginView:
self.profile_var: tk.StringVar | None = None
self.new_name_var: tk.StringVar | None = None
self._online_url_var: tk.StringVar | None = None
self._online_ip_var: tk.StringVar | None = None
self._online_port_var: tk.StringVar | None = None
self._online_user_var: tk.StringVar | None = None
self._online_pass_var: tk.StringVar | None = None
self._login_mode: str = "local" # 'local' | 'online'
self._addr_mode: str = "url" # 'url' | 'ip'
self._login_mode: str = "local"
self._first_db_dir: Path = Database.get_user_db_dir()
self._status_msg: str = ""
self._status_is_error: bool = False
@ -53,21 +46,20 @@ class LoginView:
self._cv: tk.Canvas | None = None
self._dropdown: GothDropdown | None = None
self._btn_login: ImageButton | None = None
self._entry_new: GothEntry | None = None
self._entry_url: GothEntry | None = None
self._entry_ip: GothEntry | None = None
self._entry_port: GothEntry | None = None
self._entry_online_user: GothEntry | None = None
self._entry_online_pass: GothEntry | None = None
self._btn_create: ImageButton | None = None
self._btn_pick_first_dir: ImageButton | None = None
self._btn_load_existing_db: ImageButton | None = None
self._online_panel: OnlineLoginPanel | None = None
@staticmethod
def _shorten_path(p_str: str, max_chars: int = 48) -> str:
def _shorten_path(p_str: str, max_chars: int = 54) -> str:
if len(p_str) <= max_chars:
return p_str
keep = max_chars - 5
left = keep // 2 - 2
right = keep - left
return f"{p_str[:left]}...{p_str[-right:]}"
return f"{p_str[:left]}...{p_str[-(keep - left):]}"
def show(
self,
@ -86,90 +78,54 @@ class LoginView:
self._status_is_error = is_error
self._first_db_dir = Database.get_user_db_dir()
online_prefs = DbLocator.load_online_prefs()
self._addr_mode = "ip" if online_prefs.get("addr_mode") == "ip" else "url"
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._create_widgets(preselect_name, online_prefs)
self._create_widgets(preselect_name)
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)
self._draw_scene(max(800, cv.winfo_width()), max(600, cv.winfo_height()))
if self._login_mode == "local" and not self._profiles and self._entry_new is not None:
self._entry_new.entry.focus_set()
elif self._login_mode == "online" and self._entry_online_user is not None:
if not self._online_user_var.get().strip():
self._entry_online_user.entry.focus_set()
elif self._entry_online_pass is not None:
self._entry_online_pass.entry.focus_set()
elif self._login_mode == "online" and self._online_panel is not None:
self._online_panel.focus_default()
def _create_widgets(self, preselect_name: str, online_prefs: dict):
def _create_widgets(self, preselect_name: str):
cv = self._cv
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_norm, btn_purp = self.assets.raw_btn_default, self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
self._btn_audio = ImageButton(
cv,
t("btn_settings"),
btn_norm,
btn_purp,
lambda: self.ctrl.show_settings(
on_back=lambda: self.ctrl.start(login_mode=self._login_mode)
),
sound_mgr=self.sounds,
width=126,
height=34,
style="amethyst",
self._btn_settings = ImageButton(
cv, t("btn_settings"), btn_norm, btn_purp,
lambda: self.ctrl.show_settings(on_back=lambda: self.ctrl.start(login_mode=self._login_mode)),
sound_mgr=self.sounds, width=126, height=34, style="amethyst",
)
# Modus-Tabs: [Lokales Profil] vs. [Online-Account]
is_loc = (self._login_mode == "local")
self._btn_tab_local = ImageButton(
cv,
t("login_mode_local"),
btn_fire if is_loc else btn_norm,
btn_fire if is_loc else btn_purp,
cv, t("login_mode_local"),
btn_fire if is_loc else btn_norm, btn_fire if is_loc else btn_purp,
lambda: self._switch_login_mode("local"),
sound_mgr=self.sounds,
width=212,
height=34,
style="fire" if is_loc else "amethyst",
sound_mgr=self.sounds, width=212, height=34, style="fire" if is_loc else "amethyst",
)
self._btn_tab_online = ImageButton(
cv,
t("login_mode_online"),
btn_fire if not is_loc else btn_norm,
btn_fire if not is_loc else btn_purp,
cv, t("login_mode_online"),
btn_fire if not is_loc else btn_norm, btn_fire if not is_loc else btn_purp,
lambda: self._switch_login_mode("online"),
sound_mgr=self.sounds,
width=212,
height=34,
style="fire" if not is_loc else "amethyst",
sound_mgr=self.sounds, width=212, height=34, style="fire" if not is_loc else "amethyst",
)
# --- LOKALE ELEMENTE ---
self._dropdown = None
self._btn_login = None
self._dropdown = 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=40,
cv, self.assets, values=self._profiles, textvariable=self.profile_var,
sound_mgr=self.sounds, width=270, height=40,
)
self._btn_login = ImageButton(
cv, t("login_btn"), btn_fire, btn_fire,
@ -178,220 +134,87 @@ class LoginView:
)
self.new_name_var = tk.StringVar()
self._entry_new = GothEntry(
cv, self.assets, width=270, height=40, textvariable=self.new_name_var
)
self._entry_new = GothEntry(cv, self.assets, width=270, height=40, textvariable=self.new_name_var)
self._entry_new.bind_return(lambda _e: self._submit_new_profile())
new_is_primary = (not self._profiles)
new_pri = (not self._profiles)
self._btn_create = ImageButton(
cv,
t("new_profile_btn"),
btn_fire if new_is_primary else btn_norm,
btn_fire if new_is_primary else btn_purp,
self._submit_new_profile,
sound_mgr=self.sounds,
width=168,
height=40,
style="fire" if new_is_primary else "amethyst",
cv, t("new_profile_btn"),
btn_fire if new_pri else btn_norm, btn_fire if new_pri else btn_purp,
self._submit_new_profile, sound_mgr=self.sounds,
width=168, height=40, style="fire" if new_pri else "amethyst",
)
# Erst-Start DB-Ordnerwahl & Vorhandene DB laden (wenn noch kein lokales Profil existiert)
self._btn_pick_first_dir = ImageButton(
cv, t("db_choose_dir_btn"), btn_norm, btn_purp,
self._choose_first_db_folder,
cv, t("db_choose_dir_btn"), btn_norm, btn_purp, self._choose_first_db_folder,
sound_mgr=self.sounds, width=150, height=32, style="amethyst",
)
self._btn_load_existing_db = ImageButton(
cv, t("db_load_btn"), btn_norm, btn_purp,
self._load_existing_db_from_login,
cv, t("db_load_btn"), btn_norm, btn_purp, self._load_existing_db_from_login,
sound_mgr=self.sounds, width=168, height=32, style="amethyst",
)
# --- ONLINE ELEMENTE (Einzelaccount: URL inkl. Port ODER IP + Port) ---
is_url_mode = (self._addr_mode == "url")
self._btn_addr_url = ImageButton(
cv,
t("online_addr_url"),
btn_fire if is_url_mode else btn_norm,
btn_fire if is_url_mode else btn_purp,
lambda: self._switch_addr_mode("url"),
sound_mgr=self.sounds,
width=186,
height=30,
style="fire" if is_url_mode else "amethyst",
)
self._btn_addr_ip = ImageButton(
cv,
t("online_addr_ip"),
btn_fire if not is_url_mode else btn_norm,
btn_fire if not is_url_mode else btn_purp,
lambda: self._switch_addr_mode("ip"),
sound_mgr=self.sounds,
width=186,
height=30,
style="fire" if not is_url_mode else "amethyst",
)
self._online_url_var = tk.StringVar(value=online_prefs.get("url", "https://"))
self._online_ip_var = tk.StringVar(value=online_prefs.get("ip", "127.0.0.1"))
self._online_port_var = tk.StringVar(value=online_prefs.get("port", "8443"))
self._online_user_var = tk.StringVar(value=online_prefs.get("username", ""))
self._online_pass_var = tk.StringVar(value="")
self._entry_url = GothEntry(
cv, self.assets, width=452, height=38, textvariable=self._online_url_var
)
self._entry_ip = GothEntry(
cv, self.assets, width=308, height=38, textvariable=self._online_ip_var
)
self._entry_port = GothEntry(
cv, self.assets, width=130, height=38, textvariable=self._online_port_var
)
self._entry_online_user = GothEntry(
cv, self.assets, width=220, height=38, textvariable=self._online_user_var
)
self._entry_online_pass = GothEntry(
cv, self.assets, width=218, height=38, textvariable=self._online_pass_var
)
try:
self._entry_online_pass.entry.configure(show="•")
except Exception:
pass
for ent in (
self._entry_url,
self._entry_ip,
self._entry_port,
self._entry_online_user,
self._entry_online_pass,
):
ent.bind_return(lambda _e: self._submit_online_login())
self._btn_online_connect = ImageButton(
cv,
t("online_connect_btn"),
btn_fire,
btn_fire,
self._submit_online_login,
sound_mgr=self.sounds,
width=210,
height=40,
style="fire",
self._online_panel = OnlineLoginPanel(
cv, self.assets, self.sounds,
on_submit=self._submit_online_login,
on_switch_addr_mode=lambda _m: self.show(
self._profiles, preselect_name=self.profile_var.get() if self.profile_var else "", login_mode="online"
),
)
def _switch_login_mode(self, mode: str):
if self._login_mode == mode:
return
self._status_msg = ""
self.show(
self._profiles,
preselect_name=self.profile_var.get() if self.profile_var else "",
login_mode=mode,
)
def _switch_addr_mode(self, addr_mode: str):
if self._addr_mode == addr_mode:
return
DbLocator.save_online_prefs(
addr_mode,
self._online_url_var.get() if self._online_url_var else "",
self._online_ip_var.get() if self._online_ip_var else "",
self._online_port_var.get() if self._online_port_var else "8443",
self._online_user_var.get() if self._online_user_var else "",
)
self._addr_mode = addr_mode
self._status_msg = ""
self.show(
self._profiles,
preselect_name=self.profile_var.get() if self.profile_var else "",
login_mode="online",
)
if self._login_mode != mode:
self.show(self._profiles, preselect_name=self.profile_var.get() if self.profile_var else "", login_mode=mode)
def _choose_first_db_folder(self):
chosen = filedialog.askdirectory(
parent=self.root,
initialdir=str(self._first_db_dir),
title=t("db_move_dialog_title"),
parent=self.root, initialdir=str(self._first_db_dir), title=t("db_move_dialog_title")
)
if chosen:
self._first_db_dir = Path(chosen).resolve()
if self._cv is not None and self._cv.winfo_exists():
if self._cv and self._cv.winfo_exists():
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
def _load_existing_db_from_login(self):
picked = filedialog.askopenfilename(
parent=self.root,
initialdir=str(Database.get_user_db_dir()),
parent=self.root, initialdir=str(Database.get_user_db_dir()),
title=t("db_load_dialog_title"),
filetypes=[("SQLite Database", "*.db *.sqlite *.sqlite3"), ("All Files", "*.*")],
)
if not picked:
return
ok, msg = self.ctrl.load_user_data_from_file(picked)
if not ok:
self._status_msg = msg
self._status_is_error = True
if self._cv is not None and self._cv.winfo_exists():
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
if not ok and self._cv and self._cv.winfo_exists():
self._status_msg, self._status_is_error = msg, True
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
def _submit_new_profile(self):
if self._entry_new is None:
return
name = self._entry_new.get().strip()
if not name:
return
first_dir = str(self._first_db_dir) if not self._profiles else None
self.ctrl.do_create_profile(name, first_user_db_dir=first_dir)
if self._entry_new is not None:
name = self._entry_new.get().strip()
if name:
self.ctrl.do_create_profile(name, first_user_db_dir=str(self._first_db_dir) if not self._profiles else None)
def _submit_online_login(self):
url_s = self._entry_url.get().strip() if self._entry_url else ""
ip_s = self._entry_ip.get().strip() if self._entry_ip else ""
port_s = self._entry_port.get().strip() if self._entry_port else ""
user_s = self._entry_online_user.get().strip() if self._entry_online_user else ""
pass_s = self._entry_online_pass.get() if self._entry_online_pass else ""
ok, err_msg = self.ctrl.do_online_login(
addr_mode=self._addr_mode,
raw_url=url_s,
raw_ip=ip_s,
raw_port=port_s,
username=user_s,
password=pass_s,
)
if not ok:
self._status_msg = err_msg
self._status_is_error = True
if self._cv is not None and self._cv.winfo_exists():
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
if self._online_panel is None:
return
ok, err_msg = self.ctrl.do_online_login(**self._online_panel.get_credentials())
if not ok and self._cv and self._cv.winfo_exists():
self._status_msg, self._status_is_error = err_msg, True
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
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)
if event.widget == self._cv and event.width >= 100 and event.height >= 100:
GothDropdown.close_any_open_popup()
self._draw_scene(event.width, event.height)
def _hide_unused_widgets(self):
for wgt in (
self._dropdown,
self._btn_login,
self._entry_new,
self._btn_create,
self._btn_pick_first_dir,
self._btn_load_existing_db,
self._btn_addr_url,
self._btn_addr_ip,
self._entry_url,
self._entry_ip,
self._entry_port,
self._entry_online_user,
self._entry_online_pass,
self._btn_online_connect,
self._dropdown, self._btn_login, self._entry_new,
self._btn_create, self._btn_pick_first_dir, self._btn_load_existing_db,
):
if wgt is not None and wgt.winfo_exists():
wgt.place_forget()
if self._online_panel is not None:
self._online_panel.hide_all()
def _draw_scene(self, w: int, h: int):
cv = self._cv
@ -401,27 +224,18 @@ class LoginView:
self._hide_unused_widgets()
self._photo_refs.clear()
pad_right = max(48, int(w * 0.06))
top_y = max(42, int(h * 0.065))
pad_right, top_y = max(48, int(w * 0.06)), max(42, int(h * 0.065))
cv.create_window(w - pad_right, top_y, window=self._btn_settings, anchor="e", tags="login_fg")
cv.create_window(w - pad_right, top_y, window=self._btn_audio, anchor="e", tags="login_fg")
cx, compact = w // 2, (h < 790)
box_h = (
(352 if compact else 372) if self._login_mode == "online"
else ((304 if compact else 326) if self._profiles else (312 if compact else 332))
)
cx = w // 2
compact = (h < 790)
if self._login_mode == "online":
box_h = 352 if compact else 372
elif self._profiles:
box_h = 304 if compact else 326
else:
# Erst-Erstellung inkl. DB-Speicherort-Auswahl
box_h = 312 if compact else 332
banner_w = 430 if compact else 520
title_photo = self.assets.get_proportional_photo("title_login_banner", self.assets.raw_title, banner_w)
title_photo = self.assets.get_proportional_photo("title_login_banner", self.assets.raw_title, 430 if compact else 520)
banner_h = title_photo.height() if title_photo else 76
total_block_h = banner_h + (14 if compact else 22) + box_h
start_y = max(top_y + 26, (h - total_block_h) // 2 - (10 if self._status_msg else 0))
start_y = max(top_y + 26, (h - (banner_h + (14 if compact else 22) + box_h)) // 2 - (10 if self._status_msg else 0))
if title_photo:
self._photo_refs.append(title_photo)
@ -434,13 +248,11 @@ class LoginView:
box_top = start_y + 78
box_w = 546
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")
cv.create_image(cx, box_top + box_h // 2, image=frame_photo, anchor="center", tags="login_fg")
# Modus-Schalter oben im Rahmen
tab_y = box_top + 38
cv.create_window(cx - 112, tab_y, window=self._btn_tab_local, anchor="center", tags="login_fg")
cv.create_window(cx + 112, tab_y, window=self._btn_tab_online, anchor="center", tags="login_fg")
@ -448,126 +260,47 @@ class LoginView:
if self._login_mode == "local":
self._draw_local_section(cv, cx, tab_y + 46, compact)
else:
self._draw_online_section(cv, cx, tab_y + 44, compact)
elif self._online_panel is not None:
self._online_panel.draw(cx, tab_y + 44, compact, self._photo_refs)
if self._status_msg:
st_col = FONT_COLOR_STATUS_LOSS if self._status_is_error else FONT_COLOR_STATUS_WIN
st_ph = self.assets.get_goth_text_photo(
self._status_msg,
size_px=FONT_SIZE_SMALL_MIN + 1,
color=st_col,
max_width=box_w + 80,
)
st_ph = self.assets.get_goth_text_photo(self._status_msg, FONT_SIZE_SMALL_MIN + 1, st_col, max_width=box_w + 80)
self._photo_refs.append(st_ph)
cv.create_image(cx, box_top + box_h + 20, image=st_ph, anchor="center", tags="login_fg")
def _draw_local_section(self, cv: tk.Canvas, cx: int, start_y: int, compact: bool):
row_left = cx - 226
field_cx = row_left + 135
btn_cx = row_left + 270 + 14 + 84
row_left, field_cx, btn_cx = cx - 226, cx - 91, cx + 142
cur_y = start_y
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"
)
lbl1 = self.assets.get_goth_text_photo(t("login_select_lbl"), FONT_SIZE_BODY, FONT_COLOR_HEADING_SUB, align="left")
self._photo_refs.append(lbl1)
cv.create_image(row_left, cur_y, image=lbl1, anchor="w", tags="login_fg")
cur_y += 35
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")
sep_y = cur_y + (32 if compact else 38)
cv.create_line(cx - 215, sep_y, cx + 215, sep_y, fill=SUBTLE_BORDER, width=1, tags="login_fg")
cur_y = sep_y + (22 if compact else 26)
else:
# Allererstes Profil: Speicherort für user_data.db direkt wählbar!
db_lbl = self.assets.get_goth_text_photo(
t("db_first_setup_lbl"),
size_px=FONT_SIZE_SMALL_MIN + 1,
color=FONT_COLOR_HEADING_SUB,
align="left",
)
target_preview = str((self._first_db_dir / USER_DB_FILENAME).resolve())
path_ph = self.assets.get_goth_text_photo(
self._shorten_path(target_preview, 54),
size_px=FONT_SIZE_SMALL_MIN,
color=FONT_COLOR_BODY_MUTED,
align="left",
)
db_lbl = self.assets.get_goth_text_photo(t("db_first_setup_lbl"), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left")
preview = str((self._first_db_dir / USER_DB_FILENAME).resolve())
path_ph = self.assets.get_goth_text_photo(self._shorten_path(preview, 54), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, align="left")
self._photo_refs.extend([db_lbl, path_ph])
cv.create_image(row_left, cur_y, image=db_lbl, anchor="w", tags="login_fg")
cur_y += 22
cv.create_image(row_left, cur_y, image=path_ph, anchor="w", tags="login_fg")
cur_y += 30
cv.create_window(row_left + 75, cur_y, window=self._btn_pick_first_dir, anchor="center", tags="login_fg")
cv.create_window(cx + 226 - 84, cur_y, window=self._btn_load_existing_db, anchor="center", tags="login_fg")
sep_y = cur_y + 26
cv.create_line(cx - 215, sep_y, cx + 215, sep_y, fill=SUBTLE_BORDER, width=1, tags="login_fg")
cur_y = sep_y + 22
lbl2 = self.assets.get_goth_text_photo(
t("login_create_lbl"), size_px=FONT_SIZE_BODY, color=FONT_COLOR_HEADING_SUB, align="left"
)
lbl2 = self.assets.get_goth_text_photo(t("login_create_lbl"), FONT_SIZE_BODY, FONT_COLOR_HEADING_SUB, align="left")
self._photo_refs.append(lbl2)
cv.create_image(row_left, cur_y, image=lbl2, anchor="w", tags="login_fg")
cur_y += 35
cv.create_window(field_cx, cur_y, window=self._entry_new, anchor="center", tags="login_fg")
cv.create_window(btn_cx, cur_y, window=self._btn_create, anchor="center", tags="login_fg")
def _draw_online_section(self, cv: tk.Canvas, cx: int, start_y: int, compact: bool):
row_left = cx - 226
cur_y = start_y + 6
# Sub-Switch: URL (inkl. Port) vs. IP + Port
cv.create_window(cx - 98, cur_y, window=self._btn_addr_url, anchor="center", tags="login_fg")
cv.create_window(cx + 98, cur_y, window=self._btn_addr_ip, anchor="center", tags="login_fg")
cur_y += 34
if self._addr_mode == "url":
u_lbl = self.assets.get_goth_text_photo(
t("online_url_lbl"), size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left"
)
self._photo_refs.append(u_lbl)
cv.create_image(row_left, cur_y, image=u_lbl, anchor="w", tags="login_fg")
cur_y += 30
cv.create_window(cx, cur_y, window=self._entry_url, anchor="center", tags="login_fg")
else:
ip_lbl = self.assets.get_goth_text_photo(
t("online_ip_lbl"), size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left"
)
pt_lbl = self.assets.get_goth_text_photo(
t("online_port_lbl"), size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left"
)
self._photo_refs.extend([ip_lbl, pt_lbl])
port_left = row_left + 322
cv.create_image(row_left, cur_y, image=ip_lbl, anchor="w", tags="login_fg")
cv.create_image(port_left, cur_y, image=pt_lbl, anchor="w", tags="login_fg")
cur_y += 30
cv.create_window(row_left + 154, cur_y, window=self._entry_ip, anchor="center", tags="login_fg")
cv.create_window(port_left + 65, cur_y, window=self._entry_port, anchor="center", tags="login_fg")
cur_y += 38 if not compact else 34
usr_lbl = self.assets.get_goth_text_photo(
t("online_user_lbl"), size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left"
)
pwd_lbl = self.assets.get_goth_text_photo(
t("online_pass_lbl"), size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left"
)
self._photo_refs.extend([usr_lbl, pwd_lbl])
pwd_left = row_left + 234
cv.create_image(row_left, cur_y, image=usr_lbl, anchor="w", tags="login_fg")
cv.create_image(pwd_left, cur_y, image=pwd_lbl, anchor="w", tags="login_fg")
cur_y += 30
cv.create_window(row_left + 110, cur_y, window=self._entry_online_user, anchor="center", tags="login_fg")
cv.create_window(pwd_left + 109, cur_y, window=self._entry_online_pass, anchor="center", tags="login_fg")
cur_y += 46 if not compact else 42
cv.create_window(cx, cur_y, window=self._btn_online_connect, anchor="center", tags="login_fg")

View File

@ -0,0 +1,159 @@
# -*- coding: utf-8 -*-
# view/menus/online_login_panel.py
from __future__ import annotations
import tkinter as tk
from models.db_locator import DbLocator
from resources.code_res.game_constants import (
FONT_COLOR_HEADING_SUB,
FONT_SIZE_SMALL_MIN,
)
from resources.code_res.i18n import t
from view.widgets.goth_entry import GothEntry
from view.widgets.image_button import ImageButton
class OnlineLoginPanel:
"""Kapselt die Formular-Widgets und das Canvas-Layout für den Online-Einzelaccount."""
def __init__(self, cv: tk.Canvas, assets, sounds, on_submit, on_switch_addr_mode):
self.cv = cv
self.assets = assets
self.sounds = sounds
self._on_submit = on_submit
self._on_switch_addr_mode = on_switch_addr_mode
prefs = DbLocator.load_online_prefs()
self.addr_mode: str = "ip" if prefs.get("addr_mode") == "ip" else "url"
btn_norm = assets.raw_btn_default
btn_purp = assets.raw_btn_purple
btn_fire = assets.raw_btn_fire or btn_purp
is_url = (self.addr_mode == "url")
self.btn_addr_url = ImageButton(
cv, t("online_addr_url"),
btn_fire if is_url else btn_norm, btn_fire if is_url else btn_purp,
lambda: self._switch_mode("url"), sound_mgr=sounds,
width=186, height=30, style="fire" if is_url else "amethyst",
)
self.btn_addr_ip = ImageButton(
cv, t("online_addr_ip"),
btn_fire if not is_url else btn_norm, btn_fire if not is_url else btn_purp,
lambda: self._switch_mode("ip"), sound_mgr=sounds,
width=186, height=30, style="fire" if not is_url else "amethyst",
)
self.url_var = tk.StringVar(value=prefs.get("url", "https://"))
self.ip_var = tk.StringVar(value=prefs.get("ip", "127.0.0.1"))
self.port_var = tk.StringVar(value=prefs.get("port", "8443"))
self.user_var = tk.StringVar(value=prefs.get("username", ""))
self.pass_var = tk.StringVar(value="")
self.entry_url = GothEntry(cv, assets, width=452, height=38, textvariable=self.url_var)
self.entry_ip = GothEntry(cv, assets, width=308, height=38, textvariable=self.ip_var)
self.entry_port = GothEntry(cv, assets, width=130, height=38, textvariable=self.port_var)
self.entry_user = GothEntry(cv, assets, width=220, height=38, textvariable=self.user_var)
self.entry_pass = GothEntry(cv, assets, width=218, height=38, textvariable=self.pass_var)
try:
self.entry_pass.entry.configure(show="*")
except Exception:
pass
for ent in (self.entry_url, self.entry_ip, self.entry_port, self.entry_user, self.entry_pass):
ent.bind_return(lambda _e: self._on_submit())
self.btn_connect = ImageButton(
cv, t("online_connect_btn"), btn_fire, btn_fire,
self._on_submit, sound_mgr=sounds, width=210, height=40, style="fire",
)
def _switch_mode(self, new_mode: str):
if self.addr_mode == new_mode:
return
DbLocator.save_online_prefs(
new_mode,
self.url_var.get(),
self.ip_var.get(),
self.port_var.get(),
self.user_var.get(),
)
self._on_switch_addr_mode(new_mode)
def get_credentials(self) -> dict:
return {
"addr_mode": self.addr_mode,
"raw_url": self.entry_url.get().strip(),
"raw_ip": self.entry_ip.get().strip(),
"raw_port": self.entry_port.get().strip(),
"username": self.entry_user.get().strip(),
"password": self.entry_pass.get(),
}
def focus_default(self):
if not self.user_var.get().strip():
self.entry_user.entry.focus_set()
else:
self.entry_pass.entry.focus_set()
def hide_all(self):
for wgt in (
self.btn_addr_url, self.btn_addr_ip,
self.entry_url, self.entry_ip, self.entry_port,
self.entry_user, self.entry_pass, self.btn_connect,
):
if wgt is not None and wgt.winfo_exists():
wgt.place_forget()
def draw(self, cx: int, start_y: int, compact: bool, photo_refs: list) -> None:
cv = self.cv
row_left = cx - 226
cur_y = start_y + 6
cv.create_window(cx - 98, cur_y, window=self.btn_addr_url, anchor="center", tags="login_fg")
cv.create_window(cx + 98, cur_y, window=self.btn_addr_ip, anchor="center", tags="login_fg")
cur_y += 34
if self.addr_mode == "url":
u_lbl = self.assets.get_goth_text_photo(
t("online_url_lbl"), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left"
)
photo_refs.append(u_lbl)
cv.create_image(row_left, cur_y, image=u_lbl, anchor="w", tags="login_fg")
cur_y += 30
cv.create_window(cx, cur_y, window=self.entry_url, anchor="center", tags="login_fg")
else:
ip_lbl = self.assets.get_goth_text_photo(
t("online_ip_lbl"), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left"
)
pt_lbl = self.assets.get_goth_text_photo(
t("online_port_lbl"), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left"
)
photo_refs.extend([ip_lbl, pt_lbl])
port_left = row_left + 322
cv.create_image(row_left, cur_y, image=ip_lbl, anchor="w", tags="login_fg")
cv.create_image(port_left, cur_y, image=pt_lbl, anchor="w", tags="login_fg")
cur_y += 30
cv.create_window(row_left + 154, cur_y, window=self.entry_ip, anchor="center", tags="login_fg")
cv.create_window(port_left + 65, cur_y, window=self.entry_port, anchor="center", tags="login_fg")
cur_y += 34 if compact else 38
usr_lbl = self.assets.get_goth_text_photo(
t("online_user_lbl"), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left"
)
pwd_lbl = self.assets.get_goth_text_photo(
t("online_pass_lbl"), FONT_SIZE_SMALL_MIN + 1, FONT_COLOR_HEADING_SUB, align="left"
)
photo_refs.extend([usr_lbl, pwd_lbl])
pwd_left = row_left + 234
cv.create_image(row_left, cur_y, image=usr_lbl, anchor="w", tags="login_fg")
cv.create_image(pwd_left, cur_y, image=pwd_lbl, anchor="w", tags="login_fg")
cur_y += 30
cv.create_window(row_left + 110, cur_y, window=self.entry_user, anchor="center", tags="login_fg")
cv.create_window(pwd_left + 109, cur_y, window=self.entry_pass, anchor="center", tags="login_fg")
cur_y += 42 if compact else 46
cv.create_window(cx, cur_y, window=self.btn_connect, anchor="center", tags="login_fg")

View File

@ -0,0 +1,227 @@
# -*- coding: utf-8 -*-
# view/menus/settings_cards.py
from __future__ import annotations
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_STATUS_LOSS,
FONT_COLOR_STATUS_WIN,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
FONT_SIZE_SMALL_MIN,
SUBTLE_BORDER,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
)
from resources.code_res.i18n import t
class SettingsCardsRenderer:
"""Zeichnet die einzelnen Einstellungs-Rahmenboxen auf das SettingsView-Canvas."""
@staticmethod
def shorten_path(p_str: str, max_chars: int = 72) -> str:
if len(p_str) <= max_chars:
return p_str
keep = max_chars - 5
left = keep // 2 - 2
right = keep - left
return f"{p_str[:left]}...{p_str[-right:]}"
@staticmethod
def draw_lang_card(
cv: tk.Canvas,
assets,
photo_refs: list,
cx: int,
cy: int,
box_w: int,
box_h: int,
btn_lang: tk.Widget | None,
) -> None:
x_left = cx - box_w // 2 + 24
x_right = cx + box_w // 2 - 22
box_ph = assets.get_box_photo("box_purple", (box_w, box_h))
if box_ph:
photo_refs.append(box_ph)
cv.create_image(cx, cy, image=box_ph, anchor="center", tags="settings_fg")
lbl_ph = assets.get_goth_text_photo(
t("settings_lang_title"), FONT_SIZE_BODY + 2, FONT_COLOR_BODY_DEFAULT, align="left"
)
desc_ph = assets.get_goth_text_photo(
t("settings_lang_desc"),
FONT_SIZE_SMALL_MIN,
FONT_COLOR_BODY_MUTED,
max_width=max(120, box_w - 210),
align="left",
)
photo_refs.extend([lbl_ph, desc_ph])
cv.create_image(x_left, cy - 12, image=lbl_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy + 13, image=desc_ph, anchor="w", tags="settings_fg")
if btn_lang is not None and btn_lang.winfo_exists():
cv.create_window(x_right, cy, window=btn_lang, anchor="e", tags="settings_fg")
@staticmethod
def draw_switch_card(
cv: tk.Canvas,
assets,
photo_refs: list,
cx: int,
cy: int,
box_w: int,
box_h: int,
title_txt: str,
desc_txt: str,
switch_wgt: tk.Widget | None,
) -> None:
x_left = cx - box_w // 2 + 24
x_right = cx + box_w // 2 - 22
box_ph = assets.get_box_photo("box_purple", (box_w, box_h))
if box_ph:
photo_refs.append(box_ph)
cv.create_image(cx, cy, image=box_ph, anchor="center", tags="settings_fg")
lbl_ph = assets.get_goth_text_photo(
title_txt, FONT_SIZE_BODY + 1, FONT_COLOR_BODY_DEFAULT,
max_width=max(120, box_w - 156), align="left",
)
desc_ph = assets.get_goth_text_photo(
desc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
max_width=max(120, box_w - 156), align="left",
)
photo_refs.extend([lbl_ph, desc_ph])
cv.create_image(x_left, cy - 13, image=lbl_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy + 13, image=desc_ph, anchor="w", tags="settings_fg")
if switch_wgt is not None and switch_wgt.winfo_exists():
cv.create_window(x_right, cy, window=switch_wgt, anchor="e", tags="settings_fg")
@staticmethod
def draw_slider_card(
cv: tk.Canvas,
assets,
photo_refs: list,
sliders_dict: dict,
key: str,
cx: int,
cy: int,
box_w: int,
box_h: int,
label_txt: str,
desc_txt: str,
initial_vol: float,
on_change,
) -> None:
x_left = cx - box_w // 2 + 24
x_right = cx + box_w // 2 - 24
box_ph = assets.get_box_photo("box_purple", (box_w, box_h))
if box_ph:
photo_refs.append(box_ph)
cv.create_image(cx, cy, image=box_ph, anchor="center", tags="settings_fg")
top_off = max(24, box_h // 4 + 4)
lbl_ph = assets.get_goth_text_photo(
label_txt, FONT_SIZE_BODY + 2, FONT_COLOR_BODY_DEFAULT,
max_width=max(140, box_w - 130), align="left",
)
desc_ph = assets.get_goth_text_photo(
desc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED,
max_width=max(140, box_w - 48), align="left",
)
photo_refs.extend([lbl_ph, desc_ph])
cv.create_image(x_left, cy - top_off, image=lbl_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy - 2, image=desc_ph, anchor="w", tags="settings_fg")
pct_item = cv.create_image(x_right, cy - top_off, anchor="e", tags="settings_fg")
track_y = cy + max(24, box_h // 4 + 2)
track_x1, track_x2 = x_left + 6, x_right - 6
cv.create_rectangle(
track_x1, track_y - 5, track_x2, track_y + 5,
fill="#09070e", outline=SUBTLE_BORDER, width=1, tags="settings_fg",
)
fill_id = cv.create_rectangle(
track_x1, track_y - 4, track_x1, track_y + 4,
fill=UI_ACCENT_AMETHYST, outline="", tags="settings_fg",
)
knob_id = cv.create_polygon(
0, 0, 0, 0, 0, 0, 0, 0,
fill=UI_ACCENT_GOLD, outline="#0d0b12", width=1, tags="settings_fg",
)
sliders_dict[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,
}
@classmethod
def draw_user_data_card(
cls,
cv: tk.Canvas,
assets,
photo_refs: list,
cx: int,
cy: int,
box_w: int,
box_h: int,
feedback_txt: str,
feedback_err: bool,
btn_load: tk.Widget | None,
btn_move: tk.Widget | None,
horizontal_btns: bool = True,
) -> None:
x_left = cx - box_w // 2 + 26
x_right = cx + box_w // 2 - 26
box_ph = assets.get_box_photo("box_gold_double", (box_w, box_h))
if box_ph:
photo_refs.append(box_ph)
cv.create_image(cx, cy, image=box_ph, anchor="center", tags="settings_fg")
hdr_ph = assets.get_goth_text_photo(
t("db_settings_title"), FONT_SIZE_BODY + 2, FONT_COLOR_TITLE_MAIN, align="left"
)
cur_db_str = cls.shorten_path(str(Database.get_user_db_path()), max_chars=max(42, box_w // 12))
sub_txt = feedback_txt if feedback_txt else t("db_Active_path_lbl", cur_db_str)
sub_col = (
(FONT_COLOR_STATUS_LOSS if feedback_err else FONT_COLOR_STATUS_WIN)
if feedback_txt else FONT_COLOR_BODY_DEFAULT
)
path_ph = assets.get_goth_text_photo(
sub_txt,
FONT_SIZE_SMALL_MIN + 1,
sub_col,
max_width=max(180, (box_w - 490) if (horizontal_btns and box_w >= 860) else (box_w - 56)),
align="left",
)
photo_refs.extend([hdr_ph, path_ph])
if horizontal_btns and box_w >= 860:
cv.create_image(x_left, cy - 14, image=hdr_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy + 14, image=path_ph, anchor="w", tags="settings_fg")
if btn_move is not None and btn_move.winfo_exists():
cv.create_window(x_right, cy, window=btn_move, anchor="e", tags="settings_fg")
if btn_load is not None and btn_load.winfo_exists():
cv.create_window(x_right - 220, cy, window=btn_load, anchor="e", tags="settings_fg")
else:
cv.create_image(x_left, cy - 30, image=hdr_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy - 6, image=path_ph, anchor="w", tags="settings_fg")
if btn_load is not None and btn_load.winfo_exists():
cv.create_window(x_left, cy + 26, window=btn_load, anchor="w", tags="settings_fg")
if btn_move is not None and btn_move.winfo_exists():
cv.create_window(x_right, cy + 26, window=btn_move, anchor="e", tags="settings_fg")

View File

@ -13,20 +13,14 @@ from games.solitaire.base.solitaire_tap_prefs import (
from models.database import Database
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,
SUBTLE_BORDER,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
)
from resources.code_res.i18n import t
from view.menus.settings_cards import SettingsCardsRenderer
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.goth_switch import GothSwitch
from view.widgets.image_button import (
@ -37,12 +31,7 @@ from view.widgets.image_button import (
class SettingsView:
"""
Vollflächige Einstellungs-Ansicht im Stil von StatisticsView (ohne schwebendes Popup):
- Desktop-Breitbild (2-Spalten-Layout) & Mobile/Kompakt (1-Spalten-Layout).
- Funktioniert als regulärer Menü-Screen (clear_window) ODER verlustfrei über einem
laufenden Spieltisch (in_game_overlay=True).
"""
"""Vollflächige Einstellungs-Ansicht (2-spaltig Desktop / 1-spaltig Mobile)."""
def __init__(self, root_view):
self.root = root_view
@ -80,15 +69,6 @@ class SettingsView:
self._drag_bind_id: str | None = None
self._up_bind_id: str | None = None
@staticmethod
def _shorten_path(p_str: str, max_chars: int = 72) -> str:
if len(p_str) <= max_chars:
return p_str
keep = max_chars - 5
left = keep // 2 - 2
right = keep - left
return f"{p_str[:left]}...{p_str[-right:]}"
def _destroy_owned_widgets(self):
for wgt in self._owned_widgets:
try:
@ -97,13 +77,9 @@ class SettingsView:
except Exception:
pass
self._owned_widgets.clear()
self._btn_back = None
self._btn_test = None
self._btn_lang = None
self._sw_hover = None
self._sw_tap = None
self._btn_db_load = None
self._btn_db_move = None
self._btn_back = self._btn_test = self._btn_lang = None
self._sw_hover = self._sw_tap = None
self._btn_db_load = self._btn_db_move = None
def _unbind_canvas_events(self):
if self._cv is None:
@ -119,10 +95,7 @@ class SettingsView:
self._cv.unbind(seq, bid)
except Exception:
pass
self._cfg_bind_id = None
self._down_bind_id = None
self._drag_bind_id = None
self._up_bind_id = None
self._cfg_bind_id = self._down_bind_id = self._drag_bind_id = self._up_bind_id = None
def _get_scaled_bg_pil(self, w: int, h: int) -> Image.Image | None:
if w < 40 or h < 40:
@ -132,10 +105,7 @@ class SettingsView:
src = (
self.assets.raw_bg_vertical
if (h > w and getattr(self.assets, "raw_bg_vertical", None) is not None)
else (
getattr(self.assets, "raw_bg_horizontal", None)
or getattr(self.assets, "raw_bg", None)
)
else (getattr(self.assets, "raw_bg_horizontal", None) or getattr(self.assets, "raw_bg", None))
)
if src is None:
return None
@ -143,9 +113,7 @@ class SettingsView:
self._cached_bg_size = (w, h)
return self._cached_bg_pil
def _crop_bg_patch_photo(
self, win_w: int, win_h: int, x: int, y: int, pw: int, ph: int
) -> ImageTk.PhotoImage | None:
def _crop_bg_patch_photo(self, win_w: int, win_h: int, x: int, y: int, pw: int, ph: int):
if hasattr(self.assets, "get_bg_patch_photo"):
try:
res = self.assets.get_bg_patch_photo(win_w, win_h, x, y, pw, ph)
@ -156,10 +124,8 @@ class SettingsView:
full_pil = self._get_scaled_bg_pil(win_w, win_h)
if full_pil is None:
return None
x1 = max(0, min(win_w - 1, x))
y1 = max(0, min(win_h - 1, y))
x2 = max(x1 + 1, min(win_w, x1 + pw))
y2 = max(y1 + 1, min(win_h, y1 + ph))
x1, y1 = max(0, min(win_w - 1, x)), max(0, min(win_h - 1, y))
x2, y2 = max(x1 + 1, min(win_w, x1 + pw)), max(y1 + 1, min(win_h, y1 + ph))
return ImageTk.PhotoImage(full_pil.crop((x1, y1, x2, y2)))
def show(
@ -172,7 +138,6 @@ class SettingsView:
):
GothDropdown.close_any_open_popup()
ImageButton.close_active_hover_tip()
self._unbind_canvas_events()
self._destroy_owned_widgets()
@ -183,16 +148,14 @@ class SettingsView:
self._db_feedback_err = feedback_err
self._dragging_key = None
self._close_overlay_only()
if in_game_overlay:
self._close_overlay_only()
self._lang_changed_ingame = False
cv = tk.Canvas(self.root, bg=BG_COLOR, bd=0, highlightthickness=0)
cv.place(x=0, y=0, relwidth=1.0, relheight=1.0)
tk.Widget.tkraise(cv)
self._overlay_canvas = cv
self._cv = cv
self._overlay_canvas = self._cv = cv
else:
self._close_overlay_only()
self.root.clear_window(apply_global_bg=True)
cv = self.root.bg_widget
if not isinstance(cv, tk.Canvas):
@ -204,12 +167,10 @@ class SettingsView:
self._cfg_bind_id = self._cv.bind("<Configure>", self._on_canvas_layout, add="+")
self._down_bind_id = self._cv.bind("<ButtonPress-1>", self._on_mouse_down, add="+")
self._drag_bind_id = self._cv.bind("<B1-Motion>", self._on_mouse_drag, add="+")
self._up_bind_id = self._cv.bind("<ButtonRelease-1>", self._on_mouse_up, add="+")
self._up_bind_id = self._cv.bind("<ButtonRelease-1>", lambda _e: setattr(self, "_dragging_key", None), add="+")
self.root.update_idletasks()
w = max(800, self._cv.winfo_width())
h = max(600, self._cv.winfo_height())
self._draw_scene(w, h)
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
def _close_overlay_only(self):
if self._overlay_canvas is not None:
@ -227,9 +188,7 @@ class SettingsView:
self._destroy_owned_widgets()
if self._in_game_overlay:
lang_dirty = self._lang_changed_ingame
lang_cb = self._on_ingame_lang_refresh
back_cb = self._on_back
lang_dirty, lang_cb, back_cb = self._lang_changed_ingame, self._on_ingame_lang_refresh, self._on_back
self._close_overlay_only()
if lang_dirty and callable(lang_cb):
lang_cb()
@ -246,91 +205,36 @@ class SettingsView:
def _build_static_buttons(self, cv: tk.Canvas):
self._destroy_owned_widgets()
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_norm, btn_purp = self.assets.raw_btn_default, self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
back_txt = t("btn_back")
if back_txt.startswith("[") or back_txt == "btn_back":
back_txt = t("btn_back_main")
self._btn_back = ImageButton(
cv,
back_txt,
btn_norm,
btn_purp,
self._handle_back,
sound_mgr=self.sounds,
width=148,
height=36,
style="amethyst",
cv, t("btn_back"), btn_norm, btn_purp, self._handle_back,
sound_mgr=self.sounds, width=148, height=36, style="amethyst",
)
self._btn_test = ImageButton(
cv,
t("audio_test_btn"),
btn_norm,
btn_purp,
lambda: self.sounds.play("deal"),
sound_mgr=None,
width=158,
height=36,
style="amethyst",
cv, t("audio_test_btn"), btn_norm, btn_purp, lambda: self.sounds.play("deal"),
sound_mgr=None, width=158, height=36, style="amethyst",
)
self._btn_lang = ImageButton(
cv,
t("settings_lang_btn_toggle"),
btn_fire,
btn_fire,
self._handle_language_toggle,
sound_mgr=self.sounds,
width=154,
height=34,
style="fire",
cv, t("settings_lang_btn_toggle"), btn_fire, btn_fire, self._handle_language_toggle,
sound_mgr=self.sounds, width=154, height=34, style="fire",
)
can_change_db = (not self._in_game_overlay) and self.ctrl.can_modify_user_db()
can_db = (not self._in_game_overlay) and self.ctrl.can_modify_user_db()
self._btn_db_load = ImageButton(
cv,
t("db_load_btn"),
btn_norm,
btn_purp,
self._on_load_user_db_clicked,
sound_mgr=self.sounds,
width=208,
height=36,
enabled=can_change_db,
style="amethyst",
cv, t("db_load_btn"), btn_norm, btn_purp, self._on_load_user_db_clicked,
sound_mgr=self.sounds, width=208, height=36, enabled=can_db, style="amethyst",
)
self._btn_db_move = ImageButton(
cv,
t("db_move_btn"),
btn_norm,
btn_purp,
self._on_move_user_db_clicked,
sound_mgr=self.sounds,
width=208,
height=36,
enabled=can_change_db,
style="amethyst",
cv, t("db_move_btn"), btn_norm, btn_purp, self._on_move_user_db_clicked,
sound_mgr=self.sounds, width=208, height=36, enabled=can_db, style="amethyst",
)
self._owned_widgets.extend([
self._btn_back,
self._btn_test,
self._btn_lang,
self._btn_db_load,
self._btn_db_move,
self._btn_back, self._btn_test, self._btn_lang, self._btn_db_load, self._btn_db_move
])
def _rebuild_switches(
self,
cv: tk.Canvas,
win_w: int,
win_h: int,
hover_pos: tuple[int, int],
tap_pos: tuple[int, int],
):
def _rebuild_switches(self, cv: tk.Canvas, win_w: int, win_h: int, h_pos: tuple[int, int], t_pos: tuple[int, int]):
for old_sw in (self._sw_hover, self._sw_tap):
if old_sw is not None:
try:
@ -342,37 +246,22 @@ class SettingsView:
pass
sw_w, sw_h = 92, 38
hx_right, h_cy = hover_pos
tx_right, t_cy = tap_pos
patch_hover = self._crop_bg_patch_photo(
win_w, win_h, hx_right - sw_w, h_cy - sw_h // 2, sw_w, sw_h
)
patch_tap = self._crop_bg_patch_photo(
win_w, win_h, tx_right - sw_w, t_cy - sw_h // 2, sw_w, sw_h
)
if patch_hover is not None:
self._photo_refs.append(patch_hover)
if patch_tap is not None:
self._photo_refs.append(patch_tap)
ph_h = self._crop_bg_patch_photo(win_w, win_h, h_pos[0] - sw_w, h_pos[1] - sw_h // 2, sw_w, sw_h)
ph_t = self._crop_bg_patch_photo(win_w, win_h, t_pos[0] - sw_w, t_pos[1] - sw_h // 2, sw_w, sw_h)
if ph_h:
self._photo_refs.append(ph_h)
if ph_t:
self._photo_refs.append(ph_t)
self._sw_hover = GothSwitch(
cv,
value=is_button_hover_help_enabled(),
cv, value=is_button_hover_help_enabled(),
on_change=lambda st: set_button_hover_help_enabled(st, persist=True),
sound_mgr=self.sounds,
width=sw_w,
height=sw_h,
bg_photo=patch_hover,
sound_mgr=self.sounds, width=sw_w, height=sw_h, bg_photo=ph_h,
)
self._sw_tap = GothSwitch(
cv,
value=is_single_tap_to_move_enabled(),
cv, value=is_single_tap_to_move_enabled(),
on_change=lambda st: set_single_tap_to_move_enabled(st, persist=True),
sound_mgr=self.sounds,
width=sw_w,
height=sw_h,
bg_photo=patch_tap,
sound_mgr=self.sounds, width=sw_w, height=sw_h, bg_photo=ph_t,
)
self._owned_widgets.extend([self._sw_hover, self._sw_tap])
@ -381,19 +270,15 @@ class SettingsView:
self.ctrl.toggle_language(custom_refresh=lambda: None)
self._lang_changed_ingame = True
self._build_static_buttons(self._cv)
if self._cv is not None and self._cv.winfo_exists():
if self._cv and self._cv.winfo_exists():
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
return
back_cb = self._on_back
self.ctrl.toggle_language(
custom_refresh=lambda: self.show(on_back=back_cb, in_game_overlay=False)
)
self.ctrl.toggle_language(custom_refresh=lambda: self.show(on_back=back_cb, in_game_overlay=False))
def _on_load_user_db_clicked(self):
picked = filedialog.askopenfilename(
parent=self.root,
initialdir=str(Database.get_user_db_dir()),
parent=self.root, initialdir=str(Database.get_user_db_dir()),
title=t("db_load_dialog_title"),
filetypes=[("SQLite Database", "*.db *.sqlite *.sqlite3"), ("All Files", "*.*")],
)
@ -403,43 +288,31 @@ class SettingsView:
ok, msg = self.ctrl.load_user_data_from_file(picked)
if not ok:
self.show(
on_back=self._on_back,
in_game_overlay=self._in_game_overlay,
on_back=self._on_back, in_game_overlay=self._in_game_overlay,
on_ingame_lang_refresh=self._on_ingame_lang_refresh,
feedback_txt=msg,
feedback_err=True,
feedback_txt=msg, feedback_err=True,
)
def _on_move_user_db_clicked(self):
chosen_dir = filedialog.askdirectory(
parent=self.root,
initialdir=str(Database.get_user_db_dir()),
title=t("db_move_dialog_title"),
parent=self.root, initialdir=str(Database.get_user_db_dir()), title=t("db_move_dialog_title")
)
if not chosen_dir:
return
ok, msg = self.ctrl.move_user_data_to_folder(chosen_dir)
self._db_feedback_txt = msg
self._db_feedback_err = not ok
if self._cv is not None and self._cv.winfo_exists():
self._db_feedback_txt, self._db_feedback_err = msg, (not ok)
if self._cv and self._cv.winfo_exists():
self._draw_scene(max(800, self._cv.winfo_width()), max(600, self._cv.winfo_height()))
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)
if event.widget == self._cv and event.width >= 120 and event.height >= 120:
GothDropdown.close_any_open_popup()
self._draw_scene(event.width, event.height)
# ------------------------------------------------------------------
# RESPONSIVES VOLLBILD-RENDERING (2-SPALTIG DESKTOP / 1-SPALTIG MOBILE)
# ------------------------------------------------------------------
def _draw_scene(self, w: int, h: int):
cv = self._cv
if cv is None or not cv.winfo_exists():
return
cv.delete("settings_fg")
cv.delete("settings_bg")
self._photo_refs.clear()
@ -453,22 +326,18 @@ class SettingsView:
self._photo_refs.append(bg_ph)
cv.create_image(0, 0, image=bg_ph, anchor="nw", tags="settings_bg")
compact = (h < 780)
two_cols = (w >= 960)
compact, two_cols = (h < 780), (w >= 960)
pad_x = max(72, int(w * 0.08))
top_y = max(56, int(h * 0.10)) if compact else max(66, int(h * 0.11))
# 1. Kopfbereich
if self._btn_back is not None and self._btn_back.winfo_exists():
if self._btn_back and self._btn_back.winfo_exists():
cv.create_window(pad_x, top_y, window=self._btn_back, anchor="w", tags="settings_fg")
if self._btn_test is not None and self._btn_test.winfo_exists():
if self._btn_test and self._btn_test.winfo_exists():
cv.create_window(w - pad_x, top_y, window=self._btn_test, anchor="e", tags="settings_fg")
hdr_ph = self.assets.get_goth_text_photo(
t("settings_title"),
size_px=FONT_SIZE_HEADING + (1 if compact else 3),
color=FONT_COLOR_TITLE_MAIN,
max_width=max(220, w - 480),
t("settings_title"), FONT_SIZE_HEADING + (1 if compact else 3),
FONT_COLOR_TITLE_MAIN, max_width=max(220, w - 480),
)
self._photo_refs.append(hdr_ph)
cv.create_image(w // 2, top_y, image=hdr_ph, anchor="center", tags="settings_fg")
@ -483,339 +352,86 @@ class SettingsView:
if two_cols:
col_gap = 20
col_w = (content_w - col_gap) // 2
left_cx = left_edge + col_w // 2
right_cx = left_edge + col_w + col_gap + col_w // 2
row_h = 84 if compact else 94
row_gap = 12 if compact else 16
l_cx, r_cx = left_edge + col_w // 2, left_edge + col_w + col_gap + col_w // 2
row_h, row_gap = (84 if compact else 94), (12 if compact else 16)
y1 = area_top + row_h // 2
y2 = y1 + row_h + row_gap
y3 = y2 + row_h + row_gap
left_bottom = y3 + row_h // 2
y2, y3 = y1 + row_h + row_gap, y1 + 2 * (row_h + row_gap)
sw_x_right = left_cx + col_w // 2 - 22
self._rebuild_switches(cv, w, h, (sw_x_right, y2), (sw_x_right, y3))
self._draw_lang_card(cv, left_cx, y1, col_w, row_h)
self._draw_switch_card(
cv, left_cx, y2, col_w, row_h,
t("settings_hover_help_title"),
t("settings_hover_help_desc"),
self._sw_hover,
sw_xr = l_cx + col_w // 2 - 22
self._rebuild_switches(cv, w, h, (sw_xr, y2), (sw_xr, y3))
SettingsCardsRenderer.draw_lang_card(cv, self.assets, self._photo_refs, l_cx, y1, col_w, row_h, self._btn_lang)
SettingsCardsRenderer.draw_switch_card(
cv, self.assets, self._photo_refs, l_cx, y2, col_w, row_h,
t("settings_hover_help_title"), t("settings_hover_help_desc"), self._sw_hover,
)
self._draw_switch_card(
cv, left_cx, y3, col_w, row_h,
t("settings_single_tap_title"),
t("settings_single_tap_desc"),
self._sw_tap,
)
total_left_h = left_bottom - area_top
slider_h = (total_left_h - row_gap) // 2
sy1 = area_top + slider_h // 2
sy2 = sy1 + slider_h + row_gap
self._draw_slider_card(
cv, "amb", right_cx, sy1, col_w, slider_h,
t("audio_ambiance_label"),
t("audio_ambiance_desc"),
self.sounds.ambiance_volume,
lambda v: self.sounds.set_ambiance_volume(v, persist=True),
)
self._draw_slider_card(
cv, "sfx", right_cx, sy2, col_w, slider_h,
t("audio_sfx_label"),
t("audio_sfx_desc"),
self.sounds.menu_volume,
lambda v: self.sounds.set_menu_volume(v, persist=True),
SettingsCardsRenderer.draw_switch_card(
cv, self.assets, self._photo_refs, l_cx, y3, col_w, row_h,
t("settings_single_tap_title"), t("settings_single_tap_desc"), self._sw_tap,
)
sl_h = ((y3 + row_h // 2 - area_top) - row_gap) // 2
sy1, sy2 = area_top + sl_h // 2, area_top + sl_h // 2 + sl_h + row_gap
sl_cx, sl_w = r_cx, col_w
db_h = 108 if compact else 118
db_cy = left_bottom + (16 if compact else 22) + db_h // 2
self._draw_user_data_card(cv, w // 2, db_cy, content_w, db_h, horizontal_btns=True)
db_cy = (y3 + row_h // 2) + (16 if compact else 22) + db_h // 2
horiz_db = True
else:
avail_h = max(420, h - area_top - 24)
gap = 8
row_h = max(62, min(78, (avail_h - 5 * gap) // 6))
row_h = max(62, min(78, (max(420, h - area_top - 24) - 5 * gap) // 6))
y1 = area_top + row_h // 2
y2 = y1 + row_h + gap
y3 = y2 + row_h + gap
sw_x_right = w // 2 + content_w // 2 - 22
self._rebuild_switches(cv, w, h, (sw_x_right, y2), (sw_x_right, y3))
self._draw_lang_card(cv, w // 2, y1, content_w, row_h)
self._draw_switch_card(
cv, w // 2, y2, content_w, row_h,
t("settings_hover_help_title"),
t("settings_hover_help_desc"),
self._sw_hover,
y2, y3 = y1 + row_h + gap, y1 + 2 * (row_h + gap)
sw_xr = w // 2 + content_w // 2 - 22
self._rebuild_switches(cv, w, h, (sw_xr, y2), (sw_xr, y3))
SettingsCardsRenderer.draw_lang_card(cv, self.assets, self._photo_refs, w // 2, y1, content_w, row_h, self._btn_lang)
SettingsCardsRenderer.draw_switch_card(
cv, self.assets, self._photo_refs, w // 2, y2, content_w, row_h,
t("settings_hover_help_title"), t("settings_hover_help_desc"), self._sw_hover,
)
self._draw_switch_card(
cv, w // 2, y3, content_w, row_h,
t("settings_single_tap_title"),
t("settings_single_tap_desc"),
self._sw_tap,
SettingsCardsRenderer.draw_switch_card(
cv, self.assets, self._photo_refs, w // 2, y3, content_w, row_h,
t("settings_single_tap_title"), t("settings_single_tap_desc"), self._sw_tap,
)
sl_h = max(78, row_h + 10)
sy1 = (y3 + row_h // 2 + gap) + sl_h // 2
sy2 = sy1 + sl_h + gap
self._draw_slider_card(
cv, "amb", w // 2, sy1, content_w, sl_h,
t("audio_ambiance_label"),
t("audio_ambiance_desc"),
self.sounds.ambiance_volume,
lambda v: self.sounds.set_ambiance_volume(v, persist=True),
)
self._draw_slider_card(
cv, "sfx", w // 2, sy2, content_w, sl_h,
t("audio_sfx_label"),
t("audio_sfx_desc"),
self.sounds.menu_volume,
lambda v: self.sounds.set_menu_volume(v, persist=True),
)
sl_cx, sl_w = w // 2, content_w
db_h = max(96, row_h + 26)
db_cy = (sy2 + sl_h // 2 + gap) + db_h // 2
self._draw_user_data_card(
cv, w // 2, db_cy, content_w, db_h, horizontal_btns=(content_w >= 520)
)
horiz_db = (content_w >= 520)
def _draw_lang_card(self, cv: tk.Canvas, cx: int, cy: int, box_w: int, box_h: int):
x_left = cx - box_w // 2 + 24
x_right = cx + box_w // 2 - 22
box_ph = self.assets.get_box_photo("box_purple", (box_w, box_h))
if box_ph:
self._photo_refs.append(box_ph)
cv.create_image(cx, cy, image=box_ph, anchor="center", tags="settings_fg")
lbl_ph = self.assets.get_goth_text_photo(
t("settings_lang_title"),
size_px=FONT_SIZE_BODY + 2,
color=FONT_COLOR_BODY_DEFAULT,
align="left",
SettingsCardsRenderer.draw_slider_card(
cv, self.assets, self._photo_refs, self._sliders, "amb", sl_cx, sy1, sl_w, sl_h,
t("audio_ambiance_label"), t("audio_ambiance_desc"),
self.sounds.ambiance_volume, lambda v: self.sounds.set_ambiance_volume(v, persist=True),
)
desc_ph = self.assets.get_goth_text_photo(
t("settings_lang_desc"),
size_px=FONT_SIZE_SMALL_MIN,
color=FONT_COLOR_BODY_MUTED,
max_width=max(120, box_w - 210),
align="left",
SettingsCardsRenderer.draw_slider_card(
cv, self.assets, self._photo_refs, self._sliders, "sfx", sl_cx, sy2, sl_w, sl_h,
t("audio_sfx_label"), t("audio_sfx_desc"),
self.sounds.menu_volume, lambda v: self.sounds.set_menu_volume(v, persist=True),
)
self._photo_refs.extend([lbl_ph, desc_ph])
cv.create_image(x_left, cy - 12, image=lbl_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy + 13, image=desc_ph, anchor="w", tags="settings_fg")
for k in ("amb", "sfx"):
self._update_slider_visual(k, self._sliders[k]["val"], notify=False)
if self._btn_lang is not None and self._btn_lang.winfo_exists():
cv.create_window(x_right, cy, window=self._btn_lang, anchor="e", tags="settings_fg")
def _draw_switch_card(
self,
cv: tk.Canvas,
cx: int,
cy: int,
box_w: int,
box_h: int,
title_txt: str,
desc_txt: str,
switch_wgt: GothSwitch | None,
):
x_left = cx - box_w // 2 + 24
x_right = cx + box_w // 2 - 22
box_ph = self.assets.get_box_photo("box_purple", (box_w, box_h))
if box_ph:
self._photo_refs.append(box_ph)
cv.create_image(cx, cy, image=box_ph, anchor="center", tags="settings_fg")
lbl_ph = self.assets.get_goth_text_photo(
title_txt,
size_px=FONT_SIZE_BODY + 1,
color=FONT_COLOR_BODY_DEFAULT,
max_width=max(120, box_w - 156),
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=max(120, box_w - 156),
align="left",
)
self._photo_refs.extend([lbl_ph, desc_ph])
cv.create_image(x_left, cy - 13, image=lbl_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy + 13, image=desc_ph, anchor="w", tags="settings_fg")
if switch_wgt is not None and switch_wgt.winfo_exists():
cv.create_window(x_right, cy, window=switch_wgt, anchor="e", tags="settings_fg")
def _draw_slider_card(
self,
cv: tk.Canvas,
key: str,
cx: int,
cy: int,
box_w: int,
box_h: int,
label_txt: str,
desc_txt: str,
initial_vol: float,
on_change,
):
x_left = cx - box_w // 2 + 24
x_right = cx + box_w // 2 - 24
box_ph = self.assets.get_box_photo("box_purple", (box_w, box_h))
if box_ph:
self._photo_refs.append(box_ph)
cv.create_image(cx, cy, image=box_ph, anchor="center", tags="settings_fg")
top_off = max(24, box_h // 4 + 4)
lbl_ph = self.assets.get_goth_text_photo(
label_txt,
size_px=FONT_SIZE_BODY + 2,
color=FONT_COLOR_BODY_DEFAULT,
max_width=max(140, box_w - 130),
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=max(140, box_w - 48),
align="left",
)
self._photo_refs.extend([lbl_ph, desc_ph])
cv.create_image(x_left, cy - top_off, image=lbl_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy - 2, image=desc_ph, anchor="w", tags="settings_fg")
pct_item = cv.create_image(x_right, cy - top_off, anchor="e", tags="settings_fg")
track_y = cy + max(24, box_h // 4 + 2)
track_x1 = x_left + 6
track_x2 = x_right - 6
cv.create_rectangle(
track_x1,
track_y - 5,
track_x2,
track_y + 5,
fill="#09070e",
outline=SUBTLE_BORDER,
width=1,
tags="settings_fg",
)
fill_id = cv.create_rectangle(
track_x1,
track_y - 4,
track_x1,
track_y + 4,
fill=UI_ACCENT_AMETHYST,
outline="",
tags="settings_fg",
)
knob_id = cv.create_polygon(
0, 0, 0, 0, 0, 0, 0, 0,
fill=UI_ACCENT_GOLD,
outline="#0d0b12",
width=1,
tags="settings_fg",
SettingsCardsRenderer.draw_user_data_card(
cv, self.assets, self._photo_refs, w // 2, db_cy, content_w, db_h,
self._db_feedback_txt, self._db_feedback_err,
self._btn_db_load, self._btn_db_move, horizontal_btns=horiz_db,
)
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 _draw_user_data_card(
self,
cv: tk.Canvas,
cx: int,
cy: int,
box_w: int,
box_h: int,
horizontal_btns: bool = True,
):
x_left = cx - box_w // 2 + 26
x_right = cx + box_w // 2 - 26
box_ph = self.assets.get_box_photo("box_gold_double", (box_w, box_h))
if box_ph:
self._photo_refs.append(box_ph)
cv.create_image(cx, cy, image=box_ph, anchor="center", tags="settings_fg")
hdr_ph = self.assets.get_goth_text_photo(
t("db_settings_title"),
size_px=FONT_SIZE_BODY + 2,
color=FONT_COLOR_TITLE_MAIN,
align="left",
)
cur_db_str = self._shorten_path(str(Database.get_user_db_path()), max_chars=max(42, box_w // 12))
sub_txt = self._db_feedback_txt if self._db_feedback_txt else t("db_Active_path_lbl", cur_db_str)
sub_col = (
(FONT_COLOR_STATUS_LOSS if self._db_feedback_err else FONT_COLOR_STATUS_WIN)
if self._db_feedback_txt
else FONT_COLOR_BODY_DEFAULT
)
path_ph = self.assets.get_goth_text_photo(
sub_txt,
size_px=FONT_SIZE_SMALL_MIN + 1,
color=sub_col,
max_width=max(180, (box_w - 490) if (horizontal_btns and box_w >= 860) else (box_w - 56)),
align="left",
)
self._photo_refs.extend([hdr_ph, path_ph])
if horizontal_btns and box_w >= 860:
cv.create_image(x_left, cy - 14, image=hdr_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy + 14, image=path_ph, anchor="w", tags="settings_fg")
if self._btn_db_move is not None and self._btn_db_move.winfo_exists():
cv.create_window(x_right, cy, window=self._btn_db_move, anchor="e", tags="settings_fg")
if self._btn_db_load is not None and self._btn_db_load.winfo_exists():
cv.create_window(x_right - 220, cy, window=self._btn_db_load, anchor="e", tags="settings_fg")
else:
cv.create_image(x_left, cy - 30, image=hdr_ph, anchor="w", tags="settings_fg")
cv.create_image(x_left, cy - 6, image=path_ph, anchor="w", tags="settings_fg")
if self._btn_db_load is not None and self._btn_db_load.winfo_exists():
cv.create_window(x_left, cy + 26, window=self._btn_db_load, anchor="w", tags="settings_fg")
if self._btn_db_move is not None and self._btn_db_move.winfo_exists():
cv.create_window(x_right, cy + 26, window=self._btn_db_move, anchor="e", tags="settings_fg")
# ------------------------------------------------------------------
# SLIDER-INTERAKTION (MAUS & TOUCH)
# ------------------------------------------------------------------
def _update_slider_visual(self, key: str, val: float, notify: bool = True):
if self._cv is None or not self._cv.winfo_exists() or key not in self._sliders:
return
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"]
kx, ky, r = s["x1"] + (s["x2"] - s["x1"]) * val, s["y"], 10
self._cv.coords(s["fill_id"], s["x1"] + 1, ky - 4, kx, ky + 4)
r = 10
self._cv.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",
f"{int(round(val * 100))} %", FONT_SIZE_BODY + 2, FONT_COLOR_HEADING_SUB, align="right"
)
self._pct_photos[key] = pct_ph
self._cv.itemconfigure(s["pct_item"], image=pct_ph)
if notify:
s["on_change"](val)
@ -823,15 +439,10 @@ class SettingsView:
for key, s in self._sliders.items():
if (s["x1"] - 14) <= event.x <= (s["x2"] + 14) and abs(event.y - s["y"]) <= 22:
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)
self._update_slider_visual(key, (event.x - s["x1"]) / max(1.0, float(s["x2"] - s["x1"])), 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)
def _on_mouse_up(self, _event):
self._dragging_key = None
self._update_slider_visual(self._dragging_key, (event.x - s["x1"]) / max(1.0, float(s["x2"] - s["x1"])), True)

View File

@ -1,235 +0,0 @@
# -*- coding: utf-8 -*-
# view/menus/statistics_view.py
from __future__ import annotations
import tkinter as tk
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,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.stats_board_widget import StatsBoardWidget
class StatisticsView:
def __init__(self, root_view):
self.root = root_view
self.ctrl = root_view.ctrl
self.assets = root_view.assets
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
btn_norm = self.assets.raw_btn_default
btn_purp = self.assets.raw_btn_purple
btn_fire = self.assets.raw_btn_fire or btn_purp
# 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_settings = ImageButton(
cv,
t("btn_settings"),
btn_norm,
btn_purp,
lambda: self.ctrl.show_settings(
on_back=lambda: self.show(self.ctrl.active_profile, self.selected_folder)
),
sound_mgr=self.sounds,
width=122,
height=36,
style="amethyst",
)
# Spiel-Auswahl-Buttons
self._game_btns: list[tuple[tk.Widget, int]] = []
self._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,
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))
# 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}
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),
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_settings, 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})()
))

View File

@ -0,0 +1,176 @@
# -*- coding: utf-8 -*-
# view/stats_detail_renderer.py
from __future__ import annotations
import tkinter as tk
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,
STAT_FIELD_KEYS,
SUBTLE_BORDER,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
)
from resources.code_res.i18n import t
class StatsDetailRenderer:
"""Rendert die Detail-Statistikansicht eines einzelnen Kartenspiels."""
@staticmethod
def draw_detail(
cv: tk.Canvas,
assets,
game_title: str,
rank_line: str,
xp_ratio: float,
board_heading: str,
stats_data: dict,
back_btn: tk.Widget,
hub_btn: tk.Widget | None,
var_btns: list[tuple[tk.Widget, int]],
acc_btns: list[tuple[tk.Widget, int]],
photo_refs: list,
w: int,
h: int,
) -> None:
compact = (h < 780)
pad_x = max(72, int(w * 0.08))
content_w = min(1080, w - 2 * pad_x)
left_x = (w - content_w) // 2
top_y = max(48, int(h * 0.085))
cv.create_window(left_x, top_y, window=back_btn, anchor="w", tags="fg")
if hub_btn is not None:
cv.create_window(left_x + content_w, top_y, window=hub_btn, anchor="e", tags="fg")
hdr_ph = assets.get_goth_text_photo(
t("stats_view_topbar", game_title),
size_px=FONT_SIZE_HEADING + (0 if compact else 2),
color=FONT_COLOR_TITLE_MAIN,
max_width=max(220, content_w - 340),
)
photo_refs.append(hdr_ph)
cv.create_image(w // 2, top_y, image=hdr_ph, anchor="center", tags="fg")
sep_y = top_y + (34 if compact else 42)
cv.create_line(left_x, sep_y, left_x + content_w, sep_y, fill=SUBTLE_BORDER, width=1, tags="fg")
cur_y = sep_y + (16 if compact else 22)
# 1. Rang-, Varianten- & optionale Goldbeutel-Box
has_acc = len(acc_btns) > 0
has_vars = len(var_btns) > 0
hdr_h = 112 if has_acc else (98 if has_vars else 72)
hdr_cy = cur_y + hdr_h // 2
hdr_box = assets.get_box_photo("box_gold_double", (content_w, hdr_h))
if hdr_box:
photo_refs.append(hdr_box)
cv.create_image(w // 2, hdr_cy, image=hdr_box, anchor="center", tags="fg")
top_row_y = (cur_y + 28) if (has_acc or has_vars) else hdr_cy
bar_w = 210
rank_ph = assets.get_goth_text_photo(
rank_line,
size_px=FONT_SIZE_BODY + 1,
color=FONT_COLOR_TITLE_MAIN,
max_width=max(220, content_w - bar_w - 72),
align="left",
)
photo_refs.append(rank_ph)
cv.create_image(left_x + 26, top_row_y, image=rank_ph, anchor="w", tags="fg")
# XP-Fortschrittsbalken rechts
bx2 = left_x + content_w - 26
bx1 = bx2 - bar_w
by1, by2 = top_row_y - 7, top_row_y + 7
cv.create_rectangle(bx1, by1, bx2, by2, fill="#0b0810", outline=UI_ACCENT_GOLD, width=1, tags="fg")
clamped = max(0.0, min(1.0, xp_ratio))
if clamped > 0.0:
fw = max(2, int((bar_w - 4) * clamped))
cv.create_rectangle(bx1 + 2, by1 + 2, bx1 + 2 + fw, by2 - 2, fill=UI_ACCENT_AMETHYST, outline="", tags="fg")
sub_row_y = cur_y + hdr_h - 28
if has_acc:
ax = left_x + 26
p_ph = assets.get_goth_text_photo(t("stats_pouch_lbl"), FONT_SIZE_BODY, FONT_COLOR_HEADING_SUB, align="left")
photo_refs.append(p_ph)
cv.create_image(ax, sub_row_y, image=p_ph, anchor="w", tags="fg")
ax += p_ph.width() + 12
for b_wgt, bw in acc_btns:
cv.create_window(ax, sub_row_y, window=b_wgt, anchor="w", tags="fg")
ax += bw + 8
if has_vars:
rx = left_x + content_w - 24
for b_wgt, bw in reversed(var_btns):
cv.create_window(rx, sub_row_y, window=b_wgt, anchor="e", tags="fg")
rx -= (bw + 6)
cur_y += hdr_h + (14 if compact else 18)
# 2. 8-Kacheln-Statistik-Board
bottom_safe = max(46, int(h * 0.075))
board_h = max(248, min(360, h - cur_y - bottom_safe))
board_cy = cur_y + board_h // 2
outer_box = assets.get_box_photo("box_big", (content_w, board_h))
if outer_box:
photo_refs.append(outer_box)
cv.create_image(w // 2, board_cy, image=outer_box, anchor="center", tags="fg")
sub_ph = assets.get_goth_text_photo(
board_heading,
size_px=FONT_SIZE_HEADING - 3,
color=FONT_COLOR_HEADING_SUB,
max_width=content_w - 56,
align="left",
)
photo_refs.append(sub_ph)
cv.create_image(left_x + 28, cur_y + 30, image=sub_ph, anchor="w", tags="fg")
grid_top = cur_y + 58
grid_h = board_h - 78
cols, rows = 4, 2
gap_x, gap_y = 14, 12
cell_w = (content_w - 56 - (cols - 1) * gap_x) // cols
cell_h = max(68, (grid_h - (rows - 1) * gap_y) // rows)
cell_frame = assets.get_box_photo("box_purple", (cell_w, cell_h))
if cell_frame:
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 = assets.get_goth_text_photo(
t(label_i18n_key), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=cell_w - 24
)
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
val_ph = assets.get_goth_text_photo(
str(stats_data.get(field_key, "--")), FONT_SIZE_HEADING - 2, v_col, max_width=cell_w - 24
)
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")

226
view/stats_hub_renderer.py Normal file
View File

@ -0,0 +1,226 @@
# -*- coding: utf-8 -*-
# view/stats_hub_renderer.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 (
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,
STAT_CATEGORIES,
STAT_CAT_LUCK,
STAT_FOLDER_CATEGORY_MAP,
STAT_GAME_GROUPS,
SUBTLE_BORDER,
UI_ACCENT_AMETHYST,
)
from resources.code_res.i18n import t
class StatsHubRenderer:
"""Rendert die kategorisierte Spiel-Auswahl als Einstiegspunkt für Statistiken."""
@classmethod
def draw_hub(
cls,
cv: tk.Canvas,
assets,
sounds,
profile: dict,
selected_cat: str,
cat_btns: list[tuple[tk.Widget, int]],
back_btn: tk.Widget,
settings_btn: tk.Widget | None,
on_select_game,
photo_refs: list,
w: int,
h: int,
) -> None:
compact = (h < 780)
pad_x = max(72, int(w * 0.08))
top_y = max(48, int(h * 0.085))
cv.create_window(pad_x, top_y, window=back_btn, anchor="w", tags="fg")
if settings_btn is not None:
cv.create_window(w - pad_x, top_y, window=settings_btn, anchor="e", tags="fg")
hdr_ph = assets.get_goth_text_photo(
t("stats_overall_summary", profile.get("name", "")),
size_px=FONT_SIZE_HEADING + (0 if compact else 2),
color=FONT_COLOR_TITLE_MAIN,
max_width=max(220, w - 480),
)
photo_refs.append(hdr_ph)
cv.create_image(w // 2, top_y, image=hdr_ph, anchor="center", tags="fg")
sep_y = top_y + (34 if compact else 42)
cv.create_line(pad_x, sep_y, w - pad_x, sep_y, fill=SUBTLE_BORDER, width=1, tags="fg")
# Kategorie-Leiste (Glück | Solitaire | Bayerische Spiele | Gesellschaft)
cat_y = sep_y + (28 if compact else 34)
total_tabs_w = sum(bw for _, bw in cat_btns) + max(0, len(cat_btns) - 1) * 10
tab_x = (w - total_tabs_w) // 2
for btn_wgt, bw in cat_btns:
cv.create_window(tab_x + bw // 2, cat_y, window=btn_wgt, anchor="center", tags="fg")
tab_x += bw + 10
active_cat_title = ""
active_cat_desc = ""
for cid, t_key, d_key in STAT_CATEGORIES:
if cid == selected_cat:
active_cat_title = t(t_key)
active_cat_desc = t(d_key)
break
desc_y = cat_y + (30 if compact else 36)
desc_ph = assets.get_goth_text_photo(
active_cat_desc,
size_px=FONT_SIZE_BODY,
color=FONT_COLOR_BODY_MUTED,
max_width=min(880, w - 2 * pad_x),
align="center",
)
photo_refs.append(desc_ph)
cv.create_image(w // 2, desc_y, image=desc_ph, anchor="center", tags="fg")
pid = profile["id"]
games_in_cat: list[tuple[str, str, dict]] = []
for folder, title_key in STAT_GAME_GROUPS:
g_cat = STAT_FOLDER_CATEGORY_MAP.get(folder, STAT_CAT_LUCK)
if g_cat == selected_cat:
prog = Database.get_game_progress(pid, folder)
games_in_cat.append((folder, t(title_key), prog))
area_top = desc_y + 28
area_bot = h - max(48, int(h * 0.08))
mid_y = (area_top + area_bot) // 2
if not games_in_cat:
empty_ph = assets.get_goth_text_photo(
t("no_games_in_category", active_cat_title),
size_px=FONT_SIZE_HEADING - 2,
color=FONT_COLOR_BODY_MUTED,
max_width=620,
)
photo_refs.append(empty_ph)
eb_frame = assets.get_box_photo("box_purple", (empty_ph.width() + 68, empty_ph.height() + 44))
if eb_frame:
photo_refs.append(eb_frame)
cv.create_image(w // 2, mid_y, image=eb_frame, anchor="center", tags="fg")
cv.create_image(w // 2, mid_y, image=empty_ph, anchor="center", tags="fg")
return
cols = min(4, len(games_in_cat))
rows = (len(games_in_cat) + cols - 1) // cols
tight = compact or rows > 1
col_step = min(244, max(194, (w - 2 * pad_x) // max(1, cols)))
row_step = 232 if tight else 264
start_y = mid_y - ((rows - 1) * row_step) // 2
for idx, (folder, g_title, prog) in enumerate(games_in_cat):
r, c = idx // 4, idx % 4
in_row = min(4, len(games_in_cat) - r * 4)
cx = (w // 2) - ((in_row - 1) * col_step) // 2 + c * col_step
cy = start_y + r * row_step
sub_txt = t("menu_card_rank_sub", prog["title"], prog["level"])
cls._draw_game_tile(
cv, assets, sounds, photo_refs,
cx, cy, idx, folder, g_title, sub_txt,
on_click=lambda f=folder: on_select_game(f),
compact=tight,
)
@staticmethod
def _draw_game_tile(
cv: tk.Canvas,
assets,
sounds,
photo_refs: list,
cx: int,
cy: int,
idx: int,
folder: str,
game_title: str,
rank_sub: str,
on_click,
compact: bool,
) -> None:
hit_tag = f"stat_tile_{idx}"
tags = ("fg", hit_tag)
cw_n, ch_n = (184, 214) if compact else (202, 238)
cw_h, ch_h = cw_n + 14, ch_n + 16
fn = assets.get_box_photo("box_purple", (cw_n, ch_n))
fh = assets.get_box_photo("box_gold_small", (cw_h, ch_h))
if fn:
photo_refs.append(fn)
if fh:
photo_refs.append(fh)
b_px = 90 if compact else 102
h_px = b_px + 12
ic_n = get_game_icon_photo(assets.res, folder, size_px=b_px)
ic_h = get_game_icon_photo(assets.res, folder, size_px=h_px)
if ic_n is None:
ic_n = assets.get_goth_text_photo("*", FONT_SIZE_TITLE_LG - 4, UI_ACCENT_AMETHYST)
ic_h = assets.get_goth_text_photo("*", FONT_SIZE_TITLE_LG + 2, FONT_COLOR_TITLE_MAIN)
photo_refs.extend([ic_n, ic_h])
tp_n = (FONT_SIZE_HEADING - 3) if compact else (FONT_SIZE_HEADING - 1)
t_n = assets.get_goth_text_photo(game_title, tp_n, FONT_COLOR_BODY_DEFAULT, max_width=cw_n - 24)
t_h = assets.get_goth_text_photo(game_title, tp_n + 3, FONT_COLOR_TITLE_MAIN, max_width=cw_h - 22)
s_n = assets.get_goth_text_photo(rank_sub, FONT_SIZE_SMALL_MIN, FONT_COLOR_HEADING_SUB, max_width=cw_n - 24)
s_h = assets.get_goth_text_photo(rank_sub, FONT_SIZE_SMALL_MIN + 2, "#ffffff", max_width=cw_h - 22)
photo_refs.extend([t_n, t_h, s_n, s_h])
iy_n = cy - (38 if compact else 43)
iy_h = iy_n - 3
ty_n = iy_n + b_px // 2 + (19 if compact else 22)
ty_h = iy_h + h_px // 2 + (20 if compact else 23)
sy_n = ty_n + (31 if compact else 35)
sy_h = ty_h + (34 if compact else 38)
f_id = cv.create_image(cx, cy, image=fn, anchor="center", tags=tags) if fn else None
i_id = cv.create_image(cx, iy_n, image=ic_n, anchor="center", tags=tags)
t_id = cv.create_image(cx, ty_n, image=t_n, anchor="center", tags=tags)
s_id = cv.create_image(cx, sy_n, image=s_n, anchor="center", tags=tags)
hit = cv.create_rectangle(
cx - cw_h // 2, cy - ch_h // 2, cx + cw_h // 2, cy + ch_h // 2,
fill="", outline="", width=0, tags=tags,
)
cv.tag_raise(hit)
def _enter(_e):
cv.configure(cursor="hand2")
if f_id and fh:
cv.itemconfigure(f_id, image=fh)
cv.coords(i_id, cx, iy_h)
cv.itemconfigure(i_id, image=ic_h)
cv.coords(t_id, cx, ty_h)
cv.itemconfigure(t_id, image=t_h)
cv.coords(s_id, cx, sy_h)
cv.itemconfigure(s_id, image=s_h)
def _leave(_e):
cv.configure(cursor="")
if f_id and fn:
cv.itemconfigure(f_id, image=fn)
cv.coords(i_id, cx, iy_n)
cv.itemconfigure(i_id, image=ic_n)
cv.coords(t_id, cx, ty_n)
cv.itemconfigure(t_id, image=t_n)
cv.coords(s_id, cx, sy_n)
cv.itemconfigure(s_id, image=s_n)
cv.tag_bind(hit_tag, "<Enter>", _enter)
cv.tag_bind(hit_tag, "<Leave>", _leave)
cv.tag_bind(hit_tag, "<Button-1>", lambda _e: (sounds.play("click"), on_click()))

View File

@ -8,19 +8,14 @@ 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_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,
STAT_FIELD_KEYS,
STAT_CATEGORIES,
STAT_CAT_LUCK,
STAT_FOLDER_CATEGORY_MAP,
STAT_GAME_GROUPS,
)
from resources.code_res.i18n import t
from view.stats_detail_renderer import StatsDetailRenderer
from view.stats_hub_renderer import StatsHubRenderer
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
@ -34,8 +29,7 @@ SHORT_VARIANT_TAB_KEYS: dict[str, str] = {
ENDPOINT_ALIASES: dict[str, str | None] = {
"": None,
"all": None,
"gesamt": None,
"hub": None,
"blackjack": "blackjack",
"poker": "poker",
"klondike": "solitaire/klondike",
@ -45,11 +39,12 @@ ENDPOINT_ALIASES: dict[str, str | None] = {
"spider": "solitaire/spider_solitaire",
"spider_solitaire": "solitaire/spider_solitaire",
"solitaire/spider_solitaire": "solitaire/spider_solitaire",
"pyramid": "solitaire/pyramid",
"solitaire/pyramid": "solitaire/pyramid",
}
def resolve_stats_endpoint(endpoint: str | None) -> str | None:
"""Löst Kurznamen wie 'klondike', 'spider' oder 'blackjack' auf den DB-Ordnerpfad auf."""
if endpoint is None:
return None
clean = str(endpoint).strip().lower()
@ -67,19 +62,15 @@ def resolve_stats_endpoint(endpoint: str | None) -> str | None:
class UnifiedStatsView(tk.Canvas):
"""
Zentrale Vollbild-Statistik-Ansicht für alle Spiele (ohne Topbar & ohne Bottombar):
- Parameter 1 (`game_endpoint`): Spiel-Endpunkt ('blackjack', 'poker', 'klondike', 'freecell', 'spider' oder None)
- Parameter 2 (`on_back`): Optionale Rücksprung-Funktion; falls None, schließt sich das Overlay
einfach und gibt die exakt darunterliegende Spielansicht sofort wieder frei!
Zentrale Statistik-Ansicht:
- Ohne `game_endpoint` (z. B. aus dem Hauptmenü): Kategorisierter Spielauswahl-Hub
(Glück, Solitaire, Bayerische Spiele, Gesellschaft - keine Gesamt-Statistik!).
- Mit `game_endpoint` (Klick auf Spiel-Kachel oder Direktaufruf aus GothTopbar):
Einzelspiel-Statistik inkl. Goldbeuteln (Blackjack/Poker) bzw. Varianten-Tabs.
"""
@classmethod
def open(
cls,
context,
game_endpoint: str | None = None,
on_back=None,
) -> "UnifiedStatsView":
def open(cls, context, game_endpoint: str | None = None, on_back=None) -> "UnifiedStatsView":
GothDropdown.close_any_open_popup()
root = context.root
existing = getattr(root, "_unified_stats_overlay", None)
@ -90,22 +81,20 @@ class UnifiedStatsView(tk.Canvas):
setattr(root, "_unified_stats_overlay", view)
return view
def __init__(
self,
context,
game_endpoint: str | None = None,
on_back=None,
):
super().__init__(
context.root,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
)
def __init__(self, context, game_endpoint: str | None = None, on_back=None):
super().__init__(context.root, bg=BG_COLOR, bd=0, highlightthickness=0)
self.ctx = context
self.on_back = on_back
self._opened_from_hub: bool = (resolve_stats_endpoint(game_endpoint) is None)
self._active_folder: str | None = resolve_stats_endpoint(game_endpoint)
saved_cat = Database.load_setting("last_stats_category", STAT_CAT_LUCK)
valid_cats = {c[0] for c in STAT_CATEGORIES}
self._selected_cat: str = (
STAT_FOLDER_CATEGORY_MAP.get(self._active_folder, saved_cat)
if self._active_folder
else (saved_cat if saved_cat in valid_cats else STAT_CAT_LUCK)
)
self._active_variant_id: int | None = None
self._active_account_id: int | None = None
@ -114,29 +103,30 @@ class UnifiedStatsView(tk.Canvas):
self._child_buttons: list[ImageButton] = []
self._esc_bind_id: str | None = None
self._back_btn: ImageButton | None = None
self._hub_or_settings_btn: ImageButton | None = None
self._cat_btns: list[tuple[ImageButton, int]] = []
self._var_btns: list[tuple[ImageButton, int]] = []
self._acc_btns: list[tuple[ImageButton, int]] = []
self._game_title: str = ""
self._rank_line: str = ""
self._xp_ratio: float = 0.0
self._board_heading: str = ""
self._stats_data: dict = {}
self.place(relx=0.0, rely=0.0, relwidth=1.0, relheight=1.0)
tk.Widget.tkraise(self)
self.bind("<Configure>", self._on_configure)
self.bind("<Destroy>", self._on_destroy)
try:
self._esc_bind_id = self.ctx.root.bind("<Escape>", self._handle_back, add="+")
self._esc_bind_id = self.ctx.root.bind("<Escape>", self._handle_back_action, add="+")
except tk.TclError:
self._esc_bind_id = None
self._rebuild_view()
def show(
self,
game_folder: str | None = None,
variant_id: int | None = None,
account_id: int | None = None,
):
self._active_folder = resolve_stats_endpoint(game_folder)
self._active_variant_id = variant_id
self._active_account_id = account_id
self._rebuild_view()
def _on_destroy(self, event=None):
if event is not None and event.widget is not self:
return
@ -149,21 +139,36 @@ class UnifiedStatsView(tk.Canvas):
if getattr(self.ctx.root, "_unified_stats_overlay", None) is self:
setattr(self.ctx.root, "_unified_stats_overlay", None)
def _handle_back(self, _event=None):
def _close_and_return(self):
back_cb = self.on_back
if self.winfo_exists():
self.destroy()
if callable(back_cb):
back_cb()
def _handle_back_action(self, _event=None):
if self._active_folder is not None and self._opened_from_hub:
self._active_folder = None
self._active_variant_id = None
self._active_account_id = None
self._rebuild_view()
return "break"
self._close_and_return()
return "break"
def _switch_filter(
self,
folder: str | None,
variant_id: int | None = None,
account_id: int | None = None,
):
def _select_hub_category(self, cat_id: str):
self._selected_cat = cat_id
Database.save_setting("last_stats_category", cat_id)
self._rebuild_view()
def _open_game_from_hub(self, folder: str):
self._selected_cat = STAT_FOLDER_CATEGORY_MAP.get(folder, self._selected_cat)
self._active_folder = folder
self._active_variant_id = None
self._active_account_id = None
self._rebuild_view()
def _switch_detail_filter(self, variant_id: int | None, account_id: int | None):
self._active_variant_id = variant_id
self._active_account_id = account_id
self._rebuild_view()
@ -176,6 +181,9 @@ class UnifiedStatsView(tk.Canvas):
except Exception:
pass
self._child_buttons.clear()
self._cat_btns.clear()
self._var_btns.clear()
self._acc_btns.clear()
def _render_full_bg(self, w: int, h: int):
if hasattr(self.ctx.assets, "get_bg_patch_photo"):
@ -187,10 +195,7 @@ class UnifiedStatsView(tk.Canvas):
else (self.ctx.assets.raw_bg_horizontal or self.ctx.assets.raw_bg)
)
if src is not None:
self._bg_photo = ImageTk.PhotoImage(
src.resize((w, h), Image.Resampling.BILINEAR)
)
self._bg_photo = ImageTk.PhotoImage(src.resize((w, h), Image.Resampling.BILINEAR))
if self._bg_photo is not None:
self.delete("stats_bg")
self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags="stats_bg")
@ -199,353 +204,161 @@ class UnifiedStatsView(tk.Canvas):
def _on_configure(self, event):
if event.widget is not self or event.width < 200 or event.height < 200:
return
self._draw_canvas_layout(event.width, event.height)
self._draw_active_mode(event.width, event.height)
def _rebuild_view(self):
if not self.winfo_exists():
return
self._clear_buttons()
pid = self.ctx.profile["id"]
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
self._back_btn = ImageButton(
self,
t("btn_back"),
btn_fire,
btn_fire,
self._handle_back,
sound_mgr=self.ctx.sounds,
width=118,
height=34,
style="fire",
)
self._child_buttons.append(self._back_btn)
# 1. Spiel-Umschalter (Alle Spiele + registrierte Spiele)
all_lbl = t("filter_all_games")
game_tabs: list[tuple[str | None, str]] = [(None, all_lbl)]
for folder_key, title_i18n_key in STAT_GAME_GROUPS:
game_tabs.append((folder_key, t(title_i18n_key)))
self._game_btns: list[tuple[ImageButton, int]] = []
for f_key, g_lbl in game_tabs:
is_sel = (self._active_folder == f_key)
bw = max(108, min(162, len(g_lbl) * 9 + 34))
b = ImageButton(
self,
g_lbl,
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
lambda target_f=f_key: self._switch_filter(target_f, None, None),
sound_mgr=self.ctx.sounds,
width=bw,
height=34,
style="fire" if is_sel else "amethyst",
)
self._child_buttons.append(b)
self._game_btns.append((b, b.pixel_width))
# 2. Goldbeutel-Umschalter (nur bei Blackjack & Poker)
self._acc_btns: list[tuple[ImageButton, int]] = []
accounts: list[dict] = []
active_acc_obj: dict | None = None
if self._active_folder == "blackjack":
accounts = Database.get_blackjack_accounts(pid)
elif self._active_folder == "poker":
accounts = Database.get_poker_accounts(pid)
if accounts:
for a in accounts:
if a["id"] == self._active_account_id:
active_acc_obj = a
break
if self._active_account_id is not None and active_acc_obj is None:
self._active_account_id = None
prof_all_lbl = t("stats_profile_total_tab")
is_prof_sel = (active_acc_obj is None)
b_prof = ImageButton(
self,
prof_all_lbl,
btn_fire if is_prof_sel else btn_norm,
btn_fire if is_prof_sel else btn_purp,
lambda: self._switch_filter(
self._active_folder, self._active_variant_id, None
),
sound_mgr=self.ctx.sounds,
width=142,
height=32,
style="fire" if is_prof_sel else "amethyst",
)
self._child_buttons.append(b_prof)
self._acc_btns.append((b_prof, b_prof.pixel_width))
for acc in accounts:
is_a_sel = (active_acc_obj is not None and acc["id"] == active_acc_obj["id"])
a_lbl = f"{acc['account_name']} ({acc['gold']}g)"
bw_a = max(136, min(195, len(a_lbl) * 8 + 30))
b_acc = ImageButton(
self,
a_lbl,
btn_fire if is_a_sel else btn_norm,
btn_fire if is_a_sel else btn_purp,
lambda aid=acc["id"]: self._switch_filter(
self._active_folder, self._active_variant_id, aid
),
sound_mgr=self.ctx.sounds,
width=bw_a,
height=32,
style="fire" if is_a_sel else "amethyst",
)
self._child_buttons.append(b_acc)
self._acc_btns.append((b_acc, b_acc.pixel_width))
# 3. Varianten-Umschalter (sofern das Spiel mehrere Varianten hat)
self._var_btns: list[tuple[ImageButton, int]] = []
variants = (
Database.get_variants_for_filter(self._active_folder)
if self._active_folder
else []
)
if len(variants) > 1:
v_tabs: list[tuple[int | None, str]] = [(None, t("sol_stats_tab_all"))]
for v in variants:
vk = v["variant_key"]
short_lbl = (
t(SHORT_VARIANT_TAB_KEYS[vk])
if vk in SHORT_VARIANT_TAB_KEYS
else v["translated_name"]
)
v_tabs.append((v["id"], short_lbl))
for vid, v_text in v_tabs:
is_vsel = (self._active_variant_id == vid)
bw_v = 110 if vid is None else max(136, min(190, len(v_text) * 8 + 28))
b_var = ImageButton(
self,
v_text,
btn_fire if is_vsel else btn_norm,
btn_fire if is_vsel else btn_purp,
lambda target_vid=vid: self._switch_filter(
self._active_folder, target_vid, self._active_account_id
),
sound_mgr=self.ctx.sounds,
width=bw_v,
height=32,
style="fire" if is_vsel else "amethyst",
)
self._child_buttons.append(b_var)
self._var_btns.append((b_var, b_var.pixel_width))
# 4. Datenabfrage
if self._active_folder is None:
self._rank_line = t("stats_overall_summary", self.ctx.profile["name"])
self._board_heading = all_lbl
self._stats_data = Database.get_stats_overview(pid, variant_id=None, folder_path=None)
# --- HUB-MODUS (Spiel-Auswahl nach Kategorien) ---
self._back_btn = ImageButton(
self, t("btn_back_main"), btn_norm, btn_purp,
self._close_and_return, sound_mgr=self.ctx.sounds, width=142, height=36, style="amethyst",
)
self._hub_or_settings_btn = ImageButton(
self, t("btn_settings"), btn_norm, btn_purp,
lambda: self.ctx.open_settings(on_lang_refresh=self._rebuild_view),
sound_mgr=self.ctx.sounds, width=126, height=36, style="amethyst",
)
self._child_buttons.extend([self._back_btn, self._hub_or_settings_btn])
for cid, title_key, _dkey in STAT_CATEGORIES:
is_sel = (cid == self._selected_cat)
b_cat = ImageButton(
self, t(title_key),
btn_fire if is_sel else btn_norm,
btn_fire if is_sel else btn_purp,
lambda c=cid: self._select_hub_category(c),
sound_mgr=self.ctx.sounds, width=164, height=38,
style="fire" if is_sel else "amethyst",
)
self._child_buttons.append(b_cat)
self._cat_btns.append((b_cat, b_cat.pixel_width))
else:
group_map = dict(STAT_GAME_GROUPS)
game_name = (
t(group_map[self._active_folder])
if self._active_folder in group_map
else self._active_folder
)
prog = Database.get_game_progress(pid, self._active_folder)
self._rank_line = t(
"stats_game_rank_info",
game_name,
prog["title"],
prog["level"],
prog["current_xp"],
prog["needed_xp"],
)
var_label = t("stats_all_variants_of_game", game_name)
for v in variants:
if v["id"] == self._active_variant_id:
var_label = v["translated_name"]
break
if active_acc_obj is not None and self._active_folder == "blackjack":
self._board_heading = (
f"{t('bj_stats_acc_title', active_acc_obj['account_name'])} | {var_label}"
)
self._stats_data = Database.get_bj_account_stats_overview(
active_acc_obj["id"], self._active_variant_id
)
elif active_acc_obj is not None and self._active_folder == "poker":
self._board_heading = (
f"{t('bj_stats_acc_title', active_acc_obj['account_name'])} | {var_label}"
)
self._stats_data = Database.get_pk_account_stats_overview(
active_acc_obj["id"], self._active_variant_id
)
else:
self._board_heading = t("stats_game_board_title", var_label)
self._stats_data = Database.get_stats_overview(
pid,
variant_id=self._active_variant_id,
folder_path=self._active_folder if self._active_variant_id is None else None,
)
# --- DETAIL-MODUS (Einzelspiel-Auswertung) ---
self._build_detail_controls_and_data(btn_norm, btn_purp, btn_fire)
self.ctx.root.update_idletasks()
w = max(900, self.winfo_width(), self.ctx.root.winfo_width())
h = max(620, self.winfo_height(), self.ctx.root.winfo_height())
self._draw_canvas_layout(w, h)
self._draw_active_mode(w, h)
def _draw_canvas_layout(self, w: int, h: int):
def _build_detail_controls_and_data(self, btn_norm, btn_purp, btn_fire):
pid = self.ctx.profile["id"]
back_lbl = t("btn_back_stats_hub") if self._opened_from_hub else t("btn_back")
self._back_btn = ImageButton(
self, back_lbl, btn_fire, btn_fire,
self._handle_back_action, sound_mgr=self.ctx.sounds, width=142, height=34, style="fire",
)
self._child_buttons.append(self._back_btn)
self._hub_or_settings_btn = None
if not self._opened_from_hub:
self._hub_or_settings_btn = ImageButton(
self, t("btn_back_stats_hub"), btn_norm, btn_purp,
lambda: (setattr(self, "_opened_from_hub", True), self._handle_back_action()),
sound_mgr=self.ctx.sounds, width=148, height=34, style="amethyst",
)
self._child_buttons.append(self._hub_or_settings_btn)
accounts = (
Database.get_blackjack_accounts(pid) if self._active_folder == "blackjack"
else (Database.get_poker_accounts(pid) if self._active_folder == "poker" else [])
)
active_acc = next((a for a in accounts if a["id"] == self._active_account_id), None)
if self._active_account_id is not None and active_acc is None:
self._active_account_id = None
if accounts:
b_prof = ImageButton(
self, t("stats_profile_total_tab"),
btn_fire if active_acc is None else btn_norm,
btn_fire if active_acc is None else btn_purp,
lambda: self._switch_detail_filter(self._active_variant_id, None),
sound_mgr=self.ctx.sounds, width=142, height=32,
style="fire" if active_acc is None else "amethyst",
)
self._child_buttons.append(b_prof)
self._acc_btns.append((b_prof, b_prof.pixel_width))
for acc in accounts:
is_a = (active_acc is not None and acc["id"] == active_acc["id"])
a_lbl = f"{acc['account_name']} ({acc['gold']}g)"
bw_a = max(134, min(192, len(a_lbl) * 8 + 28))
b_acc = ImageButton(
self, a_lbl,
btn_fire if is_a else btn_norm, btn_fire if is_a else btn_purp,
lambda aid=acc["id"]: self._switch_detail_filter(self._active_variant_id, aid),
sound_mgr=self.ctx.sounds, width=bw_a, height=32,
style="fire" if is_a else "amethyst",
)
self._child_buttons.append(b_acc)
self._acc_btns.append((b_acc, b_acc.pixel_width))
variants = Database.get_variants_for_filter(self._active_folder)
if len(variants) > 1:
v_tabs: list[tuple[int | None, str]] = [(None, t("sol_stats_tab_all"))]
for v in variants:
vk = v["variant_key"]
v_tabs.append((v["id"], t(SHORT_VARIANT_TAB_KEYS[vk]) if vk in SHORT_VARIANT_TAB_KEYS else v["translated_name"]))
for vid, v_txt in v_tabs:
is_v = (self._active_variant_id == vid)
bw_v = 108 if vid is None else max(134, min(186, len(v_txt) * 8 + 26))
b_v = ImageButton(
self, v_txt,
btn_fire if is_v else btn_norm, btn_fire if is_v else btn_purp,
lambda tv=vid: self._switch_detail_filter(tv, self._active_account_id),
sound_mgr=self.ctx.sounds, width=bw_v, height=32,
style="fire" if is_v else "amethyst",
)
self._child_buttons.append(b_v)
self._var_btns.append((b_v, b_v.pixel_width))
group_map = dict(STAT_GAME_GROUPS)
self._game_title = t(group_map.get(self._active_folder, self._active_folder))
prog = Database.get_game_progress(pid, self._active_folder)
self._xp_ratio = float(prog["current_xp"]) / max(1.0, float(prog["needed_xp"]))
self._rank_line = t(
"stats_game_rank_info",
self._game_title, prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"],
)
var_lbl = next(
(v["translated_name"] for v in variants if v["id"] == self._active_variant_id),
t("stats_all_variants_of_game", self._game_title),
)
if active_acc is not None and self._active_folder == "blackjack":
self._board_heading = f"{t('bj_stats_acc_title', active_acc['account_name'])} | {var_lbl}"
self._stats_data = Database.get_bj_account_stats_overview(active_acc["id"], self._active_variant_id)
elif active_acc is not None and self._active_folder == "poker":
self._board_heading = f"{t('bj_stats_acc_title', active_acc['account_name'])} | {var_lbl}"
self._stats_data = Database.get_pk_account_stats_overview(active_acc["id"], self._active_variant_id)
else:
self._board_heading = t("stats_game_board_title", var_lbl)
self._stats_data = Database.get_stats_overview(
pid, variant_id=self._active_variant_id,
folder_path=self._active_folder if self._active_variant_id is None else None,
)
def _draw_active_mode(self, w: int, h: int):
self._render_full_bg(w, h)
self.delete("fg")
self._photo_refs.clear()
pad_x = max(92, int(w * 0.088))
content_w = min(1080, w - 2 * pad_x)
left_x = (w - content_w) // 2
top_btn_cy = max(48, int(h * 0.068))
self.create_window(left_x, top_btn_cy, window=self._back_btn, anchor="w", tags="fg")
hdr_ph = self.ctx.assets.get_goth_text_photo(
t("btn_stats"),
size_px=FONT_SIZE_HEADING - 1,
color=FONT_COLOR_TITLE_MAIN,
align="right",
)
self._photo_refs.append(hdr_ph)
self.create_image(
left_x + content_w, top_btn_cy, image=hdr_ph, anchor="e", tags="fg"
)
cur_y = max(top_btn_cy + 30, int(h * 0.125))
nav_h = 58
nav_cy = cur_y + nav_h // 2
nav_box = self.ctx.assets.get_box_photo("box_gold_double", (content_w, nav_h))
if nav_box:
self._photo_refs.append(nav_box)
self.create_image(w // 2, nav_cy, image=nav_box, anchor="center", tags="fg")
total_gb_w = sum(bw for _, bw in self._game_btns) + max(0, len(self._game_btns) - 1) * 8
gx = w // 2 - total_gb_w // 2
for b_wgt, bw in self._game_btns:
self.create_window(gx, nav_cy, window=b_wgt, anchor="w", tags="fg")
gx += bw + 8
cur_y += nav_h + 14
has_acc_row = len(self._acc_btns) > 0
hdr_h = 104 if has_acc_row else 64
hdr_cy = cur_y + hdr_h // 2
hdr_box = self.ctx.assets.get_box_photo("box_purple", (content_w, hdr_h))
if hdr_box:
self._photo_refs.append(hdr_box)
self.create_image(w // 2, hdr_cy, image=hdr_box, anchor="center", tags="fg")
var_row_w = sum(bw + 6 for _, bw in self._var_btns)
top_row_y = (cur_y + 28) if has_acc_row else hdr_cy
rank_ph = self.ctx.assets.get_goth_text_photo(
self._rank_line,
size_px=FONT_SIZE_BODY + 1,
color=FONT_COLOR_TITLE_MAIN,
max_width=max(220, content_w - var_row_w - 56),
align="left",
)
self._photo_refs.append(rank_ph)
self.create_image(left_x + 24, top_row_y, image=rank_ph, anchor="w", tags="fg")
rx = left_x + content_w - 22
for b_wgt, bw in reversed(self._var_btns):
self.create_window(rx, top_row_y, window=b_wgt, anchor="e", tags="fg")
rx -= (bw + 6)
if has_acc_row:
acc_row_y = cur_y + hdr_h - 26
ax = left_x + 24
p_ph = self.ctx.assets.get_goth_text_photo(
t("stats_pouch_lbl"),
size_px=FONT_SIZE_BODY,
color=FONT_COLOR_HEADING_SUB,
align="left",
if self._active_folder is None:
StatsHubRenderer.draw_hub(
self, self.ctx.assets, self.ctx.sounds, self.ctx.profile,
self._selected_cat, self._cat_btns, self._back_btn, self._hub_or_settings_btn,
self._open_game_from_hub, self._photo_refs, w, h,
)
self._photo_refs.append(p_ph)
self.create_image(ax, acc_row_y, image=p_ph, anchor="w", tags="fg")
ax += p_ph.width() + 14
for b_wgt, bw in self._acc_btns:
self.create_window(ax, acc_row_y, window=b_wgt, anchor="w", tags="fg")
ax += bw + 8
cur_y += hdr_h + 14
bottom_safe = max(58, int(h * 0.095))
board_h = max(246, min(350, h - cur_y - bottom_safe))
board_cy = cur_y + 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)
self.create_image(w // 2, board_cy, image=outer_box, anchor="center", tags="fg")
sub_ph = self.ctx.assets.get_goth_text_photo(
self._board_heading,
size_px=FONT_SIZE_HEADING - 3,
color=FONT_COLOR_HEADING_SUB,
max_width=content_w - 56,
align="left",
)
self._photo_refs.append(sub_ph)
self.create_image(left_x + 28, cur_y + 30, image=sub_ph, anchor="w", tags="fg")
grid_top = cur_y + 58
grid_h = board_h - 78
cols, rows = 4, 2
gap_x, gap_y = 14, 12
cell_w = (content_w - 56 - (cols - 1) * gap_x) // cols
cell_h = max(68, (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:
self.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",
)
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
val_ph = self.ctx.assets.get_goth_text_photo(
str(self._stats_data.get(field_key, "--")),
FONT_SIZE_HEADING - 2,
v_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="fg"
)
self.create_image(
cx, cy + cell_h // 5 + 2, image=val_ph, anchor="center", tags="fg"
else:
StatsDetailRenderer.draw_detail(
self, self.ctx.assets, self._game_title, self._rank_line, self._xp_ratio,
self._board_heading, self._stats_data, self._back_btn, self._hub_or_settings_btn,
self._var_btns, self._acc_btns, self._photo_refs, w, h,
)

View File

@ -0,0 +1,235 @@
# -*- coding: utf-8 -*-
# view/widgets/button_art_compositor.py
from __future__ import annotations
import re
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFont, ImageTk
from resources.code_res.game_constants import (
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,
)
SIDE_CAP_ASPECT = 0.46
VERTICAL_FRAME_RATIO = 0.36
_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] = {}
_BTN_PHOTO_CACHE: dict[tuple, ImageTk.PhotoImage] = {}
_LEADING_ICON_RE = re.compile(r"^(?:[^\w\s\+\(\[\"'ÄÖÜäöüß]+|\+(?=\s))\s*", re.UNICODE)
_TRAILING_ICON_RE = re.compile(r"\s*[^\w\s\)\]\.\!\%\"'ÄÖÜäöüß]+$", re.UNICODE)
class ButtonArtCompositor:
"""Skaliert Gothic-Button-Texturen im 3-Slice-Verfahren und brennt OldLondon-Beschriftungen ein."""
@staticmethod
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]
@staticmethod
def clean_outer_black_matte(pil_img: Image.Image) -> Image.Image:
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")
w, h = rgba.size
tl = rgba.getpixel((0, 0))
if tl[3] > 240 and max(tl[:3]) < 16:
r, g, b, a = rgba.split()
luma = ImageChops.lighter(ImageChops.lighter(r, g), b)
seed_img = luma.point(lambda p: 0 if p < 18 else 255)
for seed in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)):
if seed_img.getpixel(seed) == 0:
ImageDraw.floodfill(seed_img, seed, 128)
ext_alpha = seed_img.point(lambda p: 0 if p == 128 else 255)
rgba.putalpha(ImageChops.darker(a, ext_alpha))
_ALPHA_CORNER_CACHE[key] = rgba
return rgba
@classmethod
def trim_button_art(cls, pil_img: Image.Image) -> Image.Image:
key = (id(pil_img), pil_img.width, pil_img.height)
if key in _TRIM_BTN_CACHE:
return _TRIM_BTN_CACHE[key]
clean = cls.clean_outer_black_matte(pil_img)
bbox = clean.getbbox()
cropped = clean.crop(bbox) if bbox else clean
_TRIM_BTN_CACHE[key] = cropped
return cropped
@classmethod
def scale_button_3slice(cls, src_pil: Image.Image, target_w: int, target_h: int) -> tuple[Image.Image, int]:
trimmed = cls.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
@staticmethod
def prepare_label_text(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
fixed = []
for p in cleaned.split(" "):
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 resolve_font_px(font_arg, btn_h: int) -> int:
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))
return max(14, min(max_safe_px, int(round(raw_sz * 1.85))))
except Exception:
pass
return auto_px
@staticmethod
def measure_text_px(text: str, pil_font) -> float:
if not text:
return 0.0
draw = ImageDraw.Draw(Image.new("RGBA", (4, 4), (0, 0, 0, 0)))
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
@classmethod
def compute_framed_width(cls, text: str, requested_w: int, btn_h: int, font_px: int, auto_expand: bool) -> int:
if not text or not auto_expand:
return requested_w
pil_font = cls.get_old_london(font_px)
txt_w = cls.measure_text_px(text, pil_font)
inset = max(13, int(round(btn_h * SIDE_CAP_ASPECT))) + 6
return max(requested_w, int(round(txt_w + 2 * inset)))
@classmethod
def compose_photo(
cls,
base_pil: Image.Image | None,
width: int,
height: int,
text: str,
font_px: int,
text_color: str,
dim_disabled: bool = False,
brighten_active: bool = False,
) -> ImageTk.PhotoImage | None:
if base_pil is None:
return None
cache_key = (
id(base_pil), width, height, text, font_px, text_color, dim_disabled, brighten_active
)
cached = _BTN_PHOTO_CACHE.get(cache_key)
if cached is not None:
return cached
bg, cap_w = cls.scale_button_3slice(base_pil, width, 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 text:
draw = ImageDraw.Draw(bg)
max_txt_w = max(20, width - 2 * (cap_w + 5))
f_px = font_px
pil_font = cls.get_old_london(f_px)
while cls.measure_text_px(text, pil_font) > max_txt_w and f_px > 13:
f_px -= 1
pil_font = cls.get_old_london(f_px)
tw = cls.measure_text_px(text, pil_font)
try:
ascent, descent = pil_font.getmetrics() # type: ignore[attr-defined]
th = ascent + descent
except Exception:
th = f_px
cur_x = (width - tw) / 2.0
cur_y = (height - th) / 2.0 + FONT_VERTICAL_OFFSET_PX
sx, sy = FONT_SHADOW_OFFSET_DEFAULT
for ch in 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
photo = ImageTk.PhotoImage(bg)
if len(_BTN_PHOTO_CACHE) > 400:
_BTN_PHOTO_CACHE.clear()
_BTN_PHOTO_CACHE[cache_key] = photo
return photo

View File

@ -0,0 +1,413 @@
# -*- coding: utf-8 -*-
# view/widgets/casino_arena_base.py
from __future__ import annotations
from pathlib import Path
import tkinter as tk
from PIL import Image, ImageTk
from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar
from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
ACCENT_GOLD,
BORDER_COLOR,
PK_TABLE_IMAGE,
TABLE_BG,
XP_TO_GOLD_AMOUNT,
)
from resources.code_res.i18n import t
from view.widgets.endgame_fx_overlay import EndgameFxOverlay
from view.widgets.image_button import ImageButton
IMAGES_DIR = Path(__file__).resolve().parents[2] / "resources" / "images"
class CasinoArenaBase:
"""
Gemeinsame Arena-Basisklasse für mehrsitzige Kartentische (Blackjack, Poker & künftige Runden):
Kapselt Topbar/BottomBar, HUD-Sync, Tisch-Grafik, gerahmte Sitz-Boxen und EndgameFxOverlay.
"""
GAME_FOLDER_ID: str = ""
def _init_arena_state(
self, context, variant_key: str, cfg: dict, on_back_to_menu
):
self.ctx = context
self.variant_key = variant_key
self.cfg = cfg
self.on_back_to_menu = on_back_to_menu
self.devils_locked: bool = False
self._photo_refs: list = []
self._turn_job: str | None = None
self._resize_job: str | None = None
self._fx_overlay: EndgameFxOverlay | None = None
self._result_dialog = None
self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res)
self._raw_table_pil: Image.Image | None = self._load_image_file(PK_TABLE_IMAGE)
self._raw_box_bg_pil: Image.Image | None = (
self._load_image_file("box_background.png")
or self._load_image_file("box_background.jpg")
)
self._scaled_table_photo: ImageTk.PhotoImage | None = None
self._cached_table_dims: tuple[int, int] = (0, 0)
self._box_bg_cache: dict[tuple[int, int], ImageTk.PhotoImage] = {}
@staticmethod
def _load_image_file(fname: str) -> Image.Image | None:
p = IMAGES_DIR / fname
if p.is_file():
try:
return Image.open(p).convert("RGBA")
except Exception:
return None
return None
def _canvas_alive(self) -> bool:
try:
return hasattr(self, "arena_canvas") and bool(
self.arena_canvas.winfo_exists()
)
except Exception:
return False
def _cancel_fx_overlay(self):
if self._fx_overlay is not None:
self._fx_overlay.cancel()
self._fx_overlay = None
def _cancel_jobs(self):
self._cancel_fx_overlay()
for job in (self._turn_job, self._resize_job):
if job is not None:
try:
self.ctx.root.after_cancel(job)
except Exception:
pass
self._turn_job = self._resize_job = None
def _clear_persisted_state(self):
Database.delete_game_state(self.ctx.profile["id"], self.GAME_FOLDER_ID)
def _cleanup_game_overlays(self):
"""Hook für zusätzliche Tisch-Overlays (z. B. PokerHandsOverlay)."""
def _cleanup_and_go(self, nav_callable):
if self.devils_locked or self._fx_overlay is not None:
return
ImageButton.close_active_hover_tip()
self._cleanup_game_overlays()
self._cancel_jobs()
if self._result_dialog:
self._result_dialog.close_dialog()
self._result_dialog = None
self._clear_persisted_state()
nav_callable()
def _set_hud_segments(self, *segments: str):
self.topbar.update_level_xp_text()
parts = list(segments)
if self.devils_locked:
parts.append("~Devil's Gambit")
hud_txt = "|".join(parts)
if hasattr(self, "hud_var") and self.hud_var.get() != hud_txt:
self.hud_var.set(hud_txt)
def _abort_round_low_gold(
self, account: dict, min_req: int, unlock_devils_fn
):
unlock_devils_fn(account["id"], False)
self.devils_locked = False
self._clear_persisted_state()
cur_cost = self.ctx.refresh_game_progress()["xp_exchange_cost"]
msg = t(
"bj_err_not_enough_gold_entry",
account["account_name"],
min_req,
account["gold"],
cur_cost,
XP_TO_GOLD_AMOUNT,
)
self._cleanup_and_go(lambda: self.on_back_to_menu(account["id"], msg))
def _get_current_level_chips(self) -> tuple[int, int, int, int]:
lvl = self.ctx.game_progress["level"]
return Progression.get_level_bet_chips(
lvl, bet_scale=self.cfg.get("bet_scale", 1)
)
def _build_arena_shell(self, on_lang_refresh):
self._cancel_fx_overlay()
if self._result_dialog is not None:
self._result_dialog.close_dialog()
self._result_dialog = None
ImageButton.close_active_hover_tip()
self._cached_table_dims = (0, 0)
self._scaled_table_photo = None
self.ctx.root.clear_window(apply_global_bg=True)
self.ctx.refresh_game_progress()
self.topbar = self.ctx.build_game_topbar(
self.ctx.root,
stats_endpoint=self.GAME_FOLDER_ID,
stats_enabled=not self.devils_locked,
on_lang_refresh=on_lang_refresh,
locked_exit=self.devils_locked,
)
self.hud_var = tk.StringVar(value="")
self.status_var = tk.StringVar(value="")
self.bottom_bar = SolitaireBottomBar(
self.ctx.root, self.ctx, self.hud_var, self.status_var
)
self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 8))
self.arena_canvas = tk.Canvas(
self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0
)
self.arena_canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2))
self.arena_canvas.bind("<Configure>", self._on_arena_configure)
def _set_bottom_buttons(
self,
primary_buttons: list[ImageButton],
overflow_buttons: list[ImageButton] | None = None,
):
ImageButton.close_active_hover_tip()
if hasattr(self, "bottom_bar") and self.bottom_bar.winfo_exists():
self.bottom_bar.set_buttons(
primary_buttons, overflow_buttons=overflow_buttons
)
def _on_arena_resize_redraw(self):
raise NotImplementedError
def _on_arena_configure(self, _event=None):
if not self._canvas_alive() or self._fx_overlay is not None:
return
if self._resize_job is not None:
try:
self.ctx.root.after_cancel(self._resize_job)
except Exception:
pass
try:
self._resize_job = self.ctx.root.after(35, self._on_arena_resize_redraw)
except Exception:
self._resize_job = None
def _get_stretched_table_photo(
self, exact_w: int, exact_h: int
) -> ImageTk.PhotoImage | None:
if self._raw_table_pil is None or exact_w < 160 or exact_h < 120:
return None
if (
self._scaled_table_photo is None
or self._cached_table_dims != (exact_w, exact_h)
):
stretched = self._raw_table_pil.resize(
(exact_w, exact_h), Image.Resampling.LANCZOS
)
self._scaled_table_photo = ImageTk.PhotoImage(stretched)
self._cached_table_dims = (exact_w, exact_h)
return self._scaled_table_photo
def _prepare_arena_surface(
self,
) -> tuple[int, int, int, int, int, int, int, tuple[int, int, int, int]]:
cw = max(760, self.arena_canvas.winfo_width())
ch = max(460, self.arena_canvas.winfo_height())
keep_ids = set(self.arena_canvas.find_withtag("table_bg_slice")) | set(
self.arena_canvas.find_withtag("modal_dim_veil")
)
for item_id in self.arena_canvas.find_all():
if item_id not in keep_ids:
self.arena_canvas.delete(item_id)
self._photo_refs.clear()
self._bg_renderer.draw_on_canvas(self.arena_canvas, cw, ch)
pad_x = max(24, int(cw * 0.022))
pad_top, pad_bot = 6, 6
player_zone_h = max(150, min(174, int(ch * 0.31)))
player_zone_bot = ch - pad_bot
player_zone_top = player_zone_bot - player_zone_h
table_top = pad_top
table_bot = min(ch - pad_bot - 60, player_zone_top + 64)
table_h = max(280, table_bot - table_top)
table_w = max(680, cw - 2 * pad_x - 90)
table_cx, table_cy = cw // 2, table_top + table_h // 2
table_rect = (
table_cx - table_w // 2,
table_top,
table_cx + table_w // 2,
table_top + table_h,
)
tbl_photo = self._get_stretched_table_photo(table_w, table_h)
if tbl_photo is not None:
self.arena_canvas.create_image(
table_cx, table_cy, image=tbl_photo, anchor="center", tags="fg"
)
else:
self.arena_canvas.create_oval(
table_rect[0], table_rect[1], table_rect[2], table_rect[3],
fill="#14111b", outline=BORDER_COLOR, width=3, tags="fg",
)
return (
cw, ch, pad_x, pad_top, pad_bot, player_zone_top, player_zone_bot, table_rect
)
def _get_box_bg_photo(self, w: int, h: int) -> ImageTk.PhotoImage | None:
if self._raw_box_bg_pil is None or w < 16 or h < 16:
return None
key = (w, h)
if key not in self._box_bg_cache:
if len(self._box_bg_cache) > 24:
self._box_bg_cache.clear()
self._box_bg_cache[key] = ImageTk.PhotoImage(
self._raw_box_bg_pil.resize((w, h), Image.Resampling.LANCZOS)
)
return self._box_bg_cache[key]
def _draw_framed_panel(
self,
cx: int,
cy: int,
w: int,
h: int,
frame_style: str = "purple",
status_border: str | None = None,
):
x1, y1 = cx - w // 2, cy - h // 2
x2, y2 = x1 + w, y1 + h
inset = 5
inner_w, inner_h = max(16, w - 2 * inset), max(16, h - 2 * inset)
bg_ph = (
self.ctx.assets.get_box_bg_photo((inner_w, inner_h))
if hasattr(self.ctx.assets, "get_box_bg_photo")
else self._get_box_bg_photo(inner_w, inner_h)
)
if bg_ph is not None:
self._photo_refs.append(bg_ph)
self.arena_canvas.create_image(
cx, cy, image=bg_ph, anchor="center", tags="fg"
)
else:
self.arena_canvas.create_rectangle(
x1 + inset, y1 + inset, x2 - inset, y2 - inset,
fill="#110e18", outline="", tags="fg",
)
box_key = "box_gold_double" if frame_style == "gold" else "box_purple"
frame_ph = self.ctx.assets.get_box_photo(box_key, (w, h))
if frame_ph is not None:
self._photo_refs.append(frame_ph)
self.arena_canvas.create_image(
cx, cy, image=frame_ph, anchor="center", tags="fg"
)
else:
fallback_col = ACCENT_GOLD if frame_style == "gold" else BORDER_COLOR
self.arena_canvas.create_rectangle(
x1, y1, x2, y2, fill="", outline=fallback_col, width=2, tags="fg"
)
if status_border:
self.arena_canvas.create_rectangle(
x1 + 3, y1 + 3, x2 - 3, y2 - 3,
fill="", outline=status_border, width=2, tags="fg",
)
def _make_goth_photo(
self, text: str, size_px: int, color: str, max_width: int | None = None
) -> ImageTk.PhotoImage | None:
if not text:
return None
try:
ph = self.ctx.assets.get_goth_text_photo(
text, size_px=size_px, color=color, max_width=max_width
)
if ph is not None:
self._photo_refs.append(ph)
return ph
except Exception:
return None
def _place_goth_photo_or_fallback(
self,
cx: int,
cy: int,
ph: ImageTk.PhotoImage | None,
fallback_text: str,
size_px: int,
color: str,
anchor: str = "center",
):
if ph is not None:
self.arena_canvas.create_image(
cx, cy, image=ph, anchor=anchor, tags="fg"
)
elif fallback_text:
self.arena_canvas.create_text(
cx, cy, text=fallback_text,
font=("Georgia", max(9, size_px - 3), "bold"),
fill=color, anchor=anchor, tags="fg",
)
def _draw_fanned_cards_on_canvas(
self,
cx: int,
cy: int,
photos: list,
card_size: tuple[int, int],
visible_step: int,
max_width: int = 340,
highlight_color: str | None = None,
) -> tuple[int, int, int, int]:
cw, ch = card_size
n = len(photos)
if n <= 0:
return (cx, cy, cx, cy)
step = visible_step
if n > 1 and (cw + (n - 1) * step) > max_width:
step = max(16, (max_width - cw) // (n - 1))
total_w = cw + (n - 1) * step if n > 1 else cw
start_x, start_y = cx - total_w // 2, cy - ch // 2
if highlight_color:
self.arena_canvas.create_rectangle(
start_x - 4, start_y - 4, start_x + total_w + 4, start_y + ch + 4,
outline=highlight_color, width=2, tags="fg",
)
for i, ph in enumerate(photos):
self.arena_canvas.create_image(
start_x + i * step, start_y, image=ph, anchor="nw", tags="fg"
)
return (start_x, start_y, start_x + total_w, start_y + ch)
def _play_outcome_fx_then(self, outcome, play_fx: bool, show_dialog_cb):
ImageButton.close_active_hover_tip()
self._set_bottom_buttons([])
self._cancel_fx_overlay()
if play_fx and outcome is not None and self._canvas_alive():
def _after():
self._fx_overlay = None
show_dialog_cb()
self._fx_overlay = EndgameFxOverlay.play(
self.ctx.root,
self.ctx.assets,
outcome=outcome,
on_continue=_after,
target_canvas=self.arena_canvas,
)
return
show_dialog_cb()

View File

@ -0,0 +1,190 @@
# -*- coding: utf-8 -*-
# view/widgets/casino_result_dialog_base.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_SMALL_MIN,
FONT_SIZE_TITLE_LG,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
from view.widgets.goth_dropdown import GothDropdown
from view.widgets.image_button import ImageButton
from view.widgets.modal_veil import ModalVeil
class CasinoResultDialogBase(tk.Canvas):
"""
Gemeinsame Gothic-Showdown-Modal-Basis (tk.Canvas + box_big + ModalVeil)
für Blackjack, Poker und künftige Mehrspieler-Kartentische.
"""
def __init__(
self,
parent,
assets,
sounds,
result_data: dict,
dlg_w: int,
dlg_h: int,
on_next_round,
on_back_to_menu,
):
GothDropdown.close_any_open_popup()
top_root = parent.winfo_toplevel()
try:
max_h = max(420, top_root.winfo_height() - 56)
dlg_h = min(dlg_h, max_h)
except Exception:
pass
super().__init__(
top_root,
width=dlg_w,
height=dlg_h,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
)
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._photo_refs: list = []
self.place(relx=0.5, rely=0.5, anchor="center")
self._build_scene()
self._veil = ModalVeil(top_root, assets, modal_widget=self)
def _draw_showdown_middle(self, w: int, cx: int, cur_y: int) -> int:
raise NotImplementedError
def _build_scene(self):
w, h = self._dlg_w, self._dlg_h
cx = w // 2
self._photo_refs.clear()
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")
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 = 26
p_won = self.data.get("player_won")
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)
)
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() + 8
cur_y = self._draw_showdown_middle(w, cx, cur_y)
self.create_line(36, cur_y, w - 36, cur_y, fill=SUBTLE_BORDER, width=1)
cur_y += 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
elif p_net < 0:
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), FONT_COLOR_STATUS_LOSS
else:
own_txt, own_col = t("bj_popup_your_even"), FONT_COLOR_BODY_DEFAULT
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
other_gains = self.data.get("other_gains", [])
if other_gains:
oth_ph = self.assets.get_goth_text_photo(
" | ".join(other_gains), 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
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")
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_y = h - 34
can_next = self.data.get("can_continue", True)
can_menu = self.data.get("can_leave_menu", True)
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")
def close_dialog(self):
self._veil.release()
self._photo_refs.clear()
if self.winfo_exists():
self.destroy()
def _handle_next(self):
self.close_dialog()
self.on_next_round()
def _handle_menu(self):
self.close_dialog()
self.on_back_to_menu()

View File

@ -2,10 +2,10 @@
# view/widgets/endgame_fx_overlay.py
from __future__ import annotations
from collections import deque
import random
import time
import tkinter as tk
from collections import deque
from resources.code_res.game_constants import (
FONT_COLOR_TITLE_MAIN,
@ -18,8 +18,8 @@ from view.widgets.modal_veil import ModalVeil
class EndgameFxOverlay:
"""
Vorschalt-Animation bei Spielende über dem gesperrten, abgedunkelten Spieltisch:
- Sieg ('win'): 'firework_start.gif' unten links + zufällig über den Bildschirm
verteilte 'bat_explosion.gif' & 'pumpkin_explosion.gif' an wechselnden Punkten.
- Sieg ('win'): Zufällig über den Bildschirm verteilte 'bat_explosion.gif' &
'pumpkin_explosion.gif' an wechselnden Punkten.
- Niederlage ('lose'): 'foul_pumpkin.gif' zufällig über den Bildschirm verteilt.
- Erst nach einem Klick (oder Space/Enter/Esc) geht es weiter zum Ergebnis-Screen.
"""
@ -95,9 +95,12 @@ class EndgameFxOverlay:
self._start_choreography()
def _has_any_frames(self) -> bool:
probe_name = "firework_start" if self.mode == "win" else "foul_pumpkin"
frames, _ = self.assets.get_win_lose_gif_sequence(probe_name, (160, 160))
return bool(frames)
probes = ("bat_explosion", "pumpkin_explosion") if self.mode == "win" else ("foul_pumpkin",)
for name in probes:
frames, _ = self.assets.get_win_lose_gif_sequence(name, (160, 160))
if frames:
return True
return False
def _schedule(self, delay_ms: int, fn, *args) -> str | None:
if self._finished:
@ -124,9 +127,6 @@ class EndgameFxOverlay:
except Exception:
return False
# ------------------------------------------------------------------
# KLICK-FÄNGER ÜBER DEM GESAMTEN FENSTER
# ------------------------------------------------------------------
def _install_click_catcher(self):
for seq in ("<Enter>", "<Motion>", "<B1-Motion>", "<Double-Button-1>", "<MouseWheel>"):
self.root.bind_class(self._click_tag, seq, lambda _e: "break")
@ -165,9 +165,6 @@ class EndgameFxOverlay:
self.finish()
return "break"
# ------------------------------------------------------------------
# HINWEIS-BANNER ("Klicken zum Fortfahren")
# ------------------------------------------------------------------
def _draw_continue_banner(self):
if not self._canvas_ok():
return
@ -187,54 +184,20 @@ class EndgameFxOverlay:
cx = cw // 2
cy = ch - bh // 2 - 14
if box_ph:
self.canvas.create_image(cx, cy, image=box_ph, anchor="center", tags=(self.FX_TAG, self.HINT_TAG))
self.canvas.create_image(cx, cy, image=txt_ph, anchor="center", tags=(self.FX_TAG, self.HINT_TAG))
self.canvas.create_image(
cx, cy, image=box_ph, anchor="center", tags=(self.FX_TAG, self.HINT_TAG)
)
self.canvas.create_image(
cx, cy, image=txt_ph, anchor="center", tags=(self.FX_TAG, self.HINT_TAG)
)
# ------------------------------------------------------------------
# WIN / LOSE PARTIKEL-CHOREOGRAFIE
# ------------------------------------------------------------------
def _start_choreography(self):
if self.mode == "win":
self._launch_firework_bottom_left()
self._schedule(260, self._win_explosion_wave, True)
self._schedule(40, self._win_explosion_wave, True)
else:
self._schedule(50, self._lose_pumpkin_wave, True)
def _launch_firework_bottom_left(self):
if self._finished or not self._canvas_ok():
return
cw = max(320, self.canvas.winfo_width())
ch = max(240, self.canvas.winfo_height())
fw_sz = max(175, min(285, int(min(cw, ch) * 0.38)))
frames, durs = self.assets.get_win_lose_gif_sequence("firework_start", (fw_sz, fw_sz))
if not frames:
return
item_id = self.canvas.create_image(
14, ch,
image=frames[0],
anchor="sw",
tags=(self.FX_TAG,),
)
self.canvas.tag_raise(self.HINT_TAG)
def _step_fw(idx: int):
if self._finished or not self._canvas_ok():
return
if idx >= len(frames):
try:
self.canvas.delete(item_id)
except Exception:
pass
# Neue Salve nach kurzer Feuerpause starten
self._schedule(780, self._launch_firework_bottom_left)
return
self.canvas.itemconfigure(item_id, image=frames[idx])
self._schedule(durs[idx], _step_fw, idx + 1)
self._schedule(durs[0], _step_fw, 1)
def _pick_random_spot(self, size_px: int, avoid_bottom_left: bool) -> tuple[int, int]:
def _pick_random_spot(self, size_px: int) -> tuple[int, int]:
cw = max(360, self.canvas.winfo_width())
ch = max(260, self.canvas.winfo_height())
half = size_px // 2
@ -250,21 +213,15 @@ class EndgameFxOverlay:
rx = random.randint(x_min, x_max)
ry = random.randint(y_min, y_max)
# Unten links Platz für die Raketen-Abschussrampe lassen
if avoid_bottom_left and rx < int(cw * 0.28) and ry > int(ch * 0.56):
continue
too_close = False
for ax, ay, _asz in self._active_spots.values():
if (rx - ax) ** 2 + (ry - ay) ** 2 < min_dist_sq:
too_close = True
break
too_close = any(
(rx - ax) ** 2 + (ry - ay) ** 2 < min_dist_sq
for ax, ay, _asz in self._active_spots.values()
)
if not too_close:
for px, py in self._recent_spots:
if (rx - px) ** 2 + (ry - py) ** 2 < int(min_dist_sq * 0.65):
too_close = True
break
too_close = any(
(rx - px) ** 2 + (ry - py) ** 2 < int(min_dist_sq * 0.65)
for px, py in self._recent_spots
)
if not too_close:
best_xy = (rx, ry)
break
@ -272,7 +229,7 @@ class EndgameFxOverlay:
self._recent_spots.append(best_xy)
return best_xy
def _spawn_one_shot_sprite(self, gif_name: str, scale_factor: float, avoid_bottom_left: bool):
def _spawn_one_shot_sprite(self, gif_name: str, scale_factor: float):
if self._finished or not self._canvas_ok():
return
cw = max(360, self.canvas.winfo_width())
@ -282,12 +239,9 @@ class EndgameFxOverlay:
if not frames:
return
sx, sy = self._pick_random_spot(sz, avoid_bottom_left=avoid_bottom_left)
sx, sy = self._pick_random_spot(sz)
item_id = self.canvas.create_image(
sx, sy,
image=frames[0],
anchor="center",
tags=(self.FX_TAG,),
sx, sy, image=frames[0], anchor="center", tags=(self.FX_TAG,)
)
self._active_spots[item_id] = (sx, sy, sz)
self.canvas.tag_raise(self.HINT_TAG)
@ -311,17 +265,17 @@ class EndgameFxOverlay:
if self._finished or not self._canvas_ok():
return
scales = (0.24, 0.29, 0.34)
sprites = ("bat_explosion", "pumpkin_explosion")
if initial_burst:
for extra_delay in (0, 140):
chosen = random.choice(("bat_explosion", "pumpkin_explosion"))
sc = random.choice(scales)
if extra_delay == 0:
self._spawn_one_shot_sprite(chosen, sc, avoid_bottom_left=True)
else:
self._schedule(extra_delay, self._spawn_one_shot_sprite, chosen, sc, True)
self._spawn_one_shot_sprite(random.choice(sprites), random.choice(scales))
self._schedule(
140,
self._spawn_one_shot_sprite,
random.choice(sprites),
random.choice(scales),
)
elif len(self._active_spots) < 4:
chosen = random.choice(("bat_explosion", "pumpkin_explosion"))
self._spawn_one_shot_sprite(chosen, random.choice(scales), avoid_bottom_left=True)
self._spawn_one_shot_sprite(random.choice(sprites), random.choice(scales))
self._schedule(random.randint(250, 420), self._win_explosion_wave, False)
@ -330,16 +284,13 @@ class EndgameFxOverlay:
return
scales = (0.23, 0.28, 0.33)
if initial_burst:
self._spawn_one_shot_sprite("foul_pumpkin", 0.29, avoid_bottom_left=False)
self._schedule(190, self._spawn_one_shot_sprite, "foul_pumpkin", 0.24, False)
self._spawn_one_shot_sprite("foul_pumpkin", 0.29)
self._schedule(190, self._spawn_one_shot_sprite, "foul_pumpkin", 0.24)
elif len(self._active_spots) < 3:
self._spawn_one_shot_sprite("foul_pumpkin", random.choice(scales), avoid_bottom_left=False)
self._spawn_one_shot_sprite("foul_pumpkin", random.choice(scales))
self._schedule(random.randint(330, 510), self._lose_pumpkin_wave, False)
# ------------------------------------------------------------------
# SAUBERES AUFRÄUMEN & ÜBERGANG ZUM RESULT-SCREEN
# ------------------------------------------------------------------
def cancel(self):
self._cleanup_only()

View File

@ -3,13 +3,11 @@
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageDraw, ImageEnhance, ImageTk, ImageChops
from PIL import Image, ImageChops, 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,
@ -21,9 +19,8 @@ from resources.code_res.game_constants import (
FONT_SIZE_DROPDOWN,
FONT_SIZE_SMALL_MIN,
FONT_VERTICAL_OFFSET_PX,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
)
from view.widgets.goth_dropdown_popup import GothDropdownPopup
from view.widgets.image_button import _clean_outer_black_matte, _get_old_london
_TRIM_CACHE: dict[tuple[int, int, int], Image.Image] = {}
@ -47,19 +44,9 @@ def _trim_outer_black_bbox(pil_img: Image.Image, threshold: int = 38) -> Image.I
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.
"""
"""Zweiteiliges Gothic-Dropdown mit proportionaler Button-Kappe und eigenem Popup-Renderer."""
_active_popup_owner: GothDropdown | None = None
ARROW_ZONE_H = 18
_active_popup_owner: "GothDropdown | None" = None
def __init__(
self,
@ -102,12 +89,8 @@ class GothDropdown(tk.Canvas):
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
self._popup_ctrl = GothDropdownPopup(self)
if not self._var.get() and self._values:
self._var.set(self._values[0])
@ -121,7 +104,6 @@ class GothDropdown(tk.Canvas):
self._render_closed()
# --- Kompatibilitäts-Methoden ---
def get(self) -> str:
return self._var.get()
@ -148,7 +130,6 @@ class GothDropdown(tk.Canvas):
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)
@ -162,23 +143,18 @@ class GothDropdown(tk.Canvas):
if raw_body is None:
return None, 36
h = self._height
w = self._width
w, h = self._width, self._height
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)
return body_trim.resize((w, h), Image.Resampling.LANCZOS), 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)
@ -197,13 +173,7 @@ class GothDropdown(tk.Canvas):
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,
self, img: Image.Image, text: str, x_left: int, x_right: int, color: str, font_px: int
):
if not text:
return
@ -241,12 +211,8 @@ class GothDropdown(tk.Canvas):
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,
(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)
@ -257,9 +223,7 @@ class GothDropdown(tk.Canvas):
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)
use_highlight_art = self._enabled and (self._popup_ctrl.is_open() or self._hovered)
bar_pil, btn_w = self._compose_bar_pil(is_highlighted=use_highlight_art)
if bar_pil is None:
return
@ -272,21 +236,13 @@ class GothDropdown(tk.Canvas):
bar_pil.putalpha(alpha)
txt_col = (
FONT_COLOR_DISABLED
if not self._enabled
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,
bar_pil, self._var.get(), x_left=pad_left, x_right=self._width - btn_w - 8,
color=txt_col, font_px=self._font_px,
)
self._closed_photo = ImageTk.PhotoImage(bar_pil)
@ -301,7 +257,6 @@ class GothDropdown(tk.Canvas):
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:
@ -310,255 +265,19 @@ class GothDropdown(tk.Canvas):
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
self._popup_ctrl.close()
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():
if self._popup_ctrl.is_open():
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._popup_ctrl.open()
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

@ -0,0 +1,250 @@
# -*- coding: utf-8 -*-
# view/widgets/goth_dropdown_popup.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageDraw, ImageTk
from resources.code_res.game_constants import (
BG_COLOR,
DROPDOWN_ITEM_TEXT_HOVER,
DROPDOWN_ITEM_TEXT_NORMAL,
DROPDOWN_ITEM_TEXT_SELECTED,
FONT_COLOR_DISABLED,
FONT_SIZE_SMALL_MIN,
UI_ACCENT_AMETHYST,
UI_ACCENT_GOLD,
)
class GothDropdownPopup:
"""Rahmenloses Gothic-Aufklapp-Listenfenster mit Scroll-Pfeilen und Mausrad-Unterstützung."""
ARROW_ZONE_H = 18
def __init__(self, owner):
self.owner = owner
self._popup: tk.Toplevel | None = None
self._pop_cv: tk.Canvas | None = None
self._popup_refs: list[ImageTk.PhotoImage] = []
self._scroll_offset: int = 0
self._hover_idx: int = -1
self._hover_arrow: str | None = None
self._pop_geom: tuple[int, int, int, int, int, bool, int] = (0, 0, 30, 12, 0, False, 12)
def is_open(self) -> bool:
return bool(self._popup is not None and self._popup.winfo_exists())
def close(self) -> None:
if self._popup is not None:
try:
if self._popup.winfo_exists():
self._popup.destroy()
except Exception:
pass
self._popup = None
self._pop_cv = None
self._popup_refs.clear()
self._hover_arrow = None
def open(self) -> None:
dd = self.owner
values = dd._values
scrollable = len(values) > dd._max_visible
vis_count = min(len(values), dd._max_visible)
row_h = max(30, dd._height - 6)
border_pad = 12
arrow_h = self.ARROW_ZONE_H if scrollable else 0
top_offset = border_pad + arrow_h
pop_w = dd._width
pop_h = vis_count * row_h + 2 * top_offset
cur_idx = dd.current()
if cur_idx >= vis_count:
self._scroll_offset = min(cur_idx - vis_count + 1, max(0, len(values) - vis_count))
else:
self._scroll_offset = 0
self._hover_idx = -1
self._hover_arrow = None
dd.update_idletasks()
rx = dd.winfo_rootx()
ry = dd.winfo_rooty() + dd._height + 2
if ry + pop_h > dd.winfo_screenheight() - 24:
ry = max(8, dd.winfo_rooty() - pop_h - 2)
pop = tk.Toplevel(dd)
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()
cv.bind("<Motion>", self._on_motion)
cv.bind("<Leave>", self._on_leave)
cv.bind("<Button-1>", self._on_click)
for target in (pop, cv):
target.bind("<MouseWheel>", self._on_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: dd.close_popup())
pop.bind("<FocusOut>", lambda _e: dd.close_popup())
pop.focus_force()
@staticmethod
def _draw_scroll_arrow(
draw: ImageDraw.ImageDraw,
cx: int,
cy: int,
direction: str,
enabled: bool,
hovered: bool,
) -> None:
if not enabled:
fill_col, outline_col = FONT_COLOR_DISABLED, None
elif hovered:
fill_col, outline_col = "#ffffff", UI_ACCENT_AMETHYST
else:
fill_col, outline_col = UI_ACCENT_GOLD, "#0d0b12"
hw, hh = 8, 5
pts = (
[(cx, cy - hh), (cx - hw, cy + hh), (cx + hw, cy + hh)]
if direction == "up"
else [(cx, cy + hh), (cx - hw, cy - hh), (cx + hw, cy - hh)]
)
draw.polygon(pts, fill=fill_col, outline=outline_col)
def redraw(self) -> None:
if not self.is_open() or self._pop_cv is None:
return
dd = self.owner
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()
box_pil = dd.assets.get_9slice_pil("dropdown_box", (pop_w, pop_h))
box_pil = box_pil.copy() if box_pil is not None else Image.new("RGBA", (pop_w, pop_h), (16, 13, 22, 255))
cur_val = dd.get()
values = dd._values
item_font_px = max(FONT_SIZE_SMALL_MIN, dd._font_px - 1)
for slot in range(vis_count):
val_idx = self._scroll_offset + slot
if val_idx >= len(values):
break
item_txt = values[val_idx]
y0 = top_offset + slot * row_h
if val_idx == self._hover_idx:
t_col = DROPDOWN_ITEM_TEXT_HOVER
elif item_txt == cur_val:
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))
dd._draw_tracked_text_clipped(
row_img, item_txt, x_left=18, x_right=pop_w - 18, color=t_col, font_px=item_font_px
)
box_pil.alpha_composite(row_img, (0, y0))
if scrollable:
draw = ImageDraw.Draw(box_pil)
can_up = self._scroll_offset > 0
can_down = (self._scroll_offset + vis_count) < len(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", can_up, self._hover_arrow == "up")
self._draw_scroll_arrow(draw, pop_w // 2, dn_cy, "down", can_down, 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:
_pw, pop_h, _rh, top_offset, _vc, scrollable, _bp = 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:
_pw, _ph, row_h, top_offset, vis_count, _sc, _bp = 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.owner._values):
return self._scroll_offset + slot
return -1
def _on_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, self._hover_arrow = idx, arr
self.redraw()
def _on_leave(self, _event):
if self._hover_idx != -1 or self._hover_arrow is not None:
self._hover_idx, self._hover_arrow = -1, None
self.redraw()
def _on_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
dd = self.owner
idx = self._slot_from_y(event.y)
if 0 <= idx < len(dd._values):
chosen = dd._values[idx]
changed = (chosen != dd.get())
if dd.sounds:
dd.sounds.play("click")
dd._var.set(chosen)
dd.close_popup()
if changed and callable(dd._on_change):
dd._on_change(chosen)
else:
dd.close_popup()
def _scroll_by(self, delta: int):
if not self.is_open():
return
_pw, _ph, _rh, _to, vis_count, scrollable, _bp = self._pop_geom
if not scrollable:
return
max_off = max(0, len(self.owner._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()
def _on_wheel(self, event):
if getattr(event, "delta", 0) != 0:
self._scroll_by(-1 if event.delta > 0 else 1)

View File

@ -2,11 +2,9 @@
# view/widgets/image_button.py
from __future__ import annotations
import re
from pathlib import Path
import tkinter as tk
from typing import Callable
from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFont, ImageTk
from PIL import ImageTk
from models.database import Database
from resources.code_res.game_constants import (
@ -21,42 +19,20 @@ from resources.code_res.game_constants import (
BTN_FIRE_TEXT_HOVER,
BTN_FIRE_TEXT_NORMAL,
FG_COLOR,
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,
MODAL_BG,
)
from view.widgets.button_art_compositor import ButtonArtCompositor
SETTING_BUTTON_HOVER_HELP = "show_button_hover_help"
_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] = {}
_BTN_PHOTO_CACHE: dict[tuple, ImageTk.PhotoImage] = {}
_HOVER_HELP_ENABLED_CACHE: bool | None = None
# Entfernt vorangestellte/nachgestellte Sonder-Icons & Emojis (behält Buchstaben, Ziffern, '+' vor Zahl & Klammern)
_LEADING_ICON_RE = re.compile(r"^(?:[^\w\s\+\(\[\"'ÄÖÜäöüß]+|\+(?=\s))\s*", re.UNICODE)
_TRAILING_ICON_RE = re.compile(r"\s*[^\w\s\)\]\.\!\%\"'ÄÖÜäöüß]+$", re.UNICODE)
# Geometrie-Anteil der seitlichen Zierkappen & oberen/unteren Rahmenleisten in button*.png
_SIDE_CAP_ASPECT = 0.46
_VERTICAL_FRAME_RATIO = 0.36
# Kompatibilitäts-Exporte für goth_dropdown.py & assets_manager.py
_get_old_london = ButtonArtCompositor.get_old_london
_clean_outer_black_matte = ButtonArtCompositor.clean_outer_black_matte
_trim_button_art = ButtonArtCompositor.trim_button_art
def is_button_hover_help_enabled() -> bool:
"""Liest den globalen Einstellungs-Schalter für Button-Hover-Hilfetexte (gecached)."""
global _HOVER_HELP_ENABLED_CACHE
if _HOVER_HELP_ENABLED_CACHE is None:
try:
@ -68,7 +44,6 @@ def is_button_hover_help_enabled() -> bool:
def set_button_hover_help_enabled(enabled: bool, persist: bool = True):
"""Aktualisiert den Einstellungsschalter zur Laufzeit und schließt ggf. offene Popups."""
global _HOVER_HELP_ENABLED_CACHE
_HOVER_HELP_ENABLED_CACHE = bool(enabled)
if not _HOVER_HELP_ENABLED_CACHE:
@ -80,80 +55,8 @@ def set_button_hover_help_enabled(enabled: bool, persist: bool = True):
pass
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:
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")
w, h = rgba.size
tl = rgba.getpixel((0, 0))
if tl[3] > 240 and max(tl[:3]) < 16:
r, g, b, a = rgba.split()
luma = ImageChops.lighter(ImageChops.lighter(r, g), b)
seed_img = luma.point(lambda p: 0 if p < 18 else 255)
for seed in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)):
if seed_img.getpixel(seed) == 0:
ImageDraw.floodfill(seed_img, seed, 128)
ext_alpha = seed_img.point(lambda p: 0 if p == 128 else 255)
rgba.putalpha(ImageChops.darker(a, ext_alpha))
_ALPHA_CORNER_CACHE[key] = rgba
return rgba
def _trim_button_art(pil_img: Image.Image) -> Image.Image:
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]:
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
class ImageButton(tk.Label):
"""
Gothic UI Button (Amethyst & Fire) mit automatischer Rahmen-Einberechnung
und optionalem Hover-Hilfetext (`hover_text`) in klar lesbarer Standard-Schrift,
steuerbar über die Einstellungen ('Hilfe Texte bei Buttons Anzeigen').
"""
"""Gothic UI Button (Amethyst & Fire) mit State-Caching und optionalem Hover-Hilfetext."""
_active_tip: tk.Toplevel | None = None
_active_tip_owner: "ImageButton | None" = None
@ -182,7 +85,7 @@ class ImageButton(tk.Label):
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._text = ButtonArtCompositor.prepare_label_text(str(text or ""))
self._pil_normal = pil_normal
self._pil_hover = pil_hover or pil_normal
self._sound_mgr = sound_mgr
@ -192,17 +95,14 @@ class ImageButton(tk.Label):
self._hover_text = hover_text
self._hover_after_id: str | None = None
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._style = style if style in ("fire", "amethyst") else self._detect_style(parent, pil_normal, pil_hover)
self._font_px = ButtonArtCompositor.resolve_font_px(font, self._height)
self._width = ButtonArtCompositor.compute_framed_width(
self._text, self._requested_width, self._height, self._font_px, self._auto_expand
)
self._rebuild_state_photos()
init_photo = self._ensure_normal() if self._enabled else self._ensure_disabled()
super().__init__(
parent,
text="" if init_photo is not None else self._text,
@ -229,6 +129,17 @@ class ImageButton(tk.Label):
def pixel_height(self) -> int:
return self._height
@staticmethod
def _detect_style(parent, pil_normal, pil_hover) -> str:
try:
assets = getattr(parent.winfo_toplevel(), "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"
def set_hover_text(self, hover_text: str | Callable[[], str] | None):
self._hover_text = hover_text
if not hover_text and ImageButton._active_tip_owner is self:
@ -264,17 +175,13 @@ class ImageButton(tk.Label):
def _show_hover_tooltip(self):
self._hover_after_id = None
if not self._hovered or not self.winfo_exists():
if not self._hovered or not self.winfo_exists() or not is_button_hover_help_enabled():
return
if not is_button_hover_help_enabled():
return
msg = self._resolve_hover_string()
if not msg:
return
ImageButton.close_active_hover_tip()
tip = tk.Toplevel(self)
tip.wm_overrideredirect(True)
try:
@ -284,254 +191,71 @@ class ImageButton(tk.Label):
border_frame = tk.Frame(tip, bg=ACCENT_GOTH, padx=1, pady=1)
border_frame.pack(fill="both", expand=True)
inner_frame = tk.Frame(border_frame, bg=MODAL_BG, padx=12, pady=8)
inner_frame.pack(fill="both", expand=True)
# Gut lesbare Standard-Schrift (wie in InfoBadge) statt Gothic/Serifenschrift
lbl = tk.Label(
inner_frame,
text=msg,
font=("Helvetica", 9),
fg=FG_COLOR,
bg=MODAL_BG,
justify="left",
wraplength=340,
)
lbl.pack()
tk.Label(
inner_frame, text=msg, font=("Helvetica", 9),
fg=FG_COLOR, bg=MODAL_BG, justify="left", wraplength=340,
).pack()
tip.update_idletasks()
tw = tip.winfo_reqwidth()
th = tip.winfo_reqheight()
sw = self.winfo_screenwidth()
sh = self.winfo_screenheight()
tw, th = tip.winfo_reqwidth(), tip.winfo_reqheight()
sw, sh = self.winfo_screenwidth(), self.winfo_screenheight()
bx, by = self.winfo_rootx(), self.winfo_rooty()
bx = self.winfo_rootx()
by = self.winfo_rooty()
rx = bx + (self._width - tw) // 2
rx = max(12, min(sw - tw - 12, bx + (self._width - tw) // 2))
ry = by - th - 10
if ry < 14:
ry = by + self._height + 10
rx = max(12, min(sw - tw - 12, rx))
ry = max(12, min(sh - th - 16, ry))
tip.wm_geometry(f"+{rx}+{ry}")
ImageButton._active_tip = tip
ImageButton._active_tip_owner = self
@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:
cap_px = max(13, int(round(self._height * _SIDE_CAP_ASPECT)))
return cap_px + 6
def _compute_framed_width(self) -> int:
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:
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,
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(self, base_pil, color: str, dim: bool = False, bright: bool = False) -> ImageTk.PhotoImage | None:
return ButtonArtCompositor.compose_photo(
base_pil, self._width, self._height, self._text, self._font_px, color, dim, bright
)
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
cache_key = (
id(base_pil),
self._width,
self._height,
self._text,
self._font_px,
text_color,
dim_disabled,
brighten_active,
)
cached = _BTN_PHOTO_CACHE.get(cache_key)
if cached is not None:
return cached
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)
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
photo = ImageTk.PhotoImage(bg)
if len(_BTN_PHOTO_CACHE) > 400:
_BTN_PHOTO_CACHE.clear()
_BTN_PHOTO_CACHE[cache_key] = photo
return photo
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) if self._enabled else None
self._photo_disabled = None if self._enabled else self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True)
c_norm, _, _, c_dis = self._palette()
self._photo_normal = self._compose(self._pil_normal, c_norm) if self._enabled else None
self._photo_disabled = None if self._enabled else self._compose(self._pil_normal, c_dis, dim=True)
self._photo_hover = None
self._photo_active = None
def _ensure_normal(self) -> ImageTk.PhotoImage | None:
if self._photo_normal is None:
c_norm, _, _, _ = self._palette()
self._photo_normal = self._compose_button_photo(self._pil_normal, c_norm)
self._photo_normal = self._compose(self._pil_normal, self._palette()[0])
return self._photo_normal
def _ensure_hover(self) -> ImageTk.PhotoImage | None:
if self._photo_hover is None:
_, c_hov, _, _ = self._palette()
self._photo_hover = self._compose_button_photo(self._pil_hover, c_hov)
self._photo_hover = self._compose(self._pil_hover, self._palette()[1])
return self._photo_hover
def _ensure_active(self) -> ImageTk.PhotoImage | None:
if self._photo_active is None:
_, _, c_act, _ = self._palette()
self._photo_active = self._compose_button_photo(self._pil_hover, c_act, brighten_active=True)
self._photo_active = self._compose(self._pil_hover, self._palette()[2], bright=True)
return self._photo_active
def _ensure_disabled(self) -> ImageTk.PhotoImage | None:
if self._photo_disabled is None:
_, _, _, c_dis = self._palette()
self._photo_disabled = self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True)
self._photo_disabled = self._compose(self._pil_normal, self._palette()[3], dim=True)
return self._photo_disabled
def set_text(self, new_text: str):
self._text = self._prepare_label_text(str(new_text or ""))
self._width = self._compute_framed_width()
self._text = ButtonArtCompositor.prepare_label_text(str(new_text or ""))
self._width = ButtonArtCompositor.compute_framed_width(
self._text, self._requested_width, self._height, self._font_px, self._auto_expand
)
self._rebuild_state_photos()
self.set_enabled(self._enabled)
@ -563,21 +287,19 @@ class ImageButton(tk.Label):
self._cancel_hover_timer()
if ImageButton._active_tip_owner is self:
ImageButton.close_active_hover_tip()
if not self._enabled:
return
ph = self._ensure_normal()
if ph:
self.configure(image=ph)
if self._enabled:
ph = self._ensure_normal()
if ph:
self.configure(image=ph)
def _on_press(self, _event):
self._cancel_hover_timer()
if ImageButton._active_tip_owner is self:
ImageButton.close_active_hover_tip()
if not self._enabled:
return
ph = self._ensure_active()
if ph:
self.configure(image=ph)
if self._enabled:
ph = self._ensure_active()
if ph:
self.configure(image=ph)
def _on_release(self, event):
if not self._enabled:

View File

@ -0,0 +1,493 @@
# -*- coding: utf-8 -*-
# view/widgets/luck_pouch_menu_base.py
from __future__ import annotations
import sqlite3
import tkinter as tk
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,
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
from view.widgets.menu_body_canvas import MenuBodyCanvas
class LuckPouchMenuBase:
"""
Gemeinsame Vorauswahl-Menü-Basisklasse für Spiele mit Goldbeuteln,
XP-Umtausch, Divine Punishment, The Devil's Deal und KI-Gegner-Setup.
"""
GAME_FOLDER_ID: str = ""
LAST_ACC_SETTING_PREFIX: str = ""
STARTING_GOLD: int = 1000
MAX_BOTS: int = 4
REQUIRES_MIN_ONE_BOT: bool = False
DEVILS_DEFAULT_VARIANT: str = ""
KEY_TOPBAR: str = ""
KEY_HEADER_GOLD: str = ""
KEY_SEC1_TITLE: str = ""
KEY_BOTS_TITLE: str = ""
KEY_SEC3_TITLE: str = ""
KEY_GOLD_DISPLAY: str = ""
KEY_DEFAULT_ACC_NAME: str = ""
KEY_ERR_DUPLICATE: str = ""
def __init__(self, context):
self.ctx = context
self.bot_widget: BotSetupWidget | None = None
self._photo_refs: list = []
# --- Hooks für Subklassen (Blackjack / Poker) ---
def _get_active_devils_account(self, pid: int) -> dict | None: raise NotImplementedError
def _get_accounts(self, pid: int) -> list[dict]: raise NotImplementedError
def _get_account(self, acc_id: int) -> dict | None: raise NotImplementedError
def _create_account(self, pid: int, name: str) -> dict: raise NotImplementedError
def _delete_account(self, acc_id: int) -> None: raise NotImplementedError
def _exchange_xp(self, pid: int, acc_id: int) -> tuple[bool, str]: raise NotImplementedError
def _variants_dict(self) -> dict[str, dict]: raise NotImplementedError
def _min_entry_for_variant(self, v_key: str, cfg: dict) -> int: raise NotImplementedError
def _format_variant_desc(self, v_key: str, cfg: dict) -> str: raise NotImplementedError
def _format_limit_info(self, dyn_xp_cost: int) -> str: raise NotImplementedError
def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
raise NotImplementedError
def _default_bot_configs(self) -> dict[int, tuple[str, int]]:
return {}
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
pid = self.ctx.profile["id"]
devils_acc = self._get_active_devils_account(pid)
if devils_acc is not None:
saved = Database.load_game_state(pid, self.GAME_FOLDER_ID)
if saved is not None:
self._launch_table(saved["variant_key"], devils_acc["id"], [], resume_json=saved["state_json"])
return
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()
dyn_xp_cost = prog["xp_exchange_cost"]
is_divine = prog["is_divine_punishment"]
at_floor = prog["at_divine_floor"]
devils_deal_open = prog["devils_deal_unlocked"]
setting_key = f"{self.LAST_ACC_SETTING_PREFIX}_{pid}"
accounts = self._get_accounts(pid)
has_accounts = len(accounts) > 0
if preselect_id is None and has_accounts:
saved_id_str = Database.load_setting(setting_key, "")
if saved_id_str.isdigit():
preselect_id = int(saved_id_str)
acc_by_name = {a["account_name"]: a for a in accounts}
acc_names = list(acc_by_name.keys())
active_acc = None
if has_accounts:
active_acc = next((a for a in accounts if a["id"] == preselect_id), accounts[0])
Database.save_setting(setting_key, str(active_acc["id"]))
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}
def get_current_acc() -> dict | None:
return acc_by_name.get(selected_name_var.get())
def persist_bots_if_any():
if self.bot_widget is not None and has_accounts:
_, to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, self.GAME_FOLDER_ID, to_save)
def refresh_menu():
cur = get_current_acc()
persist_bots_if_any()
self.show(preselect_id=cur["id"] if cur else None)
topbar = self.ctx.build_game_topbar(
self.ctx.root,
stats_endpoint=self.GAME_FOLDER_ID,
stats_enabled=has_accounts,
on_stats_back=refresh_menu,
on_lang_refresh=refresh_menu,
)
cv = MenuBodyCanvas(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
variants_map = self._variants_dict()
variant_items = list(variants_map.items())
table_buttons: list[tuple[str, ImageButton]] = []
def on_account_switched(_val=None):
cur = get_current_acc()
if cur is not None:
fresh = self._get_account(cur["id"])
if not fresh:
return
Database.save_setting(setting_key, str(fresh["id"]))
topbar.extra_label.configure(
text=t(self.KEY_HEADER_GOLD, fresh["account_name"], fresh["gold"])
)
for v_k, tb in table_buttons:
tb.set_enabled(fresh["gold"] >= self._min_entry_for_variant(v_k, variants_map[v_k]))
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,
)
def exchange_xp_action():
cur = get_current_acc()
if cur is None:
return
persist_bots_if_any()
ok, msg = self._exchange_xp(pid, cur["id"])
if ok and is_divine:
self.ctx.sounds.play("lose")
self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok)
can_afford_xp = is_divine or (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, exchange_xp_action,
sound_mgr=self.ctx.sounds, width=180, height=36, enabled=can_exchange, style="amethyst",
)
def delete_selected_account():
cur = get_current_acc()
if cur is not None:
self._delete_account(cur["id"])
self.show()
delete_btn = ImageButton(
cv, t("bj_delete_acc_btn"), btn_norm, btn_purp, delete_selected_account,
sound_mgr=self.ctx.sounds, width=136, height=32, enabled=has_accounts, style="amethyst",
)
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
new_acc_var = tk.StringVar(
value=t(self.KEY_DEFAULT_ACC_NAME, len(accounts) + 1)
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,
)
def create_new_account():
if not can_create_more:
return
name = new_entry.get().strip()
if not name:
state_msg["text"], state_msg["ok"] = t("bj_err_empty_name"), False
draw_layout(cv.winfo_width(), cv.winfo_height())
return
try:
persist_bots_if_any()
created = self._create_account(pid, name)
Database.save_setting(setting_key, str(created["id"]))
self.show(preselect_id=created["id"])
except (sqlite3.IntegrityError, RuntimeError) as exc:
state_msg["text"] = t(self.KEY_ERR_DUPLICATE) if isinstance(exc, sqlite3.IntegrityError) else str(exc)
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
if can_create_more:
new_entry.bind_return(lambda _e: create_new_account())
create_btn = ImageButton(
cv, t("bj_create_acc_btn", self.STARTING_GOLD),
btn_fire if not has_accounts else btn_norm,
btn_fire if not has_accounts else btn_purp,
create_new_account, sound_mgr=self.ctx.sounds,
width=180, height=36, enabled=can_create_more,
style="fire" if not has_accounts else "amethyst",
)
sac_dd = devil_btn = None
min_sac_lvl = Progression.get_devils_deal_min_level()
sac_candidates = (
Database.get_sacrificeable_profiles(pid, self.GAME_FOLDER_ID)
if (devils_deal_open and has_accounts) else []
)
if sac_candidates:
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,
)
def seal_devils_deal():
cur = get_current_acc()
victim_id = sac_map.get(sac_var.get())
if cur is None or victim_id is None:
return
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
if self.REQUIRES_MIN_ONE_BOT and not active_bots:
state_msg["text"], state_msg["ok"] = t("pk_err_need_one_bot"), False
draw_layout(cv.winfo_width(), cv.winfo_height())
return
Database.save_bot_configs(pid, self.GAME_FOLDER_ID, to_save)
ok, _msg = Database.execute_devils_deal(pid, self.GAME_FOLDER_ID, victim_id, cur["id"])
if ok:
self.ctx.sounds.play("end_battle")
self._launch_table(self.DEVILS_DEFAULT_VARIANT, cur["id"], active_bots)
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",
)
saved_bots = Database.load_bot_configs(pid, self.GAME_FOLDER_ID) or self._default_bot_configs()
self.bot_widget = BotSetupWidget(cv, saved_bots, max_bots=self.MAX_BOTS, enabled=has_accounts)
def enter_table(v_key: str):
cur = get_current_acc()
if not cur:
return
acc = self._get_account(cur["id"])
if not acc:
return
Database.save_setting(setting_key, str(acc["id"]))
active_bots, configs_to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, self.GAME_FOLDER_ID, configs_to_save)
if self.REQUIRES_MIN_ONE_BOT and not active_bots:
state_msg["text"], state_msg["ok"] = t("pk_err_need_one_bot"), False
draw_layout(cv.winfo_width(), cv.winfo_height())
return
min_req = self._min_entry_for_variant(v_key, variants_map[v_key])
cur_prog = self.ctx.refresh_game_progress()
if acc["gold"] < min_req:
state_msg["text"] = t(
"bj_err_not_enough_gold_entry",
acc["account_name"], min_req, acc["gold"],
cur_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT,
)
state_msg["ok"] = False
draw_layout(cv.winfo_width(), cv.winfo_height())
return
self._launch_table(v_key, acc["id"], active_bots)
for v_key, cfg in variant_items:
min_req = self._min_entry_for_variant(v_key, cfg)
can_play_v = bool(active_acc and active_acc["gold"] >= min_req)
t_btn = ImageButton(
cv, t("bj_enter_table_btn"), btn_fire, btn_fire,
lambda k=v_key: enter_table(k), sound_mgr=self.ctx.sounds,
width=168, height=38, enabled=can_play_v, style="fire",
)
table_buttons.append((v_key, t_btn))
def draw_layout(w: int, h: int):
cv.sync_bg(w, h)
cv.delete("fg")
self._photo_refs.clear()
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, right_x = x0, x0 + col_w + col_gap
top_sec_y = 10 if compact else 18
upper_h = max(284 if compact else 300, self.MAX_BOTS * BotSetupWidget.ROW_HEIGHT + 44)
s1_ph = self.ctx.assets.get_goth_text_photo(
t(self.KEY_SEC1_TITLE, len(accounts), GOLD_MAX_ACCOUNTS, self.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(self.KEY_BOTS_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, lbl_col_w, btn_w = 22, 118, 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, gb_w = r1_y + 54, 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_acc = self._get_account(cur_acc_obj["id"]) if cur_acc_obj else None
fresh_gold = fresh_acc["gold"] if fresh_acc else 0
gold_str = t(self.KEY_GOLD_DISPLAY, fresh_gold) if fresh_acc 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 fresh_acc 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 self._format_limit_info(dyn_xp_cost)
)
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:
cv.create_window(
right_x + col_w // 2, box_cy,
window=self.bot_widget,
width=col_w - 40, height=self.MAX_BOTS * BotSetupWidget.ROW_HEIGHT + 8,
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(self.KEY_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(
self._format_variant_desc(v_key, cfg),
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()))

View File

@ -1,192 +0,0 @@
# -*- coding: utf-8 -*-
# view/widgets/stats_board_widget.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_HEADING,
FONT_SIZE_SMALL_MIN,
STAT_FIELD_KEYS,
)
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
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,
)
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.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)
first_key = next(iter(self.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.bind("<Configure>", self._on_configure)
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())
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")