# -*- coding: utf-8 -*- # games/blackjack/views/blackjack_table_view.py from __future__ import annotations import json import time from pathlib import Path import tkinter as tk from PIL import Image, ImageTk from games.blackjack.models.blackjack_engine import BlackjackEngine from games.blackjack.models.bot_ai import BlackjackBotAI from games.blackjack.models.bot_seat import BlackjackBotSeat from games.blackjack.models.hand_evaluator import HandEvaluator from games.blackjack.models.player_hand import PlayerHand from games.blackjack.views.round_result_dialog import BlackjackResultDialog from models.database import Database from models.progression import Progression from resources.code_res.game_constants import ( ACCENT_GOLD, ACCENT_GOTH, BJ_BOT_CARD_SIZE, BJ_BOT_TURN_DELAY_MS, BJ_DEALER_DELAY_MS, BJ_INITIAL_ANTE, BJ_SPLIT_CARD_SIZE, BJ_STARTING_GOLD, BJ_VARIANTS, BORDER_COLOR, ERROR_FG, FG_COLOR, GOLD_MIN_TABLE_ENTRY, MUTED_FG, PANEL_BG, PK_TABLE_IMAGE, PLAYING_CARD_SIZE, SUBTLE_BORDER, TABLE_BG, XP_TO_GOLD_AMOUNT ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton GAME_FOLDER_ID = "blackjack" IMAGES_DIR = Path(__file__).resolve().parents[3] / "resources" / "images" BJ_OVAL_BOT_COORDS = ( (0.160, 0.76), # Platz 1: Unten links (Spieler 1) (0.160, 0.24), # Platz 2: Oben links (Spieler 2) (0.840, 0.24), # Platz 3: Oben rechts (Spieler 3) (0.840, 0.76), # Platz 4: Unten rechts (Spieler 4) ) BJ_SEAT_LAYOUT_BY_COUNT = { 1: (2,), 2: (1, 2), 3: (1, 2, 3), 4: (0, 1, 2, 3), } STEP_MITGEHEN = "MITGEHEN" STEP_ZIEHEN = "ZIEHEN" STEP_ERHOEHEN = "ERHOEHEN" class BlackjackTableView: def __init__( self, context, variant_key: str, bj_account_id: int, bot_configs: list[tuple[int, str]], on_back_to_menu, resume_state_json: str | None = None, ): self.ctx = context self.variant_key = variant_key self.cfg = BJ_VARIANTS[variant_key] self.on_back_to_menu = on_back_to_menu self.engine = BlackjackEngine(num_decks=self.cfg["decks"]) self.bot_ai = BlackjackBotAI() self.active_hand_idx: int = 0 self.turn_step: str = STEP_ZIEHEN self.settle_only_mode: bool = False self.active_bot_idx: int = -1 self.round_start_time: float = time.time() self._last_popup_payload: dict | None = None self._result_dialog: BlackjackResultDialog | None = None self._photo_refs = [] self._turn_job = None self._raw_table_pil: Image.Image | None = self._load_raw_table_image() self._scaled_table_photo: ImageTk.PhotoImage | None = None self._last_bg_size: tuple[int, int] = (0, 0) self.ctx.sounds.play_ingame_music() if resume_state_json is not None: self._restore_from_json(resume_state_json) else: self.bj_account = Database.get_blackjack_account(bj_account_id) self.devils_locked = bool(self.bj_account.get("devils_deal_active", 0)) level_chips = self._get_current_level_chips() bot_bankroll = max(BJ_STARTING_GOLD, level_chips[-1] * 4) self.bots: list[BlackjackBotSeat] = [ BlackjackBotSeat(name=b_name, ai_level=lvl, gold=bot_bankroll) for lvl, b_name in bot_configs ] self._build_ui() self._start_new_round() @staticmethod def _load_raw_table_image() -> Image.Image | None: img_path = IMAGES_DIR / PK_TABLE_IMAGE if img_path.is_file(): try: return Image.open(img_path).convert("RGB") except Exception: return None return None # --------------------------------------------------------- # AUTO-SAVE & RESUME (nur aktiv während The Devil's Deal!) # --------------------------------------------------------- def _persist_state(self): if not self.devils_locked: return state_obj = { "bj_account_id": self.bj_account["id"], "devils_locked": self.devils_locked, "active_hand_idx": self.active_hand_idx, "turn_step": self.turn_step, "settle_only_mode": self.settle_only_mode, "active_bot_idx": self.active_bot_idx, "elapsed_sec": max(0.0, time.time() - self.round_start_time), "running_count": self.bot_ai.running_count, "last_popup_payload": self._last_popup_payload, "engine": self.engine.to_dict(self.bots), } Database.save_game_state( self.ctx.profile["id"], GAME_FOLDER_ID, self.variant_key, json.dumps(state_obj), ) def _clear_persisted_state(self): Database.delete_game_state(self.ctx.profile["id"], GAME_FOLDER_ID) def _restore_from_json(self, raw_json: str): try: data = json.loads(raw_json) self.bj_account = Database.get_blackjack_account(data["bj_account_id"]) self.devils_locked = bool(data.get("devils_locked", False) or self.bj_account.get("devils_deal_active", 0)) self.active_hand_idx = int(data.get("active_hand_idx", 0)) self.turn_step = data.get("turn_step", STEP_ZIEHEN) self.settle_only_mode = bool(data.get("settle_only_mode", False)) self.active_bot_idx = int(data.get("active_bot_idx", -1)) self.round_start_time = time.time() - float(data.get("elapsed_sec", 0.0)) self.bot_ai.running_count = int(data.get("running_count", 0)) self._last_popup_payload = data.get("last_popup_payload") self.bots = self.engine.load_from_dict(data["engine"]) except Exception: self._clear_persisted_state() dev_acc = Database.get_active_devils_bj_account(self.ctx.profile["id"]) accounts = Database.get_blackjack_accounts(self.ctx.profile["id"]) self.bj_account = dev_acc or accounts[0] self.devils_locked = bool(self.bj_account.get("devils_deal_active", 0)) self.bots = [] self._build_ui() self._start_new_round() return self._build_ui() if self.engine.state == "ACTION_LOOP": self._render_table(reveal_opponents=False, reveal_dealer=False) if self.active_bot_idx >= 0: self._step_next_bot() elif 0 <= self.active_hand_idx < len(self.engine.player_hands): self._render_current_tree_step() else: self._begin_new_table_cycle() elif self.engine.state == "DEALER_TURN": self._render_table(reveal_opponents=True, reveal_dealer=True) self.status_lbl.configure(text=t("bj_dealer_reveals")) self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step) elif self.engine.state == "SHOWDOWN" and self._last_popup_payload: self._render_table(reveal_opponents=True, reveal_dealer=True) self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload)) else: self._start_new_round() def _get_current_level_chips(self) -> tuple[int, int, int, int]: bj_lvl = self.ctx.game_progress["level"] return Progression.get_level_bet_chips(bj_lvl, bet_scale=self.cfg.get("bet_scale", 1)) def _cleanup_and_go(self, nav_callable): if self.devils_locked: return if self._turn_job: try: self.ctx.root.after_cancel(self._turn_job) except Exception: pass self._turn_job = None if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None self._clear_persisted_state() nav_callable() def _on_language_switched(self): self._persist_state() self._build_ui() if self.engine.state == "ACTION_LOOP": self._render_table(reveal_opponents=False, reveal_dealer=False) if self.active_bot_idx == -1: self._render_current_tree_step() elif self.engine.state == "DEALER_TURN": self._render_table(reveal_opponents=True, reveal_dealer=True) self.status_lbl.configure(text=t("bj_dealer_reveals")) elif self.engine.state == "SHOWDOWN" and self._last_popup_payload: self._render_table(reveal_opponents=True, reveal_dealer=True) self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload)) def _build_ui(self): if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None self._last_bg_size = (0, 0) self.ctx.root.clear_window(apply_global_bg=True) self.topbar = self.ctx.build_game_topbar( self.ctx.root, t(f"variant_{self.variant_key}"), on_game_menu=lambda: self._cleanup_and_go(lambda: self.on_back_to_menu(self.bj_account["id"])), on_lang_refresh=self._on_language_switched, locked_exit=self.devils_locked, ) self.table_frame = tk.Frame( self.ctx.root, bg=TABLE_BG, padx=14, pady=8, highlightthickness=1, highlightbackground=ERROR_FG if self.devils_locked else BORDER_COLOR ) self.table_frame.place(relx=0.5, rely=0.535, anchor="center", relwidth=0.96, relheight=0.88) self.pot_lbl = tk.Label( self.table_frame, text="", font=("Georgia", 11, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG, pady=4, highlightthickness=1, highlightbackground=SUBTLE_BORDER ) self.pot_lbl.pack(fill="x", side="top", pady=(0, 4)) # Kompakte 3-Spalten-Leiste unten (identisch zu Poker) bottom_area = tk.Frame(self.table_frame, bg=TABLE_BG, height=224) bottom_area.pack(fill="x", side="bottom", pady=(6, 0)) bottom_area.pack_propagate(False) bottom_area.columnconfigure(0, weight=30, uniform="bjcols") bottom_area.columnconfigure(1, weight=44, uniform="bjcols") bottom_area.columnconfigure(2, weight=26, uniform="bjcols") bottom_area.rowconfigure(0, weight=1) self.left_info_panel = tk.Frame( bottom_area, bg=PANEL_BG, padx=8, pady=5, highlightthickness=1, highlightbackground=BORDER_COLOR ) self.left_info_panel.grid(row=0, column=0, sticky="nsew", padx=(0, 6)) center_player_wrap = tk.Frame( bottom_area, bg=PANEL_BG, padx=10, pady=6, highlightthickness=1, highlightbackground=SUBTLE_BORDER ) center_player_wrap.grid(row=0, column=1, sticky="nsew", padx=4) self.status_lbl = tk.Label( center_player_wrap, text="", font=("Georgia", 10, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG, wraplength=410, justify="center" ) self.status_lbl.pack(side="top", pady=(0, 3)) self.player_sec = tk.Frame(center_player_wrap, bg=PANEL_BG) self.player_sec.pack(fill="both", expand=True) self.controls_frame = tk.Frame( bottom_area, bg=PANEL_BG, padx=8, pady=5, highlightthickness=1, highlightbackground=BORDER_COLOR ) self.controls_frame.grid(row=0, column=2, sticky="nsew", padx=(6, 0)) # Canvas für den ovalen Tisch (`poker_table.jpg`[cite: 9]) self.arena_canvas = tk.Canvas( self.table_frame, bg="#120f18", highlightthickness=1, highlightbackground=SUBTLE_BORDER ) self.arena_canvas.pack(fill="both", expand=True) self.arena_canvas.bind("", self._on_arena_resize) # Bank-Box (oben mittig auf dem Canvas) felt_bg = "#1b1626" self.board_box = tk.Frame( self.arena_canvas, bg=felt_bg, padx=10, pady=6, highlightthickness=1, highlightbackground=SUBTLE_BORDER ) self.board_box.place(relx=0.50, rely=0.28, anchor="center") self.dealer_lbl = tk.Label( self.board_box, text=t("bj_dealer_title"), font=("Georgia", 9, "bold"), fg=MUTED_FG, bg=felt_bg ) self.dealer_lbl.pack(pady=(0, 3)) self.dealer_cards_frame = tk.Frame(self.board_box, bg=felt_bg, height=PLAYING_CARD_SIZE[1] + 2) self.dealer_cards_frame.pack() self._bot_seat_frames: list[tk.Frame] = [] self._refresh_header() def _on_arena_resize(self, event): w, h = event.width, event.height if w < 80 or h < 80 or (w, h) == self._last_bg_size: return self._last_bg_size = (w, h) self.arena_canvas.delete("table_bg") if self._raw_table_pil is not None: fitted = self._raw_table_pil.resize((w, h), Image.Resampling.LANCZOS) self._scaled_table_photo = ImageTk.PhotoImage(fitted) self.arena_canvas.create_image( 0, 0, image=self._scaled_table_photo, anchor="nw", tags="table_bg" ) self.arena_canvas.tag_lower("table_bg") else: mx, my_top, my_bot = int(w * 0.11), int(h * 0.13), int(h * 0.08) self.arena_canvas.create_oval( mx, my_top, w - mx, h - my_bot, fill="#14111b", outline=BORDER_COLOR, width=3, tags="table_bg" ) def _refresh_header(self): self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) prof = self.ctx.profile prog = self.ctx.refresh_game_progress() self.topbar.extra_label.configure(text=t("bj_header_gold", self.bj_account["account_name"], self.bj_account["gold"])) self.topbar.level_label.configure( text=t("level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]) ) self.pot_lbl.configure(text=t("bj_pot_banner", self.engine.pot, self.engine.highest_bet)) # --------------------------------------------------------- # ROUND START # --------------------------------------------------------- def _start_new_round(self): if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) self.devils_locked = bool(self.bj_account.get("devils_deal_active", 0)) gold = self.bj_account["gold"] if gold < GOLD_MIN_TABLE_ENTRY: Database.set_bj_devils_deal_active(self.bj_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", self.bj_account["account_name"], GOLD_MIN_TABLE_ENTRY, gold, cur_cost, XP_TO_GOLD_AMOUNT ) self._cleanup_and_go(lambda: self.on_back_to_menu(self.bj_account["id"], msg)) return self._last_popup_payload = None self.active_hand_idx = 0 self.settle_only_mode = False self.active_bot_idx = -1 self.round_start_time = time.time() self.ctx.sounds.play("deal") min_cards = (len(self.bots) + 3) * 6 if self.engine.check_reshuffle(min_needed=min_cards): self.bot_ai.reset_count() level_chips = self._get_current_level_chips() min_bot_stack = max(BJ_STARTING_GOLD, level_chips[-1] * 3) for b in self.bots: self.bot_ai.ensure_ante_gold(b, BJ_INITIAL_ANTE, fallback_stack=min_bot_stack) paid_ante = self.engine.deal_initial_round(BJ_INITIAL_ANTE, gold, self.bots) self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid_ante) self.bot_ai.observe_public_card(self.engine.dealer_hand[0]) self._persist_state() self._build_ui() self._render_table(reveal_opponents=False, reveal_dealer=False) self._begin_new_table_cycle() # --------------------------------------------------------- # RENDERING TISCH & SPIELER HÄNDE (Karten mit Überlappung) # --------------------------------------------------------- @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 "" def _render_bots(self, reveal_opponents: bool): for old_f in self._bot_seat_frames: if old_f.winfo_exists(): old_f.destroy() self._bot_seat_frames.clear() slot_indices = BJ_SEAT_LAYOUT_BY_COUNT.get(len(self.bots), (0, 1, 2, 3)) for bot_i, bot in enumerate(self.bots): coord_idx = slot_indices[bot_i] rx, ry = BJ_OVAL_BOT_COORDS[coord_idx] is_turn = (bot_i == self.active_bot_idx) if is_turn: b_col, thick = ACCENT_GOLD, 2 elif bot.folded or bot.busted: b_col, thick = ERROR_FG, 1 else: b_col, thick = BORDER_COLOR, 1 box = tk.Frame( self.arena_canvas, bg="#191521", padx=8, pady=4, width=175, highlightthickness=thick, highlightbackground=b_col ) box.place(relx=rx, rely=ry, anchor="center") self._bot_seat_frames.append(box) disp_name = t("bj_bot_rebuy", bot.name) if bot.rebought else bot.name tk.Label(box, text=disp_name, font=("Georgia", 9, "bold"), fg=ACCENT_GOTH, bg="#191521").pack() tk.Label(box, text=t("bj_bot_gold_lbl", bot.gold), font=("Helvetica", 8, "bold"), fg=ACCENT_GOLD, bg="#191521").pack(pady=(1, 2)) cards_f = tk.Frame(box, bg="#191521", height=82) cards_f.pack(pady=2) show_faces = reveal_opponents or bot.busted for c_idx, card in enumerate(bot.hand): photo = ( self.ctx.assets.get_card_photo(card.image_filename, size=BJ_BOT_CARD_SIZE) if show_faces else self.ctx.assets.get_card_back_photo(color=self.cfg["back_color"], size=BJ_BOT_CARD_SIZE) ) if photo: self._photo_refs.append(photo) lbl = tk.Label(cards_f, image=photo, bg="#191521", bd=0) lbl.pack(side="left") if c_idx > 0: # Karten leicht überlappen lassen (~35px sichtbar) lbl.pack_configure(padx=(-38, 0)) 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 = "" tk.Label( box, text=info_txt, font=("Helvetica", 8, "bold" if bot.busted else "normal"), fg=ERROR_FG if (bot.busted or bot.folded) else FG_COLOR, bg="#191521" ).pack(pady=(1, 0)) def _render_player_hands(self): for w in self.player_sec.winfo_children(): w.destroy() hands = self.engine.player_hands if not hands: return if len(hands) == 1: h = hands[0] cards_f = tk.Frame(self.player_sec, bg=PANEL_BG, height=132) cards_f.pack(pady=2) for c_idx, card in enumerate(h.cards): photo = self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE) if photo: self._photo_refs.append(photo) lbl = tk.Label(cards_f, image=photo, bg=PANEL_BG, bd=0) lbl.pack(side="left") if c_idx > 0: # Überlappung bei eigener Hand lbl.pack_configure(padx=(-42, 0)) p_val, p_soft = HandEvaluator.evaluate(h.cards) soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else "" suffix = self._hand_state_suffix(h) lbl_col = ERROR_FG if (h.busted or h.folded) else FG_COLOR tk.Label( self.player_sec, text=t("bj_player_total", p_val, soft_hint, h.bet_in_pot, suffix), font=("Georgia", 11, "bold"), fg=lbl_col, bg=PANEL_BG ).pack(side="bottom", pady=(2, 2)) return split_wrap = tk.Frame(self.player_sec, bg=PANEL_BG) split_wrap.pack(expand=True) for idx, h in enumerate(hands): is_active = (self.engine.state == "ACTION_LOOP" and self.active_bot_idx == -1 and idx == self.active_hand_idx) b_col = ACCENT_GOLD if is_active else (ERROR_FG if (h.busted or h.folded) else SUBTLE_BORDER) hbox = tk.Frame( split_wrap, bg=CELL_BG, padx=8, pady=4, highlightthickness=2 if is_active else 1, highlightbackground=b_col ) hbox.pack(side="left", padx=5) cards_f = tk.Frame(hbox, bg=CELL_BG, height=108) cards_f.pack(pady=2) for c_idx, card in enumerate(h.cards): photo = self.ctx.assets.get_card_photo(card.image_filename, size=BJ_SPLIT_CARD_SIZE) if photo: self._photo_refs.append(photo) lbl = tk.Label(cards_f, image=photo, bg=CELL_BG, bd=0) lbl.pack(side="left") if c_idx > 0: lbl.pack_configure(padx=(-36, 0)) p_val, p_soft = HandEvaluator.evaluate(h.cards) soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else "" suffix = self._hand_state_suffix(h) lbl_col = ACCENT_GOLD if is_active else (ERROR_FG if (h.busted or h.folded) else FG_COLOR) tk.Label( hbox, text=t("bj_hand_box_title", idx + 1, p_val, soft_hint, h.bet_in_pot, suffix), font=("Georgia", 9, "bold"), fg=lbl_col, bg=CELL_BG ).pack(pady=(1, 0)) def _render_table(self, reveal_opponents: bool, reveal_dealer: bool): self._photo_refs.clear() for w in self.dealer_cards_frame.winfo_children(): w.destroy() for c_idx, card in enumerate(self.engine.dealer_hand): photo = ( self.ctx.assets.get_card_back_photo(color=self.cfg["back_color"], size=PLAYING_CARD_SIZE) if c_idx == 1 and not reveal_dealer else self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE) ) if photo: self._photo_refs.append(photo) lbl = tk.Label(self.dealer_cards_frame, image=photo, bg="#1b1626", bd=0) lbl.pack(side="left") if c_idx > 0: lbl.pack_configure(padx=(-42, 0)) felt_bg = "#1b1626" if not reveal_dealer and self.engine.dealer_hand: up_val, _ = HandEvaluator.evaluate([self.engine.dealer_hand[0]]) self.dealer_lbl.configure(text=t("bj_dealer_shows", up_val), bg=felt_bg) elif self.engine.dealer_hand: d_val, _ = HandEvaluator.evaluate(self.engine.dealer_hand) self.dealer_lbl.configure(text=t("bj_dealer_total", d_val), bg=felt_bg) self._render_player_hands() self._render_bots(reveal_opponents=reveal_opponents) self._refresh_header() # --------------------------------------------------------- # TISCH-UMLAUF LOGIK # --------------------------------------------------------- def _begin_new_table_cycle(self): if not self.engine.any_contender_alive(self.bots): self._start_showdown_and_dealer() return self.engine.cycle_card_drawn = False self.settle_only_mode = False self.active_bot_idx = -1 self.active_hand_idx = 0 self._step_next_player_hand() def _begin_settle_bets_pass(self): self.settle_only_mode = True self.active_bot_idx = -1 self.active_hand_idx = 0 self._step_next_player_hand() def _on_table_pass_completed(self): if not self.engine.any_contender_alive(self.bots): self._start_showdown_and_dealer() return self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) wallet = self.bj_account["gold"] if self.settle_only_mode: self._start_showdown_and_dealer() return if not self.engine.cycle_card_drawn: if self.engine.has_unsettled_bets(self.bots, wallet): self._begin_settle_bets_pass() else: self._start_showdown_and_dealer() return self._begin_new_table_cycle() def _step_next_player_hand(self): self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) wallet = self.bj_account["gold"] while self.active_hand_idx < len(self.engine.player_hands): h = self.engine.player_hands[self.active_hand_idx] if not h.is_active_in_pot: self.active_hand_idx += 1 continue raw_deficit = max(0, self.engine.highest_bet - h.bet_in_pot) to_call = min(wallet, raw_deficit) if self.settle_only_mode: if to_call > 0: self.turn_step = STEP_MITGEHEN self._persist_state() self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() return self.active_hand_idx += 1 continue if to_call > 0: self.turn_step = STEP_MITGEHEN self._persist_state() self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() return h_val, _ = HandEvaluator.evaluate(h.cards) if not h.cards_locked and not h.doubled and h_val < 21: self.turn_step = STEP_ZIEHEN self._persist_state() self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() return dyn_chips = self._get_current_level_chips() if wallet >= dyn_chips[0]: self.turn_step = STEP_ERHOEHEN self._persist_state() self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() return self.active_hand_idx += 1 self._start_bots_cycle() def _finish_current_hand_turn(self): self.active_hand_idx += 1 self._persist_state() self._step_next_player_hand() def _render_current_tree_step(self): for w in self.controls_frame.winfo_children(): w.destroy() self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) wallet = self.bj_account["gold"] hand = self.engine.player_hands[self.active_hand_idx] hand_tag = t("bj_active_hand_tag", self.active_hand_idx + 1) if len(self.engine.player_hands) > 1 else "" col = tk.Frame(self.controls_frame, bg=PANEL_BG) col.pack(expand=True) if self.turn_step == STEP_MITGEHEN: raw_deficit = max(0, self.engine.highest_bet - hand.bet_in_pot) to_call = min(wallet, raw_deficit) self.status_lbl.configure(text=t("bj_tree_step1_call", hand_tag, to_call)) ImageButton( col, t("bj_tree_btn_call_yes", to_call), self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, lambda: self._on_step1_call_yes(to_call), sound_mgr=self.ctx.sounds, width=170, height=30, font=("Helvetica", 9, "bold") ).pack(pady=2) ImageButton( col, t("bj_tree_btn_call_no_lose"), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, self._on_fold_hand, sound_mgr=self.ctx.sounds, width=170, height=30, font=("Helvetica", 9, "bold") ).pack(pady=2) return if self.turn_step == STEP_ZIEHEN: self.status_lbl.configure(text=t("bj_tree_step2_draw", hand_tag)) ImageButton( col, t("bj_tree_btn_draw_yes"), self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, self._on_step2_draw_yes, sound_mgr=self.ctx.sounds, width=170, height=28, font=("Helvetica", 9, "bold") ).pack(pady=2) if self.engine.can_double_down(self.active_hand_idx, wallet): dd_cost = self.engine.get_double_down_cost(self.active_hand_idx) ImageButton( col, t("bj_double_btn", dd_cost), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, self._on_step2_double_down, sound_mgr=self.ctx.sounds, width=170, height=28, font=("Helvetica", 9, "bold") ).pack(pady=2) if self.engine.can_split_hand(self.active_hand_idx, wallet): sp_cost = self.engine.highest_bet ImageButton( col, t("bj_split_btn", sp_cost), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, self._on_step2_split, sound_mgr=self.ctx.sounds, width=170, height=28, font=("Helvetica", 9, "bold") ).pack(pady=2) ImageButton( col, t("bj_tree_btn_draw_no"), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, self._on_step2_draw_no, sound_mgr=None, width=170, height=28, font=("Helvetica", 9, "bold") ).pack(pady=2) ImageButton( col, t("bj_fold_btn"), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, self._on_fold_hand, sound_mgr=self.ctx.sounds, width=170, height=28, font=("Helvetica", 9, "bold") ).pack(pady=2) return if self.turn_step == STEP_ERHOEHEN: self.status_lbl.configure(text=t("bj_tree_step3_raise", hand_tag)) dyn_chips = self._get_current_level_chips() for chip in dyn_chips: if wallet >= chip: ImageButton( col, f"+{chip} Gold", self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, lambda c=chip: self._on_step3_raise_yes(c), sound_mgr=self.ctx.sounds, width=170, height=26, font=("Helvetica", 9, "bold") ).pack(pady=1) ImageButton( col, t("bj_tree_btn_raise_no"), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, self._on_step3_raise_no, sound_mgr=self.ctx.sounds, width=170, height=28, font=("Helvetica", 9, "bold") ).pack(pady=2) # --------------------------------------------------------- # BUTTON-AKTIONEN SPIELER # --------------------------------------------------------- def _advance_to_erhoehen_or_next(self): self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) wallet = self.bj_account["gold"] dyn_chips = self._get_current_level_chips() if not self.bots and not self.engine.cycle_card_drawn: self._finish_current_hand_turn() return if wallet >= dyn_chips[0]: self.turn_step = STEP_ERHOEHEN self._persist_state() self._render_current_tree_step() else: self._finish_current_hand_turn() def _on_step1_call_yes(self, to_call: int): if to_call > 0: paid = self.engine.player_add_gold_to_pot(self.active_hand_idx, to_call) if paid > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) self._render_table(reveal_opponents=False, reveal_dealer=False) if self.settle_only_mode: self._finish_current_hand_turn() return hand = self.engine.player_hands[self.active_hand_idx] h_val, _ = HandEvaluator.evaluate(hand.cards) if not hand.cards_locked and not hand.doubled and h_val < 21: self.turn_step = STEP_ZIEHEN self._persist_state() self._render_current_tree_step() else: self._advance_to_erhoehen_or_next() def _on_fold_hand(self): hand = self.engine.player_hands[self.active_hand_idx] hand.folded = True hand.cards_locked = True self._render_table(reveal_opponents=False, reveal_dealer=False) self._finish_current_hand_turn() def _on_step2_draw_yes(self): hand = self.engine.player_hands[self.active_hand_idx] self.engine.player_draw_card(self.active_hand_idx) if HandEvaluator.is_triple_seven(hand.cards): self._trigger_instant_777_win(winner_is_player=True, winning_bot=None) return self._render_table(reveal_opponents=False, reveal_dealer=False) if hand.busted: self._finish_current_hand_turn() return self._advance_to_erhoehen_or_next() def _on_step2_draw_no(self): self.ctx.sounds.play("stand") self._advance_to_erhoehen_or_next() def _on_step2_double_down(self): paid, _card = self.engine.double_down_player_hand(self.active_hand_idx) if paid > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) hand = self.engine.player_hands[self.active_hand_idx] if HandEvaluator.is_triple_seven(hand.cards): self._trigger_instant_777_win(winner_is_player=True, winning_bot=None) return self._render_table(reveal_opponents=False, reveal_dealer=False) self._finish_current_hand_turn() def _on_step2_split(self): paid = self.engine.split_player_hand() if paid > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) self.active_hand_idx = 0 self.turn_step = STEP_ZIEHEN self._persist_state() self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() def _on_step3_raise_yes(self, chip_amount: int): paid = self.engine.player_add_gold_to_pot(self.active_hand_idx, chip_amount) if paid > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) self._render_table(reveal_opponents=False, reveal_dealer=False) self._finish_current_hand_turn() def _on_step3_raise_no(self): self._finish_current_hand_turn() # --------------------------------------------------------- # BOT-ZYKLUS IM UMLAUF # --------------------------------------------------------- def _start_bots_cycle(self): for w in self.controls_frame.winfo_children(): w.destroy() if not self.bots or not self.engine.any_contender_alive(self.bots): self._on_table_pass_completed() return self.active_bot_idx = 0 self._persist_state() self._step_next_bot() def _step_next_bot(self): if not self.table_frame.winfo_exists(): return while self.active_bot_idx < len(self.bots): bot = self.bots[self.active_bot_idx] if bot.is_active_in_pot: if not self.settle_only_mode: break if bot.gold > 0 and bot.bet_in_pot < self.engine.highest_bet: break self.active_bot_idx += 1 if self.active_bot_idx >= len(self.bots): self.active_bot_idx = -1 self._persist_state() self._on_table_pass_completed() return bot = self.bots[self.active_bot_idx] self._persist_state() self.status_lbl.configure(text=t("bj_bot_turn_status", bot.name)) self._render_table(reveal_opponents=False, reveal_dealer=False) self._turn_job = self.ctx.root.after(BJ_BOT_TURN_DELAY_MS, lambda: self._execute_bot_action(bot)) def _execute_bot_action(self, bot: BlackjackBotSeat): if not self.table_frame.winfo_exists(): return upcard = self.engine.dealer_hand[0] dyn_chips = self._get_current_level_chips() raw_deficit = max(0, self.engine.highest_bet - bot.bet_in_pot) to_call = min(bot.gold, raw_deficit) if to_call > 0: if not self.bot_ai.decide_step1_mitgehen( bot, self.engine.highest_bet, upcard, self.engine.deck.remaining() ): bot.folded = True bot.cards_locked = True bot.status_text = t("bj_bot_action_fold") self._finish_bot_step() return self.ctx.sounds.play("click") self.engine.bot_add_gold_to_pot(bot, to_call) if self.settle_only_mode: bot.status_text = t("bj_bot_action_call", to_call) self._finish_bot_step() return drew_card = False if not bot.cards_locked and not bot.doubled: if self.bot_ai.wants_double_down(bot, upcard, self.engine.highest_bet, self.engine.deck.remaining()): dd_cost = max(self.engine.highest_bet, bot.bet_in_pot) * 2 - bot.bet_in_pot paid = self.engine.bot_add_gold_to_pot(bot, dd_cost) self.ctx.sounds.play("click") self.engine.bot_draw_card(bot) bot.doubled = True bot.cards_locked = True if HandEvaluator.is_triple_seven(bot.hand): self._trigger_instant_777_win(winner_is_player=False, winning_bot=bot) return if bot.busted: b_val, _ = HandEvaluator.evaluate(bot.hand) bot.status_text = t("bj_bot_action_bust", b_val) else: bot.status_text = t("bj_bot_action_double", paid) self._finish_bot_step() return if self.bot_ai.decide_step2_ziehen(bot, upcard, self.engine.deck.remaining()): self.ctx.sounds.play("click") self.engine.bot_draw_card(bot) drew_card = True if HandEvaluator.is_triple_seven(bot.hand): self._trigger_instant_777_win(winner_is_player=False, winning_bot=bot) return if bot.busted: b_val, _ = HandEvaluator.evaluate(bot.hand) bot.status_text = t("bj_bot_action_bust", b_val) self._finish_bot_step() return raise_amt = self.bot_ai.decide_step3_erhoehen( bot, dyn_chips, self.engine.deck.remaining(), upcard ) if raise_amt > 0: self.ctx.sounds.play("click") self.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)) self._finish_bot_step() def _finish_bot_step(self): self.active_bot_idx += 1 self._persist_state() self._render_table(reveal_opponents=False, reveal_dealer=False) self._turn_job = self.ctx.root.after(BJ_BOT_TURN_DELAY_MS, self._step_next_bot) # --------------------------------------------------------- # SHOWDOWN, HAUS-DEALER & ERGEBNIS-POPUP # --------------------------------------------------------- def _resolve_devils_lock_after_outcome(self, outcome_type: str): if not self.devils_locked: self._clear_persisted_state() return updated_acc = Database.get_blackjack_account(self.bj_account["id"]) still_only_ten_from_tie = (outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY) if not still_only_ten_from_tie: Database.set_bj_devils_deal_active(self.bj_account["id"], False) self.devils_locked = False self._clear_persisted_state() def _award_xp_and_record(self, outcome_type: str, won_stat: bool | None) -> tuple[int, int | None]: duration = max(0.5, time.time() - self.round_start_time) prog_before = self.ctx.refresh_game_progress() opp_levels = [b.ai_level for b in self.bots] xp_gained = Progression.calculate_match_xp( player_level=prog_before["level"], opponent_levels=opp_levels, outcome_type=outcome_type, variant_mult=self.cfg["xp_mult"], ) if won_stat is None: Database.add_game_points(self.ctx.profile["id"], GAME_FOLDER_ID, xp_gained) prog_after = self.ctx.refresh_game_progress() self.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 = self.ctx.record_result( self.variant_key, won=won_stat, duration_sec=duration, points_gained=xp_gained, bj_account_id=self.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)) def _collect_showdown_snapshot(self, instant_777_winner: str | None = None) -> list[dict]: snapshot: list[dict] = [] d_cards = self.engine.dealer_hand d_val, _ = HandEvaluator.evaluate(d_cards) d_rank = self.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(self.engine.player_hands) > 1 for idx, h in enumerate(self.engine.player_hands): hr = self.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 self.bots: br = self.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), }) contenders = [s for s in snapshot if s["role"] != "DEALER" and not s["busted"] and not s["folded"]] dealer_entry = snapshot[0] if instant_777_winner is not None: for s in snapshot: if instant_777_winner == "PLAYER" and s["role"] == "PLAYER" and s["rank_tuple"] == [3, 21]: s["is_winner"] = True elif s["role"] == "BOT" and s["name"] == instant_777_winner and s["rank_tuple"] == [3, 21]: s["is_winner"] = True else: s["is_winner"] = False return snapshot 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"]) if d_rnk > best_contender: dealer_entry["is_winner"] = True for s in snapshot[1:]: s["is_winner"] = False elif d_rnk == best_contender: dealer_entry["is_winner"] = True for s in snapshot[1:]: s["is_winner"] = (not s["busted"] and not s["folded"] and tuple(s["rank_tuple"]) == best_contender) else: dealer_entry["is_winner"] = False for s in snapshot[1:]: s["is_winner"] = (not s["busted"] and not s["folded"] and tuple(s["rank_tuple"]) == best_contender) return snapshot def _trigger_instant_777_win(self, winner_is_player: bool, winning_bot: BlackjackBotSeat | None): self.engine.state = "SHOWDOWN" self._count_all_table_cards() pot_total = self.engine.pot total_p_bet = self.engine.total_player_bet snap = self._collect_showdown_snapshot( instant_777_winner="PLAYER" if winner_is_player else winning_bot.name ) if winner_is_player: payout = pot_total + (total_p_bet if not self.bots else 0) net = payout - total_p_bet self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], payout) xp, leveled_to = self._award_xp_and_record("WIN_777", won_stat=True) self._resolve_devils_lock_after_outcome("WIN_777") payload = { "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, } else: winning_bot.gold += pot_total bot_net = pot_total - winning_bot.bet_in_pot xp, leveled_to = self._award_xp_and_record("LOSE", won_stat=False) self._resolve_devils_lock_after_outcome("LOSE") payload = { "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, } self._last_popup_payload = payload if self.devils_locked: self._persist_state() else: self._build_ui() self.status_lbl.configure(text="") self._render_table(reveal_opponents=True, reveal_dealer=True) self._open_result_popup(self._build_localized_popup_data(payload)) def _start_showdown_and_dealer(self): for w in self.controls_frame.winfo_children(): w.destroy() if not self.engine.any_contender_alive(self.bots): self._finalize_showdown() return self.engine.state = "DEALER_TURN" self._persist_state() self.status_lbl.configure(text=t("bj_dealer_reveals")) self._render_table(reveal_opponents=True, reveal_dealer=True) self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step) def _dealer_draw_step(self): if not self.table_frame.winfo_exists(): return if self.engine.dealer_should_hit(): self.ctx.sounds.play("click") self.engine.dealer_hit() self._persist_state() self._render_table(reveal_opponents=True, reveal_dealer=True) self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step) else: self._finalize_showdown() def _count_all_table_cards(self): if len(self.engine.dealer_hand) >= 2: for c in self.engine.dealer_hand[1:]: self.bot_ai.observe_public_card(c) for h in self.engine.player_hands: for c in h.cards: self.bot_ai.observe_public_card(c) for b in self.bots: for c in b.hand: self.bot_ai.observe_public_card(c) def _finalize_showdown(self): self._count_all_table_cards() res = self.engine.resolve_showdown(self.bots) snap = self._collect_showdown_snapshot(instant_777_winner=None) if res["player_payout"] > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], res["player_payout"]) w_type = res["winner_type"] if w_type == "PLAYER": has_natural_bj = any( h.is_active_in_pot and not h.is_split_hand and HandEvaluator.is_natural_blackjack(h.cards) for h in self.engine.player_hands ) out_code = "WIN_BJ" if has_natural_bj else "WIN" xp, leveled_to = self._award_xp_and_record(out_code, won_stat=True) player_won_flag = True elif w_type == "TIE": out_code = "TIE" xp, leveled_to = self._award_xp_and_record("TIE", won_stat=None) player_won_flag = None else: out_code = "LOSE" xp, leveled_to = self._award_xp_and_record("LOSE", won_stat=False) player_won_flag = False self._resolve_devils_lock_after_outcome(out_code) payload = { "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, } self._last_popup_payload = payload if self.devils_locked: self._persist_state() else: self._build_ui() self.status_lbl.configure(text="") self._render_table(reveal_opponents=True, reveal_dealer=True) self._open_result_popup(self._build_localized_popup_data(payload)) def _build_localized_popup_data(self, payload: dict) -> dict: from models.card import Card w_type = payload["winner_type"] if w_type == "BANK": headline = t("bj_popup_bank_won") elif w_type == "PLAYER": headline = t("bj_popup_player_won") elif w_type == "BOT": headline = t("bj_popup_bot_won", ", ".join(payload["winner_names"])) else: headline = t("bj_popup_tie") showdown_hands = [] raw_snap = payload.get("showdown_snapshot", []) for s in raw_snap: cards_obj = [Card(sr[0], sr[1]) for sr in s.get("cards_raw", [])] if s["role"] == "DEALER": owner_lbl = t("bj_showdown_seat_dealer") elif s["role"] == "PLAYER": owner_lbl = ( t("bj_showdown_seat_you_hand", s["hand_no"]) if s.get("hand_no") else t("bj_showdown_seat_you") ) else: owner_lbl = s["name"] rank_lbl = self._format_hand_rank_label( cards_obj, is_split=s.get("is_split", False), busted=s.get("busted", False), folded=s.get("folded", False), ) 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": rank_lbl, "rank_tuple": tuple(s.get("rank_tuple", [0, 0])), "role": s["role"], }) reason_text = self._build_showdown_reason(payload, showdown_hands) 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(self.bj_account["id"])["gold"] can_cont = cur_gold >= GOLD_MIN_TABLE_ENTRY return { "headline": headline, "reason_text": reason_text, "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": can_cont, "can_leave_menu": not self.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: who = t("bj_showdown_seat_you") if inst == "PLAYER" else inst return t("bj_reason_777_win", who) dealer = showdown_hands[0] contenders = [h for h in showdown_hands[1:] if not h["busted"] and not h["folded"]] if not contenders: return t("bj_reason_all_out") winners = [h for h in showdown_hands if h["is_winner"]] if not winners: return "" top_rank = winners[0]["rank_tuple"] winner_names_str = ", ".join(dict.fromkeys(w["owner_label"] for w in winners if not w["is_dealer"])) if dealer["is_winner"] and len(winners) > 1: return t("bj_reason_dealer_tie_push", dealer["rank_label"]) losers_with_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 ] win_label = dealer["owner_label"] if dealer["is_winner"] else winner_names_str if top_rank == (3, 21) and losers_with_21: return t("bj_reason_777_beats_21", win_label) if top_rank == (2, 21) and losers_with_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"] ] if others_alive: runner_up = max(others_alive, key=lambda x: x["rank_tuple"]) runner_desc = f"{runner_up['owner_label']}: {runner_up['rank_label']}" else: runner_desc = f"{dealer['owner_label']}: {dealer['rank_label']}" return t("bj_reason_higher_score", win_label, winners[0]["rank_label"], runner_desc) def _open_result_popup(self, popup_data: dict): for w in self.controls_frame.winfo_children(): w.destroy() self._result_dialog = BlackjackResultDialog( parent=self.table_frame, assets=self.ctx.assets, sounds=self.ctx.sounds, result_data=popup_data, on_next_round=self._start_new_round, on_back_to_menu=lambda: self._cleanup_and_go(lambda: self.on_back_to_menu(self.bj_account["id"])), )