307 lines
14 KiB
Python
307 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
|
# games/blackjack/views/blackjack_showdown_presenter.py
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
|
|
from games.blackjack.models.bot_seat import BlackjackBotSeat
|
|
from games.blackjack.models.hand_evaluator import HandEvaluator
|
|
from models.card import Card
|
|
from models.database import Database
|
|
from models.progression import Progression
|
|
from resources.code_res.game_constants import GOLD_MIN_TABLE_ENTRY
|
|
from resources.code_res.i18n import t
|
|
|
|
|
|
class BlackjackShowdownPresenter:
|
|
"""Kapselt Showdown-Abrechnung, 7-7-7-Sofortsieg, XP-Vergabe und Popup-Aufbereitung."""
|
|
|
|
@staticmethod
|
|
def count_all_table_cards(view) -> None:
|
|
if len(view.engine.dealer_hand) >= 2:
|
|
for c in view.engine.dealer_hand[1:]:
|
|
view.bot_ai.observe_public_card(c)
|
|
for h in view.engine.player_hands:
|
|
for c in h.cards:
|
|
view.bot_ai.observe_public_card(c)
|
|
for b in view.bots:
|
|
for c in b.hand:
|
|
view.bot_ai.observe_public_card(c)
|
|
|
|
@staticmethod
|
|
def resolve_devils_lock(view, outcome_type: str) -> None:
|
|
if not view.devils_locked:
|
|
view._clear_persisted_state()
|
|
return
|
|
updated_acc = Database.get_blackjack_account(view.bj_account["id"])
|
|
if not (outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY):
|
|
Database.set_bj_devils_deal_active(view.bj_account["id"], False)
|
|
view.devils_locked = False
|
|
view._clear_persisted_state()
|
|
|
|
@staticmethod
|
|
def award_xp_and_record(view, outcome_type: str, won_stat: bool | None) -> tuple[int, int | None]:
|
|
duration = max(0.5, time.time() - view.round_start_time)
|
|
prog_before = view.ctx.refresh_game_progress()
|
|
opp_levels = [b.ai_level for b in view.bots]
|
|
|
|
xp_gained = Progression.calculate_match_xp(
|
|
player_level=prog_before["level"],
|
|
opponent_levels=opp_levels,
|
|
outcome_type=outcome_type,
|
|
variant_mult=view.cfg["xp_mult"],
|
|
)
|
|
|
|
if won_stat is None:
|
|
Database.add_game_points(view.ctx.profile["id"], view.GAME_FOLDER_ID, xp_gained)
|
|
prog_after = view.ctx.refresh_game_progress()
|
|
view.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 = view.ctx.record_result(
|
|
view.variant_key,
|
|
won=won_stat,
|
|
duration_sec=duration,
|
|
points_gained=xp_gained,
|
|
bj_account_id=view.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))
|
|
|
|
@staticmethod
|
|
def collect_showdown_snapshot(view, instant_777_winner: str | None = None) -> list[dict]:
|
|
snapshot: list[dict] = []
|
|
d_cards = view.engine.dealer_hand
|
|
d_val, _ = HandEvaluator.evaluate(d_cards)
|
|
d_rank = view.engine._hand_rank(d_cards)
|
|
snapshot.append({
|
|
"role": "DEALER", "name": "", "hand_no": 0,
|
|
"card_images": [c.image_filename for c in d_cards],
|
|
"cards_raw": [[c.suit, c.rank] for c in d_cards],
|
|
"is_split": False, "busted": d_val > 21, "folded": False,
|
|
"rank_tuple": list(d_rank),
|
|
})
|
|
|
|
multi_p = len(view.engine.player_hands) > 1
|
|
for idx, h in enumerate(view.engine.player_hands):
|
|
hr = view.engine._hand_rank(h.cards, is_split=h.is_split_hand) if h.is_active_in_pot else (0, 0)
|
|
snapshot.append({
|
|
"role": "PLAYER", "name": "", "hand_no": (idx + 1) if multi_p else 0,
|
|
"card_images": [c.image_filename for c in h.cards],
|
|
"cards_raw": [[c.suit, c.rank] for c in h.cards],
|
|
"is_split": h.is_split_hand, "busted": h.busted, "folded": h.folded,
|
|
"rank_tuple": list(hr),
|
|
})
|
|
|
|
for b in view.bots:
|
|
br = view.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),
|
|
})
|
|
|
|
if instant_777_winner is not None:
|
|
for s in snapshot:
|
|
s["is_winner"] = bool(
|
|
(instant_777_winner == "PLAYER" and s["role"] == "PLAYER" and s["rank_tuple"] == [3, 21])
|
|
or (s["role"] == "BOT" and s["name"] == instant_777_winner and s["rank_tuple"] == [3, 21])
|
|
)
|
|
return snapshot
|
|
|
|
contenders = [s for s in snapshot[1:] if not s["busted"] and not s["folded"]]
|
|
dealer_entry = snapshot[0]
|
|
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"])
|
|
dealer_entry["is_winner"] = (d_rnk >= best_contender)
|
|
for s in snapshot[1:]:
|
|
s["is_winner"] = (
|
|
d_rnk <= best_contender
|
|
and not s["busted"]
|
|
and not s["folded"]
|
|
and tuple(s["rank_tuple"]) == best_contender
|
|
)
|
|
return snapshot
|
|
|
|
@classmethod
|
|
def trigger_instant_777(
|
|
cls, view, winner_is_player: bool, winning_bot: BlackjackBotSeat | None
|
|
) -> dict:
|
|
view.engine.state = "SHOWDOWN"
|
|
cls.count_all_table_cards(view)
|
|
pot_total = view.engine.pot
|
|
total_p_bet = view.engine.total_player_bet
|
|
snap = cls.collect_showdown_snapshot(
|
|
view, instant_777_winner="PLAYER" if winner_is_player else winning_bot.name
|
|
)
|
|
|
|
if winner_is_player:
|
|
payout = pot_total + (total_p_bet if not view.bots else 0)
|
|
net = payout - total_p_bet
|
|
view.bj_account = Database.update_blackjack_gold(view.bj_account["id"], payout)
|
|
xp, leveled_to = cls.award_xp_and_record(view, "WIN_777", won_stat=True)
|
|
cls.resolve_devils_lock(view, "WIN_777")
|
|
return {
|
|
"winner_type": "PLAYER", "winner_names": [], "instant_777": "PLAYER",
|
|
"player_won": True, "player_net": net, "bank_gain": 0, "bot_gains": [],
|
|
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
|
}
|
|
|
|
winning_bot.gold += pot_total
|
|
bot_net = pot_total - winning_bot.bet_in_pot
|
|
xp, leveled_to = cls.award_xp_and_record(view, "LOSE", won_stat=False)
|
|
cls.resolve_devils_lock(view, "LOSE")
|
|
return {
|
|
"winner_type": "BOT", "winner_names": [winning_bot.name], "instant_777": winning_bot.name,
|
|
"player_won": False, "player_net": -total_p_bet, "bank_gain": 0,
|
|
"bot_gains": [(winning_bot.name, bot_net)] if bot_net > 0 else [],
|
|
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
|
}
|
|
|
|
@classmethod
|
|
def finalize_regular_showdown(cls, view) -> dict:
|
|
cls.count_all_table_cards(view)
|
|
res = view.engine.resolve_showdown(view.bots)
|
|
snap = cls.collect_showdown_snapshot(view, instant_777_winner=None)
|
|
|
|
if res["player_payout"] > 0:
|
|
view.bj_account = Database.update_blackjack_gold(view.bj_account["id"], res["player_payout"])
|
|
|
|
w_type = res["winner_type"]
|
|
if w_type == "PLAYER":
|
|
has_nat = any(
|
|
h.is_active_in_pot and not h.is_split_hand and HandEvaluator.is_natural_blackjack(h.cards)
|
|
for h in view.engine.player_hands
|
|
)
|
|
out_code, player_won_flag = ("WIN_BJ" if has_nat else "WIN"), True
|
|
xp, leveled_to = cls.award_xp_and_record(view, out_code, won_stat=True)
|
|
elif w_type == "TIE":
|
|
out_code, player_won_flag = "TIE", None
|
|
xp, leveled_to = cls.award_xp_and_record(view, "TIE", won_stat=None)
|
|
else:
|
|
out_code, player_won_flag = "LOSE", False
|
|
xp, leveled_to = cls.award_xp_and_record(view, "LOSE", won_stat=False)
|
|
|
|
cls.resolve_devils_lock(view, out_code)
|
|
return {
|
|
"winner_type": w_type, "winner_names": res["winner_names"], "instant_777": None,
|
|
"player_won": player_won_flag, "player_net": res["player_net"],
|
|
"bank_gain": res["bank_gain"], "bot_gains": res["bot_gains"],
|
|
"xp_gained": xp, "leveled_to": leveled_to, "showdown_snapshot": snap,
|
|
}
|
|
|
|
@classmethod
|
|
def build_localized_popup_data(cls, view, payload: dict) -> dict:
|
|
w_type = payload["winner_type"]
|
|
headline = (
|
|
t("bj_popup_bank_won") if w_type == "BANK"
|
|
else (t("bj_popup_player_won") if w_type == "PLAYER"
|
|
else (t("bj_popup_bot_won", ", ".join(payload["winner_names"])) if w_type == "BOT" else t("bj_popup_tie")))
|
|
)
|
|
|
|
showdown_hands = []
|
|
for s in payload.get("showdown_snapshot", []):
|
|
cards_obj = [Card(sr[0], sr[1]) for sr in s.get("cards_raw", [])]
|
|
owner_lbl = (
|
|
t("bj_showdown_seat_dealer") if s["role"] == "DEALER"
|
|
else ((t("bj_showdown_seat_you_hand", s["hand_no"]) if s.get("hand_no") else t("bj_showdown_seat_you"))
|
|
if s["role"] == "PLAYER" else s["name"])
|
|
)
|
|
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": cls.format_hand_rank_label(
|
|
cards_obj, s.get("is_split", False), s.get("busted", False), s.get("folded", False)
|
|
),
|
|
"rank_tuple": tuple(s.get("rank_tuple", [0, 0])), "role": s["role"],
|
|
})
|
|
|
|
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(view.bj_account["id"])["gold"]
|
|
|
|
return {
|
|
"headline": headline,
|
|
"reason_text": cls._build_showdown_reason(payload, showdown_hands),
|
|
"showdown_hands": showdown_hands,
|
|
"player_won": payload["player_won"],
|
|
"player_net": payload["player_net"],
|
|
"other_gains": other_gains,
|
|
"xp_gained": payload["xp_gained"],
|
|
"new_level_title": lvl_str,
|
|
"can_continue": cur_gold >= GOLD_MIN_TABLE_ENTRY,
|
|
"can_leave_menu": not view.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:
|
|
return t("bj_reason_777_win", t("bj_showdown_seat_you") if inst == "PLAYER" else inst)
|
|
|
|
dealer = showdown_hands[0]
|
|
if not [h for h in showdown_hands[1:] if not h["busted"] and not h["folded"]]:
|
|
return t("bj_reason_all_out")
|
|
|
|
winners = [h for h in showdown_hands if h["is_winner"]]
|
|
if not winners:
|
|
return ""
|
|
if dealer["is_winner"] and len(winners) > 1:
|
|
return t("bj_reason_dealer_tie_push", dealer["rank_label"])
|
|
|
|
top_rank = winners[0]["rank_tuple"]
|
|
winner_names_str = ", ".join(dict.fromkeys(w["owner_label"] for w in winners if not w["is_dealer"]))
|
|
win_label = dealer["owner_label"] if dealer["is_winner"] else winner_names_str
|
|
losers_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
|
|
]
|
|
if top_rank == (3, 21) and losers_21:
|
|
return t("bj_reason_777_beats_21", win_label)
|
|
if top_rank == (2, 21) and losers_21:
|
|
return t("bj_reason_nat_beats_reg21", win_label)
|
|
|
|
non_dealer_winners = [w for w in winners if not w["is_dealer"]]
|
|
if len(non_dealer_winners) > 1:
|
|
return t("bj_reason_split_pot", non_dealer_winners[0]["rank_label"], winner_names_str)
|
|
if dealer["busted"] and not dealer["is_winner"]:
|
|
return t("bj_reason_dealer_bust", dealer["rank_label"], win_label, winners[0]["rank_label"])
|
|
|
|
others_alive = [h for h in showdown_hands if not h["is_winner"] and not h["busted"] and not h["folded"]]
|
|
runner = max(others_alive, key=lambda x: x["rank_tuple"]) if others_alive else dealer
|
|
return t("bj_reason_higher_score", win_label, winners[0]["rank_label"], f"{runner['owner_label']}: {runner['rank_label']}") |