the_goth_cardgame_collection/games/poker/views/poker_table_view.py

330 lines
12 KiB
Python
Raw Permalink Normal View History

# -*- coding: utf-8 -*-
# games/poker/views/poker_table_view.py
from __future__ import annotations
import json
import time
import tkinter as tk
from games.poker.models.poker_bot_ai import PokerBotAI
from games.poker.models.poker_engine import PokerEngine
from games.poker.models.poker_seat import PokerSeat
from games.poker.views.poker_arena_renderer import PokerArenaRenderer
from games.poker.views.poker_hands_overlay import PokerHandsOverlay
from games.poker.views.poker_result_dialog import PokerResultDialog
from games.poker.views.poker_turn_driver import PokerTurnDriver
from models.database import Database
from resources.code_res.game_constants import PK_STARTING_GOLD, PK_VARIANTS
from resources.code_res.i18n import t
from view.widgets.casino_arena_base import CasinoArenaBase
from view.widgets.image_button import ImageButton
GAME_FOLDER_ID = "poker"
class PokerTableView(CasinoArenaBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
def __init__(
self,
context,
variant_key: str,
pk_account_id: int,
bot_configs: list[tuple[int, str]],
on_back_to_menu,
resume_state_json: str | None = None,
):
cfg = PK_VARIANTS[variant_key]
self._init_arena_state(context, variant_key, cfg, on_back_to_menu)
self.engine = PokerEngine(sb=cfg["sb"], bb=cfg["bb"])
self.bot_ai = PokerBotAI()
self.round_start_time: float = time.time()
self._last_popup_payload: dict | None = None
self._hands_overlay: PokerHandsOverlay | None = None
self._card_ref_btn: ImageButton | None = None
self.ctx.sounds.play_ingame_music()
if resume_state_json is not None:
self._restore_from_json(resume_state_json)
else:
self.pk_account = Database.get_poker_account(pk_account_id)
self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0))
bot_bankroll = max(
PK_STARTING_GOLD, self._get_current_level_chips()[-1] * 6
)
self.engine.seats = [
PokerSeat(
seat_id=0,
name=self.ctx.profile["name"],
is_human=True,
stack=self.pk_account["gold"],
)
]
for idx, (lvl, b_name) in enumerate(bot_configs, start=1):
self.engine.seats.append(
PokerSeat(
seat_id=idx,
name=b_name,
is_human=False,
ai_level=lvl,
stack=bot_bankroll,
)
)
self._build_ui()
self._start_new_hand()
def _cleanup_game_overlays(self):
self._close_hands_overlay()
def _close_hands_overlay(self):
if self._hands_overlay is not None:
try:
if self._hands_overlay.winfo_exists():
self._hands_overlay.destroy()
except Exception:
pass
self._hands_overlay = None
def _toggle_hands_overlay(self):
if self._fx_overlay is not None or self._result_dialog is not None:
return
if self._hands_overlay is not None and self._hands_overlay.winfo_exists():
self._close_hands_overlay()
return
if self._canvas_alive():
self._hands_overlay = PokerHandsOverlay(
self.arena_canvas, self.ctx, on_close=self._close_hands_overlay
)
def _persist_state(self):
if not self.devils_locked:
return
state_obj = {
"pk_account_id": self.pk_account["id"],
"devils_locked": self.devils_locked,
"elapsed_sec": max(0.0, time.time() - self.round_start_time),
"last_popup_payload": self._last_popup_payload,
"engine": self.engine.to_dict(),
}
Database.save_game_state(
self.ctx.profile["id"],
GAME_FOLDER_ID,
self.variant_key,
json.dumps(state_obj),
)
def _restore_from_json(self, raw_json: str):
try:
data = json.loads(raw_json)
self.pk_account = Database.get_poker_account(data["pk_account_id"])
self.devils_locked = bool(
data.get("devils_locked", False)
or self.pk_account.get("devils_deal_active", 0)
)
self.round_start_time = time.time() - float(data.get("elapsed_sec", 0.0))
self._last_popup_payload = data.get("last_popup_payload")
self.engine.load_from_dict(data["engine"])
except Exception:
self._clear_persisted_state()
dev_acc = Database.get_active_devils_pk_account(self.ctx.profile["id"])
accounts = Database.get_poker_accounts(self.ctx.profile["id"])
self.pk_account = dev_acc or accounts[0]
self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0))
self.engine.seats = [
PokerSeat(
seat_id=0,
name=self.ctx.profile["name"],
is_human=True,
stack=self.pk_account["gold"],
),
PokerSeat(
seat_id=1,
name=t("bot_default_name", 1),
is_human=False,
ai_level=2,
stack=PK_STARTING_GOLD,
),
]
self._build_ui()
self._start_new_hand()
return
self._build_ui()
if self.engine.street == "SHOWDOWN" and self._last_popup_payload:
self._render_table()
self._open_result_popup(
PokerArenaRenderer.build_localized_popup_data(
self, self._last_popup_payload
),
play_fx=False,
)
else:
self._render_table()
PokerTurnDriver.process_current_turn(self)
def _on_language_switched(self):
was_help = (
self._hands_overlay is not None and self._hands_overlay.winfo_exists()
)
ImageButton.close_active_hover_tip()
self._cancel_fx_overlay()
self._close_hands_overlay()
self._persist_state()
self._build_ui()
if self.engine.street == "SHOWDOWN" and self._last_popup_payload:
self._render_table()
self._open_result_popup(
PokerArenaRenderer.build_localized_popup_data(
self, self._last_popup_payload
),
play_fx=False,
)
else:
self._render_table()
if self.engine.turn_pos == 0 and self.engine.human_seat.can_act:
PokerTurnDriver.show_human_controls(self)
else:
self._set_bottom_buttons([])
if was_help:
self._toggle_hands_overlay()
def _build_ui(self):
self._close_hands_overlay()
self._build_arena_shell(on_lang_refresh=self._on_language_switched)
self._card_ref_btn = ImageButton(
self.arena_canvas,
t("pk_btn_hands_help"),
self.ctx.assets.raw_btn_default,
self.ctx.assets.raw_btn_purple,
self._toggle_hands_overlay,
sound_mgr=self.ctx.sounds,
width=136,
height=34,
style="amethyst",
hover_text=lambda: t("pk_help_general_info"),
)
self._refresh_header()
def _on_arena_resize_redraw(self):
self._render_table()
def _refresh_header(self):
self.pk_account = Database.get_poker_account(self.pk_account["id"])
self._set_hud_segments(
t("pk_header_gold", self.pk_account["account_name"], self.pk_account["gold"]),
f"~Pot: {self.engine.total_pot}g",
f"~{t(f'pk_street_{self.engine.street}')}",
)
def _start_new_hand(self):
self._cancel_fx_overlay()
if self._result_dialog:
self._result_dialog.close_dialog()
self._result_dialog = None
ImageButton.close_active_hover_tip()
self._close_hands_overlay()
self.pk_account = Database.get_poker_account(self.pk_account["id"])
self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0))
gold, min_req = self.pk_account["gold"], self.cfg["min_entry"]
if gold < (min(min_req, 10) if self.devils_locked else min_req):
self._abort_round_low_gold(
self.pk_account, min_req, Database.set_pk_devils_deal_active
)
return
self._last_popup_payload = None
self.round_start_time = time.time()
self.ctx.sounds.play("deal")
self.engine.human_seat.stack = gold
fallback_stack = max(
PK_STARTING_GOLD, self._get_current_level_chips()[-1] * 5
)
for s in self.engine.seats[1:]:
self.bot_ai.ensure_bot_stack(s, min_req, fallback_stack=fallback_stack)
human_ante, ante_events = self.engine.start_hand()
if human_ante > 0:
self.pk_account = Database.update_poker_gold(
self.pk_account["id"], -human_ante
)
for s_idx, (_b_role, b_amt) in ante_events.items():
if s_idx > 0:
self.engine.seats[s_idx].status_text = t("pk_ante_status", b_amt)
self._persist_state()
if not self._canvas_alive():
self._build_ui()
else:
self.topbar.set_locked_exit(self.devils_locked)
self._render_table()
PokerTurnDriver.process_current_turn(self)
def _render_table(self):
if not self._canvas_alive():
return
cw, ch, pad_x, pad_top, pad_bot, p_top, p_bot, table_rect = (
self._prepare_arena_surface()
)
top_obs = PokerArenaRenderer.draw_bots(
self, cw, ch, pad_x, pad_top, pad_bot, table_rect
)
PokerArenaRenderer.draw_board_and_pot(self, table_rect, top_obs, p_top)
PokerArenaRenderer.draw_human_hand(self, cw, pad_x, p_top, p_bot)
if self.arena_canvas.find_withtag("modal_dim_veil"):
self.arena_canvas.tag_raise("modal_dim_veil")
self._refresh_header()
if self._hands_overlay is not None and self._hands_overlay.winfo_exists():
tk.Widget.tkraise(self._hands_overlay)
if self._result_dialog is not None and self._result_dialog.winfo_exists():
tk.Widget.tkraise(self._result_dialog)
def _on_human_action(self, action: str, raise_delta: int):
ImageButton.close_active_hover_tip()
self._close_hands_overlay()
if action == "CHECK":
self.ctx.sounds.play("stand")
paid = self.engine.apply_action(0, action, raise_delta)
if paid > 0:
self.pk_account = Database.update_poker_gold(
self.pk_account["id"], -paid
)
self.engine.advance_turn_pointer()
self._persist_state()
self._render_table()
PokerTurnDriver.process_current_turn(self)
def _show_result_dialog_now(self, popup_data: dict):
if not self._canvas_alive():
return
self._set_bottom_buttons([])
if self._card_ref_btn is not None and self._card_ref_btn.winfo_exists():
self._card_ref_btn.place_forget()
self._result_dialog = PokerResultDialog(
parent=self.arena_canvas,
assets=self.ctx.assets,
sounds=self.ctx.sounds,
result_data=popup_data,
on_next_round=self._start_new_hand,
on_back_to_menu=lambda: self._cleanup_and_go(
lambda: self.on_back_to_menu(self.pk_account["id"])
),
)
def _open_result_popup(self, popup_data: dict, play_fx: bool = True):
self._close_hands_overlay()
if self._card_ref_btn is not None and self._card_ref_btn.winfo_exists():
self._card_ref_btn.place_forget()
self._play_outcome_fx_then(
popup_data.get("player_won"),
play_fx,
lambda: self._show_result_dialog_now(popup_data),
)