the_goth_cardgame_collection/games/blackjack/views/blackjack_table_view.py

1330 lines
55 KiB
Python
Raw Normal View History

2026-11-14 04:25:51 +00:00
# -*- coding: utf-8 -*-
# games/blackjack/views/blackjack_table_view.py
import json
import time
import tkinter as tk
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, CELL_BG, ERROR_FG,
FG_COLOR, GOLD_MIN_TABLE_ENTRY, MUTED_FG, PANEL_BG,
PLAYING_CARD_SIZE, SUBTLE_BORDER, TABLE_BG, XP_TO_GOLD_AMOUNT
2026-11-14 04:25:51 +00:00
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "blackjack"
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
2026-11-14 04:25:51 +00:00
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.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()
# ---------------------------------------------------------
# AUTO-SAVE & RESUME (nur aktiv während The Devil's Deal!)
2026-11-14 04:25:51 +00:00
# ---------------------------------------------------------
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,
2026-11-14 04:25:51 +00:00
"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))
2026-11-14 04:25:51 +00:00
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)
2026-11-14 04:25:51 +00:00
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()
2026-11-14 04:25:51 +00:00
else:
self._begin_new_table_cycle()
2026-11-14 04:25:51 +00:00
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.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=18, pady=8,
highlightthickness=1, highlightbackground=ERROR_FG if self.devils_locked else BORDER_COLOR
)
self.table_frame.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.94, relheight=0.86)
self.pot_lbl = tk.Label(
self.table_frame, text="", font=("Georgia", 12, "bold"),
fg=ACCENT_GOLD, bg=PANEL_BG, pady=4, highlightthickness=1, highlightbackground=SUBTLE_BORDER
)
self.pot_lbl.pack(fill="x", pady=(0, 4))
dealer_sec = tk.Frame(self.table_frame, bg=TABLE_BG)
dealer_sec.pack(fill="x", pady=(2, 2))
self.dealer_lbl = tk.Label(dealer_sec, text=t("bj_dealer_title"), font=("Georgia", 11, "bold"), fg=MUTED_FG, bg=TABLE_BG)
self.dealer_lbl.pack()
self.dealer_cards_frame = tk.Frame(dealer_sec, bg=TABLE_BG, height=148)
self.dealer_cards_frame.pack(pady=2)
mid_sec = tk.Frame(self.table_frame, bg=TABLE_BG)
mid_sec.pack(fill="x")
self.status_lbl = tk.Label(mid_sec, text="", font=("Georgia", 11, "bold"), fg=ACCENT_GOLD, bg=TABLE_BG)
self.status_lbl.pack(pady=4)
seats_area = tk.Frame(self.table_frame, bg=TABLE_BG)
seats_area.pack(fill="both", expand=True, pady=(2, 4))
if self.bots:
self.bots_row = tk.Frame(seats_area, bg=TABLE_BG)
self.bots_row.pack(side="left", fill="y", padx=(0, 14))
else:
self.bots_row = None
self.player_sec = tk.Frame(seats_area, bg=TABLE_BG)
self.player_sec.pack(side="left", fill="both", expand=True)
self.controls_frame = tk.Frame(
self.table_frame, bg=PANEL_BG, padx=14, pady=10,
highlightthickness=1, highlightbackground=SUBTLE_BORDER
)
self.controls_frame.pack(fill="x", side="bottom")
self._refresh_header()
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
2026-11-14 04:25:51 +00:00
# ---------------------------------------------------------
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
2026-11-14 04:25:51 +00:00
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()
2026-11-14 04:25:51 +00:00
# ---------------------------------------------------------
# RENDERING TISCH & HÄNDE
# ---------------------------------------------------------
@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:
2026-11-14 04:25:51 +00:00
return t("bj_state_locked")
return ""
def _render_bots(self, reveal_opponents: bool):
if not self.bots_row or not self.bots_row.winfo_exists():
return
for w in self.bots_row.winfo_children():
w.destroy()
for idx, bot in enumerate(self.bots):
is_turn = (idx == self.active_bot_idx)
border_col = ACCENT_GOLD if is_turn else (ERROR_FG if (bot.busted or bot.folded) else SUBTLE_BORDER)
box = tk.Frame(
self.bots_row, bg=CELL_BG, padx=8, pady=5,
highlightthickness=2 if is_turn else 1, highlightbackground=border_col
)
box.pack(side="left", padx=4, fill="y")
disp_name = t("bj_bot_rebuy", bot.name) if bot.rebought else bot.name
tk.Label(box, text=disp_name, font=("Georgia", 10, "bold"), fg=ACCENT_GOTH, bg=CELL_BG).pack()
tk.Label(box, text=t("bj_bot_gold_lbl", bot.gold), font=("Helvetica", 9, "bold"), fg=ACCENT_GOLD, bg=CELL_BG).pack()
cards_f = tk.Frame(box, bg=CELL_BG, height=96)
cards_f.pack(pady=3)
show_faces = reveal_opponents or bot.busted
for card in 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)
tk.Label(cards_f, image=photo, bg=CELL_BG, bd=0).pack(side="left", padx=2)
if reveal_opponents and bot.hand:
2026-11-14 04:25:51 +00:00
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)
2026-11-14 04:25:51 +00:00
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", 9, "bold" if bot.busted else "normal"),
fg=ERROR_FG if (bot.busted or bot.folded) else FG_COLOR, bg=CELL_BG
).pack()
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=TABLE_BG, height=150)
cards_f.pack(pady=3)
for card in h.cards:
photo = self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE)
if photo:
self._photo_refs.append(photo)
tk.Label(cards_f, image=photo, bg=TABLE_BG, bd=0).pack(side="left", padx=4)
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", 12, "bold"), fg=lbl_col, bg=TABLE_BG
).pack()
return
split_wrap = tk.Frame(self.player_sec, bg=TABLE_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=10, pady=6,
highlightthickness=2 if is_active else 1, highlightbackground=b_col
)
hbox.pack(side="left", padx=8)
cards_f = tk.Frame(hbox, bg=CELL_BG, height=126)
cards_f.pack(pady=2)
for card in h.cards:
photo = self.ctx.assets.get_card_photo(card.image_filename, size=BJ_SPLIT_CARD_SIZE)
if photo:
self._photo_refs.append(photo)
tk.Label(cards_f, image=photo, bg=CELL_BG, bd=0).pack(side="left", padx=3)
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", 10, "bold"), fg=lbl_col, bg=CELL_BG
).pack(pady=(2, 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 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 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)
tk.Label(self.dealer_cards_frame, image=photo, bg=TABLE_BG, bd=0).pack(side="left", padx=5)
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))
elif self.engine.dealer_hand:
d_val, _ = HandEvaluator.evaluate(self.engine.dealer_hand)
self.dealer_lbl.configure(text=t("bj_dealer_total", d_val))
self._render_player_hands()
self._render_bots(reveal_opponents=reveal_opponents)
self._refresh_header()
# ---------------------------------------------------------
# TISCH-UMLAUF LOGIK (Keine Karte gezogen -> Auto-Showdown!)
2026-11-14 04:25:51 +00:00
# ---------------------------------------------------------
def _begin_new_table_cycle(self):
"""Startet einen neuen Tisch-Umlauf mit cycle_card_drawn = False."""
if not self.engine.any_contender_alive(self.bots):
2026-11-14 04:25:51 +00:00
self._start_showdown_and_dealer()
return
self.engine.cycle_card_drawn = False
self.settle_only_mode = False
2026-11-14 04:25:51 +00:00
self.active_bot_idx = -1
self.active_hand_idx = 0
self._step_next_player_hand()
def _begin_settle_bets_pass(self):
"""
Niemand hat im Umlauf eine Karte gezogen, aber ein letzter Raise ist noch offen:
Jeder mit Rückstand darf nur noch Mitgehen oder Austreten, danach sofort Aufdecken!
"""
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):
"""Wird am Ende jedes Tisch-Umlaufs (Spieler + alle Bots) aufgerufen."""
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:
# Alle offenen Einsätze beglichen -> sofort aufdecken!
self._start_showdown_and_dealer()
return
if not self.engine.cycle_card_drawn:
# KEINER hat in dieser Runde eine Karte gezogen!
if self.engine.has_unsettled_bets(self.bots, wallet):
self._begin_settle_bets_pass()
else:
self._start_showdown_and_dealer()
return
# Mindestens einer hat eine Karte gezogen -> nächster regulärer Umlauf!
self._begin_new_table_cycle()
# ---------------------------------------------------------
# SPIELER-SCHRITTE IM UMLAUF
# ---------------------------------------------------------
2026-11-14 04:25:51 +00:00
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
# Regulärer Zug im Umlauf:
# 1. Falls ein Raise offen ist -> erst Mitgehen? fragen
if to_call > 0:
2026-11-14 04:25:51 +00:00
self.turn_step = STEP_MITGEHEN
self._persist_state()
self._render_table(reveal_opponents=False, reveal_dealer=False)
self._render_current_tree_step()
return
# 2. Kein offener Raise -> direkt fragen: Karte ziehen oder Keine neue Karte?
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
# 3. Hand steht schon bei 21 / Double Down -> darf bei verfügbarem Gold noch erhöhen
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
2026-11-14 04:25:51 +00:00
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 ""
row = tk.Frame(self.controls_frame, bg=PANEL_BG)
row.pack()
# =====================================================
# SCHRITT 1: MITGEHEN? (nur wenn ein Gegner erhöht hat!)
2026-11-14 04:25:51 +00:00
# =====================================================
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(
row, 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=220, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
2026-11-14 04:25:51 +00:00
ImageButton(
row, 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=230, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
2026-11-14 04:25:51 +00:00
return
# =====================================================
# SCHRITT 2: KARTE ZIEHEN ODER KEINE NEUE KARTE?
2026-11-14 04:25:51 +00:00
# =====================================================
if self.turn_step == STEP_ZIEHEN:
self.status_lbl.configure(text=t("bj_tree_step2_draw", hand_tag))
ImageButton(
row, 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=185, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=5)
2026-11-14 04:25:51 +00:00
if self.engine.can_double_down(self.active_hand_idx, wallet):
2026-11-14 04:25:51 +00:00
dd_cost = self.engine.get_double_down_cost(self.active_hand_idx)
ImageButton(
row, 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=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=5)
2026-11-14 04:25:51 +00:00
if self.engine.can_split_hand(self.active_hand_idx, wallet):
sp_cost = self.engine.highest_bet
ImageButton(
row, 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=145, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=5)
2026-11-14 04:25:51 +00:00
ImageButton(
row, 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=180, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=5)
ImageButton(
row, 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=120, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=5)
2026-11-14 04:25:51 +00:00
return
# =====================================================
# SCHRITT 3: ERHÖHEN?
2026-11-14 04:25:51 +00:00
# =====================================================
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(
row, 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=115, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=5)
ImageButton(
row, 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=190, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
# ---------------------------------------------------------
# BUTTON-AKTIONEN SPIELER
2026-11-14 04:25:51 +00:00
# ---------------------------------------------------------
def _advance_to_erhoehen_or_next(self):
2026-11-14 04:25:51 +00:00
self.bj_account = Database.get_blackjack_account(self.bj_account["id"])
wallet = self.bj_account["gold"]
dyn_chips = self._get_current_level_chips()
# Solo ohne Bots und ohne gezogene Karte im Umlauf -> sofort aufdecken ohne unnötige Erhöhungs-Frage!
if not self.bots and not self.engine.cycle_card_drawn:
self._finish_current_hand_turn()
return
if wallet >= dyn_chips[0]:
2026-11-14 04:25:51 +00:00
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):
2026-11-14 04:25:51 +00:00
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)
2026-11-14 04:25:51 +00:00
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:
2026-11-14 04:25:51 +00:00
self.turn_step = STEP_ZIEHEN
self._persist_state()
self._render_current_tree_step()
else:
self._advance_to_erhoehen_or_next()
2026-11-14 04:25:51 +00:00
def _on_fold_hand(self):
2026-11-14 04:25:51 +00:00
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()
2026-11-14 04:25:51 +00:00
def _on_step2_draw_no(self):
"""Keine neue Karte genommen -> cycle_card_drawn bleibt unverändert!"""
self.ctx.sounds.play("stand")
self._advance_to_erhoehen_or_next()
2026-11-14 04:25:51 +00:00
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
2026-11-14 04:25:51 +00:00
# ---------------------------------------------------------
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()
2026-11-14 04:25:51 +00:00
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
2026-11-14 04:25:51 +00:00
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()
2026-11-14 04:25:51 +00:00
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)
# 1. Offene Erhöhung mitgehen oder austreten?
if to_call > 0:
if not self.bot_ai.decide_step1_mitgehen(
bot, self.engine.highest_bet, upcard, self.engine.deck.remaining()
):
2026-11-14 04:25:51 +00:00
bot.folded = True
bot.cards_locked = True
bot.status_text = t("bj_bot_action_fold")
self._finish_bot_step()
return
2026-11-14 04:25:51 +00:00
self.ctx.sounds.play("click")
self.engine.bot_add_gold_to_pot(bot, to_call)
# Im Settle-Modus nach kartenlosem Umlauf nur noch begleichen -> fertig!
if self.settle_only_mode:
bot.status_text = t("bj_bot_action_call", to_call)
self._finish_bot_step()
return
# 2. Karte ziehen oder keine neue Karte?
2026-11-14 04:25:51 +00:00
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()):
2026-11-14 04:25:51 +00:00
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
# 3. Optional erhöhen (nur wenn im aktuellen Umlauf schon eine Karte gezogen wurde oder man Druck macht)
2026-11-14 04:25:51 +00:00
raise_amt = self.bot_ai.decide_step3_erhoehen(
bot, dyn_chips, self.engine.deck.remaining(), upcard
2026-11-14 04:25:51 +00:00
)
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)
2026-11-14 04:25:51 +00:00
else:
bot.status_text = t("bj_bot_action_ready", len(bot.hand))
2026-11-14 04:25:51 +00:00
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]:
"""Serialisiert alle Tischhände JSON-sicher für Popup & Devil's-Deal-Save."""
snapshot: list[dict] = []
# 1. Haus-Dealer
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),
})
# 2. Spieler-Hand / Split-Hände
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),
})
# 3. Alle Bots am Tisch
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),
})
# Gewinner-Markierung anhand derselben Showdown-Regeln wie BlackjackEngine
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
2026-11-14 04:25:51 +00:00
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
)
2026-11-14 04:25:51 +00:00
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",
2026-11-14 04:25:51 +00:00
"player_won": True,
"player_net": net,
"bank_gain": 0,
"bot_gains": [],
"xp_gained": xp,
"leveled_to": leveled_to,
"showdown_snapshot": snap,
2026-11-14 04:25:51 +00:00
}
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,
2026-11-14 04:25:51 +00:00
"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,
2026-11-14 04:25:51 +00:00
}
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)
2026-11-14 04:25:51 +00:00
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,
2026-11-14 04:25:51 +00:00
"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,
2026-11-14 04:25:51 +00:00
}
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
2026-11-14 04:25:51 +00:00
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")
# Lokalisierte Hand-Karten & Begründung aufbauen
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)
2026-11-14 04:25:51 +00:00
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,
2026-11-14 04:25:51 +00:00
"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"]))
# Fall 1: Gleichstand mit dem Haus-Dealer (Push)
if dealer["is_winner"] and len(winners) > 1:
return t("bj_reason_dealer_tie_push", dealer["rank_label"])
# Fall 2: Jemand hat ebenfalls 21 Punkte, verliert aber wegen 2-Karten-Blackjack oder 7-7-7!
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)
# Fall 3: Mehrere Spieler/Bots teilen sich den Sieg
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)
# Fall 4: Haus-Dealer hat sich überkauft
if dealer["busted"] and not dealer["is_winner"]:
return t("bj_reason_dealer_bust", dealer["rank_label"], win_label, winners[0]["rank_label"])
# Fall 5: Regulärer Punktesieg gegen die nächstbeste Hand am Tisch
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)
2026-11-14 04:25:51 +00:00
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"])),
)