the_goth_cardgame_collection/games/blackjack/views/blackjack_table_view.py

1112 lines
47 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_MAX_RAISES_PER_ROUND,
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
)
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"
STEP_FERTIG = "FERTIG"
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_MITGEHEN
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 (speichert auch den exakten Baum-Knoten!)
# ---------------------------------------------------------
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,
"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_MITGEHEN)
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":
if self.active_bot_idx >= 0:
self._render_table(reveal_opponents=False, reveal_dealer=False)
self._step_next_bot()
else:
self._render_table(reveal_opponents=False, reveal_dealer=False)
if 0 <= self.active_hand_idx < len(self.engine.player_hands) and self.engine.player_hand_needs_turn(
self.engine.player_hands[self.active_hand_idx], self.bj_account["gold"]
):
self._render_current_tree_step()
else:
self._begin_next_turn_cycle()
elif self.engine.state == "DEALER_TURN":
self._render_table(reveal_opponents=True, reveal_dealer=True)
self.status_lbl.configure(text=t("bj_dealer_reveals"))
self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step)
elif self.engine.state == "SHOWDOWN" and self._last_popup_payload:
self._render_table(reveal_opponents=True, reveal_dealer=True)
self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload))
else:
self._start_new_round()
def _get_current_level_chips(self) -> tuple[int, int, int, int]:
bj_lvl = self.ctx.game_progress["level"]
return Progression.get_level_bet_chips(bj_lvl, bet_scale=self.cfg.get("bet_scale", 1))
def _cleanup_and_go(self, nav_callable):
if self.devils_locked:
return
if self._turn_job:
try:
self.ctx.root.after_cancel(self._turn_job)
except Exception:
pass
self._turn_job = None
if self._result_dialog:
self._result_dialog.close_dialog()
self._result_dialog = None
self._clear_persisted_state()
nav_callable()
def _on_language_switched(self):
self._persist_state()
self._build_ui()
if self.engine.state == "ACTION_LOOP":
self._render_table(reveal_opponents=False, reveal_dealer=False)
if self.active_bot_idx == -1:
self._render_current_tree_step()
elif self.engine.state == "DEALER_TURN":
self._render_table(reveal_opponents=True, reveal_dealer=True)
self.status_lbl.configure(text=t("bj_dealer_reveals"))
elif self.engine.state == "SHOWDOWN" and self._last_popup_payload:
self._render_table(reveal_opponents=True, reveal_dealer=True)
self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload))
def _build_ui(self):
if self._result_dialog:
self._result_dialog.close_dialog()
self._result_dialog = None
self.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 (10 Gold Grundeinsatz -> Karten verteilen)
# ---------------------------------------------------------
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.turn_step = STEP_MITGEHEN
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_next_turn_cycle()
# ---------------------------------------------------------
# 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.cards_locked:
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 and bot.is_active_in_pot:
b_val, _ = HandEvaluator.evaluate(bot.hand)
info_txt = t("bj_bot_showdown_val", b_val, bot.bet_in_pot)
elif bot.status_text:
info_txt = bot.status_text
elif bot.hand:
info_txt = t("bj_bot_cards_hidden", len(bot.hand), bot.bet_in_pot)
else:
info_txt = ""
tk.Label(
box, text=info_txt, font=("Helvetica", 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()
# ---------------------------------------------------------
# STUFENWEISER ABLAUFBAUM FÜR DEN SPIELER
# ---------------------------------------------------------
def _begin_next_turn_cycle(self):
self.bj_account = Database.get_blackjack_account(self.bj_account["id"])
if self.engine.is_everyone_finished(self.bots, self.bj_account["gold"]):
self._start_showdown_and_dealer()
return
self.active_bot_idx = -1
self.active_hand_idx = 0
self._step_next_player_hand()
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 self.engine.player_hand_needs_turn(h, wallet):
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
# Alle eigenen Hände durch -> sofort der nächste Gegner dran!
self._start_bots_cycle()
def _finish_current_hand_turn(self):
self.active_hand_idx += 1
self.turn_step = STEP_MITGEHEN
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()
# =====================================================
# KNOTEN 1: MITGEHEN?
# =====================================================
if self.turn_step == STEP_MITGEHEN:
raw_deficit = max(0, self.engine.highest_bet - hand.bet_in_pot)
to_call = min(wallet, raw_deficit)
if to_call > 0:
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_yes(to_call),
sound_mgr=self.ctx.sounds, width=215, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
ImageButton(
row, t("bj_tree_btn_call_no_lose"),
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
self._on_step1_no_when_raised,
sound_mgr=self.ctx.sounds, width=225, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
else:
self.status_lbl.configure(text=t("bj_tree_step1_even", hand_tag))
ImageButton(
row, t("bj_tree_btn_play_yes"),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
lambda: self._on_step1_yes(0),
sound_mgr=self.ctx.sounds, width=235, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
ImageButton(
row, t("bj_tree_btn_even_no_done"),
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
self._on_step1_no_mark_ready,
sound_mgr=None, width=225, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
ImageButton(
row, t("bj_fold_btn"),
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
self._on_step1_no_when_raised,
sound_mgr=self.ctx.sounds, width=130, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
return
# =====================================================
# KNOTEN 2: ZIEHEN? (inkl. Split / Double Down bei 2 Karten)
# =====================================================
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=6)
if self.engine.can_double_down(self.active_hand_idx, wallet, already_drew_this_turn=False):
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=175, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=6)
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=150, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=6)
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=self.ctx.sounds, width=180, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=6)
return
# =====================================================
# KNOTEN 3: ERHÖHEN? (erst NACH Weiter/Ziehen sichtbar!)
# =====================================================
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)
return
# =====================================================
# KNOTEN 4: FERTIG?
# =====================================================
if self.turn_step == STEP_FERTIG:
self.status_lbl.configure(text=t("bj_tree_step4_done", hand_tag))
ImageButton(
row, t("bj_tree_btn_done_yes"),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
self._on_step4_done_yes,
sound_mgr=None, width=225, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
ImageButton(
row, t("bj_tree_btn_done_no"),
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
self._on_step4_done_no,
sound_mgr=self.ctx.sounds, width=230, height=38, font=("Helvetica", 10, "bold")
).pack(side="left", padx=8)
# ---------------------------------------------------------
# ÜBERGÄNGE ZWISCHEN DEN BAUM-KNOTEN
# ---------------------------------------------------------
def _advance_to_erhoehen_or_fertig(self):
"""Springt zu Knoten 3 (Erhöhen?), oder direkt weiter, falls kein Gold/Raise-Cap mehr frei ist."""
self.bj_account = Database.get_blackjack_account(self.bj_account["id"])
wallet = self.bj_account["gold"]
dyn_chips = self._get_current_level_chips()
can_raise = (self.engine.raises_in_round < BJ_MAX_RAISES_PER_ROUND) and (wallet >= dyn_chips[0])
if can_raise:
self.turn_step = STEP_ERHOEHEN
self._persist_state()
self._render_current_tree_step()
else:
self._advance_to_fertig_or_next()
def _advance_to_fertig_or_next(self):
"""Springt zu Knoten 4 (Fertig?), oder gibt direkt an den nächsten Spieler ab, falls Karten schon feststehen."""
hand = self.engine.player_hands[self.active_hand_idx]
if hand.cards_locked:
self._finish_current_hand_turn()
else:
self.turn_step = STEP_FERTIG
self._persist_state()
self._render_current_tree_step()
def _on_step1_yes(self, to_call: int):
"""Knoten 1 -> Ja (Mitgehen): Zahlt ggf. Differenz ein und geht zu Knoten 2 (Ziehen?)."""
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)
hand = self.engine.player_hands[self.active_hand_idx]
hand.acted_once = True
h_val, _ = HandEvaluator.evaluate(hand.cards)
if not hand.cards_locked 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()
else:
# Karten standen bereits fest (z.B. 21 oder vorher Fertig gemeldet) -> weiter zu Erhöhen? / Nächster!
self._render_table(reveal_opponents=False, reveal_dealer=False)
self._advance_to_erhoehen_or_fertig()
def _on_step1_no_mark_ready(self):
"""Knoten 1 -> Nein (ohne offenen Raise): Spieler wird als Fertig markiert -> direkt Nächster dran!"""
self.ctx.sounds.play("stand")
hand = self.engine.player_hands[self.active_hand_idx]
hand.cards_locked = True
hand.acted_once = True
self._render_table(reveal_opponents=False, reveal_dealer=False)
self._finish_current_hand_turn()
def _on_step1_no_when_raised(self):
"""Knoten 1 -> Nein gegen Erhöhung / Austreten: Sofort Verloren (Out) -> Nächster dran!"""
hand = self.engine.player_hands[self.active_hand_idx]
hand.folded = True
hand.cards_locked = True
hand.acted_once = True
self._render_table(reveal_opponents=False, reveal_dealer=False)
self._finish_current_hand_turn()
def _on_step2_draw_yes(self):
"""Knoten 2 -> Ja (Ziehen!): Zieht Karte -> über 21 = Verloren, sonst zu Knoten 3 (Erhöhen?)."""
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:
# Über 21 -> sofort Verloren & nächster Spieler dran!
self._finish_current_hand_turn()
return
self._advance_to_erhoehen_or_fertig()
def _on_step2_draw_no(self):
"""Knoten 2 -> Nein (Nicht ziehen): Direkt weiter zu Knoten 3 (Erhöhen?)."""
self._advance_to_erhoehen_or_fertig()
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):
"""Knoten 3 -> Ja (Erhöhen!): Erhöht den Pot und übergibt laut Baum direkt an Next round / nächsten Spieler!"""
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):
"""Knoten 3 -> Nein: Weiter zu Knoten 4 (Fertig?)."""
self._advance_to_fertig_or_next()
def _on_step4_done_yes(self):
"""Knoten 4 -> Ja (Fertig): Karten stehen endgültig fest -> Nächster dran!"""
self.ctx.sounds.play("stand")
hand = self.engine.player_hands[self.active_hand_idx]
hand.cards_locked = True
self._render_table(reveal_opponents=False, reveal_dealer=False)
self._finish_current_hand_turn()
def _on_step4_done_no(self):
"""Knoten 4 -> Nein (Offen bleiben): Direkt der Nächste dran!"""
self._finish_current_hand_turn()
# ---------------------------------------------------------
# BOT-ZYKLUS (durchläuft denselben 4-Knoten-Baum)
# ---------------------------------------------------------
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._begin_next_turn_cycle()
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 self.engine.bot_needs_turn(bot):
break
self.active_bot_idx += 1
if self.active_bot_idx >= len(self.bots):
self.active_bot_idx = -1
self._persist_state()
self._begin_next_turn_cycle()
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)
bot.acted_once = True
# --- KNOTEN 1: Mitgehen? ---
if not self.bot_ai.decide_step1_mitgehen(bot, self.engine.highest_bet):
if to_call > 0:
bot.folded = True
bot.cards_locked = True
bot.status_text = t("bj_bot_action_fold")
else:
bot.cards_locked = True
bot.status_text = t("bj_bot_action_ready", len(bot.hand))
self._finish_bot_step()
return
# Bot geht mit!
if to_call > 0:
self.ctx.sounds.play("click")
self.engine.bot_add_gold_to_pot(bot, to_call)
# --- KNOTEN 2: Ziehen? ---
drew_card = False
if not bot.cards_locked:
if self.bot_ai.wants_double_down(bot, upcard, self.engine.highest_bet, self.engine.raises_in_round):
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
# Über 21? -> Verloren!
if bot.busted:
b_val, _ = HandEvaluator.evaluate(bot.hand)
bot.status_text = t("bj_bot_action_bust", b_val)
self._finish_bot_step()
return
# --- KNOTEN 3: Erhöhen? ---
raise_amt = self.bot_ai.decide_step3_erhoehen(
bot, dyn_chips, self.engine.deck.remaining(), self.engine.raises_in_round
)
if raise_amt > 0:
self.ctx.sounds.play("click")
self.engine.bot_add_gold_to_pot(bot, raise_amt)
if self.bot_ai.decide_step4_fertig(bot, upcard, self.engine.deck.remaining()):
bot.cards_locked = True
bot.status_text = t("bj_bot_action_bet", raise_amt)
self._finish_bot_step()
return
# --- KNOTEN 4: Fertig? ---
if self.bot_ai.decide_step4_fertig(bot, upcard, self.engine.deck.remaining()):
bot.cards_locked = True
bot.status_text = (
t("bj_bot_action_call", to_call) if to_call > 0 else t("bj_bot_action_ready", len(bot.hand))
)
else:
bot.status_text = (
t("bj_bot_action_hit", len(bot.hand)) if drew_card else t("bj_bot_action_check", len(bot.hand))
)
self._finish_bot_step()
def _finish_bot_step(self):
self.active_bot_idx += 1
self._persist_state()
self._render_table(reveal_opponents=False, reveal_dealer=False)
self._turn_job = self.ctx.root.after(BJ_BOT_TURN_DELAY_MS, self._step_next_bot)
# ---------------------------------------------------------
# SHOWDOWN, HAUS-DEALER & ERGEBNIS-POPUP
# ---------------------------------------------------------
def _resolve_devils_lock_after_outcome(self, outcome_type: str):
if not self.devils_locked:
self._clear_persisted_state()
return
updated_acc = Database.get_blackjack_account(self.bj_account["id"])
still_only_ten_from_tie = (outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY)
if not still_only_ten_from_tie:
Database.set_bj_devils_deal_active(self.bj_account["id"], False)
self.devils_locked = False
self._clear_persisted_state()
def _award_xp_and_record(self, outcome_type: str, won_stat: bool | None) -> tuple[int, int | None]:
duration = max(0.5, time.time() - self.round_start_time)
prog_before = self.ctx.refresh_game_progress()
opp_levels = [b.ai_level for b in self.bots]
xp_gained = Progression.calculate_match_xp(
player_level=prog_before["level"],
opponent_levels=opp_levels,
outcome_type=outcome_type,
variant_mult=self.cfg["xp_mult"],
)
if won_stat is None:
Database.add_game_points(self.ctx.profile["id"], GAME_FOLDER_ID, xp_gained)
prog_after = self.ctx.refresh_game_progress()
self.ctx.sounds.play("end_battle")
new_lvl = prog_after["level"] if prog_after["level"] > prog_before["level"] else None
return xp_gained, new_lvl
old_lvl, new_lvl = self.ctx.record_result(
self.variant_key, won=won_stat, duration_sec=duration,
points_gained=xp_gained, bj_account_id=self.bj_account["id"]
)
return xp_gained, (new_lvl if new_lvl > old_lvl else None)
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
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": [],
"player_won": True,
"player_net": net,
"bank_gain": 0,
"bot_gains": [],
"xp_gained": xp,
"leveled_to": leveled_to,
}
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],
"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,
}
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)
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"],
"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,
}
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:
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")
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,
"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,
}
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"])),
)