# -*- coding: utf-8 -*- # games/poker/views/poker_table_view.py import json import time from pathlib import Path import tkinter as tk from PIL import Image, ImageTk from games.poker.models.poker_bot_ai import PokerBotAI from games.poker.models.poker_engine import PokerEngine from games.poker.models.poker_evaluator import PokerEvaluator from games.poker.models.poker_seat import PokerSeat from games.poker.views.poker_result_dialog import PokerResultDialog from models.database import Database from models.progression import Progression from resources.code_res.game_constants import ( ACCENT_GOLD, ACCENT_GOTH, BORDER_COLOR, CELL_BG, ERROR_FG, FG_COLOR, MUTED_FG, PANEL_BG, PK_BOT_TURN_DELAY_MS, PK_STARTING_GOLD, PK_STREET_DELAY_MS, PK_TABLE_IMAGE, PK_VARIANTS, PLAYING_CARD_SIZE, RED_SUITS, SUBTLE_BORDER, SUIT_SYMBOLS, TABLE_BG, XP_TO_GOLD_AMOUNT ) from resources.code_res.i18n import get_lang, t from view.widgets.image_button import ImageButton from view.widgets.info_badge import InfoBadge GAME_FOLDER_ID = "poker" IMAGES_DIR = Path(__file__).resolve().parents[3] / "resources" / "images" PK_OVAL_BOARD_CARD = (76, 112) OVAL_BOT_COORDS = ( (0.155, 0.77), # Platz 1: Unten links (0.155, 0.23), # Platz 2: Oben links (0.500, 0.14), # Platz 3: Oben Mitte (0.845, 0.23), # Platz 4: Oben rechts (0.845, 0.77), # Platz 5: Unten rechts ) SEAT_LAYOUT_BY_COUNT = { 1: (2,), 2: (1, 3), 3: (1, 2, 3), 4: (0, 1, 3, 4), 5: (0, 1, 2, 3, 4), } HAND_REFERENCE_EXAMPLES = ( (1, 9, (("A", "S"), ("K", "S"), ("Q", "S"), ("J", "S"), ("10", "S"))), (2, 8, (("J", "S"), ("10", "S"), ("9", "S"), ("8", "S"), ("7", "S"))), (3, 7, (("K", "H"), ("K", "C"), ("K", "D"), ("K", "S"), None)), (4, 6, (("A", "H"), ("A", "C"), ("A", "D"), ("9", "S"), ("9", "H"))), (5, 5, (("K", "S"), ("J", "S"), ("8", "S"), ("7", "S"), ("5", "S"))), (6, 4, (("J", "H"), ("10", "C"), ("9", "D"), ("8", "S"), ("7", "H"))), (7, 3, (("K", "H"), ("K", "C"), ("K", "D"), None, None)), (8, 2, (("A", "H"), ("A", "C"), ("9", "D"), ("9", "S"), None)), (9, 1, (("K", "H"), ("K", "C"), None, None, None)), (10, 0, (("A", "H"), None, None, None, None)), ) class PokerTableView: def __init__( self, context, variant_key: str, pk_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 = PK_VARIANTS[variant_key] self.on_back_to_menu = on_back_to_menu self.engine = PokerEngine(sb=self.cfg["sb"], bb=self.cfg["bb"]) self.bot_ai = PokerBotAI() self.round_start_time: float = time.time() self._last_popup_payload: dict | None = None self._result_dialog: PokerResultDialog | 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.pk_account = Database.get_poker_account(pk_account_id) self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0)) level_chips = self._get_current_level_chips() bot_bankroll = max(PK_STARTING_GOLD, level_chips[-1] * 6) self.engine.seats = [ PokerSeat(seat_id=0, name=self.ctx.profile["name"], is_human=True, stack=self.pk_account["gold"]) ] for idx, (lvl, b_name) in enumerate(bot_configs, start=1): self.engine.seats.append( PokerSeat(seat_id=idx, name=b_name, is_human=False, ai_level=lvl, stack=bot_bankroll) ) self._build_ui() self._start_new_hand() @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 bei aktivem Devil's Deal!) # --------------------------------------------------------- def _persist_state(self): if not self.devils_locked: return state_obj = { "pk_account_id": self.pk_account["id"], "devils_locked": self.devils_locked, "elapsed_sec": max(0.0, time.time() - self.round_start_time), "last_popup_payload": self._last_popup_payload, "engine": self.engine.to_dict(), } 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.pk_account = Database.get_poker_account(data["pk_account_id"]) self.devils_locked = bool(data.get("devils_locked", False) or self.pk_account.get("devils_deal_active", 0)) self.round_start_time = time.time() - float(data.get("elapsed_sec", 0.0)) self._last_popup_payload = data.get("last_popup_payload") self.engine.load_from_dict(data["engine"]) except Exception: self._clear_persisted_state() dev_acc = Database.get_active_devils_pk_account(self.ctx.profile["id"]) accounts = Database.get_poker_accounts(self.ctx.profile["id"]) self.pk_account = dev_acc or accounts[0] self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0)) self.engine.seats = [ PokerSeat(seat_id=0, name=self.ctx.profile["name"], is_human=True, stack=self.pk_account["gold"]), PokerSeat(seat_id=1, name=t("bot_default_name", 1), is_human=False, ai_level=2, stack=PK_STARTING_GOLD), ] self._build_ui() self._start_new_hand() return self._build_ui() if self.engine.street == "SHOWDOWN" and self._last_popup_payload: self._render_table() self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload)) else: self._render_table() self._process_current_turn() def _get_current_level_chips(self) -> tuple[int, int, int, int]: pk_lvl = self.ctx.game_progress["level"] return Progression.get_level_bet_chips(pk_lvl, bet_scale=self.cfg.get("bet_scale", 1)) def _cleanup_and_go(self, nav_callable): if self.devils_locked: return InfoBadge.close_global_tip() 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): InfoBadge.close_global_tip() self._persist_state() self._build_ui() if self.engine.street == "SHOWDOWN" and self._last_popup_payload: self._render_table() self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload)) else: self._render_table() if self.engine.turn_pos == 0 and self.engine.human_seat.can_act: self._show_human_controls() # --------------------------------------------------------- # UI AUFBAU MIT STATISCHER BEISPIEL-HILFE & INFO-BADGES # --------------------------------------------------------- def _build_ui(self): if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None InfoBadge.close_global_tip() 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.pk_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)) bottom_area = tk.Frame(self.table_frame, bg=TABLE_BG, height=244) bottom_area.pack(fill="x", side="bottom", pady=(6, 0)) bottom_area.pack_propagate(False) bottom_area.columnconfigure(0, weight=34, uniform="bcols") bottom_area.columnconfigure(1, weight=39, uniform="bcols") bottom_area.columnconfigure(2, weight=27, uniform="bcols") bottom_area.rowconfigure(0, weight=1) self.help_panel = tk.Frame( bottom_area, bg=PANEL_BG, padx=8, pady=5, highlightthickness=1, highlightbackground=BORDER_COLOR ) self.help_panel.grid(row=0, column=0, sticky="nsew", padx=(0, 6)) self._populate_static_hand_examples() 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)) 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) 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.5, rely=0.52, anchor="center") tk.Label( self.board_box, text=t("pk_board_title"), font=("Georgia", 9, "bold"), fg=MUTED_FG, bg=felt_bg ).pack(pady=(0, 3)) self.board_cards_frame = tk.Frame(self.board_box, bg=felt_bg, height=PK_OVAL_BOARD_CARD[1] + 2) self.board_cards_frame.pack() self._bot_seat_frames: list[tk.Frame] = [] self._refresh_header() # --------------------------------------------------------- # STATISCHE POKER-HÄNDE-TAFEL MIT MINI-BEISPIELKARTEN & ⓘ # --------------------------------------------------------- @staticmethod def _draw_mini_example_strip(parent, cards_spec: tuple) -> tk.Canvas: cw, ch, gap = 21, 23, 2 total_w = 5 * cw + 4 * gap cv = tk.Canvas(parent, width=total_w, height=ch, bg=PANEL_BG, highlightthickness=0) for i, spec in enumerate(cards_spec): x0 = i * (cw + gap) if spec is None: cv.create_rectangle( x0, 1, x0 + cw - 1, ch - 1, fill="#3a1722", outline="#5c2838", width=1 ) else: rank, suit = spec is_red = suit in RED_SUITS fg_col = "#d93848" if is_red else "#1c1824" sym = SUIT_SYMBOLS.get(suit, suit) cv.create_rectangle( x0, 1, x0 + cw - 1, ch - 1, fill="#ede8f5", outline="#8e82a6", width=1 ) cv.create_text( x0 + cw // 2, 7, text=rank, font=("Helvetica", 6, "bold"), fill=fg_col ) cv.create_text( x0 + cw // 2, 16, text=sym, font=("Helvetica", 7, "bold"), fill=fg_col ) return cv def _populate_static_hand_examples(self): for w in self.help_panel.winfo_children(): w.destroy() hdr_row = tk.Frame(self.help_panel, bg=PANEL_BG) hdr_row.pack(fill="x", pady=(0, 2)) tk.Label( hdr_row, text=t("pk_help_header"), font=("Georgia", 9, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG ).pack(side="left") InfoBadge( hdr_row, text_provider=lambda: t("pk_help_general_info"), bg=PANEL_BG, font_size=9, ).pack(side="right") tk.Frame(self.help_panel, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(0, 3)) cols_wrap = tk.Frame(self.help_panel, bg=PANEL_BG) cols_wrap.pack(fill="both", expand=True) cols_wrap.columnconfigure(0, weight=1, uniform="hcol") cols_wrap.columnconfigure(1, weight=0) cols_wrap.columnconfigure(2, weight=1, uniform="hcol") left_f = tk.Frame(cols_wrap, bg=PANEL_BG) left_f.grid(row=0, column=0, sticky="nsew", padx=(0, 4)) tk.Frame(cols_wrap, bg=SUBTLE_BORDER, width=1).grid(row=0, column=1, sticky="ns", pady=2) right_f = tk.Frame(cols_wrap, bg=PANEL_BG) right_f.grid(row=0, column=2, sticky="nsew", padx=(4, 0)) for rank_no, cat_id, cards_spec in HAND_REFERENCE_EXAMPLES: target_col = left_f if rank_no <= 5 else right_f cell = tk.Frame(target_col, bg=PANEL_BG) cell.pack(fill="x", pady=1) strip = self._draw_mini_example_strip(cell, cards_spec) strip.pack(anchor="w") lbl_row = tk.Frame(cell, bg=PANEL_BG) lbl_row.pack(fill="x") raw_name = t(f"pk_hand_{cat_id}").replace("★ ", "").replace(" ★", "") short_name = raw_name.split(" (")[0] tk.Label( lbl_row, text=f"{rank_no}. {short_name}", font=("Helvetica", 7, "bold"), fg=ACCENT_GOLD if rank_no == 1 else FG_COLOR, bg=PANEL_BG, anchor="w", ).pack(side="left") InfoBadge( lbl_row, text_provider=lambda cid=cat_id: t(f"pk_help_hand_{cid}"), bg=PANEL_BG, font_size=8, ).pack(side="left", padx=(2, 0)) # --------------------------------------------------------- # TISCHBILD SKALIERUNG & 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.pk_account = Database.get_poker_account(self.pk_account["id"]) prof = self.ctx.profile prog = self.ctx.refresh_game_progress() self.topbar.extra_label.configure(text=t("pk_header_gold", self.pk_account["account_name"], self.pk_account["gold"])) self.topbar.level_label.configure( text=t("level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]) ) street_txt = t(f"pk_street_{self.engine.street}") self.pot_lbl.configure(text=t("pk_pot_banner", self.engine.total_pot, street_txt, self.engine.current_bet)) # --------------------------------------------------------- # HAND STARTEN (Direkter Grundeinsatz / Ante wie bei Blackjack!) # --------------------------------------------------------- def _start_new_hand(self): if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None InfoBadge.close_global_tip() self.pk_account = Database.get_poker_account(self.pk_account["id"]) self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0)) gold = self.pk_account["gold"] min_req = self.cfg["min_entry"] eff_min = min(min_req, 10) if self.devils_locked else min_req if gold < eff_min: Database.set_pk_devils_deal_active(self.pk_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.pk_account["account_name"], min_req, gold, cur_cost, XP_TO_GOLD_AMOUNT ) self._cleanup_and_go(lambda: self.on_back_to_menu(self.pk_account["id"], msg)) return self._last_popup_payload = None self.round_start_time = time.time() self.ctx.sounds.play("deal") self.engine.human_seat.stack = gold level_chips = self._get_current_level_chips() fallback_stack = max(PK_STARTING_GOLD, level_chips[-1] * 5) for s in self.engine.seats[1:]: self.bot_ai.ensure_bot_stack(s, min_req, fallback_stack=fallback_stack) human_ante, ante_events = self.engine.start_hand() if human_ante > 0: self.pk_account = Database.update_poker_gold(self.pk_account["id"], -human_ante) ante_lbl = "Grundeinsatz" if get_lang() == "DE" else "Entry Ante" for s_idx, (_b_role, b_amt) in ante_events.items(): if s_idx > 0: self.engine.seats[s_idx].status_text = f"{ante_lbl} ({b_amt}g)" self._persist_state() self._build_ui() self._render_table() self._process_current_turn() # --------------------------------------------------------- # RENDERING TISCH # --------------------------------------------------------- def _role_badge(self, seat_idx: int) -> str: badges = [] if seat_idx == self.engine.dealer_pos: badges.append(t("pk_role_dealer")) if seat_idx == self.engine.sb_pos: badges.append(t("pk_role_sb")) if seat_idx == self.engine.bb_pos: badges.append(t("pk_role_bb")) return "".join(badges) def _render_table(self): self._photo_refs.clear() for old_f in self._bot_seat_frames: if old_f.winfo_exists(): old_f.destroy() self._bot_seat_frames.clear() bot_seats = self.engine.seats[1:] slot_indices = SEAT_LAYOUT_BY_COUNT.get(len(bot_seats), (0, 1, 2, 3, 4)) for bot_i, seat in enumerate(bot_seats): coord_idx = slot_indices[bot_i] rx, ry = OVAL_BOT_COORDS[coord_idx] is_turn = (self.engine.street != "SHOWDOWN" and self.engine.turn_pos == seat.seat_id) if is_turn: b_col, thick = ACCENT_GOLD, 2 elif seat.folded: b_col, thick = ERROR_FG, 1 elif seat.all_in: b_col, thick = ACCENT_GOTH, 2 else: b_col, thick = BORDER_COLOR, 1 box = tk.Frame( self.arena_canvas, bg="#191521", padx=10, pady=5, width=188, highlightthickness=thick, highlightbackground=b_col ) box.place(relx=rx, rely=ry, anchor="center") self._bot_seat_frames.append(box) base_name = t("bj_bot_rebuy", seat.name) if seat.rebought else seat.name title_txt = f"{base_name}{self._role_badge(seat.seat_id)}" tk.Label( box, text=title_txt, font=("Georgia", 9, "bold"), fg=MUTED_FG if seat.folded else ACCENT_GOTH, bg="#191521" ).pack() tk.Label( box, text=t("pk_bot_stack_lbl", seat.stack, seat.street_bet), font=("Helvetica", 8, "bold"), fg=ACCENT_GOLD, bg="#191521" ).pack(pady=(1, 2)) st_txt = seat.status_text or "—" st_col = ERROR_FG if seat.folded else (ACCENT_GOLD if is_turn else FG_COLOR) tk.Label(box, text=st_txt, font=("Helvetica", 8, "bold"), fg=st_col, bg="#191521").pack() # 2. Gemeinschaftskarten (Board) felt_bg = "#1b1626" for w in self.board_cards_frame.winfo_children(): w.destroy() for slot_i in range(5): if slot_i < len(self.engine.board): c = self.engine.board[slot_i] photo = self.ctx.assets.get_card_photo(c.image_filename, size=PK_OVAL_BOARD_CARD) if photo: self._photo_refs.append(photo) tk.Label(self.board_cards_frame, image=photo, bg=felt_bg, bd=0).pack(side="left", padx=5) else: empty_slot = tk.Frame( self.board_cards_frame, width=PK_OVAL_BOARD_CARD[0], height=PK_OVAL_BOARD_CARD[1], bg="#221c2e", highlightthickness=1, highlightbackground=SUBTLE_BORDER ) empty_slot.pack(side="left", padx=5) # 3. Eigene Karten + neutrale Einsatz-Info for w in self.player_sec.winfo_children(): w.destroy() human = self.engine.human_seat h_cards_f = tk.Frame(self.player_sec, bg=PANEL_BG) h_cards_f.pack(expand=True, pady=(2, 2)) for card in human.hole_cards: photo = self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE) if photo: self._photo_refs.append(photo) tk.Label(h_cards_f, image=photo, bg=PANEL_BG, bd=0).pack(side="left", padx=6) state_tag = t("pk_state_folded") if human.folded else (t("pk_state_allin") if human.all_in else "") role_str = self._role_badge(0) or t("pk_role_player") tk.Label( self.player_sec, text=t("pk_player_bet_only", role_str, human.street_bet, human.total_committed, state_tag), font=("Georgia", 10, "bold"), fg=ERROR_FG if human.folded else FG_COLOR, bg=PANEL_BG, wraplength=410, justify="center", ).pack(side="bottom", pady=(2, 2)) self._refresh_header() # --------------------------------------------------------- # ZUG-SCHLEIFE & STRASSEN-WECHSEL # --------------------------------------------------------- def _process_current_turn(self): if not self.table_frame.winfo_exists(): return if self.engine.only_one_left(): self._finalize_hand() return if self.engine.is_betting_round_complete(): self._advance_street_or_showdown() return if self.engine.turn_pos < 0 or not self.engine.seats[self.engine.turn_pos].can_act: self.engine.advance_turn_pointer() if self.engine.turn_pos < 0: self._advance_street_or_showdown() return if self.engine.turn_pos == 0: self._render_table() self._show_human_controls() else: self._render_waiting_controls() bot = self.engine.seats[self.engine.turn_pos] self.status_lbl.configure(text=t("pk_bot_turn_status", bot.name)) self._render_table() self._turn_job = self.ctx.root.after(PK_BOT_TURN_DELAY_MS, lambda b=bot: self._execute_bot_turn(b)) def _advance_street_or_showdown(self): self._render_waiting_controls() if self.engine.street == "RIVER": self._finalize_hand() return self.ctx.sounds.play("click") new_street = self.engine.advance_to_next_street() self._persist_state() self._render_table() if new_street == "SHOWDOWN": self._finalize_hand() return if self.engine.should_auto_runout_board(): self.status_lbl.configure(text=t("pk_showdown_running")) self._turn_job = self.ctx.root.after(PK_STREET_DELAY_MS, self._advance_street_or_showdown) else: self._process_current_turn() # --------------------------------------------------------- # RECHTE SPALTE: VERTIKALE BUTTONS + ⓘ INFO-SYMBOLE (U+24D8) # --------------------------------------------------------- def _add_action_row( self, parent: tk.Frame, text: str, pil_norm, pil_hov, command, tip_key: str, sound_mgr=None, enabled: bool = True, btn_w: int = 176, btn_h: int = 29, pady: tuple[int, int] = (1, 2), ): row = tk.Frame(parent, bg=PANEL_BG) row.pack(pady=pady) ImageButton( row, text, pil_norm, pil_hov, command, sound_mgr=sound_mgr, width=btn_w, height=btn_h, font=("Helvetica", 9, "bold"), enabled=enabled, ).pack(side="left") InfoBadge( row, text_provider=lambda k=tip_key: t(k), bg=PANEL_BG, font_size=9, ).pack(side="left", padx=(5, 0)) def _render_waiting_controls(self): for w in self.controls_frame.winfo_children(): w.destroy() col = tk.Frame(self.controls_frame, bg=PANEL_BG) col.pack(expand=True) self._add_action_row( col, t("pk_btn_check"), self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, None, "pk_tip_check", enabled=False, pady=(3, 3) ) self._add_action_row( col, t("pk_btn_allin", 0), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, None, "pk_tip_allin", enabled=False, pady=(3, 3) ) self._add_action_row( col, t("pk_btn_fold"), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, None, "pk_tip_fold", enabled=False, pady=(3, 3) ) def _show_human_controls(self): for w in self.controls_frame.winfo_children(): w.destroy() human = self.engine.human_seat to_call = max(0, self.engine.current_bet - human.street_bet) street_txt = t(f"pk_street_{self.engine.street}") dyn_chips = self._get_current_level_chips() if to_call > 0: self.status_lbl.configure(text=t("pk_turn_prompt_call", street_txt, min(human.stack, to_call))) else: self.status_lbl.configure(text=t("pk_turn_prompt_check", street_txt)) btn_col = tk.Frame(self.controls_frame, bg=PANEL_BG) btn_col.pack(expand=True) # 1. Check (Hold) oder Mitgehen (Call) + ⓘ if to_call == 0: self._add_action_row( btn_col, t("pk_btn_check"), self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, lambda: self._on_human_action("CHECK", 0), "pk_tip_check", sound_mgr=None, btn_h=29, pady=(0, 2) ) elif human.stack > to_call: self._add_action_row( btn_col, t("pk_btn_call", to_call), self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, lambda: self._on_human_action("CALL", 0), "pk_tip_call", sound_mgr=self.ctx.sounds, btn_h=29, pady=(0, 2) ) # 2. Erhöhen (Raise) Header + ⓘ & kompakter 2x2 Chip-Block avail_after_call = human.stack - to_call min_r = self.engine.min_raise_delta offered = sorted({max(min_r, c) for c in dyn_chips if max(min_r, c) < avail_after_call})[:4] if avail_after_call > min_r and offered: r_hdr = tk.Frame(btn_col, bg=PANEL_BG) r_hdr.pack(pady=(1, 1)) tk.Label( r_hdr, text=t("pk_raise_lbl"), font=("Helvetica", 8, "bold"), fg=MUTED_FG, bg=PANEL_BG ).pack(side="left") InfoBadge( r_hdr, text_provider=lambda: t("pk_tip_raise"), bg=PANEL_BG, font_size=9 ).pack(side="left", padx=(4, 0)) r_grid = tk.Frame(btn_col, bg=PANEL_BG) r_grid.pack(pady=(0, 2)) for idx, r_delta in enumerate(offered): ImageButton( r_grid, f"+{r_delta}", self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, lambda d=r_delta: self._on_human_action("RAISE", d), sound_mgr=self.ctx.sounds, width=85, height=25, font=("Helvetica", 8, "bold") ).grid(row=idx // 2, column=idx % 2, padx=2, pady=1) # 3. ALL-IN + ⓘ if human.stack > 0: self._add_action_row( btn_col, t("pk_btn_allin", human.stack), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, lambda: self._on_human_action("ALLIN", 0), "pk_tip_allin", sound_mgr=self.ctx.sounds, btn_h=28, pady=(1, 2) ) # 4. Passen (Fold) + ⓘ self._add_action_row( btn_col, t("pk_btn_fold"), self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, lambda: self._on_human_action("FOLD", 0), "pk_tip_fold", sound_mgr=self.ctx.sounds, btn_h=28, pady=(0, 0) ) def _on_human_action(self, action: str, raise_delta: int): InfoBadge.close_global_tip() if action == "CHECK": self.ctx.sounds.play("stand") paid = self.engine.apply_action(0, action, raise_delta) if paid > 0: self.pk_account = Database.update_poker_gold(self.pk_account["id"], -paid) self.engine.advance_turn_pointer() self._persist_state() self._render_table() self._process_current_turn() # --------------------------------------------------------- # BOT-ZUG AUSFÜHREN # --------------------------------------------------------- def _execute_bot_turn(self, bot: PokerSeat): if not self.table_frame.winfo_exists(): return active_opps = sum(1 for s in self.engine.seats if s.is_in_hand and s.seat_id != bot.seat_id) dyn_chips = self._get_current_level_chips() act, r_delta = self.bot_ai.decide_action( bot=bot, board=self.engine.board, current_bet=self.engine.current_bet, pot=self.engine.total_pot, min_raise_delta=self.engine.min_raise_delta, chips=dyn_chips, active_opponents=active_opps, ) paid = self.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": self.ctx.sounds.play("click") bot.status_text = t("pk_bot_act_allin", bot.total_committed) elif act == "RAISE": self.ctx.sounds.play("click") bot.status_text = t("pk_bot_act_raise", paid) else: self.ctx.sounds.play("click") bot.status_text = t("pk_bot_act_call", paid) self.engine.advance_turn_pointer() self._persist_state() self._render_table() self._process_current_turn() # --------------------------------------------------------- # SHOWDOWN, KARTEN-AUFDECKUNG IM POPUP & XP # --------------------------------------------------------- def _collect_all_seats_reveal(self, winner_names: list[str]) -> list[dict]: win_set = set(winner_names) entries = [] for s in self.engine.seats: if not s.hole_cards: continue cat_id, _ = PokerEvaluator.evaluate_best(s.hole_cards + self.engine.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 def _finalize_hand(self): InfoBadge.close_global_tip() self._render_waiting_controls() res = self.engine.resolve_hand() if res["human_payout"] > 0: self.pk_account = Database.update_poker_gold(self.pk_account["id"], res["human_payout"]) duration = max(0.5, time.time() - self.round_start_time) prog_before = self.ctx.refresh_game_progress() opp_levels = [s.ai_level for s in self.engine.seats[1:]] win_cat = res["winning_hand_cat"] or 0 if res["human_won"]: out_type = "WIN_777" if win_cat >= 8 else ("WIN_BJ" if win_cat >= 6 else "WIN") won_stat = True elif res["human_net"] == 0 and res["human_payout"] > 0: out_type = "TIE" won_stat = None else: out_type = "LOSE" won_stat = False xp_gained = Progression.calculate_match_xp( player_level=prog_before["level"], opponent_levels=opp_levels, outcome_type=out_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") leveled_to = prog_after["level"] if prog_after["level"] > prog_before["level"] else None else: old_lvl, new_lvl = self.ctx.record_result( self.variant_key, won=won_stat, duration_sec=duration, points_gained=xp_gained, pk_account_id=self.pk_account["id"] ) leveled_to = new_lvl if new_lvl > old_lvl else None if self.devils_locked: fresh_acc = Database.get_poker_account(self.pk_account["id"]) if not (out_type == "TIE" and fresh_acc["gold"] == 10): Database.set_pk_devils_deal_active(self.pk_account["id"], False) self.devils_locked = False self._clear_persisted_state() else: self._clear_persisted_state() payload = { "by_fold": res["by_fold"], "winner_names": res["winner_names"], "winning_hand_cat": res["winning_hand_cat"], "player_won": 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 self.engine.board], "seats_reveal": self._collect_all_seats_reveal(res["winner_names"]), } self._last_popup_payload = payload if self.devils_locked: self._persist_state() else: self._build_ui() self.status_lbl.configure(text="") self._render_table() self._open_result_popup(self._build_localized_popup_data(payload)) def _build_localized_popup_data(self, payload: dict) -> dict: if payload["by_fold"]: hand_desc = t("pk_popup_fold_win") else: cat = payload["winning_hand_cat"] or 0 hand_desc = t(f"pk_hand_{cat}") if payload["player_won"]: 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_name, b_gain) for b_name, b_gain in payload["bot_gains"] if b_gain > 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_combo = t(f"pk_hand_{s_rev['cat_id']}").replace("★ ", "").replace(" ★", "") short_combo = raw_combo.split(" (")[0] if len(raw_combo) > 20 else raw_combo if s_rev["folded"]: combo_txt = f"{t('pk_bot_act_fold')} ({short_combo})" else: combo_txt = short_combo seat_showdown.append({ "name": s_rev["name"], "cards": s_rev["cards"], "folded": s_rev["folded"], "is_winner": s_rev["is_winner"], "combo_text": combo_txt, }) cur_gold = Database.get_poker_account(self.pk_account["id"])["gold"] can_cont = cur_gold >= self.cfg["min_entry"] 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": can_cont, "can_leave_menu": not self.devils_locked, } def _open_result_popup(self, popup_data: dict): self._result_dialog = PokerResultDialog( parent=self.table_frame, assets=self.ctx.assets, sounds=self.ctx.sounds, result_data=popup_data, on_next_round=self._start_new_hand, on_back_to_menu=lambda: self._cleanup_and_go(lambda: self.on_back_to_menu(self.pk_account["id"])), )