# -*- 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("", 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()))