the_goth_cardgame_collection/games/poker/views/poker_table_view.py

1273 lines
46 KiB
Python

# -*- coding: utf-8 -*-
# games/poker/views/poker_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.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_hands_overlay import PokerHandsOverlay
from games.poker.views.poker_result_dialog import PokerResultDialog
from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar
from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer
from models.database import Database
from models.progression import Progression
from resources.code_res.game_constants import (
ACCENT_GOLD,
ACCENT_GOTH,
BORDER_COLOR,
ERROR_FG,
FG_COLOR,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
MUTED_FG,
PK_BOT_TURN_DELAY_MS,
PK_STARTING_GOLD,
PK_STREET_DELAY_MS,
PK_TABLE_IMAGE,
PK_VARIANTS,
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 = "poker"
IMAGES_DIR = Path(__file__).resolve().parents[3] / "resources" / "images"
PK_OVAL_BOARD_CARD = (78, 114)
SEAT_LAYOUT_BY_COUNT = {
1: (2,),
2: (1, 3),
3: (1, 2, 3),
4: (0, 1, 3, 4),
5: (0, 1, 2, 3, 4),
}
class 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._hands_overlay: PokerHandsOverlay | None = None
self._card_ref_btn: ImageButton | None = None
self._photo_refs: list = []
self._turn_job: str | None = None
self._resize_job: str | None = None
self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res)
self._raw_table_pil: Image.Image | None = self._load_raw_table_image()
self._raw_box_bg_pil: Image.Image | None = self._load_raw_box_bg_image()
self._scaled_table_photo: ImageTk.PhotoImage | None = None
self._cached_table_dims: tuple[int, int] = (0, 0)
self._box_bg_cache: dict[tuple[int, int], ImageTk.PhotoImage] = {}
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("RGBA")
except Exception:
return None
return None
@staticmethod
def _load_raw_box_bg_image() -> Image.Image | None:
for fname in ("box_background.png", "box_background.jpg"):
p = IMAGES_DIR / fname
if p.is_file():
try:
return Image.open(p).convert("RGBA")
except Exception:
pass
return None
def _canvas_alive(self) -> bool:
try:
return hasattr(self, "arena_canvas") and bool(self.arena_canvas.winfo_exists())
except Exception:
return False
def _cancel_jobs(self):
for job in (self._turn_job, self._resize_job):
if job is not None:
try:
self.ctx.root.after_cancel(job)
except Exception:
pass
self._turn_job = None
self._resize_job = None
def _close_hands_overlay(self):
if self._hands_overlay is not None:
try:
if self._hands_overlay.winfo_exists():
self._hands_overlay.destroy()
except Exception:
pass
self._hands_overlay = None
def _toggle_hands_overlay(self):
if self._hands_overlay is not None and self._hands_overlay.winfo_exists():
self._close_hands_overlay()
return
if self._canvas_alive():
self._hands_overlay = PokerHandsOverlay(
self.arena_canvas,
self.ctx,
on_close=self._close_hands_overlay,
)
def _get_box_bg_photo(self, w: int, h: int) -> ImageTk.PhotoImage | None:
if self._raw_box_bg_pil is None or w < 16 or h < 16:
return None
key = (w, h)
cached = self._box_bg_cache.get(key)
if cached is not None:
return cached
if len(self._box_bg_cache) > 24:
self._box_bg_cache.clear()
scaled = self._raw_box_bg_pil.resize((w, h), Image.Resampling.LANCZOS)
ph = ImageTk.PhotoImage(scaled)
self._box_bg_cache[key] = ph
return ph
def _draw_framed_panel(
self,
cx: int,
cy: int,
w: int,
h: int,
frame_style: str = "purple",
status_border: str | None = None,
):
x1, y1 = cx - w // 2, cy - h // 2
x2, y2 = x1 + w, y1 + h
inset = 5
inner_w, inner_h = max(16, w - 2 * inset), max(16, h - 2 * inset)
if hasattr(self.ctx.assets, "get_box_bg_photo"):
bg_ph = self.ctx.assets.get_box_bg_photo((inner_w, inner_h))
else:
bg_ph = self._get_box_bg_photo(inner_w, inner_h)
if bg_ph is not None:
self._photo_refs.append(bg_ph)
self.arena_canvas.create_image(cx, cy, image=bg_ph, anchor="center", tags="fg")
else:
self.arena_canvas.create_rectangle(
x1 + inset, y1 + inset, x2 - inset, y2 - inset,
fill="#110e18", outline="", tags="fg",
)
box_key = "box_gold_double" if frame_style == "gold" else "box_purple"
frame_ph = self.ctx.assets.get_box_photo(box_key, (w, h))
if frame_ph is not None:
self._photo_refs.append(frame_ph)
self.arena_canvas.create_image(cx, cy, image=frame_ph, anchor="center", tags="fg")
else:
fallback_col = ACCENT_GOLD if frame_style == "gold" else BORDER_COLOR
self.arena_canvas.create_rectangle(
x1, y1, x2, y2, fill="", outline=fallback_col, width=2, tags="fg"
)
if status_border:
self.arena_canvas.create_rectangle(
x1 + 3, y1 + 3, x2 - 3, y2 - 3,
fill="", outline=status_border, width=2, tags="fg",
)
def _make_goth_photo(
self,
text: str,
size_px: int,
color: str,
max_width: int | None = None,
) -> ImageTk.PhotoImage | None:
if not text:
return None
try:
kwargs = {"size_px": size_px, "color": color}
if max_width is not None:
kwargs["max_width"] = max_width
ph = self.ctx.assets.get_goth_text_photo(text, **kwargs)
if ph is not None:
self._photo_refs.append(ph)
return ph
except TypeError:
try:
ph = self.ctx.assets.get_goth_text_photo(text, size_px=size_px, color=color)
if ph is not None:
self._photo_refs.append(ph)
return ph
except Exception:
return None
except Exception:
return None
def _place_goth_photo_or_fallback(
self,
cx: int,
cy: int,
ph: ImageTk.PhotoImage | None,
fallback_text: str,
size_px: int,
color: str,
anchor: str = "center",
):
if ph is not None:
self.arena_canvas.create_image(cx, cy, image=ph, anchor=anchor, tags="fg")
elif fallback_text:
self.arena_canvas.create_text(
cx,
cy,
text=fallback_text,
font=("Georgia", max(9, size_px - 3), "bold"),
fill=color,
anchor=anchor,
tags="fg",
)
# ---------------------------------------------------------
# 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
ImageButton.close_active_hover_tip()
self._close_hands_overlay()
self._cancel_jobs()
if self._result_dialog:
self._result_dialog.close_dialog()
self._result_dialog = None
self._clear_persisted_state()
nav_callable()
def _on_language_switched(self):
was_help_open = (
self._hands_overlay is not None and self._hands_overlay.winfo_exists()
)
ImageButton.close_active_hover_tip()
self._close_hands_overlay()
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()
else:
self._render_waiting_controls()
if was_help_open:
self._toggle_hands_overlay()
# ---------------------------------------------------------
# UI AUFBAU (Vollbild-Canvas + Universal-Topbar + Bottom-Bar)
# ---------------------------------------------------------
def _build_ui(self):
if self._result_dialog:
self._result_dialog.close_dialog()
self._result_dialog = None
self._close_hands_overlay()
self._cached_table_dims = (0, 0)
self._scaled_table_photo = None
self.ctx.root.clear_window(apply_global_bg=True)
self.ctx.refresh_game_progress()
self.topbar = self.ctx.build_game_topbar(
self.ctx.root,
stats_endpoint="poker",
stats_enabled=not self.devils_locked,
on_lang_refresh=self._on_language_switched,
locked_exit=self.devils_locked,
)
self.hud_var = tk.StringVar(value="")
self.status_var = tk.StringVar(value="")
self.bottom_bar = SolitaireBottomBar(
self.ctx.root, self.ctx, self.hud_var, self.status_var
)
self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 8))
self.arena_canvas = tk.Canvas(
self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0
)
self.arena_canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2))
self.arena_canvas.bind("<Configure>", self._on_arena_configure)
self._card_ref_btn = ImageButton(
self.arena_canvas,
t("pk_btn_hands_help"),
self.ctx.assets.raw_btn_default,
self.ctx.assets.raw_btn_purple,
self._toggle_hands_overlay,
sound_mgr=self.ctx.sounds,
width=136,
height=34,
style="amethyst",
hover_text=lambda: t("pk_help_general_info"),
)
self._refresh_header()
def _set_bottom_buttons(
self,
primary_buttons: list[ImageButton],
overflow_buttons: list[ImageButton] | None = None,
):
ImageButton.close_active_hover_tip()
if hasattr(self, "bottom_bar") and self.bottom_bar.winfo_exists():
self.bottom_bar.set_buttons(primary_buttons, overflow_buttons=overflow_buttons)
def _on_arena_configure(self, _event=None):
if not self._canvas_alive():
return
if self._resize_job is not None:
try:
self.ctx.root.after_cancel(self._resize_job)
except Exception:
pass
try:
self._resize_job = self.ctx.root.after(35, self._render_table)
except Exception:
self._resize_job = None
def _get_stretched_table_photo(self, exact_w: int, exact_h: int) -> ImageTk.PhotoImage | None:
if self._raw_table_pil is None or exact_w < 160 or exact_h < 120:
return None
if self._scaled_table_photo is None or self._cached_table_dims != (exact_w, exact_h):
stretched = self._raw_table_pil.resize((exact_w, exact_h), Image.Resampling.LANCZOS)
self._scaled_table_photo = ImageTk.PhotoImage(stretched)
self._cached_table_dims = (exact_w, exact_h)
return self._scaled_table_photo
def _refresh_header(self):
self.pk_account = Database.get_poker_account(self.pk_account["id"])
self.topbar.update_level_xp_text()
gold_str = t("pk_header_gold", self.pk_account["account_name"], self.pk_account["gold"])
street_txt = t(f"pk_street_{self.engine.street}")
hud_segments = [
gold_str,
f"~Pot: {self.engine.total_pot}g",
f"~{street_txt}",
]
if self.devils_locked:
hud_segments.append("~Devil's Gambit")
hud_txt = "|".join(hud_segments)
if hasattr(self, "hud_var") and self.hud_var.get() != hud_txt:
self.hud_var.set(hud_txt)
# ---------------------------------------------------------
# HAND STARTEN
# ---------------------------------------------------------
def _start_new_hand(self):
if self._result_dialog:
self._result_dialog.close_dialog()
self._result_dialog = None
ImageButton.close_active_hover_tip()
self._close_hands_overlay()
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)
for s_idx, (_b_role, b_amt) in ante_events.items():
if s_idx > 0:
self.engine.seats[s_idx].status_text = t("pk_ante_status", b_amt)
self._persist_state()
if not self._canvas_alive():
self._build_ui()
else:
self.topbar.set_locked_exit(self.devils_locked)
self._render_table()
self._process_current_turn()
# ---------------------------------------------------------
# VOLL-CANVAS RENDERING (6-MAX BOTS, BOARD & POT INNEN, SPIELER + REFERENZ UNTEN)
# ---------------------------------------------------------
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 _draw_bots_around_table(
self,
cw: int,
ch: int,
pad_x: int,
pad_top: int,
pad_bot: int,
table_rect: tuple[int, int, int, int],
) -> int:
bot_seats = self.engine.seats[1:]
if not bot_seats:
return table_rect[1] + 24
tx1, ty1, tx2, ty2 = table_rect
box_h = 88
base_box_w = 204
top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4)
bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22)
if bot_cy - top_cy < box_h + 16:
mid_y = (top_cy + bot_cy) // 2
top_cy = mid_y - (box_h + 16) // 2
bot_cy = mid_y + (box_h + 16) // 2
top_center_cy = max(pad_top + box_h // 2, ty1 + int(box_h * 0.42))
top_center_bottom = ty1 + 24
slot_indices = SEAT_LAYOUT_BY_COUNT.get(len(bot_seats), (0, 1, 2, 3, 4))
name_sz = max(14, FONT_SIZE_BODY - 1)
sub_sz = max(13, FONT_SIZE_BODY - 2)
for bot_i, seat in enumerate(bot_seats):
coord_idx = slot_indices[bot_i]
is_turn = (self.engine.street != "SHOWDOWN" and self.engine.turn_pos == seat.seat_id)
frame_style = "gold" if is_turn else "purple"
if seat.folded:
status_border = ERROR_FG
elif seat.all_in:
status_border = ACCENT_GOTH
else:
status_border = None
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)}"
title_col = MUTED_FG if seat.folded else (ACCENT_GOLD if is_turn else ACCENT_GOTH)
stack_txt = t("pk_bot_stack_lbl", seat.stack, seat.street_bet)
st_txt = seat.status_text or "—"
st_col = ERROR_FG if seat.folded else (ACCENT_GOLD if is_turn else FG_COLOR)
title_ph = self._make_goth_photo(title_txt, size_px=name_sz, color=title_col, max_width=230)
stack_ph = self._make_goth_photo(stack_txt, size_px=sub_sz, color=ACCENT_GOLD, max_width=230)
st_ph = self._make_goth_photo(st_txt, size_px=sub_sz, color=st_col, max_width=230)
widest_txt = max(
(ph.width() for ph in (title_ph, stack_ph, st_ph) if ph is not None),
default=148,
)
box_w = max(base_box_w, min(274, widest_txt + 52))
if coord_idx == 2:
bx, by = cw // 2, top_center_cy
top_center_bottom = max(top_center_bottom, by + box_h // 2)
elif coord_idx in (0, 1):
bx = max(pad_x + box_w // 2, tx1 + int(box_w * 0.36))
by = bot_cy if coord_idx == 0 else top_cy
else:
bx = min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36))
by = top_cy if coord_idx == 3 else bot_cy
self._draw_framed_panel(
bx, by, box_w, box_h, frame_style=frame_style, status_border=status_border
)
self._place_goth_photo_or_fallback(bx, by - 23, title_ph, title_txt, name_sz, title_col)
self._place_goth_photo_or_fallback(bx, by, stack_ph, stack_txt, sub_sz, ACCENT_GOLD)
self._place_goth_photo_or_fallback(bx, by + 23, st_ph, st_txt, sub_sz, st_col)
return top_center_bottom
def _draw_board_and_pot_inside_table(
self,
table_rect: tuple[int, int, int, int],
top_obstacle_y: int,
player_top_y: int,
):
tx1, ty1, tx2, ty2 = table_rect
t_cx = (tx1 + tx2) // 2
t_h = max(260, ty2 - ty1)
felt_top = max(ty1 + max(32, int(t_h * 0.14)), top_obstacle_y + 12)
felt_bot = min(ty2 - max(24, int(t_h * 0.10)), player_top_y - 10)
avail_h = max(148, felt_bot - felt_top)
base_cw, base_ch = PK_OVAL_BOARD_CARD
max_board_ch = max(84, min(base_ch, avail_h - 58))
scale = max_board_ch / max(1, base_ch)
card_w = max(58, int(round(base_cw * scale)))
card_h = int(round(base_ch * scale))
card_sz = (card_w, card_h)
gap = max(8, int(card_w * 0.13))
total_board_w = 5 * card_w + 4 * gap
start_x = t_cx - total_board_w // 2
board_cy = felt_top + card_h // 2 + max(4, (avail_h - card_h - 52) // 3)
card_top = board_cy - card_h // 2
for slot_i in range(5):
sx = start_x + slot_i * (card_w + gap)
if slot_i < len(self.engine.board):
c = self.engine.board[slot_i]
photo = self.ctx.assets.get_card_photo(c.image_filename, size=card_sz)
if photo:
self._photo_refs.append(photo)
self.arena_canvas.create_image(
sx, card_top, image=photo, anchor="nw", tags="fg"
)
continue
self.arena_canvas.create_rectangle(
sx,
card_top,
sx + card_w,
card_top + card_h,
fill="#161220",
outline=SUBTLE_BORDER,
width=1,
tags="fg",
)
self.arena_canvas.create_text(
sx + card_w // 2,
card_top + card_h // 2,
text="♦",
font=("Georgia", max(12, card_w // 5)),
fill="#2d243b",
tags="fg",
)
pot_raw = t("pk_pot_banner", self.engine.total_pot, "", self.engine.current_bet)
pot_txt = pot_raw.split("|")[0].strip()
pot_cy = min(
felt_bot - 20,
max(board_cy + card_h // 2 + 28, (board_cy + card_h // 2 + felt_bot) // 2),
)
pot_sz = max(15, FONT_SIZE_BODY)
pot_ph = self._make_goth_photo(pot_txt, size_px=pot_sz, color=FONT_COLOR_TITLE_MAIN)
if pot_ph is not None:
bw = max(230, pot_ph.width() + 64)
bh = max(38, pot_ph.height() + 16)
self._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold")
self.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg")
else:
self._draw_framed_panel(t_cx, pot_cy, 240, 38, frame_style="gold")
self._place_goth_photo_or_fallback(
t_cx, pot_cy, None, pot_txt, size_px=pot_sz, color=ACCENT_GOLD
)
def _draw_human_hand_below_table(
self, cw: int, pad_x: int, player_zone_top: int, player_zone_bot: int
):
human = self.engine.human_seat
avail_h = max(140, player_zone_bot - player_zone_top)
zone_cy = (player_zone_top + player_zone_bot) // 2
base_w, base_h = PLAYING_CARD_SIZE
max_card_h = max(88, min(base_h, avail_h - 52))
scale = max_card_h / max(1, base_h)
card_w = max(60, int(round(base_w * scale)))
card_h = int(round(base_h * scale))
card_sz = (card_w, card_h)
p_photos = []
for card in human.hole_cards:
photo = self.ctx.assets.get_card_photo(card.image_filename, size=card_sz)
if photo:
self._photo_refs.append(photo)
p_photos.append(photo)
state_tag = (
t("pk_state_folded")
if human.folded
else (t("pk_state_allin") if human.all_in else "")
)
role_str = self._role_badge(0) or t("pk_role_player")
lbl_txt = t(
"pk_player_bet_only",
role_str,
human.street_bet,
human.total_committed,
state_tag,
)
is_my_turn = (
self.engine.street != "SHOWDOWN"
and self.engine.turn_pos == 0
and human.can_act
)
lbl_col = ERROR_FG if human.folded else FONT_COLOR_TITLE_MAIN
lbl_sz = max(14, FONT_SIZE_BODY - 1)
lbl_ph = self._make_goth_photo(lbl_txt, size_px=lbl_sz, color=lbl_col)
cards_gap = 12
cards_span_w = (
len(p_photos) * card_w + max(0, len(p_photos) - 1) * cards_gap
if p_photos
else card_w * 2
)
txt_w = lbl_ph.width() if lbl_ph is not None else 250
box_w = max(300, min(540, max(cards_span_w + 96, txt_w + 72)))
box_h = min(avail_h, card_h + 52)
box_cx = cw // 2
status_bdr = ERROR_FG if human.folded else (ACCENT_GOTH if human.all_in else None)
self._draw_framed_panel(
box_cx,
zone_cy,
box_w,
box_h,
frame_style="gold" if is_my_turn else "purple",
status_border=status_bdr,
)
if p_photos:
c_start_x = box_cx - cards_span_w // 2
c_top_y = (zone_cy - 11) - card_h // 2
for idx, ph in enumerate(p_photos):
self.arena_canvas.create_image(
c_start_x + idx * (card_w + cards_gap),
c_top_y,
image=ph,
anchor="nw",
tags="fg",
)
self._place_goth_photo_or_fallback(
box_cx, zone_cy + box_h // 2 - 20, lbl_ph, lbl_txt, lbl_sz, lbl_col
)
if self._card_ref_btn is not None and self._card_ref_btn.winfo_exists():
if self._result_dialog is not None:
self._card_ref_btn.place_forget()
else:
ref_bw = self._card_ref_btn.pixel_width
ref_bh = self._card_ref_btn.pixel_height
ref_x = box_cx + box_w // 2 + 16
if ref_x + ref_bw > cw - pad_x - 6:
ref_x = max(pad_x + 6, box_cx - box_w // 2 - ref_bw - 16)
ref_y = zone_cy + box_h // 2 - ref_bh - 6
self._card_ref_btn.place(x=ref_x, y=ref_y, width=ref_bw, height=ref_bh)
tk.Widget.tkraise(self._card_ref_btn)
def _render_table(self):
if not self._canvas_alive():
return
cw = max(760, self.arena_canvas.winfo_width())
ch = max(460, self.arena_canvas.winfo_height())
bg_ids = set(self.arena_canvas.find_withtag("table_bg_slice"))
for item_id in self.arena_canvas.find_all():
if item_id not in bg_ids:
self.arena_canvas.delete(item_id)
self._photo_refs.clear()
self._bg_renderer.draw_on_canvas(self.arena_canvas, cw, ch)
pad_x = max(24, int(cw * 0.022))
pad_top = 6
pad_bot = 6
player_zone_h = max(150, min(174, int(ch * 0.31)))
player_zone_bot = ch - pad_bot
player_zone_top = player_zone_bot - player_zone_h
table_top = pad_top
table_bot = min(ch - pad_bot - 60, player_zone_top + 64)
table_h = max(280, table_bot - table_top)
table_w = max(680, cw - 2 * pad_x - 90)
table_cx = cw // 2
table_cy = table_top + table_h // 2
table_rect = (
table_cx - table_w // 2,
table_top,
table_cx + table_w // 2,
table_top + table_h,
)
tbl_photo = self._get_stretched_table_photo(table_w, table_h)
if tbl_photo is not None:
self.arena_canvas.create_image(
table_cx, table_cy, image=tbl_photo, anchor="center", tags="fg"
)
else:
self.arena_canvas.create_oval(
table_rect[0], table_rect[1], table_rect[2], table_rect[3],
fill="#14111b", outline=BORDER_COLOR, width=3, tags="fg",
)
top_obstacle_y = self._draw_bots_around_table(
cw, ch, pad_x, pad_top, pad_bot, table_rect
)
self._draw_board_and_pot_inside_table(table_rect, top_obstacle_y, player_zone_top)
self._draw_human_hand_below_table(cw, pad_x, player_zone_top, player_zone_bot)
self._refresh_header()
if self._hands_overlay is not None and self._hands_overlay.winfo_exists():
tk.Widget.tkraise(self._hands_overlay)
if self._result_dialog is not None and self._result_dialog.winfo_exists():
tk.Widget.tkraise(self._result_dialog)
# ---------------------------------------------------------
# ZUG-SCHLEIFE & BOTTOM-BAR AKTIONEN MIT HOVER-HILFE
# ---------------------------------------------------------
def _process_current_turn(self):
if not self._canvas_alive():
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._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._turn_job = self.ctx.root.after(
PK_STREET_DELAY_MS, self._advance_street_or_showdown
)
else:
self._process_current_turn()
def _render_waiting_controls(self):
if not hasattr(self, "bottom_bar") or not self.bottom_bar.winfo_exists():
return
self._set_bottom_buttons([])
def _show_human_controls(self):
if not hasattr(self, "bottom_bar") or not self.bottom_bar.winfo_exists():
return
human = self.engine.human_seat
to_call = max(0, self.engine.current_bet - human.street_bet)
dyn_chips = self._get_current_level_chips()
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
primary_btns: list[ImageButton] = []
overflow_btns: list[ImageButton] = []
if to_call == 0:
primary_btns.append(
ImageButton(
self.bottom_bar,
t("pk_btn_check"),
btn_fire,
btn_fire,
lambda: self._on_human_action("CHECK", 0),
sound_mgr=None,
width=138,
height=30,
style="fire",
hover_text=lambda: t("pk_tip_check"),
)
)
elif human.stack > to_call:
primary_btns.append(
ImageButton(
self.bottom_bar,
t("pk_btn_call", to_call),
btn_fire,
btn_fire,
lambda: self._on_human_action("CALL", 0),
sound_mgr=self.ctx.sounds,
width=138,
height=30,
style="fire",
hover_text=lambda: t("pk_tip_call"),
)
)
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]
for r_delta in offered:
primary_btns.append(
ImageButton(
self.bottom_bar,
f"+{r_delta}g",
btn_norm,
btn_purp,
lambda d=r_delta: self._on_human_action("RAISE", d),
sound_mgr=self.ctx.sounds,
width=74,
height=30,
style="amethyst",
hover_text=lambda: t("pk_tip_raise"),
)
)
if human.stack > 0:
allin_style = "fire" if (to_call > 0 and human.stack <= to_call) else "amethyst"
allin_bg = btn_fire if allin_style == "fire" else btn_norm
allin_hov = btn_fire if allin_style == "fire" else btn_purp
overflow_btns.append(
ImageButton(
self.bottom_bar,
t("pk_btn_allin", human.stack),
allin_bg,
allin_hov,
lambda: self._on_human_action("ALLIN", 0),
sound_mgr=self.ctx.sounds,
width=132,
height=30,
style=allin_style,
hover_text=lambda: t("pk_tip_allin"),
)
)
overflow_btns.append(
ImageButton(
self.bottom_bar,
t("pk_btn_fold"),
btn_norm,
btn_purp,
lambda: self._on_human_action("FOLD", 0),
sound_mgr=self.ctx.sounds,
width=122,
height=30,
style="amethyst",
hover_text=lambda: t("pk_tip_fold"),
)
)
self._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns)
def _on_human_action(self, action: str, raise_delta: int):
ImageButton.close_active_hover_tip()
self._close_hands_overlay()
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._canvas_alive():
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):
ImageButton.close_active_hover_tip()
self._close_hands_overlay()
self._set_bottom_buttons([])
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()
elif self._canvas_alive():
self.topbar.set_locked_exit(False)
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._set_bottom_buttons([])
if self._card_ref_btn is not None and self._card_ref_btn.winfo_exists():
self._card_ref_btn.place_forget()
self._result_dialog = PokerResultDialog(
parent=self.arena_canvas,
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"])
),
)