feat(poker,ui): add 6-max Texas Hold'em module, Old London font loader, window persistence & custom art assets
This commit is contained in:
parent
80fdb0aa3b
commit
4e96cf8b56
Binary file not shown.
Binary file not shown.
|
|
@ -42,13 +42,20 @@ class AppContext:
|
|||
won: bool,
|
||||
duration_sec: float,
|
||||
points_gained: int = 0,
|
||||
bj_account_id: int | None = None
|
||||
bj_account_id: int | None = None,
|
||||
pk_account_id: int | None = None,
|
||||
) -> tuple[int, int]:
|
||||
if not self._ctrl.active_profile:
|
||||
return (1, 1)
|
||||
pid = self._ctrl.active_profile["id"]
|
||||
old_lvl, new_lvl = Database.record_game_result(
|
||||
pid, variant_key, won, duration_sec, points_gained, bj_account_id=bj_account_id
|
||||
pid,
|
||||
variant_key,
|
||||
won,
|
||||
duration_sec,
|
||||
points_gained,
|
||||
bj_account_id=bj_account_id,
|
||||
pk_account_id=pk_account_id,
|
||||
)
|
||||
self.sounds.play("end_battle" if new_lvl > old_lvl else ("win" if won else "lose"))
|
||||
return old_lvl, new_lvl
|
||||
|
|
|
|||
|
|
@ -60,22 +60,28 @@ class AppController:
|
|||
self.active_profile = None
|
||||
self.view.show_login(Database.get_profiles(), preselect_name=last_prof)
|
||||
|
||||
def has_active_devils_lock(self) -> bool:
|
||||
"""Nur aktiv, wenn wirklich das DB-Flag devils_deal_active == 1 gesetzt wurde!"""
|
||||
def get_locked_devils_game_folder(self) -> str | None:
|
||||
if not self.active_profile:
|
||||
return False
|
||||
return None
|
||||
pid = self.active_profile["id"]
|
||||
devils_acc = Database.get_active_devils_bj_account(pid)
|
||||
if devils_acc is None:
|
||||
# Verwaiste Blackjack-Savegames ohne aktives Pakt-Flag sofort wegräumen
|
||||
if Database.get_active_devils_bj_account(pid) is not None:
|
||||
return "blackjack"
|
||||
Database.delete_game_state(pid, "blackjack")
|
||||
return False
|
||||
return True
|
||||
|
||||
if Database.get_active_devils_pk_account(pid) is not None:
|
||||
return "poker"
|
||||
Database.delete_game_state(pid, "poker")
|
||||
return None
|
||||
|
||||
def has_active_devils_lock(self) -> bool:
|
||||
return self.get_locked_devils_game_folder() is not None
|
||||
|
||||
def resume_devils_deal(self):
|
||||
games = self.loader.discover_games()
|
||||
for g in games:
|
||||
if g["folder"] == "blackjack":
|
||||
target_folder = self.get_locked_devils_game_folder()
|
||||
if not target_folder:
|
||||
return
|
||||
for g in self.loader.discover_games():
|
||||
if g["folder"] == target_folder:
|
||||
self.launch_game(g)
|
||||
return
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
# Texas Hold'em (6-Max No-Limit) — Modul-Dokumentation / Module Documentation
|
||||
|
||||
[**🇩🇪 Deutsch**](#-deutsch) | [**🇬🇧 English**](#-english)
|
||||
|
||||
---
|
||||
|
||||
## 🇩🇪 Deutsch
|
||||
|
||||
### 1. Überblick
|
||||
Das Modul `games/poker/` implementiert **6-Max No-Limit Texas Hold'em** innerhalb der Kategorie **Glück**. Es besitzt eine **vollständig autarke Ökonomie** (`poker_accounts` & `poker_account_stats`) sowie eine eigene Erfahrungs- und Rang-Kurve (`game_folder = 'poker'`), strikt getrennt von Blackjack.
|
||||
|
||||
### 2. Spielregeln & Tischablauf
|
||||
* **6-Max Tisch (`poker_table.jpg`):** Du spielst gegen **1 bis maximal 5 KI-Gegner** rund um einen dynamisch skalierenden gotischen Pokertisch.
|
||||
* **Einheitlicher Grundeinsatz (Ante) statt asymmetrischer Blinds:** Beim Start einer Hand zahlt jeder aktive Sitz automatisch denselben Grundeinsatz in den Pot (`10 Gold` bei *Klassisch*, `20 Gold` bei *Hoher Einsatz*). Der Dealer-Button `[D]` rotiert jede Runde im Uhrzeigersinn weiter und bestimmt die Zugreihenfolge.
|
||||
* **Setzrunden (Streets):** `Pre-Flop` (2 Hole Cards) $\rightarrow$ `Flop` (3 Gemeinschaftskarten) $\rightarrow$ `Turn` (4. Karte) $\rightarrow$ `River` (5. Karte) $\rightarrow$ `Showdown`.
|
||||
* **No-Limit, All-In & Side-Pots:** Jederzeit **All-In** möglich. Bei unterschiedlich hohen Stacks berechnet die `PokerEngine` automatisch exakte Haupt- und **Side-Pots**.
|
||||
* **Statische Hand-Referenz & `ⓘ`-Hilfesystem:** Unten links zeigt eine 2-spaltige Übersicht mit Mini-Beispielkarten alle 10 Poker-Kombinationen (ohne die eigene aktuelle Hand vorab zu verraten). Über die `ⓘ`-Symbole (`InfoBadge`) lassen sich jederzeit Erklärungen zu Kombinationen und Wettbegriffen (*Check/Hold*, *Call*, *Raise*, *All-In*, *Fold*) einblenden.
|
||||
* **Showdown-Aufdeckung:** Im Ergebnis-Dialog werden am Rundenende die Gemeinschaftskarten sowie alle beteiligten Spielerhände mit echten Kartenbildern und erreichter Kombination aufgedeckt.
|
||||
|
||||
### 3. KI-Stufen (0 bis 6 „Gottheit“)
|
||||
* **Stufe 0–5:** Vom losen Zufallsspieler über vorsichtige Akolythen bis zum Tight-Aggressive-Hai.
|
||||
* **Stufe 6 (Gottheit / Online-Standard):** Monte-Carlo-Equity-Simulation gegen alle aktiven Gegner, strikte Pot-Odds-/Implied-Odds-Kalkulation und gezielte Semi-Bluffs.
|
||||
|
||||
---
|
||||
|
||||
## 🇬🇧 English
|
||||
|
||||
### 1. Overview
|
||||
The `games/poker/` module implements **6-Max No-Limit Texas Hold'em** under the **Luck** category with a **standalone economy** (`poker_accounts`, `poker_account_stats`) and isolated XP progression (`game_folder = 'poker'`).
|
||||
|
||||
### 2. Rules & Table Features
|
||||
* **6-Max Arena (`poker_table.jpg`):** Play against **1 to 5 AI opponents** arranged around a dynamically scaling Gothic poker table.
|
||||
* **Equal Entry Ante:** At the start of each hand, every active seat automatically posts the table's base ante (`10 Gold` in *Classic*, `20 Gold` in *High Stakes*) before starting in **Pre-Flop**, while the Dealer button `[D]` rotates clockwise.
|
||||
* **Streets & Side Pots:** Full `Pre-Flop` $\rightarrow$ `Flop` $\rightarrow$ `Turn` $\rightarrow$ `River` $\rightarrow$ `Showdown` flow with automatic multi-way **Side Pot** resolution on uneven All-Ins.
|
||||
* **Visual Hand Reference & `ⓘ` Tooltips:** Static 2-column mini-card cheat sheet (no hand spoilers during play) paired with hover/click `ⓘ` (`InfoBadge`) explanations for all 10 hand rankings and betting actions.
|
||||
* **Full Showdown Reveal:** End-of-hand overlay displaying community cards and every seat's hole-card graphics alongside their evaluated combination.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,192 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/models/poker_bot_ai.py
|
||||
import random
|
||||
from games.poker.models.poker_evaluator import PokerEvaluator
|
||||
from games.poker.models.poker_seat import PokerSeat
|
||||
from models.card import Card
|
||||
from resources.code_res.game_constants import BOT_DEITY_LEVEL, PK_STARTING_GOLD, RANKS, SUITS
|
||||
|
||||
|
||||
class PokerBotAI:
|
||||
"""
|
||||
6-Max No-Limit Hold'em KI:
|
||||
- Stufe 0..5: Vom Zufalls-Fisch bis zum tight-aggressiven Haifisch
|
||||
- Stufe 6 (BOT_DEITY_LEVEL): Monte-Carlo Equity vs. exakte Pot-Odds + kalkulierter Semi-Bluff-Druck
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def enforce_online_deity_bots(bot_configs: list[tuple[int, str]]) -> list[tuple[int, str]]:
|
||||
return [(BOT_DEITY_LEVEL, name) for _lvl, name in bot_configs]
|
||||
|
||||
@staticmethod
|
||||
def ensure_bot_stack(seat: PokerSeat, min_entry: int, fallback_stack: int = PK_STARTING_GOLD):
|
||||
if seat.stack < min_entry:
|
||||
seat.stack = fallback_stack
|
||||
seat.rebought = True
|
||||
else:
|
||||
seat.rebought = False
|
||||
|
||||
def decide_action(
|
||||
self,
|
||||
bot: PokerSeat,
|
||||
board: list[Card],
|
||||
current_bet: int,
|
||||
pot: int,
|
||||
min_raise_delta: int,
|
||||
chips: tuple[int, ...],
|
||||
active_opponents: int,
|
||||
) -> tuple[str, int]:
|
||||
"""
|
||||
Gibt ('FOLD' | 'CHECK' | 'CALL' | 'RAISE' | 'ALLIN', raise_delta) zurück.
|
||||
"""
|
||||
to_call = max(0, current_bet - bot.street_bet)
|
||||
lvl = bot.ai_level
|
||||
|
||||
# Stufe 0: Verwirrte Seele (Zufall)
|
||||
if lvl == 0:
|
||||
if to_call == 0:
|
||||
if bot.stack >= chips[0] and random.random() < 0.22:
|
||||
return ("RAISE", max(min_raise_delta, chips[0]))
|
||||
return ("CHECK", 0)
|
||||
if random.random() < 0.28:
|
||||
return ("FOLD", 0)
|
||||
if to_call >= bot.stack:
|
||||
return ("ALLIN", 0)
|
||||
if bot.stack > to_call + chips[0] and random.random() < 0.15:
|
||||
return ("RAISE", max(min_raise_delta, chips[0]))
|
||||
return ("CALL", 0)
|
||||
|
||||
# Equity / Handstärke [0.0 .. 1.0] berechnen
|
||||
samples = {1: 18, 2: 28, 3: 45, 4: 70, 5: 100}.get(lvl, 150)
|
||||
equity = self._estimate_equity(bot.hole_cards, board, max(1, active_opponents), samples)
|
||||
|
||||
# Effektive Pot-Odds berechnen
|
||||
eff_call = min(bot.stack, to_call)
|
||||
pot_odds = eff_call / max(1, pot + eff_call) if eff_call > 0 else 0.0
|
||||
|
||||
# Stufen-Charakteristik
|
||||
if lvl == 1:
|
||||
# Vorsichtiger Akolyth (spielt passiv, callt zu oft kleine Bets, erhöht selten)
|
||||
if to_call > 0 and equity + 0.08 < pot_odds and random.random() < 0.80:
|
||||
return ("FOLD", 0)
|
||||
if equity > 0.78 and bot.stack > to_call + chips[0] and random.random() < 0.45:
|
||||
return ("RAISE", max(min_raise_delta, chips[0]))
|
||||
return self._check_or_call(bot, to_call)
|
||||
|
||||
if lvl in (2, 3):
|
||||
margin = 0.04 if lvl == 2 else 0.01
|
||||
if to_call > 0 and equity + margin < pot_odds:
|
||||
return ("FOLD", 0)
|
||||
if equity >= 0.68 and bot.stack > to_call:
|
||||
return self._pick_raise(bot, to_call, min_raise_delta, chips, pot, equity, aggressive=(lvl == 3))
|
||||
return self._check_or_call(bot, to_call)
|
||||
|
||||
if lvl in (4, 5):
|
||||
# TAG / Kartenzähler-Hai
|
||||
bluff_chance = 0.08 if lvl == 4 else 0.13
|
||||
if to_call > 0:
|
||||
if equity < pot_odds - 0.02:
|
||||
if to_call <= chips[0] and random.random() < bluff_chance and bot.stack > to_call + min_raise_delta:
|
||||
return ("RAISE", max(min_raise_delta, chips[0]))
|
||||
return ("FOLD", 0)
|
||||
if equity >= 0.62 or (to_call == 0 and random.random() < bluff_chance):
|
||||
return self._pick_raise(bot, to_call, min_raise_delta, chips, pot, equity, aggressive=True)
|
||||
return self._check_or_call(bot, to_call)
|
||||
|
||||
# --- STUFE 6: GOTTHEIT (Gnadenlose EV-Maximierung + Polarized Bluffs) ---
|
||||
opp_scale = 1.0 / max(1, active_opponents)
|
||||
strong_thresh = max(0.54, opp_scale + 0.20)
|
||||
|
||||
if to_call > 0:
|
||||
# Exakter Pot-Odds + Implied-Odds Cut
|
||||
implied_bonus = 0.035 if len(board) < 5 else 0.0
|
||||
if equity + implied_bonus < pot_odds:
|
||||
# Gezielter Re-Steal Bluff bei kleinem Einsatz auf späten Straßen
|
||||
if eff_call <= max(chips[0], pot // 4) and bot.stack > to_call + min_raise_delta and random.random() < 0.14:
|
||||
return ("RAISE", max(min_raise_delta, chips[min(1, len(chips) - 1)]))
|
||||
return ("FOLD", 0)
|
||||
|
||||
if equity >= strong_thresh + 0.14 and bot.stack > to_call:
|
||||
if equity >= 0.84 and random.random() < 0.45:
|
||||
return ("ALLIN", 0)
|
||||
return self._pick_raise(bot, to_call, min_raise_delta, chips, pot, equity, aggressive=True)
|
||||
return self._check_or_call(bot, to_call)
|
||||
|
||||
# Gottheit ohne offenen Einsatz (Check oder Attacke)
|
||||
if equity >= strong_thresh or random.random() < 0.18:
|
||||
return self._pick_raise(bot, 0, min_raise_delta, chips, pot, equity, aggressive=True)
|
||||
return ("CHECK", 0)
|
||||
|
||||
@staticmethod
|
||||
def _check_or_call(bot: PokerSeat, to_call: int) -> tuple[str, int]:
|
||||
if to_call <= 0:
|
||||
return ("CHECK", 0)
|
||||
if to_call >= bot.stack:
|
||||
return ("ALLIN", 0)
|
||||
return ("CALL", 0)
|
||||
|
||||
@staticmethod
|
||||
def _pick_raise(
|
||||
bot: PokerSeat,
|
||||
to_call: int,
|
||||
min_raise_delta: int,
|
||||
chips: tuple[int, ...],
|
||||
pot: int,
|
||||
equity: float,
|
||||
aggressive: bool,
|
||||
) -> tuple[str, int]:
|
||||
avail_for_raise = bot.stack - to_call
|
||||
if avail_for_raise <= 0:
|
||||
return ("ALLIN", 0) if to_call >= bot.stack else ("CALL", 0)
|
||||
if avail_for_raise <= min_raise_delta:
|
||||
return ("ALLIN", 0)
|
||||
|
||||
target = max(min_raise_delta, int(pot * (0.75 if aggressive else 0.5)))
|
||||
affordable = [c for c in chips if min_raise_delta <= c <= avail_for_raise]
|
||||
if affordable:
|
||||
chosen = min(affordable, key=lambda c: abs(c - target))
|
||||
if equity >= 0.82 and aggressive:
|
||||
chosen = affordable[min(len(affordable) - 1, 2)]
|
||||
else:
|
||||
chosen = min_raise_delta
|
||||
|
||||
if chosen >= avail_for_raise:
|
||||
return ("ALLIN", 0)
|
||||
return ("RAISE", chosen)
|
||||
|
||||
@classmethod
|
||||
def _estimate_equity(cls, hole: list[Card], board: list[Card], num_opps: int, iterations: int) -> float:
|
||||
if len(hole) < 2:
|
||||
return 0.0
|
||||
|
||||
known = {(c.suit, c.rank) for c in hole} | {(c.suit, c.rank) for c in board}
|
||||
rem_deck = [Card(s, r) for s in SUITS for r in RANKS if (s, r) not in known]
|
||||
need_board = 5 - len(board)
|
||||
cards_per_sim = need_board + 2 * num_opps
|
||||
|
||||
if len(rem_deck) < cards_per_sim:
|
||||
return 0.5
|
||||
|
||||
wins = 0.0
|
||||
for _ in range(iterations):
|
||||
sampled = random.sample(rem_deck, cards_per_sim)
|
||||
sim_board = board + sampled[:need_board]
|
||||
my_score = PokerEvaluator.evaluate_best(hole + sim_board)
|
||||
|
||||
idx = need_board
|
||||
beaten = False
|
||||
tied = 0
|
||||
for _o in range(num_opps):
|
||||
opp_hole = sampled[idx:idx + 2]
|
||||
idx += 2
|
||||
opp_score = PokerEvaluator.evaluate_best(opp_hole + sim_board)
|
||||
if opp_score > my_score:
|
||||
beaten = True
|
||||
break
|
||||
if opp_score == my_score:
|
||||
tied += 1
|
||||
|
||||
if not beaten:
|
||||
wins += 1.0 / (1 + tied)
|
||||
|
||||
return wins / iterations
|
||||
|
|
@ -0,0 +1,369 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/models/poker_engine.py
|
||||
from games.poker.models.poker_evaluator import PokerEvaluator
|
||||
from games.poker.models.poker_seat import PokerSeat
|
||||
from models.card import Card
|
||||
from models.deck import Deck
|
||||
|
||||
|
||||
class PokerEngine:
|
||||
STREETS = ("PREFLOP", "FLOP", "TURN", "RIVER", "SHOWDOWN")
|
||||
|
||||
def __init__(self, sb: int = 5, bb: int = 10):
|
||||
self.sb = sb
|
||||
self.bb = bb # Dient gleichzeitig als fester Tisch-Grundeinsatz (Ante) beim Start!
|
||||
self.deck = Deck(num_decks=1, include_jokers=False)
|
||||
|
||||
self.seats: list[PokerSeat] = []
|
||||
self.board: list[Card] = []
|
||||
|
||||
self.dealer_pos: int = -1
|
||||
self.sb_pos: int = -1
|
||||
self.bb_pos: int = -1
|
||||
self.turn_pos: int = 0
|
||||
|
||||
self.street: str = "PREFLOP"
|
||||
self.current_bet: int = 0
|
||||
self.min_raise_delta: int = bb
|
||||
|
||||
@property
|
||||
def total_pot(self) -> int:
|
||||
return sum(s.total_committed for s in self.seats)
|
||||
|
||||
@property
|
||||
def human_seat(self) -> PokerSeat:
|
||||
return self.seats[0]
|
||||
|
||||
# --- Serialisierung für Devil's Deal Auto-Save ---
|
||||
@staticmethod
|
||||
def _cards_to_list(cards: list[Card]) -> list[list[str]]:
|
||||
return [[c.suit, c.rank] for c in cards]
|
||||
|
||||
@staticmethod
|
||||
def _list_to_cards(raw: list[list[str]]) -> list[Card]:
|
||||
return [Card(s, r) for s, r in raw]
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"sb": self.sb,
|
||||
"bb": self.bb,
|
||||
"deck_cards": self._cards_to_list(self.deck.cards),
|
||||
"board": self._cards_to_list(self.board),
|
||||
"dealer_pos": self.dealer_pos,
|
||||
"sb_pos": self.sb_pos,
|
||||
"bb_pos": self.bb_pos,
|
||||
"turn_pos": self.turn_pos,
|
||||
"street": self.street,
|
||||
"current_bet": self.current_bet,
|
||||
"min_raise_delta": self.min_raise_delta,
|
||||
"seats": [
|
||||
{
|
||||
"seat_id": s.seat_id,
|
||||
"name": s.name,
|
||||
"is_human": s.is_human,
|
||||
"ai_level": s.ai_level,
|
||||
"stack": s.stack,
|
||||
"hole_cards": self._cards_to_list(s.hole_cards),
|
||||
"street_bet": s.street_bet,
|
||||
"total_committed": s.total_committed,
|
||||
"folded": s.folded,
|
||||
"all_in": s.all_in,
|
||||
"acted_this_street": s.acted_this_street,
|
||||
"status_text": s.status_text,
|
||||
"rebought": s.rebought,
|
||||
}
|
||||
for s in self.seats
|
||||
],
|
||||
}
|
||||
|
||||
def load_from_dict(self, data: dict):
|
||||
self.sb = data["sb"]
|
||||
self.bb = data["bb"]
|
||||
self.deck.cards = self._list_to_cards(data["deck_cards"])
|
||||
self.board = self._list_to_cards(data["board"])
|
||||
self.dealer_pos = data["dealer_pos"]
|
||||
self.sb_pos = data.get("sb_pos", -1)
|
||||
self.bb_pos = data.get("bb_pos", -1)
|
||||
self.turn_pos = data["turn_pos"]
|
||||
self.street = data["street"]
|
||||
self.current_bet = data["current_bet"]
|
||||
self.min_raise_delta = data["min_raise_delta"]
|
||||
self.seats = [
|
||||
PokerSeat(
|
||||
seat_id=sd["seat_id"],
|
||||
name=sd["name"],
|
||||
is_human=sd["is_human"],
|
||||
ai_level=sd["ai_level"],
|
||||
stack=sd["stack"],
|
||||
hole_cards=self._list_to_cards(sd["hole_cards"]),
|
||||
street_bet=sd["street_bet"],
|
||||
total_committed=sd["total_committed"],
|
||||
folded=sd["folded"],
|
||||
all_in=sd["all_in"],
|
||||
acted_this_street=sd["acted_this_street"],
|
||||
status_text=sd["status_text"],
|
||||
rebought=sd["rebought"],
|
||||
)
|
||||
for sd in data["seats"]
|
||||
]
|
||||
|
||||
# --- Start einer neuen Hand: Gleicher Grundeinsatz (Ante) für alle wie bei Blackjack! ---
|
||||
def start_hand(self) -> tuple[int, dict[int, tuple[str, int]]]:
|
||||
"""
|
||||
Mischt neu, zieht von JEDEM aktiven Sitz automatisch den Grundeinsatz (self.bb) ein,
|
||||
teilt 2 Hole Cards aus und startet direkt ausgeglichen in Runde 1 (Pre-Flop).
|
||||
"""
|
||||
self.deck.reset(shuffle=True)
|
||||
self.board.clear()
|
||||
self.street = "PREFLOP"
|
||||
self.current_bet = 0
|
||||
self.min_raise_delta = self.bb
|
||||
self.sb_pos = -1
|
||||
self.bb_pos = -1
|
||||
|
||||
active_indices = [i for i, s in enumerate(self.seats) if s.stack > 0]
|
||||
for s in self.seats:
|
||||
s.hole_cards.clear()
|
||||
s.street_bet = 0
|
||||
s.total_committed = 0
|
||||
s.folded = (s.stack <= 0)
|
||||
s.all_in = False
|
||||
s.acted_this_street = False
|
||||
s.status_text = ""
|
||||
|
||||
# Dealer-Button [D] rotiert für die Zugreihenfolge weiter
|
||||
n = len(self.seats)
|
||||
for offset in range(1, n + 1):
|
||||
cand = (self.dealer_pos + offset) % n
|
||||
if cand in active_indices:
|
||||
self.dealer_pos = cand
|
||||
break
|
||||
|
||||
# Jeder aktive Sitz zahlt direkt beim Betreten/Starten der Runde den Grundeinsatz (Ante = self.bb)
|
||||
ante_events: dict[int, tuple[str, int]] = {}
|
||||
max_ante = 0
|
||||
for idx in active_indices:
|
||||
self.seats[idx].hole_cards = [self.deck.draw(), self.deck.draw()]
|
||||
paid = self._commit_chips(self.seats[idx], self.bb)
|
||||
ante_events[idx] = ("ANTE", paid)
|
||||
if paid > max_ante:
|
||||
max_ante = paid
|
||||
|
||||
self.current_bet = max_ante
|
||||
|
||||
# Erster aktiver Spieler links vom Dealer beginnt Runde 1 (oder du selbst)
|
||||
pos_in_active = active_indices.index(self.dealer_pos)
|
||||
first_to_act = active_indices[(pos_in_active + 1) % len(active_indices)]
|
||||
self.turn_pos = first_to_act
|
||||
if not self.seats[self.turn_pos].can_act:
|
||||
self.advance_turn_pointer()
|
||||
|
||||
human_ante = ante_events.get(0, ("", 0))[1]
|
||||
return human_ante, ante_events
|
||||
|
||||
def _commit_chips(self, seat: PokerSeat, amount: int) -> int:
|
||||
amt = max(0, min(int(amount), seat.stack))
|
||||
seat.stack -= amt
|
||||
seat.street_bet += amt
|
||||
seat.total_committed += amt
|
||||
if seat.stack == 0:
|
||||
seat.all_in = True
|
||||
return amt
|
||||
|
||||
# --- Spieler- & Bot-Aktionen ---
|
||||
def apply_action(self, seat_idx: int, action: str, raise_delta: int = 0) -> int:
|
||||
seat = self.seats[seat_idx]
|
||||
to_call = max(0, self.current_bet - seat.street_bet)
|
||||
paid = 0
|
||||
|
||||
if action == "FOLD":
|
||||
seat.folded = True
|
||||
seat.acted_this_street = True
|
||||
return 0
|
||||
|
||||
if action == "CHECK":
|
||||
seat.acted_this_street = True
|
||||
return 0
|
||||
|
||||
if action == "CALL":
|
||||
paid = self._commit_chips(seat, to_call)
|
||||
seat.acted_this_street = True
|
||||
return paid
|
||||
|
||||
if action == "ALLIN":
|
||||
prev_max = self.current_bet
|
||||
paid = self._commit_chips(seat, seat.stack)
|
||||
seat.acted_this_street = True
|
||||
if seat.street_bet > prev_max:
|
||||
raise_diff = seat.street_bet - prev_max
|
||||
if raise_diff >= self.min_raise_delta:
|
||||
self.min_raise_delta = raise_diff
|
||||
self.current_bet = seat.street_bet
|
||||
for idx, other in enumerate(self.seats):
|
||||
if idx != seat_idx and other.can_act:
|
||||
other.acted_this_street = False
|
||||
return paid
|
||||
|
||||
if action == "RAISE":
|
||||
prev_max = self.current_bet
|
||||
desired_total_add = to_call + max(self.min_raise_delta, int(raise_delta))
|
||||
paid = self._commit_chips(seat, desired_total_add)
|
||||
seat.acted_this_street = True
|
||||
if seat.street_bet > prev_max:
|
||||
actual_raise = seat.street_bet - prev_max
|
||||
self.min_raise_delta = max(self.min_raise_delta, actual_raise)
|
||||
self.current_bet = seat.street_bet
|
||||
for idx, other in enumerate(self.seats):
|
||||
if idx != seat_idx and other.can_act:
|
||||
other.acted_this_street = False
|
||||
return paid
|
||||
|
||||
return 0
|
||||
|
||||
# --- Runden- & Straßen-Steuerung ---
|
||||
def active_in_hand_seats(self) -> list[PokerSeat]:
|
||||
return [s for s in self.seats if s.is_in_hand]
|
||||
|
||||
def acting_seats(self) -> list[PokerSeat]:
|
||||
return [s for s in self.seats if s.can_act]
|
||||
|
||||
def only_one_left(self) -> bool:
|
||||
return len(self.active_in_hand_seats()) <= 1
|
||||
|
||||
def is_betting_round_complete(self) -> bool:
|
||||
if self.only_one_left():
|
||||
return True
|
||||
for s in self.seats:
|
||||
if s.can_act:
|
||||
if not s.acted_this_street or s.street_bet < self.current_bet:
|
||||
return False
|
||||
return True
|
||||
|
||||
def should_auto_runout_board(self) -> bool:
|
||||
if self.only_one_left():
|
||||
return False
|
||||
return len(self.acting_seats()) <= 1 and self.is_betting_round_complete()
|
||||
|
||||
def advance_turn_pointer(self) -> int:
|
||||
n = len(self.seats)
|
||||
for offset in range(1, n + 1):
|
||||
cand = (self.turn_pos + offset) % n
|
||||
s = self.seats[cand]
|
||||
if s.can_act and (not s.acted_this_street or s.street_bet < self.current_bet):
|
||||
self.turn_pos = cand
|
||||
return cand
|
||||
return -1
|
||||
|
||||
def advance_to_next_street(self) -> str:
|
||||
for s in self.seats:
|
||||
s.street_bet = 0
|
||||
s.acted_this_street = False
|
||||
|
||||
self.current_bet = 0
|
||||
self.min_raise_delta = self.bb
|
||||
|
||||
if self.street == "PREFLOP":
|
||||
self.street = "FLOP"
|
||||
self.board.extend([self.deck.draw(), self.deck.draw(), self.deck.draw()])
|
||||
elif self.street == "FLOP":
|
||||
self.street = "TURN"
|
||||
self.board.append(self.deck.draw())
|
||||
elif self.street == "TURN":
|
||||
self.street = "RIVER"
|
||||
self.board.append(self.deck.draw())
|
||||
else:
|
||||
self.street = "SHOWDOWN"
|
||||
return self.street
|
||||
|
||||
n = len(self.seats)
|
||||
self.turn_pos = -1
|
||||
for offset in range(1, n + 1):
|
||||
cand = (self.dealer_pos + offset) % n
|
||||
if self.seats[cand].can_act:
|
||||
self.turn_pos = cand
|
||||
break
|
||||
return self.street
|
||||
|
||||
# --- Pot- & Side-Pot-Abrechnung ---
|
||||
def resolve_hand(self) -> dict:
|
||||
self.street = "SHOWDOWN"
|
||||
survivors = self.active_in_hand_seats()
|
||||
human_committed = self.human_seat.total_committed
|
||||
|
||||
if len(survivors) == 1:
|
||||
winner = survivors[0]
|
||||
pot_amt = self.total_pot
|
||||
if not winner.is_human:
|
||||
winner.stack += pot_amt
|
||||
human_payout = pot_amt if winner.is_human else 0
|
||||
human_net = human_payout - human_committed
|
||||
bot_gains = (
|
||||
[(winner.name, pot_amt - winner.total_committed)]
|
||||
if not winner.is_human and (pot_amt - winner.total_committed) > 0
|
||||
else []
|
||||
)
|
||||
return {
|
||||
"by_fold": True,
|
||||
"winner_names": [winner.name],
|
||||
"winning_hand_cat": None,
|
||||
"human_payout": human_payout,
|
||||
"human_net": human_net,
|
||||
"human_won": winner.is_human,
|
||||
"is_split": False,
|
||||
"bot_gains": bot_gains,
|
||||
"hand_ranks": {},
|
||||
}
|
||||
|
||||
scores: dict[int, tuple[int, tuple[int, ...]]] = {}
|
||||
for s in survivors:
|
||||
scores[s.seat_id] = PokerEvaluator.evaluate_best(s.hole_cards + self.board)
|
||||
|
||||
levels = sorted({s.total_committed for s in self.seats if s.total_committed > 0})
|
||||
payouts: dict[int, int] = {s.seat_id: 0 for s in self.seats}
|
||||
main_pot_winners: list[PokerSeat] = []
|
||||
best_overall_cat = 0
|
||||
|
||||
prev_lvl = 0
|
||||
for lvl in levels:
|
||||
slice_delta = lvl - prev_lvl
|
||||
contributors = [s for s in self.seats if s.total_committed >= lvl]
|
||||
slice_pot = slice_delta * len(contributors)
|
||||
eligible = [s for s in contributors if s.is_in_hand]
|
||||
|
||||
if eligible and slice_pot > 0:
|
||||
best_score = max(scores[s.seat_id] for s in eligible)
|
||||
slice_winners = [s for s in eligible if scores[s.seat_id] == best_score]
|
||||
share = slice_pot // len(slice_winners)
|
||||
rem = slice_pot % len(slice_winners)
|
||||
for i, w in enumerate(slice_winners):
|
||||
payouts[w.seat_id] += share + (rem if i == 0 else 0)
|
||||
main_pot_winners = slice_winners
|
||||
best_overall_cat = best_score[0]
|
||||
prev_lvl = lvl
|
||||
|
||||
for s in self.seats:
|
||||
if not s.is_human and payouts[s.seat_id] > 0:
|
||||
s.stack += payouts[s.seat_id]
|
||||
|
||||
human_payout = payouts[0]
|
||||
human_net = human_payout - human_committed
|
||||
bot_gains = [
|
||||
(s.name, payouts[s.seat_id] - s.total_committed)
|
||||
for s in self.seats
|
||||
if not s.is_human and (payouts[s.seat_id] - s.total_committed) > 0
|
||||
]
|
||||
|
||||
winner_names = [w.name for w in main_pot_winners]
|
||||
human_among_winners = any(w.is_human for w in main_pot_winners) or human_net > 0
|
||||
|
||||
return {
|
||||
"by_fold": False,
|
||||
"winner_names": winner_names,
|
||||
"winning_hand_cat": best_overall_cat,
|
||||
"human_payout": human_payout,
|
||||
"human_net": human_net,
|
||||
"human_won": human_among_winners,
|
||||
"is_split": len(main_pot_winners) > 1,
|
||||
"bot_gains": bot_gains,
|
||||
"hand_ranks": {sid: sc[0] for sid, sc in scores.items()},
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/models/poker_evaluator.py
|
||||
from collections import Counter
|
||||
from itertools import combinations
|
||||
from models.card import Card
|
||||
|
||||
RANK_VAL = {
|
||||
"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8,
|
||||
"9": 9, "10": 10, "J": 11, "Q": 12, "K": 13, "A": 14,
|
||||
}
|
||||
|
||||
|
||||
class PokerEvaluator:
|
||||
"""Bewertet 2..7 Karten nach offiziellen Texas Hold'em Hand-Rängen (0..9)."""
|
||||
|
||||
@classmethod
|
||||
def card_val(cls, card: Card) -> int:
|
||||
return RANK_VAL[card.rank]
|
||||
|
||||
@classmethod
|
||||
def evaluate_best(cls, cards: list[Card]) -> tuple[int, tuple[int, ...]]:
|
||||
"""
|
||||
Gibt (category_0_to_9, tiebreaker_tuple) zurück.
|
||||
Größeres Tupel gewinnt immer direkt per Python-Tupelvergleich!
|
||||
"""
|
||||
if len(cards) < 5:
|
||||
return cls._eval_partial(cards)
|
||||
return max(cls._eval_five(combo) for combo in combinations(cards, 5))
|
||||
|
||||
@classmethod
|
||||
def _eval_partial(cls, cards: list[Card]) -> tuple[int, tuple[int, ...]]:
|
||||
vals = sorted((RANK_VAL[c.rank] for c in cards), reverse=True)
|
||||
counts = Counter(vals)
|
||||
ordered = sorted(counts.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)
|
||||
top_cnt = ordered[0][1] if ordered else 0
|
||||
kickers = tuple(v for v, _c in ordered)
|
||||
if top_cnt == 4:
|
||||
return (7, kickers)
|
||||
if top_cnt == 3:
|
||||
return (3, kickers)
|
||||
if top_cnt == 2:
|
||||
if len(ordered) > 1 and ordered[1][1] == 2:
|
||||
return (2, kickers)
|
||||
return (1, kickers)
|
||||
return (0, tuple(vals))
|
||||
|
||||
@classmethod
|
||||
def _eval_five(cls, five_cards: tuple[Card, ...]) -> tuple[int, tuple[int, ...]]:
|
||||
vals = sorted((RANK_VAL[c.rank] for c in five_cards), reverse=True)
|
||||
suits = [c.suit for c in five_cards]
|
||||
is_flush = len(set(suits)) == 1
|
||||
|
||||
is_straight = False
|
||||
straight_high = 0
|
||||
if len(set(vals)) == 5:
|
||||
if vals[0] - vals[4] == 4:
|
||||
is_straight = True
|
||||
straight_high = vals[0]
|
||||
elif vals == [14, 5, 4, 3, 2]:
|
||||
is_straight = True
|
||||
straight_high = 5
|
||||
|
||||
if is_flush and is_straight:
|
||||
if straight_high == 14:
|
||||
return (9, (14,))
|
||||
return (8, (straight_high,))
|
||||
|
||||
counts = Counter(vals)
|
||||
ordered = sorted(counts.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)
|
||||
pattern = [cnt for _val, cnt in ordered]
|
||||
rank_tiebreak = tuple(val for val, _cnt in ordered)
|
||||
|
||||
if pattern == [4, 1]:
|
||||
return (7, rank_tiebreak)
|
||||
if pattern == [3, 2]:
|
||||
return (6, rank_tiebreak)
|
||||
if is_flush:
|
||||
return (5, tuple(vals))
|
||||
if is_straight:
|
||||
return (4, (straight_high,))
|
||||
if pattern == [3, 1, 1]:
|
||||
return (3, rank_tiebreak)
|
||||
if pattern == [2, 2, 1]:
|
||||
return (2, rank_tiebreak)
|
||||
if pattern == [2, 1, 1, 1]:
|
||||
return (1, rank_tiebreak)
|
||||
return (0, tuple(vals))
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/models/poker_seat.py
|
||||
from dataclasses import dataclass, field
|
||||
from models.card import Card
|
||||
|
||||
|
||||
@dataclass
|
||||
class PokerSeat:
|
||||
seat_id: int # 0 = Spieler, 1..5 = Bots
|
||||
name: str
|
||||
is_human: bool
|
||||
ai_level: int = 0
|
||||
stack: int = 1000
|
||||
hole_cards: list[Card] = field(default_factory=list)
|
||||
street_bet: int = 0
|
||||
total_committed: int = 0
|
||||
folded: bool = False
|
||||
all_in: bool = False
|
||||
acted_this_street: bool = False
|
||||
status_text: str = ""
|
||||
rebought: bool = False
|
||||
|
||||
@property
|
||||
def is_in_hand(self) -> bool:
|
||||
return not self.folded and len(self.hole_cards) == 2
|
||||
|
||||
@property
|
||||
def can_act(self) -> bool:
|
||||
return self.is_in_hand and not self.all_in and self.stack > 0
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/start.py
|
||||
from games.poker.views.poker_menu_view import PokerMenuView
|
||||
from games.poker.views.poker_table_view import PokerTableView
|
||||
from models.database import Database
|
||||
from resources.code_res.game_constants import CAT_LUCK, PK_MAX_BOTS
|
||||
from resources.code_res.i18n import t
|
||||
|
||||
GAME_TITLE_KEY = "game_title_poker"
|
||||
GAME_FOLDER_ID = "poker"
|
||||
GAME_CATEGORY = CAT_LUCK
|
||||
|
||||
|
||||
def start_game(context):
|
||||
pid = context.profile["id"]
|
||||
devils_acc = Database.get_active_devils_pk_account(pid)
|
||||
|
||||
if devils_acc is not None:
|
||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
||||
menu_ref = PokerMenuView(context)
|
||||
if saved is not None:
|
||||
PokerTableView(
|
||||
context,
|
||||
variant_key=saved["variant_key"],
|
||||
pk_account_id=devils_acc["id"],
|
||||
bot_configs=[],
|
||||
on_back_to_menu=lambda acc_id, msg="": menu_ref.show(preselect_id=acc_id, status_msg=msg),
|
||||
resume_state_json=saved["state_json"],
|
||||
)
|
||||
else:
|
||||
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
|
||||
active_bots = [(lvl, name) for _idx, (name, lvl) in sorted(saved_bots.items()) if lvl >= 0][:PK_MAX_BOTS]
|
||||
if not active_bots:
|
||||
active_bots = [(2, t("bot_default_name", 1))]
|
||||
PokerTableView(
|
||||
context,
|
||||
variant_key="poker_holdem",
|
||||
pk_account_id=devils_acc["id"],
|
||||
bot_configs=active_bots,
|
||||
on_back_to_menu=lambda acc_id, msg="": menu_ref.show(preselect_id=acc_id, status_msg=msg),
|
||||
)
|
||||
return
|
||||
|
||||
Database.delete_game_state(pid, GAME_FOLDER_ID)
|
||||
PokerMenuView(context).show()
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,452 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/views/poker_menu_view.py
|
||||
import sqlite3
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
from games.poker.views.poker_stats_view import PokerStatsView
|
||||
from games.poker.views.poker_table_view import PokerTableView
|
||||
from models.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, CELL_BG,
|
||||
DEVILS_DEAL_GOLD_REWARD, ERROR_FG, FG_COLOR, GOLD_MAX_ACCOUNTS,
|
||||
INPUT_BG, MUTED_FG, PANEL_BG, PK_MAX_BOTS, PK_STARTING_GOLD,
|
||||
PK_VARIANTS, SUBTLE_BORDER, XP_TO_GOLD_AMOUNT
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.bot_setup_widget import BotSetupWidget
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
GAME_FOLDER_ID = "poker"
|
||||
|
||||
|
||||
class PokerMenuView:
|
||||
def __init__(self, context):
|
||||
self.ctx = context
|
||||
self.bot_widget: BotSetupWidget | None = None
|
||||
|
||||
def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False):
|
||||
pid = self.ctx.profile["id"]
|
||||
|
||||
devils_acc = Database.get_active_devils_pk_account(pid)
|
||||
if devils_acc is not None:
|
||||
saved = Database.load_game_state(pid, GAME_FOLDER_ID)
|
||||
if saved is not None:
|
||||
PokerTableView(
|
||||
self.ctx,
|
||||
variant_key=saved["variant_key"],
|
||||
pk_account_id=devils_acc["id"],
|
||||
bot_configs=[],
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
||||
resume_state_json=saved["state_json"],
|
||||
)
|
||||
return
|
||||
|
||||
self.ctx.sounds.play_menu_music()
|
||||
self.ctx.root.clear_window(apply_global_bg=True)
|
||||
pk_prog = self.ctx.refresh_game_progress()
|
||||
|
||||
dyn_xp_cost = pk_prog["xp_exchange_cost"]
|
||||
is_divine = pk_prog["is_divine_punishment"]
|
||||
at_floor = pk_prog["at_divine_floor"]
|
||||
devils_deal_open = pk_prog["devils_deal_unlocked"]
|
||||
|
||||
setting_key = f"last_pk_account_{pid}"
|
||||
accounts = Database.get_poker_accounts(pid)
|
||||
has_accounts = len(accounts) > 0
|
||||
|
||||
if preselect_id is None and has_accounts:
|
||||
saved_id_str = Database.load_setting(setting_key, "")
|
||||
if saved_id_str.isdigit():
|
||||
preselect_id = int(saved_id_str)
|
||||
|
||||
acc_by_name = {a["account_name"]: a for a in accounts}
|
||||
acc_names = list(acc_by_name.keys())
|
||||
|
||||
active_acc = None
|
||||
if has_accounts:
|
||||
active_acc = accounts[0]
|
||||
if preselect_id is not None:
|
||||
for a in accounts:
|
||||
if a["id"] == preselect_id:
|
||||
active_acc = a
|
||||
break
|
||||
Database.save_setting(setting_key, str(active_acc["id"]))
|
||||
|
||||
selected_name_var = tk.StringVar(
|
||||
value=active_acc["account_name"] if active_acc else t("bj_no_account_item")
|
||||
)
|
||||
feedback_var = tk.StringVar(value=status_msg)
|
||||
|
||||
def get_current_acc() -> dict | None:
|
||||
return acc_by_name.get(selected_name_var.get())
|
||||
|
||||
def open_pk_stats():
|
||||
cur = get_current_acc()
|
||||
if cur is None:
|
||||
return
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
PokerStatsView(
|
||||
self.ctx,
|
||||
on_back_to_pk_menu=lambda aid: self.show(preselect_id=aid)
|
||||
).show(selected_acc_id=cur["id"])
|
||||
|
||||
def refresh_on_lang_switch():
|
||||
cur = get_current_acc()
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
self.show(preselect_id=cur["id"] if cur else None)
|
||||
|
||||
topbar_gold_txt = (
|
||||
t("pk_header_gold", active_acc["account_name"], active_acc["gold"])
|
||||
if active_acc else ""
|
||||
)
|
||||
topbar = self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t("pk_menu_topbar"),
|
||||
on_game_menu=None,
|
||||
on_stats=open_pk_stats,
|
||||
stats_enabled=has_accounts,
|
||||
extra_right_text=topbar_gold_txt,
|
||||
on_lang_refresh=refresh_on_lang_switch,
|
||||
)
|
||||
|
||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=12)
|
||||
container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.93, relheight=0.85)
|
||||
|
||||
main_card = tk.Frame(
|
||||
container, bg=PANEL_BG, padx=24, pady=16,
|
||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
||||
)
|
||||
main_card.pack(fill="x")
|
||||
|
||||
upper_split = tk.Frame(main_card, bg=PANEL_BG)
|
||||
upper_split.pack(fill="x", pady=(0, 10))
|
||||
upper_split.columnconfigure(0, weight=1, uniform="cols")
|
||||
upper_split.columnconfigure(1, weight=1, uniform="cols")
|
||||
|
||||
# =====================================================================
|
||||
# SPALTE 1: Poker-Goldkonto
|
||||
# =====================================================================
|
||||
left_col = tk.Frame(upper_split, bg=PANEL_BG)
|
||||
left_col.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
|
||||
|
||||
tk.Label(
|
||||
left_col,
|
||||
text=t("pk_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, PK_STARTING_GOLD),
|
||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
|
||||
).pack(anchor="w", pady=(0, 6))
|
||||
|
||||
acc_box = tk.Frame(left_col, bg=CELL_BG, padx=14, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
|
||||
acc_box.pack(fill="both", expand=True)
|
||||
|
||||
form_grid = tk.Frame(acc_box, bg=CELL_BG)
|
||||
form_grid.pack(fill="x")
|
||||
form_grid.columnconfigure(1, weight=1)
|
||||
|
||||
lbl_w = max(len(t("bj_active_acc_lbl")), len(t("bj_new_acc_lbl")))
|
||||
tk.Label(
|
||||
form_grid, text=t("bj_active_acc_lbl"), width=lbl_w, anchor="w",
|
||||
font=("Helvetica", 10, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
|
||||
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
|
||||
|
||||
acc_cb = ttk.Combobox(
|
||||
form_grid,
|
||||
textvariable=selected_name_var,
|
||||
values=acc_names if has_accounts else [t("bj_no_account_item")],
|
||||
state="readonly" if has_accounts else "disabled",
|
||||
font=("Helvetica", 10),
|
||||
style="Goth.TCombobox",
|
||||
)
|
||||
acc_cb.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=2)
|
||||
|
||||
def exchange_xp_action():
|
||||
cur = get_current_acc()
|
||||
if cur is None:
|
||||
return
|
||||
if self.bot_widget is not None:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
ok, msg = Database.exchange_xp_for_pk_gold(pid, cur["id"])
|
||||
if ok and is_divine:
|
||||
self.ctx.sounds.play("lose")
|
||||
self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok)
|
||||
|
||||
can_afford_xp = is_divine or (pk_prog["total_points"] >= dyn_xp_cost)
|
||||
can_exchange = has_accounts and (not at_floor) and can_afford_xp
|
||||
|
||||
ex_btn_txt = (
|
||||
t("bj_exchange_divine_btn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
||||
if is_divine else t("bj_exchange_btn", dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||
)
|
||||
ImageButton(
|
||||
form_grid, ex_btn_txt,
|
||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
||||
exchange_xp_action, sound_mgr=self.ctx.sounds,
|
||||
width=185, height=34, font=("Helvetica", 9, "bold"),
|
||||
enabled=can_exchange,
|
||||
).grid(row=0, column=2, sticky="e", pady=4)
|
||||
|
||||
# Prominente Gold-Anzeige
|
||||
gold_banner = tk.Frame(
|
||||
acc_box, bg=PANEL_BG, padx=12, pady=8,
|
||||
highlightthickness=1, highlightbackground=BORDER_COLOR if has_accounts else SUBTLE_BORDER
|
||||
)
|
||||
gold_banner.pack(fill="x", pady=(8, 8))
|
||||
|
||||
gold_var = tk.StringVar(
|
||||
value=t("bj_gold_display_lbl", active_acc["gold"]) if active_acc else t("bj_gold_display_none")
|
||||
)
|
||||
tk.Label(
|
||||
gold_banner, textvariable=gold_var,
|
||||
font=("Georgia", 13, "bold"),
|
||||
fg=ACCENT_GOLD if active_acc else MUTED_FG,
|
||||
bg=PANEL_BG,
|
||||
).pack(side="left")
|
||||
|
||||
def delete_selected_account():
|
||||
cur = get_current_acc()
|
||||
if cur is not None:
|
||||
Database.delete_poker_account(cur["id"])
|
||||
self.show()
|
||||
|
||||
ImageButton(
|
||||
gold_banner, t("bj_delete_acc_btn"),
|
||||
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
|
||||
delete_selected_account, sound_mgr=self.ctx.sounds,
|
||||
width=120, height=30, font=("Helvetica", 9, "bold"),
|
||||
enabled=has_accounts,
|
||||
).pack(side="right")
|
||||
|
||||
# Neues Konto anlegen (exakt gleiche Spaltenbreite)
|
||||
create_grid = tk.Frame(acc_box, bg=CELL_BG)
|
||||
create_grid.pack(fill="x")
|
||||
create_grid.columnconfigure(1, weight=1)
|
||||
|
||||
can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS
|
||||
tk.Label(
|
||||
create_grid, text=t("bj_new_acc_lbl"), width=lbl_w, anchor="w",
|
||||
font=("Helvetica", 10, "bold" if not has_accounts else "normal"),
|
||||
fg=ACCENT_GOLD if not has_accounts else (FG_COLOR if can_create_more else MUTED_FG),
|
||||
bg=CELL_BG,
|
||||
).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4)
|
||||
|
||||
next_idx = len(accounts) + 1
|
||||
new_acc_var = tk.StringVar(
|
||||
value=t("pk_default_acc_name", next_idx) if can_create_more else t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)
|
||||
)
|
||||
new_entry = tk.Entry(
|
||||
create_grid, textvariable=new_acc_var, font=("Helvetica", 10),
|
||||
bg=INPUT_BG, fg=FG_COLOR, disabledbackground="#16141c", disabledforeground="#666070",
|
||||
bd=0, highlightthickness=1, highlightbackground=ACCENT_GOLD if not has_accounts else BORDER_COLOR,
|
||||
insertbackground="white", state="normal" if can_create_more else "disabled"
|
||||
)
|
||||
new_entry.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=5)
|
||||
|
||||
def create_new_account():
|
||||
if not can_create_more:
|
||||
return
|
||||
name = new_acc_var.get().strip()
|
||||
if not name:
|
||||
feedback_var.set(t("bj_err_empty_name"))
|
||||
return
|
||||
try:
|
||||
if self.bot_widget is not None and has_accounts:
|
||||
_, to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
created = Database.create_poker_account(pid, name)
|
||||
Database.save_setting(setting_key, str(created["id"]))
|
||||
self.show(preselect_id=created["id"])
|
||||
except (sqlite3.IntegrityError, RuntimeError) as exc:
|
||||
feedback_var.set(t("pk_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc))
|
||||
|
||||
if can_create_more:
|
||||
new_entry.bind("<Return>", lambda _e: create_new_account())
|
||||
|
||||
ImageButton(
|
||||
create_grid, t("bj_create_acc_btn", PK_STARTING_GOLD),
|
||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
||||
create_new_account, sound_mgr=self.ctx.sounds,
|
||||
width=185, height=34, font=("Helvetica", 9, "bold"),
|
||||
enabled=can_create_more,
|
||||
).grid(row=0, column=2, sticky="e", pady=4)
|
||||
|
||||
# Info / Divine Punishment / The Devil's Deal (Poker-autark!)
|
||||
min_sac_lvl = Progression.get_devils_deal_min_level()
|
||||
classic_cfg = PK_VARIANTS["poker_holdem"]
|
||||
if devils_deal_open and has_accounts:
|
||||
tk.Label(
|
||||
acc_box,
|
||||
text=t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
|
||||
font=("Helvetica", 8, "bold"), fg=ERROR_FG, bg=CELL_BG, wraplength=480, justify="left"
|
||||
).pack(anchor="w", pady=(6, 4))
|
||||
|
||||
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID)
|
||||
if sac_candidates:
|
||||
devil_row = tk.Frame(acc_box, bg=CELL_BG)
|
||||
devil_row.pack(fill="x", pady=(2, 0))
|
||||
sac_map = {f"{c['name']} ({c['title']} • Lv. {c['level']})": c["id"] for c in sac_candidates}
|
||||
sac_var = tk.StringVar(value=next(iter(sac_map.keys())))
|
||||
ttk.Combobox(
|
||||
devil_row, textvariable=sac_var, values=list(sac_map.keys()),
|
||||
state="readonly", font=("Helvetica", 9), width=26, style="Goth.TCombobox"
|
||||
).pack(side="left", fill="x", expand=True, padx=(0, 8))
|
||||
|
||||
def seal_devils_deal():
|
||||
cur = get_current_acc()
|
||||
victim_id = sac_map.get(sac_var.get())
|
||||
if cur is None or victim_id is None:
|
||||
return
|
||||
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
|
||||
if not active_bots:
|
||||
feedback_var.set(t("pk_err_need_one_bot"))
|
||||
return
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
|
||||
ok, _msg = Database.execute_devils_deal(pid, GAME_FOLDER_ID, victim_id, cur["id"])
|
||||
if ok:
|
||||
self.ctx.sounds.play("end_battle")
|
||||
PokerTableView(
|
||||
self.ctx,
|
||||
variant_key="poker_holdem",
|
||||
pk_account_id=cur["id"],
|
||||
bot_configs=active_bots,
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
|
||||
)
|
||||
|
||||
ImageButton(
|
||||
devil_row, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
|
||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
||||
seal_devils_deal, sound_mgr=None, width=185, height=32, font=("Helvetica", 9, "bold")
|
||||
).pack(side="right")
|
||||
else:
|
||||
tk.Label(
|
||||
acc_box, text=t("bj_devils_deal_none", min_sac_lvl),
|
||||
font=("Helvetica", 8), fg=MUTED_FG, bg=CELL_BG
|
||||
).pack(anchor="w")
|
||||
else:
|
||||
info_text = (
|
||||
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
|
||||
if is_divine
|
||||
else t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic_cfg["sb"], classic_cfg["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
|
||||
)
|
||||
tk.Label(
|
||||
acc_box, text=info_text,
|
||||
font=("Helvetica", 8, "bold" if is_divine else "normal"),
|
||||
fg=ERROR_FG if is_divine else MUTED_FG,
|
||||
bg=CELL_BG, wraplength=480, justify="left"
|
||||
).pack(anchor="w", pady=(6, 0))
|
||||
|
||||
# =====================================================================
|
||||
# SPALTE 2: 6-Max Gegner-Setup (1 bis 5 Bots)
|
||||
# =====================================================================
|
||||
right_col = tk.Frame(upper_split, bg=PANEL_BG)
|
||||
right_col.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
|
||||
|
||||
tk.Label(
|
||||
right_col, text=t("pk_bots_sec_title"),
|
||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
|
||||
).pack(anchor="w", pady=(0, 6))
|
||||
|
||||
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
|
||||
if not saved_bots:
|
||||
# Komfort-Default beim allerersten Poker-Besuch: 2 solide Gegner voreingestellt
|
||||
saved_bots = {
|
||||
0: (t("bot_default_name", 1), 1),
|
||||
1: (t("bot_default_name", 2), 2),
|
||||
}
|
||||
self.bot_widget = BotSetupWidget(right_col, saved_bots, max_bots=PK_MAX_BOTS, enabled=has_accounts)
|
||||
self.bot_widget.pack(fill="both", expand=True)
|
||||
|
||||
fb_lbl = tk.Label(
|
||||
main_card, textvariable=feedback_var,
|
||||
font=("Helvetica", 9, "bold"),
|
||||
fg="#7be08a" if status_is_ok else ERROR_FG,
|
||||
bg=PANEL_BG
|
||||
)
|
||||
fb_lbl.pack(anchor="w", pady=(2, 4))
|
||||
|
||||
# =====================================================================
|
||||
# SEKTION 3: Tischvariante wählen
|
||||
# =====================================================================
|
||||
tk.Label(
|
||||
main_card, text=t("pk_sec3_title"),
|
||||
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
|
||||
).pack(anchor="w", pady=(2, 8))
|
||||
|
||||
def enter_table(v_key: str):
|
||||
fb_lbl.configure(fg=ERROR_FG)
|
||||
cur = get_current_acc()
|
||||
if not cur:
|
||||
return
|
||||
acc = Database.get_poker_account(cur["id"])
|
||||
if not acc:
|
||||
return
|
||||
Database.save_setting(setting_key, str(acc["id"]))
|
||||
active_bots, configs_to_save = self.bot_widget.collect_configs()
|
||||
Database.save_bot_configs(pid, GAME_FOLDER_ID, configs_to_save)
|
||||
|
||||
if not active_bots:
|
||||
feedback_var.set(t("pk_err_need_one_bot"))
|
||||
return
|
||||
|
||||
min_req = PK_VARIANTS[v_key]["min_entry"]
|
||||
cur_pk_prog = self.ctx.refresh_game_progress()
|
||||
if acc["gold"] < min_req:
|
||||
feedback_var.set(t(
|
||||
"bj_err_not_enough_gold_entry",
|
||||
acc["account_name"], min_req, acc["gold"],
|
||||
cur_pk_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT
|
||||
))
|
||||
return
|
||||
|
||||
PokerTableView(
|
||||
self.ctx, v_key, acc["id"], active_bots,
|
||||
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg)
|
||||
)
|
||||
|
||||
variants_row = tk.Frame(main_card, bg=PANEL_BG)
|
||||
variants_row.pack(fill="x")
|
||||
for idx in range(len(PK_VARIANTS)):
|
||||
variants_row.columnconfigure(idx, weight=1)
|
||||
|
||||
table_buttons: list[tuple[str, ImageButton]] = []
|
||||
for idx, (v_key, cfg) in enumerate(PK_VARIANTS.items()):
|
||||
card = tk.Frame(variants_row, bg=CELL_BG, padx=16, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
|
||||
card.grid(row=0, column=idx, padx=(0, 8) if idx == 0 else (8, 0), sticky="nsew")
|
||||
|
||||
tk.Label(
|
||||
card, text=t(f"variant_{v_key}"),
|
||||
font=("Georgia", 12, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
|
||||
).pack(anchor="w")
|
||||
tk.Label(
|
||||
card, text=t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"]),
|
||||
font=("Helvetica", 9), fg=MUTED_FG, bg=CELL_BG
|
||||
).pack(anchor="w", pady=(4, 10))
|
||||
|
||||
can_play_v = bool(active_acc and active_acc["gold"] >= cfg["min_entry"])
|
||||
t_btn = ImageButton(
|
||||
card, t("bj_enter_table_btn"),
|
||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
||||
lambda k=v_key: enter_table(k),
|
||||
sound_mgr=self.ctx.sounds, width=160, height=36,
|
||||
font=("Helvetica", 10, "bold"), enabled=can_play_v,
|
||||
)
|
||||
t_btn.pack(anchor="e")
|
||||
table_buttons.append((v_key, t_btn))
|
||||
|
||||
def on_account_switched(*_):
|
||||
cur = get_current_acc()
|
||||
if cur is not None:
|
||||
fresh = Database.get_poker_account(cur["id"])
|
||||
Database.save_setting(setting_key, str(fresh["id"]))
|
||||
gold_var.set(t("bj_gold_display_lbl", fresh["gold"]))
|
||||
topbar.extra_label.configure(text=t("pk_header_gold", fresh["account_name"], fresh["gold"]))
|
||||
for v_k, tb in table_buttons:
|
||||
tb.set_enabled(fresh["gold"] >= PK_VARIANTS[v_k]["min_entry"])
|
||||
feedback_var.set("")
|
||||
|
||||
acc_cb.bind("<<ComboboxSelected>>", on_account_switched)
|
||||
|
|
@ -0,0 +1,204 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/views/poker_result_dialog.py
|
||||
import tkinter as tk
|
||||
from models.card import Card
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD, ACCENT_GOTH, CELL_BG, ERROR_FG,
|
||||
FG_COLOR, MODAL_BG, MUTED_FG, SUBTLE_BORDER
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.image_button import ImageButton
|
||||
|
||||
POPUP_GIF_SIZE = (145, 80)
|
||||
POPUP_HOLE_CARD_SIZE = (48, 70)
|
||||
POPUP_BOARD_CARD_SIZE = (44, 64)
|
||||
|
||||
|
||||
class PokerResultDialog(tk.Frame):
|
||||
"""Ergebnis-Overlay im einheitlichen BlackjackResultDialog-Stil inkl. Kartenbild-Showdown."""
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
assets,
|
||||
sounds,
|
||||
result_data: dict,
|
||||
on_next_round,
|
||||
on_back_to_menu,
|
||||
):
|
||||
super().__init__(
|
||||
parent, bg=MODAL_BG, padx=26, pady=18,
|
||||
highlightthickness=2, highlightbackground=ACCENT_GOTH
|
||||
)
|
||||
self.assets = assets
|
||||
self.sounds = sounds
|
||||
self.data = result_data
|
||||
self.on_next_round = on_next_round
|
||||
self.on_back_to_menu = on_back_to_menu
|
||||
self._gif_job = None
|
||||
self._card_photos = []
|
||||
|
||||
self.place(relx=0.5, rely=0.5, anchor="center")
|
||||
self.lift()
|
||||
self._build()
|
||||
|
||||
def _build(self):
|
||||
self.gif_lbl = tk.Label(self, bg=MODAL_BG, bd=0)
|
||||
self.gif_lbl.pack(pady=(0, 4))
|
||||
|
||||
p_won = self.data.get("player_won")
|
||||
if p_won is True:
|
||||
self._start_gif("win_gif")
|
||||
elif p_won is False:
|
||||
self._start_gif("lose_gif")
|
||||
|
||||
headline_color = ACCENT_GOLD if p_won else (
|
||||
MUTED_FG if p_won is None else ERROR_FG
|
||||
)
|
||||
tk.Label(
|
||||
self, text=self.data["headline"],
|
||||
font=("Georgia", 16, "bold"), fg=headline_color, bg=MODAL_BG,
|
||||
wraplength=680, justify="center"
|
||||
).pack(pady=(2, 10))
|
||||
|
||||
# --- Karten-Aufdeckung: Gemeinschaftskarten + alle Sitze mit Kartenbildern ---
|
||||
reveal_box = tk.Frame(
|
||||
self, bg=CELL_BG, padx=12, pady=8,
|
||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
reveal_box.pack(fill="x", pady=(0, 10))
|
||||
|
||||
board_raw = self.data.get("board_cards", [])
|
||||
if board_raw:
|
||||
b_row = tk.Frame(reveal_box, bg=CELL_BG)
|
||||
b_row.pack(pady=(0, 6))
|
||||
tk.Label(
|
||||
b_row, text=f"{t('pk_board_title')}:",
|
||||
font=("Georgia", 9, "bold"), fg=MUTED_FG, bg=CELL_BG
|
||||
).pack(side="left", padx=(0, 8))
|
||||
|
||||
for s_suit, s_rank in board_raw:
|
||||
c_obj = Card(s_suit, s_rank)
|
||||
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_BOARD_CARD_SIZE)
|
||||
if ph:
|
||||
self._card_photos.append(ph)
|
||||
tk.Label(b_row, image=ph, bg=CELL_BG, bd=0).pack(side="left", padx=2)
|
||||
|
||||
tk.Frame(reveal_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(2, 6))
|
||||
|
||||
seats_row = tk.Frame(reveal_box, bg=CELL_BG)
|
||||
seats_row.pack()
|
||||
|
||||
for idx, entry in enumerate(self.data.get("seat_showdown", [])):
|
||||
is_win = entry["is_winner"]
|
||||
folded = entry["folded"]
|
||||
|
||||
border_c = ACCENT_GOLD if is_win else (SUBTLE_BORDER if not folded else "#3a252a")
|
||||
s_card = tk.Frame(
|
||||
seats_row, bg="#191521", padx=8, pady=5,
|
||||
highlightthickness=2 if is_win else 1, highlightbackground=border_c
|
||||
)
|
||||
s_card.grid(row=idx // 6, column=idx % 6, padx=4, pady=2, sticky="nsew")
|
||||
|
||||
name_col = ACCENT_GOLD if is_win else (MUTED_FG if folded else ACCENT_GOTH)
|
||||
tk.Label(
|
||||
s_card, text=entry["name"],
|
||||
font=("Georgia", 9, "bold"), fg=name_col, bg="#191521"
|
||||
).pack()
|
||||
|
||||
c_frame = tk.Frame(s_card, bg="#191521", height=POPUP_HOLE_CARD_SIZE[1] + 2)
|
||||
c_frame.pack(pady=3)
|
||||
for s_suit, s_rank in entry["cards"]:
|
||||
c_obj = Card(s_suit, s_rank)
|
||||
ph = self.assets.get_card_photo(c_obj.image_filename, size=POPUP_HOLE_CARD_SIZE)
|
||||
if ph:
|
||||
self._card_photos.append(ph)
|
||||
tk.Label(c_frame, image=ph, bg="#191521", bd=0).pack(side="left", padx=1)
|
||||
|
||||
combo_col = "#7be08a" if is_win else (ERROR_FG if folded else FG_COLOR)
|
||||
tk.Label(
|
||||
s_card, text=entry["combo_text"],
|
||||
font=("Helvetica", 8, "bold"), fg=combo_col, bg="#191521",
|
||||
wraplength=112, justify="center"
|
||||
).pack()
|
||||
|
||||
# --- Gewinn / Verlust & XP Box (identisch zu BlackjackResultDialog) ---
|
||||
info_box = tk.Frame(
|
||||
self, bg=CELL_BG, padx=20, pady=10,
|
||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
info_box.pack(fill="x", pady=(0, 12))
|
||||
|
||||
p_net = self.data["player_net"]
|
||||
if p_net > 0:
|
||||
own_txt, own_col = t("bj_popup_your_gain", p_net), "#7be08a"
|
||||
elif p_net < 0:
|
||||
own_txt, own_col = t("bj_popup_your_loss", abs(p_net)), ERROR_FG
|
||||
else:
|
||||
own_txt, own_col = t("bj_popup_your_even"), FG_COLOR
|
||||
|
||||
tk.Label(info_box, text=own_txt, font=("Helvetica", 11, "bold"), fg=own_col, bg=CELL_BG).pack(pady=2)
|
||||
|
||||
for extra_line in self.data.get("other_gains", []):
|
||||
tk.Label(info_box, text=extra_line, font=("Helvetica", 10), fg=MUTED_FG, bg=CELL_BG).pack(pady=1)
|
||||
|
||||
tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=8)
|
||||
|
||||
tk.Label(
|
||||
info_box, text=t("bj_popup_xp_earned", self.data["xp_gained"]),
|
||||
font=("Helvetica", 11, "bold"), fg=ACCENT_GOTH, bg=CELL_BG,
|
||||
).pack(pady=1)
|
||||
|
||||
if self.data.get("new_level_title"):
|
||||
tk.Label(
|
||||
info_box, text=self.data["new_level_title"],
|
||||
font=("Georgia", 11, "bold"), fg=ACCENT_GOLD, bg=CELL_BG,
|
||||
).pack(pady=(3, 0))
|
||||
|
||||
# --- Buttons ---
|
||||
btn_row = tk.Frame(self, bg=MODAL_BG)
|
||||
btn_row.pack(fill="x", pady=(4, 0))
|
||||
|
||||
if self.data.get("can_continue", True):
|
||||
ImageButton(
|
||||
btn_row, t("bj_popup_next_round_btn"),
|
||||
self.assets.raw_btn, self.assets.raw_btn_active,
|
||||
self._handle_next, sound_mgr=self.sounds, width=200, height=40, font=("Helvetica", 10, "bold")
|
||||
).pack(side="left", padx=(0, 10))
|
||||
|
||||
if self.data.get("can_leave_menu", True):
|
||||
ImageButton(
|
||||
btn_row, t("bj_popup_to_menu_btn"),
|
||||
self.assets.raw_sel, self.assets.raw_sel_active,
|
||||
self._handle_menu, sound_mgr=self.sounds, width=170, height=40, font=("Helvetica", 10, "bold")
|
||||
).pack(side="right")
|
||||
|
||||
def _start_gif(self, key: str):
|
||||
frames = self.assets.get_gif_frames(key, size=POPUP_GIF_SIZE)
|
||||
if not frames:
|
||||
return
|
||||
|
||||
def _step(idx=0):
|
||||
if not self.gif_lbl.winfo_exists():
|
||||
return
|
||||
self.gif_lbl.configure(image=frames[idx])
|
||||
self._gif_job = self.after(90, _step, (idx + 1) % len(frames))
|
||||
|
||||
_step(0)
|
||||
|
||||
def close_dialog(self):
|
||||
if self._gif_job:
|
||||
try:
|
||||
self.after_cancel(self._gif_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._gif_job = None
|
||||
if self.winfo_exists():
|
||||
self.destroy()
|
||||
|
||||
def _handle_next(self):
|
||||
self.close_dialog()
|
||||
self.on_next_round()
|
||||
|
||||
def _handle_menu(self):
|
||||
self.close_dialog()
|
||||
self.on_back_to_menu()
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/views/poker_stats_view.py
|
||||
import tkinter as tk
|
||||
from models.database import Database
|
||||
from resources.code_res.game_constants import ACCENT_GOLD, BG_COLOR, BORDER_COLOR, PANEL_BG
|
||||
from resources.code_res.i18n import t
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.stats_board_widget import StatsBoardWidget
|
||||
|
||||
GAME_FOLDER_ID = "poker"
|
||||
|
||||
|
||||
class PokerStatsView:
|
||||
"""Dedizierte Statistik-Ansicht für die einzelnen Poker-Goldbeutel."""
|
||||
def __init__(self, context, on_back_to_pk_menu):
|
||||
self.ctx = context
|
||||
self.on_back_to_pk_menu = on_back_to_pk_menu
|
||||
|
||||
def show(self, selected_acc_id: int | None = None):
|
||||
self.ctx.root.clear_window(apply_global_bg=True)
|
||||
pid = self.ctx.profile["id"]
|
||||
accounts = Database.get_poker_accounts(pid)
|
||||
|
||||
if not accounts:
|
||||
self.on_back_to_pk_menu(None)
|
||||
return
|
||||
|
||||
active_acc = accounts[0]
|
||||
if selected_acc_id is not None:
|
||||
for a in accounts:
|
||||
if a["id"] == selected_acc_id:
|
||||
active_acc = a
|
||||
break
|
||||
|
||||
self.ctx.build_game_topbar(
|
||||
self.ctx.root,
|
||||
t("pk_stats_view_topbar"),
|
||||
on_game_menu=lambda: self.on_back_to_pk_menu(active_acc["id"]),
|
||||
extra_right_text=t("pk_header_gold", active_acc["account_name"], active_acc["gold"]),
|
||||
on_lang_refresh=lambda: self.show(active_acc["id"]),
|
||||
)
|
||||
|
||||
container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=18)
|
||||
container.place(relx=0.5, rely=0.54, anchor="center", relwidth=0.88, relheight=0.82)
|
||||
|
||||
selector_panel = tk.Frame(
|
||||
container, bg=PANEL_BG, padx=18, pady=14,
|
||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
||||
)
|
||||
selector_panel.pack(fill="x", pady=(0, 16))
|
||||
|
||||
tk.Label(
|
||||
selector_panel, text=t("bj_stats_select_acc_lbl"),
|
||||
font=("Georgia", 13, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
|
||||
).pack(anchor="w", pady=(0, 10))
|
||||
|
||||
tabs_row = tk.Frame(selector_panel, bg=PANEL_BG)
|
||||
tabs_row.pack(fill="x")
|
||||
|
||||
for acc in accounts:
|
||||
is_sel = (acc["id"] == active_acc["id"])
|
||||
pil_norm = self.ctx.assets.raw_btn if is_sel else self.ctx.assets.raw_sel
|
||||
pil_hov = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active
|
||||
btn_lbl = f"{acc['account_name']} ({acc['gold']}g)"
|
||||
|
||||
ImageButton(
|
||||
tabs_row, btn_lbl, pil_norm, pil_hov,
|
||||
lambda aid=acc["id"]: self.show(selected_acc_id=aid),
|
||||
sound_mgr=self.ctx.sounds, width=185, height=38, font=("Helvetica", 9, "bold")
|
||||
).pack(side="left", padx=(0, 8))
|
||||
|
||||
pk_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID)
|
||||
pk_filter_map = {t("pk_filter_all_tables"): None}
|
||||
for v in pk_variants:
|
||||
pk_filter_map[v["translated_name"]] = v["id"]
|
||||
|
||||
board = StatsBoardWidget(
|
||||
container,
|
||||
title=t("bj_stats_acc_title", active_acc["account_name"]),
|
||||
filter_map=pk_filter_map,
|
||||
fetch_callback=lambda vid: Database.get_pk_account_stats_overview(active_acc["id"], vid)
|
||||
)
|
||||
board.pack(fill="x")
|
||||
|
|
@ -0,0 +1,997 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# games/poker/views/poker_table_view.py
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
import tkinter as tk
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
from games.poker.models.poker_bot_ai import PokerBotAI
|
||||
from games.poker.models.poker_engine import PokerEngine
|
||||
from games.poker.models.poker_evaluator import PokerEvaluator
|
||||
from games.poker.models.poker_seat import PokerSeat
|
||||
from games.poker.views.poker_result_dialog import PokerResultDialog
|
||||
from models.database import Database
|
||||
from models.progression import Progression
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD, ACCENT_GOTH, BORDER_COLOR, CELL_BG, ERROR_FG,
|
||||
FG_COLOR, MUTED_FG, PANEL_BG, PK_BOT_TURN_DELAY_MS,
|
||||
PK_STARTING_GOLD, PK_STREET_DELAY_MS, PK_TABLE_IMAGE,
|
||||
PK_VARIANTS, PLAYING_CARD_SIZE, RED_SUITS, SUBTLE_BORDER,
|
||||
SUIT_SYMBOLS, TABLE_BG, XP_TO_GOLD_AMOUNT
|
||||
)
|
||||
from resources.code_res.i18n import get_lang, t
|
||||
from view.widgets.image_button import ImageButton
|
||||
from view.widgets.info_badge import InfoBadge
|
||||
|
||||
GAME_FOLDER_ID = "poker"
|
||||
IMAGES_DIR = Path(__file__).resolve().parents[3] / "resources" / "images"
|
||||
|
||||
PK_OVAL_BOARD_CARD = (76, 112)
|
||||
|
||||
OVAL_BOT_COORDS = (
|
||||
(0.155, 0.77), # Platz 1: Unten links
|
||||
(0.155, 0.23), # Platz 2: Oben links
|
||||
(0.500, 0.14), # Platz 3: Oben Mitte
|
||||
(0.845, 0.23), # Platz 4: Oben rechts
|
||||
(0.845, 0.77), # Platz 5: Unten rechts
|
||||
)
|
||||
|
||||
SEAT_LAYOUT_BY_COUNT = {
|
||||
1: (2,),
|
||||
2: (1, 3),
|
||||
3: (1, 2, 3),
|
||||
4: (0, 1, 3, 4),
|
||||
5: (0, 1, 2, 3, 4),
|
||||
}
|
||||
|
||||
HAND_REFERENCE_EXAMPLES = (
|
||||
(1, 9, (("A", "S"), ("K", "S"), ("Q", "S"), ("J", "S"), ("10", "S"))),
|
||||
(2, 8, (("J", "S"), ("10", "S"), ("9", "S"), ("8", "S"), ("7", "S"))),
|
||||
(3, 7, (("K", "H"), ("K", "C"), ("K", "D"), ("K", "S"), None)),
|
||||
(4, 6, (("A", "H"), ("A", "C"), ("A", "D"), ("9", "S"), ("9", "H"))),
|
||||
(5, 5, (("K", "S"), ("J", "S"), ("8", "S"), ("7", "S"), ("5", "S"))),
|
||||
(6, 4, (("J", "H"), ("10", "C"), ("9", "D"), ("8", "S"), ("7", "H"))),
|
||||
(7, 3, (("K", "H"), ("K", "C"), ("K", "D"), None, None)),
|
||||
(8, 2, (("A", "H"), ("A", "C"), ("9", "D"), ("9", "S"), None)),
|
||||
(9, 1, (("K", "H"), ("K", "C"), None, None, None)),
|
||||
(10, 0, (("A", "H"), None, None, None, None)),
|
||||
)
|
||||
|
||||
|
||||
class PokerTableView:
|
||||
def __init__(
|
||||
self,
|
||||
context,
|
||||
variant_key: str,
|
||||
pk_account_id: int,
|
||||
bot_configs: list[tuple[int, str]],
|
||||
on_back_to_menu,
|
||||
resume_state_json: str | None = None,
|
||||
):
|
||||
self.ctx = context
|
||||
self.variant_key = variant_key
|
||||
self.cfg = PK_VARIANTS[variant_key]
|
||||
self.on_back_to_menu = on_back_to_menu
|
||||
self.engine = PokerEngine(sb=self.cfg["sb"], bb=self.cfg["bb"])
|
||||
self.bot_ai = PokerBotAI()
|
||||
|
||||
self.round_start_time: float = time.time()
|
||||
self._last_popup_payload: dict | None = None
|
||||
self._result_dialog: PokerResultDialog | None = None
|
||||
self._photo_refs = []
|
||||
self._turn_job = None
|
||||
|
||||
self._raw_table_pil: Image.Image | None = self._load_raw_table_image()
|
||||
self._scaled_table_photo: ImageTk.PhotoImage | None = None
|
||||
self._last_bg_size: tuple[int, int] = (0, 0)
|
||||
|
||||
self.ctx.sounds.play_ingame_music()
|
||||
|
||||
if resume_state_json is not None:
|
||||
self._restore_from_json(resume_state_json)
|
||||
else:
|
||||
self.pk_account = Database.get_poker_account(pk_account_id)
|
||||
self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0))
|
||||
|
||||
level_chips = self._get_current_level_chips()
|
||||
bot_bankroll = max(PK_STARTING_GOLD, level_chips[-1] * 6)
|
||||
|
||||
self.engine.seats = [
|
||||
PokerSeat(seat_id=0, name=self.ctx.profile["name"], is_human=True, stack=self.pk_account["gold"])
|
||||
]
|
||||
for idx, (lvl, b_name) in enumerate(bot_configs, start=1):
|
||||
self.engine.seats.append(
|
||||
PokerSeat(seat_id=idx, name=b_name, is_human=False, ai_level=lvl, stack=bot_bankroll)
|
||||
)
|
||||
|
||||
self._build_ui()
|
||||
self._start_new_hand()
|
||||
|
||||
@staticmethod
|
||||
def _load_raw_table_image() -> Image.Image | None:
|
||||
img_path = IMAGES_DIR / PK_TABLE_IMAGE
|
||||
if img_path.is_file():
|
||||
try:
|
||||
return Image.open(img_path).convert("RGB")
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# AUTO-SAVE & RESUME (nur bei aktivem Devil's Deal!)
|
||||
# ---------------------------------------------------------
|
||||
def _persist_state(self):
|
||||
if not self.devils_locked:
|
||||
return
|
||||
state_obj = {
|
||||
"pk_account_id": self.pk_account["id"],
|
||||
"devils_locked": self.devils_locked,
|
||||
"elapsed_sec": max(0.0, time.time() - self.round_start_time),
|
||||
"last_popup_payload": self._last_popup_payload,
|
||||
"engine": self.engine.to_dict(),
|
||||
}
|
||||
Database.save_game_state(
|
||||
self.ctx.profile["id"],
|
||||
GAME_FOLDER_ID,
|
||||
self.variant_key,
|
||||
json.dumps(state_obj),
|
||||
)
|
||||
|
||||
def _clear_persisted_state(self):
|
||||
Database.delete_game_state(self.ctx.profile["id"], GAME_FOLDER_ID)
|
||||
|
||||
def _restore_from_json(self, raw_json: str):
|
||||
try:
|
||||
data = json.loads(raw_json)
|
||||
self.pk_account = Database.get_poker_account(data["pk_account_id"])
|
||||
self.devils_locked = bool(data.get("devils_locked", False) or self.pk_account.get("devils_deal_active", 0))
|
||||
self.round_start_time = time.time() - float(data.get("elapsed_sec", 0.0))
|
||||
self._last_popup_payload = data.get("last_popup_payload")
|
||||
self.engine.load_from_dict(data["engine"])
|
||||
except Exception:
|
||||
self._clear_persisted_state()
|
||||
dev_acc = Database.get_active_devils_pk_account(self.ctx.profile["id"])
|
||||
accounts = Database.get_poker_accounts(self.ctx.profile["id"])
|
||||
self.pk_account = dev_acc or accounts[0]
|
||||
self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0))
|
||||
self.engine.seats = [
|
||||
PokerSeat(seat_id=0, name=self.ctx.profile["name"], is_human=True, stack=self.pk_account["gold"]),
|
||||
PokerSeat(seat_id=1, name=t("bot_default_name", 1), is_human=False, ai_level=2, stack=PK_STARTING_GOLD),
|
||||
]
|
||||
self._build_ui()
|
||||
self._start_new_hand()
|
||||
return
|
||||
|
||||
self._build_ui()
|
||||
if self.engine.street == "SHOWDOWN" and self._last_popup_payload:
|
||||
self._render_table()
|
||||
self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload))
|
||||
else:
|
||||
self._render_table()
|
||||
self._process_current_turn()
|
||||
|
||||
def _get_current_level_chips(self) -> tuple[int, int, int, int]:
|
||||
pk_lvl = self.ctx.game_progress["level"]
|
||||
return Progression.get_level_bet_chips(pk_lvl, bet_scale=self.cfg.get("bet_scale", 1))
|
||||
|
||||
def _cleanup_and_go(self, nav_callable):
|
||||
if self.devils_locked:
|
||||
return
|
||||
InfoBadge.close_global_tip()
|
||||
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):
|
||||
InfoBadge.close_global_tip()
|
||||
self._persist_state()
|
||||
self._build_ui()
|
||||
if self.engine.street == "SHOWDOWN" and self._last_popup_payload:
|
||||
self._render_table()
|
||||
self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload))
|
||||
else:
|
||||
self._render_table()
|
||||
if self.engine.turn_pos == 0 and self.engine.human_seat.can_act:
|
||||
self._show_human_controls()
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# UI AUFBAU MIT STATISCHER BEISPIEL-HILFE & INFO-BADGES
|
||||
# ---------------------------------------------------------
|
||||
def _build_ui(self):
|
||||
if self._result_dialog:
|
||||
self._result_dialog.close_dialog()
|
||||
self._result_dialog = None
|
||||
|
||||
InfoBadge.close_global_tip()
|
||||
self._last_bg_size = (0, 0)
|
||||
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.pk_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=14, pady=8,
|
||||
highlightthickness=1, highlightbackground=ERROR_FG if self.devils_locked else BORDER_COLOR
|
||||
)
|
||||
self.table_frame.place(relx=0.5, rely=0.535, anchor="center", relwidth=0.96, relheight=0.88)
|
||||
|
||||
self.pot_lbl = tk.Label(
|
||||
self.table_frame, text="", font=("Georgia", 11, "bold"),
|
||||
fg=ACCENT_GOLD, bg=PANEL_BG, pady=4, highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
self.pot_lbl.pack(fill="x", side="top", pady=(0, 4))
|
||||
|
||||
bottom_area = tk.Frame(self.table_frame, bg=TABLE_BG, height=244)
|
||||
bottom_area.pack(fill="x", side="bottom", pady=(6, 0))
|
||||
bottom_area.pack_propagate(False)
|
||||
|
||||
bottom_area.columnconfigure(0, weight=34, uniform="bcols")
|
||||
bottom_area.columnconfigure(1, weight=39, uniform="bcols")
|
||||
bottom_area.columnconfigure(2, weight=27, uniform="bcols")
|
||||
bottom_area.rowconfigure(0, weight=1)
|
||||
|
||||
self.help_panel = tk.Frame(
|
||||
bottom_area, bg=PANEL_BG, padx=8, pady=5,
|
||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
||||
)
|
||||
self.help_panel.grid(row=0, column=0, sticky="nsew", padx=(0, 6))
|
||||
self._populate_static_hand_examples()
|
||||
|
||||
center_player_wrap = tk.Frame(
|
||||
bottom_area, bg=PANEL_BG, padx=10, pady=6,
|
||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
center_player_wrap.grid(row=0, column=1, sticky="nsew", padx=4)
|
||||
|
||||
self.status_lbl = tk.Label(
|
||||
center_player_wrap, text="", font=("Georgia", 10, "bold"),
|
||||
fg=ACCENT_GOLD, bg=PANEL_BG, wraplength=410, justify="center"
|
||||
)
|
||||
self.status_lbl.pack(side="top", pady=(0, 3))
|
||||
|
||||
self.player_sec = tk.Frame(center_player_wrap, bg=PANEL_BG)
|
||||
self.player_sec.pack(fill="both", expand=True)
|
||||
|
||||
self.controls_frame = tk.Frame(
|
||||
bottom_area, bg=PANEL_BG, padx=8, pady=5,
|
||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
||||
)
|
||||
self.controls_frame.grid(row=0, column=2, sticky="nsew", padx=(6, 0))
|
||||
|
||||
self.arena_canvas = tk.Canvas(
|
||||
self.table_frame, bg="#120f18", highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
self.arena_canvas.pack(fill="both", expand=True)
|
||||
self.arena_canvas.bind("<Configure>", self._on_arena_resize)
|
||||
|
||||
felt_bg = "#1b1626"
|
||||
self.board_box = tk.Frame(
|
||||
self.arena_canvas, bg=felt_bg, padx=10, pady=6,
|
||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
self.board_box.place(relx=0.5, rely=0.52, anchor="center")
|
||||
|
||||
tk.Label(
|
||||
self.board_box, text=t("pk_board_title"),
|
||||
font=("Georgia", 9, "bold"), fg=MUTED_FG, bg=felt_bg
|
||||
).pack(pady=(0, 3))
|
||||
|
||||
self.board_cards_frame = tk.Frame(self.board_box, bg=felt_bg, height=PK_OVAL_BOARD_CARD[1] + 2)
|
||||
self.board_cards_frame.pack()
|
||||
|
||||
self._bot_seat_frames: list[tk.Frame] = []
|
||||
self._refresh_header()
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# STATISCHE POKER-HÄNDE-TAFEL MIT MINI-BEISPIELKARTEN & ⓘ
|
||||
# ---------------------------------------------------------
|
||||
@staticmethod
|
||||
def _draw_mini_example_strip(parent, cards_spec: tuple) -> tk.Canvas:
|
||||
cw, ch, gap = 21, 23, 2
|
||||
total_w = 5 * cw + 4 * gap
|
||||
cv = tk.Canvas(parent, width=total_w, height=ch, bg=PANEL_BG, highlightthickness=0)
|
||||
|
||||
for i, spec in enumerate(cards_spec):
|
||||
x0 = i * (cw + gap)
|
||||
if spec is None:
|
||||
cv.create_rectangle(
|
||||
x0, 1, x0 + cw - 1, ch - 1,
|
||||
fill="#3a1722", outline="#5c2838", width=1
|
||||
)
|
||||
else:
|
||||
rank, suit = spec
|
||||
is_red = suit in RED_SUITS
|
||||
fg_col = "#d93848" if is_red else "#1c1824"
|
||||
sym = SUIT_SYMBOLS.get(suit, suit)
|
||||
|
||||
cv.create_rectangle(
|
||||
x0, 1, x0 + cw - 1, ch - 1,
|
||||
fill="#ede8f5", outline="#8e82a6", width=1
|
||||
)
|
||||
cv.create_text(
|
||||
x0 + cw // 2, 7,
|
||||
text=rank, font=("Helvetica", 6, "bold"), fill=fg_col
|
||||
)
|
||||
cv.create_text(
|
||||
x0 + cw // 2, 16,
|
||||
text=sym, font=("Helvetica", 7, "bold"), fill=fg_col
|
||||
)
|
||||
return cv
|
||||
|
||||
def _populate_static_hand_examples(self):
|
||||
for w in self.help_panel.winfo_children():
|
||||
w.destroy()
|
||||
|
||||
hdr_row = tk.Frame(self.help_panel, bg=PANEL_BG)
|
||||
hdr_row.pack(fill="x", pady=(0, 2))
|
||||
|
||||
tk.Label(
|
||||
hdr_row, text=t("pk_help_header"),
|
||||
font=("Georgia", 9, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG
|
||||
).pack(side="left")
|
||||
|
||||
InfoBadge(
|
||||
hdr_row,
|
||||
text_provider=lambda: t("pk_help_general_info"),
|
||||
bg=PANEL_BG,
|
||||
font_size=9,
|
||||
).pack(side="right")
|
||||
|
||||
tk.Frame(self.help_panel, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(0, 3))
|
||||
|
||||
cols_wrap = tk.Frame(self.help_panel, bg=PANEL_BG)
|
||||
cols_wrap.pack(fill="both", expand=True)
|
||||
cols_wrap.columnconfigure(0, weight=1, uniform="hcol")
|
||||
cols_wrap.columnconfigure(1, weight=0)
|
||||
cols_wrap.columnconfigure(2, weight=1, uniform="hcol")
|
||||
|
||||
left_f = tk.Frame(cols_wrap, bg=PANEL_BG)
|
||||
left_f.grid(row=0, column=0, sticky="nsew", padx=(0, 4))
|
||||
|
||||
tk.Frame(cols_wrap, bg=SUBTLE_BORDER, width=1).grid(row=0, column=1, sticky="ns", pady=2)
|
||||
|
||||
right_f = tk.Frame(cols_wrap, bg=PANEL_BG)
|
||||
right_f.grid(row=0, column=2, sticky="nsew", padx=(4, 0))
|
||||
|
||||
for rank_no, cat_id, cards_spec in HAND_REFERENCE_EXAMPLES:
|
||||
target_col = left_f if rank_no <= 5 else right_f
|
||||
cell = tk.Frame(target_col, bg=PANEL_BG)
|
||||
cell.pack(fill="x", pady=1)
|
||||
|
||||
strip = self._draw_mini_example_strip(cell, cards_spec)
|
||||
strip.pack(anchor="w")
|
||||
|
||||
lbl_row = tk.Frame(cell, bg=PANEL_BG)
|
||||
lbl_row.pack(fill="x")
|
||||
|
||||
raw_name = t(f"pk_hand_{cat_id}").replace("★ ", "").replace(" ★", "")
|
||||
short_name = raw_name.split(" (")[0]
|
||||
|
||||
tk.Label(
|
||||
lbl_row,
|
||||
text=f"{rank_no}. {short_name}",
|
||||
font=("Helvetica", 7, "bold"),
|
||||
fg=ACCENT_GOLD if rank_no == 1 else FG_COLOR,
|
||||
bg=PANEL_BG,
|
||||
anchor="w",
|
||||
).pack(side="left")
|
||||
|
||||
InfoBadge(
|
||||
lbl_row,
|
||||
text_provider=lambda cid=cat_id: t(f"pk_help_hand_{cid}"),
|
||||
bg=PANEL_BG,
|
||||
font_size=8,
|
||||
).pack(side="left", padx=(2, 0))
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# TISCHBILD SKALIERUNG & HEADER
|
||||
# ---------------------------------------------------------
|
||||
def _on_arena_resize(self, event):
|
||||
w, h = event.width, event.height
|
||||
if w < 80 or h < 80 or (w, h) == self._last_bg_size:
|
||||
return
|
||||
self._last_bg_size = (w, h)
|
||||
|
||||
self.arena_canvas.delete("table_bg")
|
||||
|
||||
if self._raw_table_pil is not None:
|
||||
fitted = self._raw_table_pil.resize((w, h), Image.Resampling.LANCZOS)
|
||||
self._scaled_table_photo = ImageTk.PhotoImage(fitted)
|
||||
self.arena_canvas.create_image(
|
||||
0, 0, image=self._scaled_table_photo, anchor="nw", tags="table_bg"
|
||||
)
|
||||
self.arena_canvas.tag_lower("table_bg")
|
||||
else:
|
||||
mx, my_top, my_bot = int(w * 0.11), int(h * 0.13), int(h * 0.08)
|
||||
self.arena_canvas.create_oval(
|
||||
mx, my_top, w - mx, h - my_bot,
|
||||
fill="#14111b", outline=BORDER_COLOR, width=3, tags="table_bg"
|
||||
)
|
||||
|
||||
def _refresh_header(self):
|
||||
self.pk_account = Database.get_poker_account(self.pk_account["id"])
|
||||
prof = self.ctx.profile
|
||||
prog = self.ctx.refresh_game_progress()
|
||||
self.topbar.extra_label.configure(text=t("pk_header_gold", self.pk_account["account_name"], self.pk_account["gold"]))
|
||||
self.topbar.level_label.configure(
|
||||
text=t("level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"])
|
||||
)
|
||||
street_txt = t(f"pk_street_{self.engine.street}")
|
||||
self.pot_lbl.configure(text=t("pk_pot_banner", self.engine.total_pot, street_txt, self.engine.current_bet))
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# HAND STARTEN (Direkter Grundeinsatz / Ante wie bei Blackjack!)
|
||||
# ---------------------------------------------------------
|
||||
def _start_new_hand(self):
|
||||
if self._result_dialog:
|
||||
self._result_dialog.close_dialog()
|
||||
self._result_dialog = None
|
||||
|
||||
InfoBadge.close_global_tip()
|
||||
self.pk_account = Database.get_poker_account(self.pk_account["id"])
|
||||
self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0))
|
||||
gold = self.pk_account["gold"]
|
||||
min_req = self.cfg["min_entry"]
|
||||
|
||||
eff_min = min(min_req, 10) if self.devils_locked else min_req
|
||||
if gold < eff_min:
|
||||
Database.set_pk_devils_deal_active(self.pk_account["id"], False)
|
||||
self.devils_locked = False
|
||||
self._clear_persisted_state()
|
||||
cur_cost = self.ctx.refresh_game_progress()["xp_exchange_cost"]
|
||||
msg = t(
|
||||
"bj_err_not_enough_gold_entry",
|
||||
self.pk_account["account_name"], min_req, gold,
|
||||
cur_cost, XP_TO_GOLD_AMOUNT
|
||||
)
|
||||
self._cleanup_and_go(lambda: self.on_back_to_menu(self.pk_account["id"], msg))
|
||||
return
|
||||
|
||||
self._last_popup_payload = None
|
||||
self.round_start_time = time.time()
|
||||
self.ctx.sounds.play("deal")
|
||||
|
||||
self.engine.human_seat.stack = gold
|
||||
level_chips = self._get_current_level_chips()
|
||||
fallback_stack = max(PK_STARTING_GOLD, level_chips[-1] * 5)
|
||||
for s in self.engine.seats[1:]:
|
||||
self.bot_ai.ensure_bot_stack(s, min_req, fallback_stack=fallback_stack)
|
||||
|
||||
human_ante, ante_events = self.engine.start_hand()
|
||||
if human_ante > 0:
|
||||
self.pk_account = Database.update_poker_gold(self.pk_account["id"], -human_ante)
|
||||
|
||||
ante_lbl = "Grundeinsatz" if get_lang() == "DE" else "Entry Ante"
|
||||
for s_idx, (_b_role, b_amt) in ante_events.items():
|
||||
if s_idx > 0:
|
||||
self.engine.seats[s_idx].status_text = f"{ante_lbl} ({b_amt}g)"
|
||||
|
||||
self._persist_state()
|
||||
self._build_ui()
|
||||
self._render_table()
|
||||
self._process_current_turn()
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# RENDERING TISCH
|
||||
# ---------------------------------------------------------
|
||||
def _role_badge(self, seat_idx: int) -> str:
|
||||
badges = []
|
||||
if seat_idx == self.engine.dealer_pos:
|
||||
badges.append(t("pk_role_dealer"))
|
||||
if seat_idx == self.engine.sb_pos:
|
||||
badges.append(t("pk_role_sb"))
|
||||
if seat_idx == self.engine.bb_pos:
|
||||
badges.append(t("pk_role_bb"))
|
||||
return "".join(badges)
|
||||
|
||||
def _render_table(self):
|
||||
self._photo_refs.clear()
|
||||
|
||||
for old_f in self._bot_seat_frames:
|
||||
if old_f.winfo_exists():
|
||||
old_f.destroy()
|
||||
self._bot_seat_frames.clear()
|
||||
|
||||
bot_seats = self.engine.seats[1:]
|
||||
slot_indices = SEAT_LAYOUT_BY_COUNT.get(len(bot_seats), (0, 1, 2, 3, 4))
|
||||
|
||||
for bot_i, seat in enumerate(bot_seats):
|
||||
coord_idx = slot_indices[bot_i]
|
||||
rx, ry = OVAL_BOT_COORDS[coord_idx]
|
||||
|
||||
is_turn = (self.engine.street != "SHOWDOWN" and self.engine.turn_pos == seat.seat_id)
|
||||
if is_turn:
|
||||
b_col, thick = ACCENT_GOLD, 2
|
||||
elif seat.folded:
|
||||
b_col, thick = ERROR_FG, 1
|
||||
elif seat.all_in:
|
||||
b_col, thick = ACCENT_GOTH, 2
|
||||
else:
|
||||
b_col, thick = BORDER_COLOR, 1
|
||||
|
||||
box = tk.Frame(
|
||||
self.arena_canvas, bg="#191521", padx=10, pady=5, width=188,
|
||||
highlightthickness=thick, highlightbackground=b_col
|
||||
)
|
||||
box.place(relx=rx, rely=ry, anchor="center")
|
||||
self._bot_seat_frames.append(box)
|
||||
|
||||
base_name = t("bj_bot_rebuy", seat.name) if seat.rebought else seat.name
|
||||
title_txt = f"{base_name}{self._role_badge(seat.seat_id)}"
|
||||
tk.Label(
|
||||
box, text=title_txt, font=("Georgia", 9, "bold"),
|
||||
fg=MUTED_FG if seat.folded else ACCENT_GOTH, bg="#191521"
|
||||
).pack()
|
||||
|
||||
tk.Label(
|
||||
box, text=t("pk_bot_stack_lbl", seat.stack, seat.street_bet),
|
||||
font=("Helvetica", 8, "bold"), fg=ACCENT_GOLD, bg="#191521"
|
||||
).pack(pady=(1, 2))
|
||||
|
||||
st_txt = seat.status_text or "—"
|
||||
st_col = ERROR_FG if seat.folded else (ACCENT_GOLD if is_turn else FG_COLOR)
|
||||
tk.Label(box, text=st_txt, font=("Helvetica", 8, "bold"), fg=st_col, bg="#191521").pack()
|
||||
|
||||
# 2. Gemeinschaftskarten (Board)
|
||||
felt_bg = "#1b1626"
|
||||
for w in self.board_cards_frame.winfo_children():
|
||||
w.destroy()
|
||||
|
||||
for slot_i in range(5):
|
||||
if slot_i < len(self.engine.board):
|
||||
c = self.engine.board[slot_i]
|
||||
photo = self.ctx.assets.get_card_photo(c.image_filename, size=PK_OVAL_BOARD_CARD)
|
||||
if photo:
|
||||
self._photo_refs.append(photo)
|
||||
tk.Label(self.board_cards_frame, image=photo, bg=felt_bg, bd=0).pack(side="left", padx=5)
|
||||
else:
|
||||
empty_slot = tk.Frame(
|
||||
self.board_cards_frame, width=PK_OVAL_BOARD_CARD[0], height=PK_OVAL_BOARD_CARD[1],
|
||||
bg="#221c2e", highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
empty_slot.pack(side="left", padx=5)
|
||||
|
||||
# 3. Eigene Karten + neutrale Einsatz-Info
|
||||
for w in self.player_sec.winfo_children():
|
||||
w.destroy()
|
||||
|
||||
human = self.engine.human_seat
|
||||
h_cards_f = tk.Frame(self.player_sec, bg=PANEL_BG)
|
||||
h_cards_f.pack(expand=True, pady=(2, 2))
|
||||
|
||||
for card in human.hole_cards:
|
||||
photo = self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE)
|
||||
if photo:
|
||||
self._photo_refs.append(photo)
|
||||
tk.Label(h_cards_f, image=photo, bg=PANEL_BG, bd=0).pack(side="left", padx=6)
|
||||
|
||||
state_tag = t("pk_state_folded") if human.folded else (t("pk_state_allin") if human.all_in else "")
|
||||
role_str = self._role_badge(0) or t("pk_role_player")
|
||||
tk.Label(
|
||||
self.player_sec,
|
||||
text=t("pk_player_bet_only", role_str, human.street_bet, human.total_committed, state_tag),
|
||||
font=("Georgia", 10, "bold"),
|
||||
fg=ERROR_FG if human.folded else FG_COLOR,
|
||||
bg=PANEL_BG,
|
||||
wraplength=410,
|
||||
justify="center",
|
||||
).pack(side="bottom", pady=(2, 2))
|
||||
|
||||
self._refresh_header()
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# ZUG-SCHLEIFE & STRASSEN-WECHSEL
|
||||
# ---------------------------------------------------------
|
||||
def _process_current_turn(self):
|
||||
if not self.table_frame.winfo_exists():
|
||||
return
|
||||
|
||||
if self.engine.only_one_left():
|
||||
self._finalize_hand()
|
||||
return
|
||||
|
||||
if self.engine.is_betting_round_complete():
|
||||
self._advance_street_or_showdown()
|
||||
return
|
||||
|
||||
if self.engine.turn_pos < 0 or not self.engine.seats[self.engine.turn_pos].can_act:
|
||||
self.engine.advance_turn_pointer()
|
||||
if self.engine.turn_pos < 0:
|
||||
self._advance_street_or_showdown()
|
||||
return
|
||||
|
||||
if self.engine.turn_pos == 0:
|
||||
self._render_table()
|
||||
self._show_human_controls()
|
||||
else:
|
||||
self._render_waiting_controls()
|
||||
bot = self.engine.seats[self.engine.turn_pos]
|
||||
self.status_lbl.configure(text=t("pk_bot_turn_status", bot.name))
|
||||
self._render_table()
|
||||
self._turn_job = self.ctx.root.after(PK_BOT_TURN_DELAY_MS, lambda b=bot: self._execute_bot_turn(b))
|
||||
|
||||
def _advance_street_or_showdown(self):
|
||||
self._render_waiting_controls()
|
||||
|
||||
if self.engine.street == "RIVER":
|
||||
self._finalize_hand()
|
||||
return
|
||||
|
||||
self.ctx.sounds.play("click")
|
||||
new_street = self.engine.advance_to_next_street()
|
||||
self._persist_state()
|
||||
self._render_table()
|
||||
|
||||
if new_street == "SHOWDOWN":
|
||||
self._finalize_hand()
|
||||
return
|
||||
|
||||
if self.engine.should_auto_runout_board():
|
||||
self.status_lbl.configure(text=t("pk_showdown_running"))
|
||||
self._turn_job = self.ctx.root.after(PK_STREET_DELAY_MS, self._advance_street_or_showdown)
|
||||
else:
|
||||
self._process_current_turn()
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# RECHTE SPALTE: VERTIKALE BUTTONS + ⓘ INFO-SYMBOLE (U+24D8)
|
||||
# ---------------------------------------------------------
|
||||
def _add_action_row(
|
||||
self,
|
||||
parent: tk.Frame,
|
||||
text: str,
|
||||
pil_norm,
|
||||
pil_hov,
|
||||
command,
|
||||
tip_key: str,
|
||||
sound_mgr=None,
|
||||
enabled: bool = True,
|
||||
btn_w: int = 176,
|
||||
btn_h: int = 29,
|
||||
pady: tuple[int, int] = (1, 2),
|
||||
):
|
||||
row = tk.Frame(parent, bg=PANEL_BG)
|
||||
row.pack(pady=pady)
|
||||
|
||||
ImageButton(
|
||||
row,
|
||||
text,
|
||||
pil_norm,
|
||||
pil_hov,
|
||||
command,
|
||||
sound_mgr=sound_mgr,
|
||||
width=btn_w,
|
||||
height=btn_h,
|
||||
font=("Helvetica", 9, "bold"),
|
||||
enabled=enabled,
|
||||
).pack(side="left")
|
||||
|
||||
InfoBadge(
|
||||
row,
|
||||
text_provider=lambda k=tip_key: t(k),
|
||||
bg=PANEL_BG,
|
||||
font_size=9,
|
||||
).pack(side="left", padx=(5, 0))
|
||||
|
||||
def _render_waiting_controls(self):
|
||||
for w in self.controls_frame.winfo_children():
|
||||
w.destroy()
|
||||
|
||||
col = tk.Frame(self.controls_frame, bg=PANEL_BG)
|
||||
col.pack(expand=True)
|
||||
|
||||
self._add_action_row(
|
||||
col, t("pk_btn_check"),
|
||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
||||
None, "pk_tip_check", enabled=False, pady=(3, 3)
|
||||
)
|
||||
self._add_action_row(
|
||||
col, t("pk_btn_allin", 0),
|
||||
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
|
||||
None, "pk_tip_allin", enabled=False, pady=(3, 3)
|
||||
)
|
||||
self._add_action_row(
|
||||
col, t("pk_btn_fold"),
|
||||
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
|
||||
None, "pk_tip_fold", enabled=False, pady=(3, 3)
|
||||
)
|
||||
|
||||
def _show_human_controls(self):
|
||||
for w in self.controls_frame.winfo_children():
|
||||
w.destroy()
|
||||
|
||||
human = self.engine.human_seat
|
||||
to_call = max(0, self.engine.current_bet - human.street_bet)
|
||||
street_txt = t(f"pk_street_{self.engine.street}")
|
||||
dyn_chips = self._get_current_level_chips()
|
||||
|
||||
if to_call > 0:
|
||||
self.status_lbl.configure(text=t("pk_turn_prompt_call", street_txt, min(human.stack, to_call)))
|
||||
else:
|
||||
self.status_lbl.configure(text=t("pk_turn_prompt_check", street_txt))
|
||||
|
||||
btn_col = tk.Frame(self.controls_frame, bg=PANEL_BG)
|
||||
btn_col.pack(expand=True)
|
||||
|
||||
# 1. Check (Hold) oder Mitgehen (Call) + ⓘ
|
||||
if to_call == 0:
|
||||
self._add_action_row(
|
||||
btn_col, t("pk_btn_check"),
|
||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
||||
lambda: self._on_human_action("CHECK", 0),
|
||||
"pk_tip_check", sound_mgr=None, btn_h=29, pady=(0, 2)
|
||||
)
|
||||
elif human.stack > to_call:
|
||||
self._add_action_row(
|
||||
btn_col, t("pk_btn_call", to_call),
|
||||
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
|
||||
lambda: self._on_human_action("CALL", 0),
|
||||
"pk_tip_call", sound_mgr=self.ctx.sounds, btn_h=29, pady=(0, 2)
|
||||
)
|
||||
|
||||
# 2. Erhöhen (Raise) Header + ⓘ & kompakter 2x2 Chip-Block
|
||||
avail_after_call = human.stack - to_call
|
||||
min_r = self.engine.min_raise_delta
|
||||
offered = sorted({max(min_r, c) for c in dyn_chips if max(min_r, c) < avail_after_call})[:4]
|
||||
|
||||
if avail_after_call > min_r and offered:
|
||||
r_hdr = tk.Frame(btn_col, bg=PANEL_BG)
|
||||
r_hdr.pack(pady=(1, 1))
|
||||
tk.Label(
|
||||
r_hdr, text=t("pk_raise_lbl"),
|
||||
font=("Helvetica", 8, "bold"), fg=MUTED_FG, bg=PANEL_BG
|
||||
).pack(side="left")
|
||||
InfoBadge(
|
||||
r_hdr, text_provider=lambda: t("pk_tip_raise"), bg=PANEL_BG, font_size=9
|
||||
).pack(side="left", padx=(4, 0))
|
||||
|
||||
r_grid = tk.Frame(btn_col, bg=PANEL_BG)
|
||||
r_grid.pack(pady=(0, 2))
|
||||
for idx, r_delta in enumerate(offered):
|
||||
ImageButton(
|
||||
r_grid, f"+{r_delta}",
|
||||
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
|
||||
lambda d=r_delta: self._on_human_action("RAISE", d),
|
||||
sound_mgr=self.ctx.sounds, width=85, height=25, font=("Helvetica", 8, "bold")
|
||||
).grid(row=idx // 2, column=idx % 2, padx=2, pady=1)
|
||||
|
||||
# 3. ALL-IN + ⓘ
|
||||
if human.stack > 0:
|
||||
self._add_action_row(
|
||||
btn_col, t("pk_btn_allin", human.stack),
|
||||
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
|
||||
lambda: self._on_human_action("ALLIN", 0),
|
||||
"pk_tip_allin", sound_mgr=self.ctx.sounds, btn_h=28, pady=(1, 2)
|
||||
)
|
||||
|
||||
# 4. Passen (Fold) + ⓘ
|
||||
self._add_action_row(
|
||||
btn_col, t("pk_btn_fold"),
|
||||
self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active,
|
||||
lambda: self._on_human_action("FOLD", 0),
|
||||
"pk_tip_fold", sound_mgr=self.ctx.sounds, btn_h=28, pady=(0, 0)
|
||||
)
|
||||
|
||||
def _on_human_action(self, action: str, raise_delta: int):
|
||||
InfoBadge.close_global_tip()
|
||||
if action == "CHECK":
|
||||
self.ctx.sounds.play("stand")
|
||||
paid = self.engine.apply_action(0, action, raise_delta)
|
||||
if paid > 0:
|
||||
self.pk_account = Database.update_poker_gold(self.pk_account["id"], -paid)
|
||||
|
||||
self.engine.advance_turn_pointer()
|
||||
self._persist_state()
|
||||
self._render_table()
|
||||
self._process_current_turn()
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# BOT-ZUG AUSFÜHREN
|
||||
# ---------------------------------------------------------
|
||||
def _execute_bot_turn(self, bot: PokerSeat):
|
||||
if not self.table_frame.winfo_exists():
|
||||
return
|
||||
|
||||
active_opps = sum(1 for s in self.engine.seats if s.is_in_hand and s.seat_id != bot.seat_id)
|
||||
dyn_chips = self._get_current_level_chips()
|
||||
|
||||
act, r_delta = self.bot_ai.decide_action(
|
||||
bot=bot,
|
||||
board=self.engine.board,
|
||||
current_bet=self.engine.current_bet,
|
||||
pot=self.engine.total_pot,
|
||||
min_raise_delta=self.engine.min_raise_delta,
|
||||
chips=dyn_chips,
|
||||
active_opponents=active_opps,
|
||||
)
|
||||
|
||||
paid = self.engine.apply_action(bot.seat_id, act, r_delta)
|
||||
if act == "FOLD":
|
||||
bot.status_text = t("pk_bot_act_fold")
|
||||
elif act == "CHECK":
|
||||
bot.status_text = t("pk_bot_act_check")
|
||||
elif act == "ALLIN":
|
||||
self.ctx.sounds.play("click")
|
||||
bot.status_text = t("pk_bot_act_allin", bot.total_committed)
|
||||
elif act == "RAISE":
|
||||
self.ctx.sounds.play("click")
|
||||
bot.status_text = t("pk_bot_act_raise", paid)
|
||||
else:
|
||||
self.ctx.sounds.play("click")
|
||||
bot.status_text = t("pk_bot_act_call", paid)
|
||||
|
||||
self.engine.advance_turn_pointer()
|
||||
self._persist_state()
|
||||
self._render_table()
|
||||
self._process_current_turn()
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# SHOWDOWN, KARTEN-AUFDECKUNG IM POPUP & XP
|
||||
# ---------------------------------------------------------
|
||||
def _collect_all_seats_reveal(self, winner_names: list[str]) -> list[dict]:
|
||||
win_set = set(winner_names)
|
||||
entries = []
|
||||
for s in self.engine.seats:
|
||||
if not s.hole_cards:
|
||||
continue
|
||||
cat_id, _ = PokerEvaluator.evaluate_best(s.hole_cards + self.engine.board)
|
||||
entries.append({
|
||||
"name": s.name,
|
||||
"cards": [[c.suit, c.rank] for c in s.hole_cards],
|
||||
"folded": s.folded,
|
||||
"cat_id": cat_id,
|
||||
"is_winner": (s.name in win_set) and (not s.folded),
|
||||
})
|
||||
return entries
|
||||
|
||||
def _finalize_hand(self):
|
||||
InfoBadge.close_global_tip()
|
||||
self._render_waiting_controls()
|
||||
|
||||
res = self.engine.resolve_hand()
|
||||
if res["human_payout"] > 0:
|
||||
self.pk_account = Database.update_poker_gold(self.pk_account["id"], res["human_payout"])
|
||||
|
||||
duration = max(0.5, time.time() - self.round_start_time)
|
||||
prog_before = self.ctx.refresh_game_progress()
|
||||
opp_levels = [s.ai_level for s in self.engine.seats[1:]]
|
||||
|
||||
win_cat = res["winning_hand_cat"] or 0
|
||||
if res["human_won"]:
|
||||
out_type = "WIN_777" if win_cat >= 8 else ("WIN_BJ" if win_cat >= 6 else "WIN")
|
||||
won_stat = True
|
||||
elif res["human_net"] == 0 and res["human_payout"] > 0:
|
||||
out_type = "TIE"
|
||||
won_stat = None
|
||||
else:
|
||||
out_type = "LOSE"
|
||||
won_stat = False
|
||||
|
||||
xp_gained = Progression.calculate_match_xp(
|
||||
player_level=prog_before["level"],
|
||||
opponent_levels=opp_levels,
|
||||
outcome_type=out_type,
|
||||
variant_mult=self.cfg["xp_mult"],
|
||||
)
|
||||
|
||||
if won_stat is None:
|
||||
Database.add_game_points(self.ctx.profile["id"], GAME_FOLDER_ID, xp_gained)
|
||||
prog_after = self.ctx.refresh_game_progress()
|
||||
self.ctx.sounds.play("end_battle")
|
||||
leveled_to = prog_after["level"] if prog_after["level"] > prog_before["level"] else None
|
||||
else:
|
||||
old_lvl, new_lvl = self.ctx.record_result(
|
||||
self.variant_key, won=won_stat, duration_sec=duration,
|
||||
points_gained=xp_gained, pk_account_id=self.pk_account["id"]
|
||||
)
|
||||
leveled_to = new_lvl if new_lvl > old_lvl else None
|
||||
|
||||
if self.devils_locked:
|
||||
fresh_acc = Database.get_poker_account(self.pk_account["id"])
|
||||
if not (out_type == "TIE" and fresh_acc["gold"] == 10):
|
||||
Database.set_pk_devils_deal_active(self.pk_account["id"], False)
|
||||
self.devils_locked = False
|
||||
self._clear_persisted_state()
|
||||
else:
|
||||
self._clear_persisted_state()
|
||||
|
||||
payload = {
|
||||
"by_fold": res["by_fold"],
|
||||
"winner_names": res["winner_names"],
|
||||
"winning_hand_cat": res["winning_hand_cat"],
|
||||
"player_won": bool(res["human_won"]),
|
||||
"is_split": res["is_split"],
|
||||
"player_net": res["human_net"],
|
||||
"bot_gains": res["bot_gains"],
|
||||
"xp_gained": xp_gained,
|
||||
"leveled_to": leveled_to,
|
||||
"board_cards": [[c.suit, c.rank] for c in self.engine.board],
|
||||
"seats_reveal": self._collect_all_seats_reveal(res["winner_names"]),
|
||||
}
|
||||
self._last_popup_payload = payload
|
||||
if self.devils_locked:
|
||||
self._persist_state()
|
||||
else:
|
||||
self._build_ui()
|
||||
|
||||
self.status_lbl.configure(text="")
|
||||
self._render_table()
|
||||
self._open_result_popup(self._build_localized_popup_data(payload))
|
||||
|
||||
def _build_localized_popup_data(self, payload: dict) -> dict:
|
||||
if payload["by_fold"]:
|
||||
hand_desc = t("pk_popup_fold_win")
|
||||
else:
|
||||
cat = payload["winning_hand_cat"] or 0
|
||||
hand_desc = t(f"pk_hand_{cat}")
|
||||
|
||||
if payload["player_won"]:
|
||||
headline = t("pk_popup_split_won", hand_desc) if payload["is_split"] else t("pk_popup_player_won", hand_desc)
|
||||
else:
|
||||
headline = t("pk_popup_bot_won", ", ".join(payload["winner_names"]), hand_desc)
|
||||
|
||||
other_gains = [
|
||||
t("pk_popup_bot_gain", b_name, b_gain)
|
||||
for b_name, b_gain in payload["bot_gains"] if b_gain > 0
|
||||
]
|
||||
|
||||
lvl_to = payload["leveled_to"]
|
||||
lvl_str = (
|
||||
t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to))
|
||||
if lvl_to is not None else None
|
||||
)
|
||||
|
||||
seat_showdown = []
|
||||
for s_rev in payload.get("seats_reveal", []):
|
||||
raw_combo = t(f"pk_hand_{s_rev['cat_id']}").replace("★ ", "").replace(" ★", "")
|
||||
short_combo = raw_combo.split(" (")[0] if len(raw_combo) > 20 else raw_combo
|
||||
if s_rev["folded"]:
|
||||
combo_txt = f"{t('pk_bot_act_fold')} ({short_combo})"
|
||||
else:
|
||||
combo_txt = short_combo
|
||||
seat_showdown.append({
|
||||
"name": s_rev["name"],
|
||||
"cards": s_rev["cards"],
|
||||
"folded": s_rev["folded"],
|
||||
"is_winner": s_rev["is_winner"],
|
||||
"combo_text": combo_txt,
|
||||
})
|
||||
|
||||
cur_gold = Database.get_poker_account(self.pk_account["id"])["gold"]
|
||||
can_cont = cur_gold >= self.cfg["min_entry"]
|
||||
|
||||
return {
|
||||
"headline": headline,
|
||||
"player_won": payload["player_won"],
|
||||
"player_net": payload["player_net"],
|
||||
"other_gains": other_gains,
|
||||
"xp_gained": payload["xp_gained"],
|
||||
"new_level_title": lvl_str,
|
||||
"board_cards": payload.get("board_cards", []),
|
||||
"seat_showdown": seat_showdown,
|
||||
"can_continue": can_cont,
|
||||
"can_leave_menu": not self.devils_locked,
|
||||
}
|
||||
|
||||
def _open_result_popup(self, popup_data: dict):
|
||||
self._result_dialog = PokerResultDialog(
|
||||
parent=self.table_frame,
|
||||
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"])),
|
||||
)
|
||||
202
main.py
202
main.py
|
|
@ -1,15 +1,217 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
from controller.app_controller import AppController
|
||||
from resources.code_res.game_constants import APP_ICON_REL_PATH
|
||||
from view.font_loader import FontLoader
|
||||
from view.main_window import GothCardCollectionView
|
||||
from view.window_state import WindowStatePersistence
|
||||
|
||||
APP_WM_CLASS = "goth-cardgame-collection"
|
||||
|
||||
|
||||
def _prepare_os_app_identity():
|
||||
if sys.platform.startswith("win"):
|
||||
try:
|
||||
import ctypes
|
||||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
|
||||
"kuro.goth_cardgame_collection.app.1"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elif sys.platform.startswith("linux"):
|
||||
try:
|
||||
import ctypes
|
||||
libc = ctypes.CDLL("libc.so.6")
|
||||
libc.prctl(15, APP_WM_CLASS.encode("utf-8")[:15], 0, 0, 0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _extract_ico_frames(icon_path: Path) -> tuple[Image.Image | None, list[Image.Image]]:
|
||||
"""Liest das größte Bild aus game_icon.ico (auch wenn es intern PNG/JPEG/BMP-codiert ist)."""
|
||||
try:
|
||||
with Image.open(icon_path) as ico:
|
||||
best_img = None
|
||||
best_area = -1
|
||||
|
||||
ico_helper = getattr(ico, "ico", None)
|
||||
if ico_helper is not None and hasattr(ico_helper, "sizes"):
|
||||
for sz in ico_helper.sizes():
|
||||
try:
|
||||
frame = ico_helper.getimage(sz).convert("RGBA")
|
||||
area = frame.width * frame.height
|
||||
if area > best_area:
|
||||
best_area = area
|
||||
best_img = frame
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if best_img is None:
|
||||
n_frames = getattr(ico, "n_frames", 1)
|
||||
for idx in range(n_frames):
|
||||
try:
|
||||
ico.seek(idx)
|
||||
frame = ico.copy().convert("RGBA")
|
||||
area = frame.width * frame.height
|
||||
if area > best_area:
|
||||
best_area = area
|
||||
best_img = frame
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if best_img is None:
|
||||
best_img = ico.convert("RGBA")
|
||||
|
||||
cascade = [
|
||||
best_img.resize((px, px), Image.Resampling.LANCZOS)
|
||||
for px in (256, 128, 64, 48, 32, 16)
|
||||
]
|
||||
return best_img, cascade
|
||||
except Exception:
|
||||
return None, []
|
||||
|
||||
|
||||
def _apply_windows_icon(app, icon_path: Path, best_pil: Image.Image | None):
|
||||
"""
|
||||
Setzt das Icon unter Windows nativ via Tk iconbitmap + Win32 WM_SETICON,
|
||||
ohne dass iconphoto() es wieder mit der Standard-Feder überschreibt.
|
||||
"""
|
||||
import ctypes
|
||||
|
||||
target_ico = icon_path
|
||||
|
||||
# Falls die .ico versehentlich eine umbenannte PNG/JPG ist oder nur einen 256px-PNG-Header hat,
|
||||
# den Tcl/Tk 8.6 auf Windows ablehnt -> saubere Multi-Size-BMP-ICO in Temp erzeugen:
|
||||
if best_pil is not None:
|
||||
try:
|
||||
with open(icon_path, "rb") as f:
|
||||
magic = f.read(4)
|
||||
is_real_ico = (magic == b"\x00\x00\x01\x00")
|
||||
except Exception:
|
||||
is_real_ico = False
|
||||
|
||||
try:
|
||||
if not is_real_ico:
|
||||
raise ValueError("Kein nativer ICO-Header")
|
||||
app.wm_iconbitmap(default=str(target_ico))
|
||||
app.wm_iconbitmap(str(target_ico))
|
||||
except Exception:
|
||||
tmp_ico = Path(tempfile.gettempdir()) / "goth_cardgame_collection_win.ico"
|
||||
best_pil.save(
|
||||
tmp_ico,
|
||||
format="ICO",
|
||||
sizes=[(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
|
||||
)
|
||||
target_ico = tmp_ico
|
||||
try:
|
||||
app.wm_iconbitmap(default=str(target_ico))
|
||||
app.wm_iconbitmap(str(target_ico))
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
app.wm_iconbitmap(default=str(target_ico))
|
||||
app.wm_iconbitmap(str(target_ico))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Zusätzlich direkt per Win32 API ans echte Top-Level-HWND schicken (Titelleiste + Taskbar!)
|
||||
try:
|
||||
app.update_idletasks()
|
||||
hwnd = ctypes.windll.user32.GetParent(app.winfo_id()) or app.winfo_id()
|
||||
IMAGE_ICON = 1
|
||||
LR_LOADFROMFILE = 0x0010
|
||||
LR_DEFAULTSIZE = 0x0040
|
||||
WM_SETICON = 0x0080
|
||||
ICON_SMALL = 0
|
||||
ICON_BIG = 1
|
||||
|
||||
hicon_big = ctypes.windll.user32.LoadImageW(
|
||||
None, str(target_ico), IMAGE_ICON, 48, 48, LR_LOADFROMFILE
|
||||
) or ctypes.windll.user32.LoadImageW(
|
||||
None, str(target_ico), IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE
|
||||
)
|
||||
hicon_small = ctypes.windll.user32.LoadImageW(
|
||||
None, str(target_ico), IMAGE_ICON, 16, 16, LR_LOADFROMFILE
|
||||
) or hicon_big
|
||||
|
||||
if hicon_big:
|
||||
ctypes.windll.user32.SendMessageW(hwnd, WM_SETICON, ICON_BIG, hicon_big)
|
||||
if hicon_small:
|
||||
ctypes.windll.user32.SendMessageW(hwnd, WM_SETICON, ICON_SMALL, hicon_small)
|
||||
app._win_hicons = (hicon_big, hicon_small)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _apply_cross_platform_icon(app, root_path: Path):
|
||||
"""Setzt game_icon.ico zuverlässig auf Windows, Linux, ChromeOS (Crostini) und macOS."""
|
||||
if sys.platform.startswith("linux"):
|
||||
try:
|
||||
app.tk.call("tk", "appname", APP_WM_CLASS)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
icon_path = (root_path / APP_ICON_REL_PATH).resolve()
|
||||
if not icon_path.is_file():
|
||||
return
|
||||
|
||||
best_pil, cascade_pils = _extract_ico_frames(icon_path)
|
||||
|
||||
# WICHTIG: Unter Windows KEIN iconphoto() nach iconbitmap() aufrufen!
|
||||
if sys.platform.startswith("win"):
|
||||
_apply_windows_icon(app, icon_path, best_pil)
|
||||
return
|
||||
|
||||
# Linux, ChromeOS (Crostini) & macOS: Multi-Size iconphoto
|
||||
if cascade_pils:
|
||||
try:
|
||||
tk_photos = [ImageTk.PhotoImage(im) for im in cascade_pils]
|
||||
app._app_icon_refs = tk_photos
|
||||
app.iconphoto(True, *tk_photos)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# macOS Dock-Icon Bonus
|
||||
if sys.platform == "darwin" and best_pil is not None:
|
||||
try:
|
||||
import io
|
||||
from AppKit import NSApplication, NSImage, NSData # type: ignore
|
||||
buf = io.BytesIO()
|
||||
best_pil.save(buf, format="PNG")
|
||||
raw = buf.getvalue()
|
||||
ns_data = NSData.dataWithBytes_length_(raw, len(raw))
|
||||
ns_img = NSImage.alloc().initWithData_(ns_data)
|
||||
if ns_img is not None:
|
||||
NSApplication.sharedApplication().setApplicationIconImage_(ns_img)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
_prepare_os_app_identity()
|
||||
root_path = Path(__file__).resolve().parent
|
||||
|
||||
FontLoader.register_fonts(root_path)
|
||||
|
||||
controller = AppController(root_path)
|
||||
app = GothCardCollectionView(controller, root_path)
|
||||
|
||||
FontLoader.bind_to_tk_root(app)
|
||||
_apply_cross_platform_icon(app, root_path)
|
||||
WindowStatePersistence(app)
|
||||
|
||||
controller.bind_view(app)
|
||||
controller.start()
|
||||
|
||||
# Stellt sicher, dass das Windows-HWND-Icon auch nach dem ersten Map-Event sitzt
|
||||
if sys.platform.startswith("win"):
|
||||
app.after(60, lambda: _apply_cross_platform_icon(app, root_path))
|
||||
|
||||
app.mainloop()
|
||||
|
||||
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -5,8 +5,8 @@ from pathlib import Path
|
|||
import resources.code_res.sql_queries as sql
|
||||
from resources.code_res.game_constants import (
|
||||
BJ_DEFAULT_BET, BJ_STARTING_GOLD, DEVILS_DEAL_GOLD_REWARD,
|
||||
GOLD_MAX_ACCOUNTS, INTERNAL_DB_REL_PATH, USER_DB_FILENAME,
|
||||
XP_TO_GOLD_AMOUNT
|
||||
GOLD_MAX_ACCOUNTS, INTERNAL_DB_REL_PATH, PK_STARTING_GOLD,
|
||||
USER_DB_FILENAME, XP_TO_GOLD_AMOUNT
|
||||
)
|
||||
|
||||
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||
|
|
@ -91,7 +91,7 @@ class Database:
|
|||
def save_setting(cls, key: str, value: str):
|
||||
cls.execute(sql.UPSERT_SETTING, (key, str(value)))
|
||||
|
||||
# --- Profile (reiner Account ohne übergreifendes Level!) ---
|
||||
# --- Profile ---
|
||||
@classmethod
|
||||
def get_profiles(cls) -> list[str]:
|
||||
return [r["name"] for r in cls.fetch_all(sql.SELECT_ALL_PROFILES)]
|
||||
|
|
@ -105,7 +105,7 @@ class Database:
|
|||
def get_profile_by_id(cls, profile_id: int) -> dict | None:
|
||||
return cls.fetch_one(sql.SELECT_PROFILE_BY_ID, (profile_id,))
|
||||
|
||||
# --- Spielgebundene Progression (eigenes Level je Spiel!) ---
|
||||
# --- Spielgebundene Progression ---
|
||||
@classmethod
|
||||
def get_game_progress(cls, profile_id: int, game_folder: str) -> dict:
|
||||
from models.progression import Progression
|
||||
|
|
@ -152,13 +152,12 @@ class Database:
|
|||
|
||||
@classmethod
|
||||
def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict:
|
||||
"""Für künftige Spiel-spezifische Rückstufungen (z.B. Solitaire-Strafen)."""
|
||||
cur = cls.get_game_progress(profile_id, game_folder)
|
||||
new_pts = max(min_floor_xp, cur["total_points"] + int(delta_points))
|
||||
cls.execute(sql.SET_GAME_POINTS, (new_pts, profile_id, game_folder))
|
||||
return cls.get_game_progress(profile_id, game_folder)
|
||||
|
||||
# --- Spielgebundener THE DEVIL'S DEAL (Opfer muss Rang 'Stütze I' IM SELBEN SPIEL haben!) ---
|
||||
# --- Spielgebundener THE DEVIL'S DEAL (Blackjack & Poker jeweils autark!) ---
|
||||
@classmethod
|
||||
def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]:
|
||||
from models.progression import Progression
|
||||
|
|
@ -177,7 +176,7 @@ class Database:
|
|||
|
||||
@classmethod
|
||||
def execute_devils_deal(
|
||||
cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, bj_account_id: int
|
||||
cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, account_id: int
|
||||
) -> tuple[bool, str]:
|
||||
from resources.code_res.i18n import t
|
||||
candidates = {c["id"]: c for c in cls.get_sacrificeable_profiles(active_profile_id, game_folder)}
|
||||
|
|
@ -185,12 +184,19 @@ class Database:
|
|||
if not victim:
|
||||
return False, ""
|
||||
|
||||
if game_folder == "poker":
|
||||
with cls.conn():
|
||||
cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
|
||||
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, bj_account_id))
|
||||
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1, bj_account_id))
|
||||
cls.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
|
||||
cls.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1, account_id))
|
||||
acc = cls.get_poker_account(account_id)
|
||||
else:
|
||||
with cls.conn():
|
||||
cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,))
|
||||
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, account_id))
|
||||
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1, account_id))
|
||||
acc = cls.get_blackjack_account(account_id)
|
||||
|
||||
acc = cls.get_blackjack_account(bj_account_id)
|
||||
return True, t("bj_devils_deal_success", victim["name"], DEVILS_DEAL_GOLD_REWARD, acc["account_name"])
|
||||
|
||||
@classmethod
|
||||
|
|
@ -201,6 +207,14 @@ class Database:
|
|||
def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool):
|
||||
cls.execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1 if active else 0, bj_account_id))
|
||||
|
||||
@classmethod
|
||||
def get_active_devils_pk_account(cls, profile_id: int) -> dict | None:
|
||||
return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_PK_ACCOUNT, (profile_id,))
|
||||
|
||||
@classmethod
|
||||
def set_pk_devils_deal_active(cls, pk_account_id: int, active: bool):
|
||||
cls.execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (1 if active else 0, pk_account_id))
|
||||
|
||||
# --- Savegames ---
|
||||
@classmethod
|
||||
def save_game_state(cls, profile_id: int, game_folder: str, variant_key: str, state_json: str):
|
||||
|
|
@ -214,7 +228,7 @@ class Database:
|
|||
def delete_game_state(cls, profile_id: int, game_folder: str):
|
||||
cls.execute(sql.DELETE_SAVEGAME, (profile_id, game_folder))
|
||||
|
||||
# --- Blackjack Gold-Konten & Blackjack-spezifischer XP->Gold-Tausch ---
|
||||
# --- Blackjack Gold-Konten ---
|
||||
@classmethod
|
||||
def get_blackjack_accounts(cls, profile_id: int) -> list[dict]:
|
||||
return cls.fetch_all(sql.SELECT_BJ_ACCOUNTS_BY_PROFILE, (profile_id,))
|
||||
|
|
@ -252,38 +266,79 @@ class Database:
|
|||
|
||||
@classmethod
|
||||
def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]:
|
||||
"""Zieht XP AUSSCHLIESSLICH vom Blackjack-Spielfortschritt ('blackjack') ab!"""
|
||||
return cls._exchange_game_xp_for_gold(profile_id, "blackjack", bj_account_id)
|
||||
|
||||
# --- Poker Gold-Konten (autarke Bankroll + eigener XP-Tausch!) ---
|
||||
@classmethod
|
||||
def get_poker_accounts(cls, profile_id: int) -> list[dict]:
|
||||
return cls.fetch_all(sql.SELECT_PK_ACCOUNTS_BY_PROFILE, (profile_id,))
|
||||
|
||||
@classmethod
|
||||
def get_poker_account(cls, pk_account_id: int) -> dict | None:
|
||||
return cls.fetch_one(sql.SELECT_PK_ACCOUNT_BY_ID, (pk_account_id,))
|
||||
|
||||
@classmethod
|
||||
def create_poker_account(cls, profile_id: int, account_name: str) -> dict:
|
||||
from resources.code_res.i18n import t
|
||||
clean_name = account_name.strip()
|
||||
if not clean_name:
|
||||
raise ValueError(t("bj_err_empty_name"))
|
||||
if len(cls.get_poker_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS:
|
||||
raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS))
|
||||
cls.execute(sql.INSERT_PK_ACCOUNT, (profile_id, clean_name, PK_STARTING_GOLD))
|
||||
return cls.fetch_one(sql.SELECT_PK_ACCOUNT_BY_NAME, (profile_id, clean_name))
|
||||
|
||||
@classmethod
|
||||
def update_poker_gold(cls, pk_account_id: int, gold_delta: int) -> dict:
|
||||
cls.execute(sql.UPDATE_PK_GOLD_ONLY, (int(gold_delta), pk_account_id))
|
||||
return cls.get_poker_account(pk_account_id)
|
||||
|
||||
@classmethod
|
||||
def delete_poker_account(cls, pk_account_id: int):
|
||||
cls.execute(sql.DELETE_PK_ACCOUNT, (pk_account_id,))
|
||||
|
||||
@classmethod
|
||||
def exchange_xp_for_pk_gold(cls, profile_id: int, pk_account_id: int) -> tuple[bool, str]:
|
||||
return cls._exchange_game_xp_for_gold(profile_id, "poker", pk_account_id)
|
||||
|
||||
@classmethod
|
||||
def _exchange_game_xp_for_gold(cls, profile_id: int, game_folder: str, account_id: int) -> tuple[bool, str]:
|
||||
"""Gemeinsame Logik für streng spielgebundenen XP->Gold-Tausch inkl. Divine Punishment."""
|
||||
from models.progression import Progression
|
||||
from resources.code_res.i18n import t
|
||||
|
||||
bj_prog = cls.get_game_progress(profile_id, "blackjack")
|
||||
if bj_prog.get("at_divine_floor"):
|
||||
prog = cls.get_game_progress(profile_id, game_folder)
|
||||
if prog.get("at_divine_floor"):
|
||||
return False, t("bj_err_floor_reached")
|
||||
|
||||
cost = bj_prog["xp_exchange_cost"]
|
||||
is_divine = bj_prog["is_divine_punishment"]
|
||||
cost = prog["xp_exchange_cost"]
|
||||
is_divine = prog["is_divine_punishment"]
|
||||
|
||||
if not is_divine and bj_prog["total_points"] < cost:
|
||||
return False, t("bj_err_not_enough_xp", bj_prog["total_points"], cost)
|
||||
if not is_divine and prog["total_points"] < cost:
|
||||
return False, t("bj_err_not_enough_xp", prog["total_points"], cost)
|
||||
|
||||
if is_divine:
|
||||
floor_xp = Progression.get_creator_spirit_v_floor_xp()
|
||||
new_points = max(floor_xp, bj_prog["total_points"] - cost)
|
||||
actual_deducted = bj_prog["total_points"] - new_points
|
||||
new_points = max(floor_xp, prog["total_points"] - cost)
|
||||
actual_deducted = prog["total_points"] - new_points
|
||||
if actual_deducted <= 0:
|
||||
return False, t("bj_err_floor_reached")
|
||||
else:
|
||||
new_points = max(0, bj_prog["total_points"] - cost)
|
||||
new_points = max(0, prog["total_points"] - cost)
|
||||
actual_deducted = cost
|
||||
|
||||
with cls.conn():
|
||||
cls.conn().execute(sql.SET_GAME_POINTS, (new_points, profile_id, "blackjack"))
|
||||
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, bj_account_id))
|
||||
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (0, bj_account_id))
|
||||
|
||||
acc = cls.get_blackjack_account(bj_account_id)
|
||||
updated_prog = cls.get_game_progress(profile_id, "blackjack")
|
||||
cls.conn().execute(sql.SET_GAME_POINTS, (new_points, profile_id, game_folder))
|
||||
if game_folder == "poker":
|
||||
cls.conn().execute(sql.UPDATE_PK_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
|
||||
cls.conn().execute(sql.SET_PK_DEVILS_DEAL_ACTIVE, (0, account_id))
|
||||
acc = cls.get_poker_account(account_id)
|
||||
else:
|
||||
cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, account_id))
|
||||
cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (0, account_id))
|
||||
acc = cls.get_blackjack_account(account_id)
|
||||
|
||||
updated_prog = cls.get_game_progress(profile_id, game_folder)
|
||||
if is_divine:
|
||||
return True, t(
|
||||
"bj_exchange_divine_success",
|
||||
|
|
@ -339,9 +394,9 @@ class Database:
|
|||
won: bool,
|
||||
duration_sec: float,
|
||||
points_gained: int = 0,
|
||||
bj_account_id: int | None = None
|
||||
bj_account_id: int | None = None,
|
||||
pk_account_id: int | None = None,
|
||||
) -> tuple[int, int]:
|
||||
"""Ermittelt aus variant_key automatisch den game_folder und bucht XP nur auf dieses Spiel!"""
|
||||
var_info = cls.fetch_one(sql.SELECT_VARIANT_INFO_BY_KEY, (variant_key,))
|
||||
if not var_info:
|
||||
raise ValueError(f"Unbekannte Spielvariante in internal_base.db: {variant_key}")
|
||||
|
|
@ -358,6 +413,8 @@ class Database:
|
|||
cls._upsert_stat("profile", profile_id, variant_id, won, duration_sec)
|
||||
if bj_account_id is not None:
|
||||
cls._upsert_stat("bj_account", bj_account_id, variant_id, won, duration_sec)
|
||||
if pk_account_id is not None:
|
||||
cls._upsert_stat("pk_account", pk_account_id, variant_id, won, duration_sec)
|
||||
|
||||
new_lvl = cls.get_game_progress(profile_id, game_folder)["level"]
|
||||
return old_lvl, new_lvl
|
||||
|
|
@ -412,6 +469,10 @@ class Database:
|
|||
def get_bj_account_stats_overview(cls, bj_account_id: int, variant_id: int | None = None) -> dict:
|
||||
return cls._query_stats("bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack")
|
||||
|
||||
@classmethod
|
||||
def get_pk_account_stats_overview(cls, pk_account_id: int, variant_id: int | None = None) -> dict:
|
||||
return cls._query_stats("pk_account", pk_account_id, variant_id=variant_id, folder_path="poker")
|
||||
|
||||
@staticmethod
|
||||
def format_seconds(sec: float | None) -> str:
|
||||
if sec is None:
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
|
|
@ -10,7 +10,7 @@ DEFAULT_CARD_THEME = "default"
|
|||
|
||||
UI_IMAGES = {
|
||||
"background": "background.jpeg",
|
||||
"title": "title1.png",
|
||||
"title": "title.jpg",
|
||||
"btn_normal": "button1.png",
|
||||
"btn_active": "button1_active.png",
|
||||
"sel_inactive": "selection_inactive.png",
|
||||
|
|
@ -20,6 +20,18 @@ UI_IMAGES = {
|
|||
"lose_gif": "lose.gif",
|
||||
}
|
||||
|
||||
APP_ICON_REL_PATH = "resources/images/game_icon.ico"
|
||||
FONTS_REL_DIR = "resources/fonts"
|
||||
CUSTOM_FONT_FILES = (
|
||||
"OldLondon.ttf",
|
||||
"OldLondonAlternate.ttf",
|
||||
)
|
||||
|
||||
# Interne Familiennamen aus den TTF-Metadaten (+ Fallback)
|
||||
FONT_GOTH_TITLE = "Old London"
|
||||
FONT_GOTH_ALT = "Old London Alternate"
|
||||
FONT_UI_BODY = "Helvetica"
|
||||
|
||||
# --- Flache Hauptkategorien (niemals Unterkategorien!) ---
|
||||
CAT_LUCK = "luck"
|
||||
CAT_SOLO = "solo"
|
||||
|
|
@ -127,6 +139,8 @@ STAT_FIELD_KEYS = (
|
|||
# --- Bots (0..5 Offline-Stufen, 6 = Gottheit / Online-Standard!) ---
|
||||
BOT_DEITY_LEVEL = 6
|
||||
BOT_LEVEL_COUNT = 7
|
||||
|
||||
# --- Blackjack ---
|
||||
BJ_MAX_BOTS = 3
|
||||
BJ_STARTING_GOLD = 1000
|
||||
BJ_INITIAL_ANTE = 10
|
||||
|
|
@ -155,6 +169,32 @@ BJ_VARIANTS = {
|
|||
},
|
||||
}
|
||||
|
||||
# --- Texas Hold'em Poker (6-Max, autarke Goldbeutel) ---
|
||||
PK_MAX_BOTS = 5
|
||||
PK_STARTING_GOLD = 1000
|
||||
PK_BOT_TURN_DELAY_MS = 600
|
||||
PK_STREET_DELAY_MS = 700
|
||||
PK_TABLE_IMAGE = "poker_table.jpg"
|
||||
|
||||
PK_VARIANTS = {
|
||||
"poker_holdem": {
|
||||
"sb": 5,
|
||||
"bb": 10,
|
||||
"min_entry": 10,
|
||||
"bet_scale": 1,
|
||||
"xp_mult": 1.15,
|
||||
"back_color": "Black",
|
||||
},
|
||||
"poker_holdem_high": {
|
||||
"sb": 10,
|
||||
"bb": 20,
|
||||
"min_entry": 20,
|
||||
"bet_scale": 2,
|
||||
"xp_mult": 1.65,
|
||||
"back_color": "Red",
|
||||
},
|
||||
}
|
||||
|
||||
# --- UI Theme & Geometrie ---
|
||||
DEFAULT_WINDOW_GEOM = "1150x800"
|
||||
MIN_WINDOW_SIZE = (980, 700)
|
||||
|
|
@ -162,6 +202,8 @@ MENU_CARD_SIZE = (185, 245)
|
|||
PLAYING_CARD_SIZE = (102, 148)
|
||||
BJ_SPLIT_CARD_SIZE = (84, 122)
|
||||
BJ_BOT_CARD_SIZE = (64, 94)
|
||||
PK_BOARD_CARD_SIZE = (88, 128)
|
||||
PK_BOT_CARD_SIZE = (54, 80)
|
||||
OUTCOME_GIF_SIZE = (170, 95)
|
||||
|
||||
BG_COLOR = "#0d0b12"
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -740,4 +740,148 @@ INSERT INTO base_i18n (key, lang, val) VALUES
|
|||
('bj_popup_next_round_btn', 'EN', 'Start Next Round'),
|
||||
('bj_popup_to_menu_btn', 'EN', 'Back to Game Menu');
|
||||
|
||||
|
||||
INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
|
||||
-- =========================================================================
|
||||
-- DE: TEXAS HOLD'EM POKER (Menü, Konten, 6-Max Tisch, Hände & Ergebnis)
|
||||
-- =========================================================================
|
||||
('pk_menu_topbar', 'DE', 'Texas Hold''em – Konten & 6-Max Tischauswahl'),
|
||||
('pk_stats_view_topbar', 'DE', 'Texas Hold''em – Konto-Statistiken'),
|
||||
('pk_sec1_title', 'DE', '1. Poker-Goldkonto ({0}/{1} Beutel • Start: {2} Gold)'),
|
||||
('pk_bots_sec_title', 'DE', '2. Gegner am 6-Max-Tisch (mind. 1 bis max. 5 Bots)'),
|
||||
('pk_sec3_title', 'DE', '3. Tischvariante wählen'),
|
||||
('pk_default_acc_name', 'DE', 'Pokerbeutel #{0}'),
|
||||
('pk_acc_limit_info', 'DE', 'Max. {0} Goldbeutel. Blinds ab {1}/{2} Gold, No-Limit mit All-In & Side-Pots. Tausch: {3} XP → +{4} Gold.'),
|
||||
('pk_err_duplicate_name', 'DE', 'Ein Poker-Konto mit diesem Namen existiert bereits.'),
|
||||
('pk_err_need_one_bot', 'DE', 'Beim Poker muss mindestens 1 Gegner am Tisch sitzen!'),
|
||||
('pk_variant_desc', 'DE', '6-Max No-Limit • Blinds: {0}/{1} Gold • Min. Buy-In: {2} Gold • Side-Pots aktiv'),
|
||||
('pk_filter_all_tables', 'DE', 'Dieses Konto (Alle Poker-Tische)'),
|
||||
('pk_header_gold', 'DE', 'Konto ''{0}'': {1} Gold'),
|
||||
|
||||
-- Straßen & Tisch-Banner
|
||||
('pk_pot_banner', 'DE', 'GESAMT-POT: {0} Gold | Phase: {1} | Aktueller Einsatz: {2} Gold'),
|
||||
('pk_street_PREFLOP', 'DE', 'Pre-Flop'),
|
||||
('pk_street_FLOP', 'DE', 'Flop (3 Karten)'),
|
||||
('pk_street_TURN', 'DE', 'Turn (4. Karte)'),
|
||||
('pk_street_RIVER', 'DE', 'River (5. Karte)'),
|
||||
('pk_street_SHOWDOWN', 'DE', 'Showdown'),
|
||||
('pk_board_title', 'DE', 'Gemeinschaftskarten (Board)'),
|
||||
('pk_player_info', 'DE', 'Deine Hand: {0} | Runde: {1}g | Gesamt im Pot: {2}g{3}'),
|
||||
('pk_role_dealer', 'DE', ' [D]'),
|
||||
('pk_role_sb', 'DE', ' [SB]'),
|
||||
('pk_role_bb', 'DE', ' [BB]'),
|
||||
('pk_state_folded', 'DE', ' [GEPASST]'),
|
||||
('pk_state_allin', 'DE', ' [ALL-IN]'),
|
||||
|
||||
-- Spieler-Steuerung
|
||||
('pk_turn_prompt_check', 'DE', 'Dein Zug ({0}): Schieben (Check), Anspielen (Raise), All-In oder Passen.'),
|
||||
('pk_turn_prompt_call', 'DE', 'Dein Zug ({0}): +{1} Gold zum Mitgehen (Call) — oder Erhöhen, All-In, Passen.'),
|
||||
('pk_btn_fold', 'DE', 'Passen (Fold)'),
|
||||
('pk_btn_check', 'DE', 'Schieben (Check)'),
|
||||
('pk_btn_call', 'DE', 'Mitgehen (+{0})'),
|
||||
('pk_btn_allin', 'DE', 'ALL-IN (+{0})'),
|
||||
('pk_raise_lbl', 'DE', 'Erhöhen +:'),
|
||||
|
||||
-- Bots am 6-Max Tisch
|
||||
('pk_bot_turn_status', 'DE', '{0} überlegt...'),
|
||||
('pk_bot_stack_lbl', 'DE', 'Stack: {0}g • Einsatz: {1}g'),
|
||||
('pk_bot_act_sb', 'DE', 'Small Blind ({0}g)'),
|
||||
('pk_bot_act_bb', 'DE', 'Big Blind ({0}g)'),
|
||||
('pk_bot_act_check', 'DE', 'Schiebt (Check)'),
|
||||
('pk_bot_act_call', 'DE', 'Geht mit (+{0}g)'),
|
||||
('pk_bot_act_raise', 'DE', 'Erhöht (+{0}g)'),
|
||||
('pk_bot_act_allin', 'DE', 'ALL-IN! ({0}g)'),
|
||||
('pk_bot_act_fold', 'DE', 'Gepasst'),
|
||||
('pk_showdown_running', 'DE', 'Alle verbleibenden Karten werden aufgedeckt — Showdown!'),
|
||||
|
||||
-- Poker Hand-Ränge (0..9)
|
||||
('pk_hand_0', 'DE', 'Höchste Karte (High Card)'),
|
||||
('pk_hand_1', 'DE', 'Ein Paar (One Pair)'),
|
||||
('pk_hand_2', 'DE', 'Zwei Paare (Two Pair)'),
|
||||
('pk_hand_3', 'DE', 'Drilling (Three of a Kind)'),
|
||||
('pk_hand_4', 'DE', 'Straße (Straight)'),
|
||||
('pk_hand_5', 'DE', 'Flush'),
|
||||
('pk_hand_6', 'DE', 'Full House'),
|
||||
('pk_hand_7', 'DE', 'Vierling (Four of a Kind)'),
|
||||
('pk_hand_8', 'DE', 'Straight Flush'),
|
||||
('pk_hand_9', 'DE', '★ ROYAL FLUSH ★'),
|
||||
|
||||
-- Ergebnis-Popup
|
||||
('pk_popup_player_won', 'DE', 'Du gewinnst den Pot! ({0})'),
|
||||
('pk_popup_split_won', 'DE', 'Split-Pot gewonnen! ({0})'),
|
||||
('pk_popup_bot_won', 'DE', '{0} gewinnt ({1})'),
|
||||
('pk_popup_fold_win', 'DE', 'Alle Gegner haben gepasst'),
|
||||
('pk_popup_bot_gain', 'DE', 'Pot-Gewinn von {0}: +{1} Gold'),
|
||||
|
||||
-- =========================================================================
|
||||
-- EN: TEXAS HOLD'EM POKER
|
||||
-- =========================================================================
|
||||
('pk_menu_topbar', 'EN', 'Texas Hold''em – Accounts & 6-Max Table Selection'),
|
||||
('pk_stats_view_topbar', 'EN', 'Texas Hold''em – Account Statistics'),
|
||||
('pk_sec1_title', 'EN', '1. Poker Gold Account ({0}/{1} Pouches • Start: {2} Gold)'),
|
||||
('pk_bots_sec_title', 'EN', '2. Opponents at 6-Max Table (min. 1 to max. 5 Bots)'),
|
||||
('pk_sec3_title', 'EN', '3. Choose Table Variant'),
|
||||
('pk_default_acc_name', 'EN', 'Poker Pouch #{0}'),
|
||||
('pk_acc_limit_info', 'EN', 'Max {0} Pouches. Blinds from {1}/{2} Gold, No-Limit with All-In & Side Pots. Exchange: {3} XP → +{4} Gold.'),
|
||||
('pk_err_duplicate_name', 'EN', 'A Poker account with this name already exists.'),
|
||||
('pk_err_need_one_bot', 'EN', 'At least 1 opponent must sit at a Poker table!'),
|
||||
('pk_variant_desc', 'EN', '6-Max No-Limit • Blinds: {0}/{1} Gold • Min Buy-In: {2} Gold • Side Pots active'),
|
||||
('pk_filter_all_tables', 'EN', 'This Account (All Poker Tables)'),
|
||||
('pk_header_gold', 'EN', 'Account ''{0}'': {1} Gold'),
|
||||
|
||||
-- Streets & Table Banner
|
||||
('pk_pot_banner', 'EN', 'TOTAL POT: {0} Gold | Street: {1} | Current Bet: {2} Gold'),
|
||||
('pk_street_PREFLOP', 'EN', 'Pre-Flop'),
|
||||
('pk_street_FLOP', 'EN', 'Flop (3 Cards)'),
|
||||
('pk_street_TURN', 'EN', 'Turn (4th Card)'),
|
||||
('pk_street_RIVER', 'EN', 'River (5th Card)'),
|
||||
('pk_street_SHOWDOWN', 'EN', 'Showdown'),
|
||||
('pk_board_title', 'EN', 'Community Cards (Board)'),
|
||||
('pk_player_info', 'EN', 'Your Hand: {0} | Street: {1}g | Total in Pot: {2}g{3}'),
|
||||
('pk_role_dealer', 'EN', ' [D]'),
|
||||
('pk_role_sb', 'EN', ' [SB]'),
|
||||
('pk_role_bb', 'EN', ' [BB]'),
|
||||
('pk_state_folded', 'EN', ' [FOLDED]'),
|
||||
('pk_state_allin', 'EN', ' [ALL-IN]'),
|
||||
|
||||
-- Player Controls
|
||||
('pk_turn_prompt_check', 'EN', 'Your turn ({0}): Check, Bet/Raise, All-In, or Fold.'),
|
||||
('pk_turn_prompt_call', 'EN', 'Your turn ({0}): +{1} Gold to Call — or Raise, All-In, Fold.'),
|
||||
('pk_btn_fold', 'EN', 'Fold'),
|
||||
('pk_btn_check', 'EN', 'Check'),
|
||||
('pk_btn_call', 'EN', 'Call (+{0})'),
|
||||
('pk_btn_allin', 'EN', 'ALL-IN (+{0})'),
|
||||
('pk_raise_lbl', 'EN', 'Raise +:'),
|
||||
|
||||
-- 6-Max Bots
|
||||
('pk_bot_turn_status', 'EN', '{0} is thinking...'),
|
||||
('pk_bot_stack_lbl', 'EN', 'Stack: {0}g • Bet: {1}g'),
|
||||
('pk_bot_act_sb', 'EN', 'Small Blind ({0}g)'),
|
||||
('pk_bot_act_bb', 'EN', 'Big Blind ({0}g)'),
|
||||
('pk_bot_act_check', 'EN', 'Checks'),
|
||||
('pk_bot_act_call', 'EN', 'Calls (+{0}g)'),
|
||||
('pk_bot_act_raise', 'EN', 'Raises (+{0}g)'),
|
||||
('pk_bot_act_allin', 'EN', 'ALL-IN! ({0}g)'),
|
||||
('pk_bot_act_fold', 'EN', 'Folded'),
|
||||
('pk_showdown_running', 'EN', 'Revealing remaining board cards — Showdown!'),
|
||||
|
||||
-- Poker Hand Ranks (0..9)
|
||||
('pk_hand_0', 'EN', 'High Card'),
|
||||
('pk_hand_1', 'EN', 'One Pair'),
|
||||
('pk_hand_2', 'EN', 'Two Pair'),
|
||||
('pk_hand_3', 'EN', 'Three of a Kind'),
|
||||
('pk_hand_4', 'EN', 'Straight'),
|
||||
('pk_hand_5', 'EN', 'Flush'),
|
||||
('pk_hand_6', 'EN', 'Full House'),
|
||||
('pk_hand_7', 'EN', 'Four of a Kind'),
|
||||
('pk_hand_8', 'EN', 'Straight Flush'),
|
||||
('pk_hand_9', 'EN', '★ ROYAL FLUSH ★'),
|
||||
|
||||
-- Result Popup
|
||||
('pk_popup_player_won', 'EN', 'You won the Pot! ({0})'),
|
||||
('pk_popup_split_won', 'EN', 'Split Pot Won! ({0})'),
|
||||
('pk_popup_bot_won', 'EN', '{0} Won ({1})'),
|
||||
('pk_popup_fold_win', 'EN', 'All opponents folded'),
|
||||
('pk_popup_bot_gain', 'EN', 'Pot profit of {0}: +{1} Gold');
|
||||
|
||||
COMMIT;
|
||||
|
|
@ -57,6 +57,17 @@ CREATE TABLE IF NOT EXISTS blackjack_accounts (
|
|||
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS poker_accounts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
profile_id INTEGER NOT NULL,
|
||||
account_name TEXT NOT NULL,
|
||||
gold INTEGER NOT NULL DEFAULT 1000,
|
||||
devils_deal_active INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(profile_id, account_name),
|
||||
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS player_stats (
|
||||
profile_id INTEGER NOT NULL,
|
||||
variant_id INTEGER NOT NULL,
|
||||
|
|
@ -85,6 +96,20 @@ CREATE TABLE IF NOT EXISTS blackjack_account_stats (
|
|||
FOREIGN KEY (bj_account_id) REFERENCES blackjack_accounts(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS poker_account_stats (
|
||||
pk_account_id INTEGER NOT NULL,
|
||||
variant_id INTEGER NOT NULL,
|
||||
games_played INTEGER NOT NULL DEFAULT 0,
|
||||
games_won INTEGER NOT NULL DEFAULT 0,
|
||||
games_lost INTEGER NOT NULL DEFAULT 0,
|
||||
current_streak INTEGER NOT NULL DEFAULT 0,
|
||||
longest_streak INTEGER NOT NULL DEFAULT 0,
|
||||
best_time_sec REAL DEFAULT NULL,
|
||||
total_time_sec REAL NOT NULL DEFAULT 0.0,
|
||||
PRIMARY KEY (pk_account_id, variant_id),
|
||||
FOREIGN KEY (pk_account_id) REFERENCES poker_accounts(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bot_configs (
|
||||
profile_id INTEGER NOT NULL,
|
||||
game_folder TEXT NOT NULL,
|
||||
|
|
@ -113,14 +138,14 @@ INSERT INTO settings (key, value) VALUES (?, ?)
|
|||
ON CONFLICT(key) DO UPDATE SET value = excluded.value;
|
||||
"""
|
||||
|
||||
# --- Profiles (rein Account-Identität, ohne globales Level!) ---
|
||||
# --- Profiles ---
|
||||
SELECT_ALL_PROFILES = "SELECT name FROM profiles ORDER BY name COLLATE NOCASE;"
|
||||
INSERT_PROFILE_IGNORE = "INSERT OR IGNORE INTO profiles (name) VALUES (?);"
|
||||
SELECT_PROFILE_BY_NAME = "SELECT id, name FROM profiles WHERE name = ?;"
|
||||
SELECT_PROFILE_BY_ID = "SELECT id, name FROM profiles WHERE id = ?;"
|
||||
DELETE_PROFILE_BY_ID = "DELETE FROM profiles WHERE id = ?;"
|
||||
|
||||
# --- Spielgebundene Progression & Level-Historie (pro profile_id + game_folder) ---
|
||||
# --- Spielgebundene Progression & Level-Historie ---
|
||||
INSERT_GAME_PROGRESS_IGNORE = """
|
||||
INSERT OR IGNORE INTO game_progress (profile_id, game_folder, points, ever_reached_deity)
|
||||
VALUES (?, ?, 0, 0);
|
||||
|
|
@ -204,6 +229,30 @@ UPDATE_BJ_LAST_BET = "UPDATE blackjack_accounts SET last_bet = ? WHERE id = ?;"
|
|||
SET_BJ_DEVILS_DEAL_ACTIVE = "UPDATE blackjack_accounts SET devils_deal_active = ? WHERE id = ?;"
|
||||
DELETE_BJ_ACCOUNT = "DELETE FROM blackjack_accounts WHERE id = ?;"
|
||||
|
||||
# --- Poker Gold Accounts (komplett autark!) ---
|
||||
SELECT_PK_ACCOUNTS_BY_PROFILE = """
|
||||
SELECT id, profile_id, account_name, gold, devils_deal_active
|
||||
FROM poker_accounts WHERE profile_id = ? ORDER BY id ASC;
|
||||
"""
|
||||
SELECT_PK_ACCOUNT_BY_ID = """
|
||||
SELECT id, profile_id, account_name, gold, devils_deal_active
|
||||
FROM poker_accounts WHERE id = ?;
|
||||
"""
|
||||
SELECT_PK_ACCOUNT_BY_NAME = """
|
||||
SELECT id, profile_id, account_name, gold, devils_deal_active
|
||||
FROM poker_accounts WHERE profile_id = ? AND account_name = ?;
|
||||
"""
|
||||
SELECT_ACTIVE_DEVILS_PK_ACCOUNT = """
|
||||
SELECT id, profile_id, account_name, gold, devils_deal_active
|
||||
FROM poker_accounts
|
||||
WHERE profile_id = ? AND devils_deal_active = 1
|
||||
LIMIT 1;
|
||||
"""
|
||||
INSERT_PK_ACCOUNT = "INSERT INTO poker_accounts (profile_id, account_name, gold, devils_deal_active) VALUES (?, ?, ?, 0);"
|
||||
UPDATE_PK_GOLD_ONLY = "UPDATE poker_accounts SET gold = MAX(0, gold + ?) WHERE id = ?;"
|
||||
SET_PK_DEVILS_DEAL_ACTIVE = "UPDATE poker_accounts SET devils_deal_active = ? WHERE id = ?;"
|
||||
DELETE_PK_ACCOUNT = "DELETE FROM poker_accounts WHERE id = ?;"
|
||||
|
||||
# --- Bot Configs ---
|
||||
SELECT_BOT_CONFIGS = "SELECT slot_idx, bot_name, ai_level FROM bot_configs WHERE profile_id = ? AND game_folder = ? ORDER BY slot_idx ASC;"
|
||||
UPSERT_BOT_CONFIG = """
|
||||
|
|
@ -300,4 +349,46 @@ STATS_SQL = {
|
|||
FROM blackjack_account_stats WHERE bj_account_id = ?;
|
||||
""",
|
||||
},
|
||||
"pk_account": {
|
||||
"select_one": """
|
||||
SELECT games_played, games_won, games_lost, current_streak,
|
||||
longest_streak, best_time_sec, total_time_sec
|
||||
FROM poker_account_stats WHERE pk_account_id = ? AND variant_id = ?;
|
||||
""",
|
||||
"insert": """
|
||||
INSERT INTO poker_account_stats (
|
||||
pk_account_id, variant_id, games_played, games_won, games_lost,
|
||||
current_streak, longest_streak, best_time_sec, total_time_sec
|
||||
) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?);
|
||||
""",
|
||||
"update": """
|
||||
UPDATE poker_account_stats SET
|
||||
games_played = ?, games_won = ?, games_lost = ?,
|
||||
current_streak = ?, longest_streak = ?,
|
||||
best_time_sec = ?, total_time_sec = ?
|
||||
WHERE pk_account_id = ? AND variant_id = ?;
|
||||
""",
|
||||
"aggregate_folder": """
|
||||
SELECT COALESCE(SUM(ps.games_played), 0) AS played,
|
||||
COALESCE(SUM(ps.games_won), 0) AS won,
|
||||
COALESCE(SUM(ps.games_lost), 0) AS lost,
|
||||
COALESCE(SUM(ps.current_streak), 0) AS c_streak,
|
||||
COALESCE(MAX(ps.longest_streak), 0) AS l_streak,
|
||||
MIN(ps.best_time_sec) AS best_time,
|
||||
COALESCE(SUM(ps.total_time_sec), 0.0) AS total_time
|
||||
FROM poker_account_stats ps
|
||||
JOIN core.game_variants gv ON gv.id = ps.variant_id
|
||||
WHERE ps.pk_account_id = ? AND gv.folder_path = ?;
|
||||
""",
|
||||
"aggregate_all": """
|
||||
SELECT COALESCE(SUM(games_played), 0) AS played,
|
||||
COALESCE(SUM(games_won), 0) AS won,
|
||||
COALESCE(SUM(games_lost), 0) AS lost,
|
||||
COALESCE(SUM(current_streak), 0) AS c_streak,
|
||||
COALESCE(MAX(longest_streak), 0) AS l_streak,
|
||||
MIN(best_time_sec) AS best_time,
|
||||
COALESCE(SUM(total_time_sec), 0.0) AS total_time
|
||||
FROM poker_account_stats WHERE pk_account_id = ?;
|
||||
""",
|
||||
},
|
||||
}
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
BEGIN TRANSACTION;
|
||||
|
||||
INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
|
||||
-- =========================================================================
|
||||
-- DE: TEXAS HOLD'EM POKER (Menü, Konten, 6-Max Tisch, Hände & Ergebnis)
|
||||
-- =========================================================================
|
||||
('pk_menu_topbar', 'DE', 'Texas Hold''em – Konten & 6-Max Tischauswahl'),
|
||||
('pk_stats_view_topbar', 'DE', 'Texas Hold''em – Konto-Statistiken'),
|
||||
('pk_sec1_title', 'DE', '1. Poker-Goldkonto ({0}/{1} Beutel • Start: {2} Gold)'),
|
||||
('pk_bots_sec_title', 'DE', '2. Gegner am 6-Max-Tisch (mind. 1 bis max. 5 Bots)'),
|
||||
('pk_sec3_title', 'DE', '3. Tischvariante wählen'),
|
||||
('pk_default_acc_name', 'DE', 'Pokerbeutel #{0}'),
|
||||
('pk_acc_limit_info', 'DE', 'Max. {0} Goldbeutel. Blinds ab {1}/{2} Gold, No-Limit mit All-In & Side-Pots. Tausch: {3} XP → +{4} Gold.'),
|
||||
('pk_err_duplicate_name', 'DE', 'Ein Poker-Konto mit diesem Namen existiert bereits.'),
|
||||
('pk_err_need_one_bot', 'DE', 'Beim Poker muss mindestens 1 Gegner am Tisch sitzen!'),
|
||||
('pk_variant_desc', 'DE', '6-Max No-Limit • Blinds: {0}/{1} Gold • Min. Buy-In: {2} Gold • Side-Pots aktiv'),
|
||||
('pk_filter_all_tables', 'DE', 'Dieses Konto (Alle Poker-Tische)'),
|
||||
('pk_header_gold', 'DE', 'Konto ''{0}'': {1} Gold'),
|
||||
|
||||
-- Straßen & Tisch-Banner
|
||||
('pk_pot_banner', 'DE', 'GESAMT-POT: {0} Gold | Phase: {1} | Aktueller Einsatz: {2} Gold'),
|
||||
('pk_street_PREFLOP', 'DE', 'Pre-Flop'),
|
||||
('pk_street_FLOP', 'DE', 'Flop (3 Karten)'),
|
||||
('pk_street_TURN', 'DE', 'Turn (4. Karte)'),
|
||||
('pk_street_RIVER', 'DE', 'River (5. Karte)'),
|
||||
('pk_street_SHOWDOWN', 'DE', 'Showdown'),
|
||||
('pk_board_title', 'DE', 'Gemeinschaftskarten (Board)'),
|
||||
('pk_player_info', 'DE', 'Deine Hand: {0} | Runde: {1}g | Gesamt im Pot: {2}g{3}'),
|
||||
('pk_role_dealer', 'DE', ' [D]'),
|
||||
('pk_role_sb', 'DE', ' [SB]'),
|
||||
('pk_role_bb', 'DE', ' [BB]'),
|
||||
('pk_state_folded', 'DE', ' [GEPASST]'),
|
||||
('pk_state_allin', 'DE', ' [ALL-IN]'),
|
||||
|
||||
-- Spieler-Steuerung
|
||||
('pk_turn_prompt_check', 'DE', 'Dein Zug ({0}): Schieben (Check), Anspielen (Raise), All-In oder Passen.'),
|
||||
('pk_turn_prompt_call', 'DE', 'Dein Zug ({0}): +{1} Gold zum Mitgehen (Call) — oder Erhöhen, All-In, Passen.'),
|
||||
('pk_btn_fold', 'DE', 'Passen (Fold)'),
|
||||
('pk_btn_check', 'DE', 'Schieben (Check)'),
|
||||
('pk_btn_call', 'DE', 'Mitgehen (+{0})'),
|
||||
('pk_btn_allin', 'DE', 'ALL-IN (+{0})'),
|
||||
('pk_raise_lbl', 'DE', 'Erhöhen +:'),
|
||||
|
||||
-- Bots am 6-Max Tisch
|
||||
('pk_bot_turn_status', 'DE', '{0} überlegt...'),
|
||||
('pk_bot_stack_lbl', 'DE', 'Stack: {0}g • Einsatz: {1}g'),
|
||||
('pk_bot_act_sb', 'DE', 'Small Blind ({0}g)'),
|
||||
('pk_bot_act_bb', 'DE', 'Big Blind ({0}g)'),
|
||||
('pk_bot_act_check', 'DE', 'Schiebt (Check)'),
|
||||
('pk_bot_act_call', 'DE', 'Geht mit (+{0}g)'),
|
||||
('pk_bot_act_raise', 'DE', 'Erhöht (+{0}g)'),
|
||||
('pk_bot_act_allin', 'DE', 'ALL-IN! ({0}g)'),
|
||||
('pk_bot_act_fold', 'DE', 'Gepasst'),
|
||||
('pk_showdown_running', 'DE', 'Alle verbleibenden Karten werden aufgedeckt — Showdown!'),
|
||||
|
||||
-- Poker Hand-Ränge (0..9)
|
||||
('pk_hand_0', 'DE', 'Höchste Karte (High Card)'),
|
||||
('pk_hand_1', 'DE', 'Ein Paar (One Pair)'),
|
||||
('pk_hand_2', 'DE', 'Zwei Paare (Two Pair)'),
|
||||
('pk_hand_3', 'DE', 'Drilling (Three of a Kind)'),
|
||||
('pk_hand_4', 'DE', 'Straße (Straight)'),
|
||||
('pk_hand_5', 'DE', 'Flush'),
|
||||
('pk_hand_6', 'DE', 'Full House'),
|
||||
('pk_hand_7', 'DE', 'Vierling (Four of a Kind)'),
|
||||
('pk_hand_8', 'DE', 'Straight Flush'),
|
||||
('pk_hand_9', 'DE', '★ ROYAL FLUSH ★'),
|
||||
|
||||
-- Ergebnis-Popup
|
||||
('pk_popup_player_won', 'DE', 'Du gewinnst den Pot! ({0})'),
|
||||
('pk_popup_split_won', 'DE', 'Split-Pot gewonnen! ({0})'),
|
||||
('pk_popup_bot_won', 'DE', '{0} gewinnt ({1})'),
|
||||
('pk_popup_fold_win', 'DE', 'Alle Gegner haben gepasst'),
|
||||
('pk_popup_bot_gain', 'DE', 'Pot-Gewinn von {0}: +{1} Gold'),
|
||||
|
||||
-- =========================================================================
|
||||
-- EN: TEXAS HOLD'EM POKER
|
||||
-- =========================================================================
|
||||
('pk_menu_topbar', 'EN', 'Texas Hold''em – Accounts & 6-Max Table Selection'),
|
||||
('pk_stats_view_topbar', 'EN', 'Texas Hold''em – Account Statistics'),
|
||||
('pk_sec1_title', 'EN', '1. Poker Gold Account ({0}/{1} Pouches • Start: {2} Gold)'),
|
||||
('pk_bots_sec_title', 'EN', '2. Opponents at 6-Max Table (min. 1 to max. 5 Bots)'),
|
||||
('pk_sec3_title', 'EN', '3. Choose Table Variant'),
|
||||
('pk_default_acc_name', 'EN', 'Poker Pouch #{0}'),
|
||||
('pk_acc_limit_info', 'EN', 'Max {0} Pouches. Blinds from {1}/{2} Gold, No-Limit with All-In & Side Pots. Exchange: {3} XP → +{4} Gold.'),
|
||||
('pk_err_duplicate_name', 'EN', 'A Poker account with this name already exists.'),
|
||||
('pk_err_need_one_bot', 'EN', 'At least 1 opponent must sit at a Poker table!'),
|
||||
('pk_variant_desc', 'EN', '6-Max No-Limit • Blinds: {0}/{1} Gold • Min Buy-In: {2} Gold • Side Pots active'),
|
||||
('pk_filter_all_tables', 'EN', 'This Account (All Poker Tables)'),
|
||||
('pk_header_gold', 'EN', 'Account ''{0}'': {1} Gold'),
|
||||
|
||||
-- Streets & Table Banner
|
||||
('pk_pot_banner', 'EN', 'TOTAL POT: {0} Gold | Street: {1} | Current Bet: {2} Gold'),
|
||||
('pk_street_PREFLOP', 'EN', 'Pre-Flop'),
|
||||
('pk_street_FLOP', 'EN', 'Flop (3 Cards)'),
|
||||
('pk_street_TURN', 'EN', 'Turn (4th Card)'),
|
||||
('pk_street_RIVER', 'EN', 'River (5th Card)'),
|
||||
('pk_street_SHOWDOWN', 'EN', 'Showdown'),
|
||||
('pk_board_title', 'EN', 'Community Cards (Board)'),
|
||||
('pk_player_info', 'EN', 'Your Hand: {0} | Street: {1}g | Total in Pot: {2}g{3}'),
|
||||
('pk_role_dealer', 'EN', ' [D]'),
|
||||
('pk_role_sb', 'EN', ' [SB]'),
|
||||
('pk_role_bb', 'EN', ' [BB]'),
|
||||
('pk_state_folded', 'EN', ' [FOLDED]'),
|
||||
('pk_state_allin', 'EN', ' [ALL-IN]'),
|
||||
|
||||
-- Player Controls
|
||||
('pk_turn_prompt_check', 'EN', 'Your turn ({0}): Check, Bet/Raise, All-In, or Fold.'),
|
||||
('pk_turn_prompt_call', 'EN', 'Your turn ({0}): +{1} Gold to Call — or Raise, All-In, Fold.'),
|
||||
('pk_btn_fold', 'EN', 'Fold'),
|
||||
('pk_btn_check', 'EN', 'Check'),
|
||||
('pk_btn_call', 'EN', 'Call (+{0})'),
|
||||
('pk_btn_allin', 'EN', 'ALL-IN (+{0})'),
|
||||
('pk_raise_lbl', 'EN', 'Raise +:'),
|
||||
|
||||
-- 6-Max Bots
|
||||
('pk_bot_turn_status', 'EN', '{0} is thinking...'),
|
||||
('pk_bot_stack_lbl', 'EN', 'Stack: {0}g • Bet: {1}g'),
|
||||
('pk_bot_act_sb', 'EN', 'Small Blind ({0}g)'),
|
||||
('pk_bot_act_bb', 'EN', 'Big Blind ({0}g)'),
|
||||
('pk_bot_act_check', 'EN', 'Checks'),
|
||||
('pk_bot_act_call', 'EN', 'Calls (+{0}g)'),
|
||||
('pk_bot_act_raise', 'EN', 'Raises (+{0}g)'),
|
||||
('pk_bot_act_allin', 'EN', 'ALL-IN! ({0}g)'),
|
||||
('pk_bot_act_fold', 'EN', 'Folded'),
|
||||
('pk_showdown_running', 'EN', 'Revealing remaining board cards — Showdown!'),
|
||||
|
||||
-- Poker Hand Ranks (0..9)
|
||||
('pk_hand_0', 'EN', 'High Card'),
|
||||
('pk_hand_1', 'EN', 'One Pair'),
|
||||
('pk_hand_2', 'EN', 'Two Pair'),
|
||||
('pk_hand_3', 'EN', 'Three of a Kind'),
|
||||
('pk_hand_4', 'EN', 'Straight'),
|
||||
('pk_hand_5', 'EN', 'Flush'),
|
||||
('pk_hand_6', 'EN', 'Full House'),
|
||||
('pk_hand_7', 'EN', 'Four of a Kind'),
|
||||
('pk_hand_8', 'EN', 'Straight Flush'),
|
||||
('pk_hand_9', 'EN', '★ ROYAL FLUSH ★'),
|
||||
|
||||
-- Result Popup
|
||||
('pk_popup_player_won', 'EN', 'You won the Pot! ({0})'),
|
||||
('pk_popup_split_won', 'EN', 'Split Pot Won! ({0})'),
|
||||
('pk_popup_bot_won', 'EN', '{0} Won ({1})'),
|
||||
('pk_popup_fold_win', 'EN', 'All opponents folded'),
|
||||
('pk_popup_bot_gain', 'EN', 'Pot profit of {0}: +{1} Gold');
|
||||
|
||||
COMMIT;
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
BEGIN TRANSACTION;
|
||||
|
||||
INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
|
||||
-- DE: Neutrale Spielerzeile (ohne Hand-Spoiler) & Hilfe-Header
|
||||
('pk_player_bet_only', 'DE', 'Position:{0} | Runde: {1}g | Gesamt im Pot: {2}g{3}'),
|
||||
('pk_role_player', 'DE', ' Spieler'),
|
||||
('pk_help_header', 'DE', 'Poker-Hände (1 = Beste)'),
|
||||
('pk_help_general_info', 'DE', 'Aus deinen 2 Handkarten und den 5 Gemeinschaftskarten zählt am Ende immer automatisch die beste 5er-Kombination (1 = höchste bis 10 = niedrigste).'),
|
||||
|
||||
-- DE: Erklärungen zu den 10 Kombinationen
|
||||
('pk_help_hand_9', 'DE', 'Royal Flush: 10, Bube, Dame, König und Ass in derselben Kartenfarbe. Die unschlagbar höchste Hand beim Poker!'),
|
||||
('pk_help_hand_8', 'DE', 'Straight Flush: Fünf aufeinanderfolgende Karten in genau derselben Farbe (z. B. 7-8-9-10-Bube in Pik).'),
|
||||
('pk_help_hand_7', 'DE', 'Vierling (Four of a Kind): Vier Karten desselben Werts (z. B. vier Könige) plus eine beliebige fünfte Beikarte.'),
|
||||
('pk_help_hand_6', 'DE', 'Full House: Kombination aus einem Drilling und einem Paar (z. B. drei Asse und zwei Neunen).'),
|
||||
('pk_help_hand_5', 'DE', 'Flush: Fünf beliebige Karten derselben Farbe (z. B. fünfmal Pik), nicht in direkter Reihenfolge.'),
|
||||
('pk_help_hand_4', 'DE', 'Straße (Straight): Fünf direkt aufeinanderfolgende Karten unterschiedlicher Farben (Ass zählt hoch nach König oder tief vor der 2).'),
|
||||
('pk_help_hand_3', 'DE', 'Drilling (Three of a Kind): Drei Karten desselben Werts (z. B. drei Könige) plus zwei ungebundene Beikarten.'),
|
||||
('pk_help_hand_2', 'DE', 'Zwei Paare (Two Pair): Zwei verschiedene Paare (z. B. zwei Asse und zwei Neunen) plus eine fünfte Beikarte.'),
|
||||
('pk_help_hand_1', 'DE', 'Ein Paar (One Pair): Zwei Karten mit gleichem Wert (z. B. zwei Könige) plus drei Beikarten.'),
|
||||
('pk_help_hand_0', 'DE', 'Höchste Karte (High Card): Passt keine Kombination, entscheidet die höchste Einzelkarte (Ass ist am höchsten).'),
|
||||
|
||||
-- DE: Erklärungen zu den Wett-Buttons
|
||||
('pk_tip_check', 'DE', 'Schieben / Halten (Check / Hold): Du setzt kein neues Gold, gibst deine Hand aber nicht auf und reichst den Zug weiter. Nur möglich, solange niemand erhöht hat.'),
|
||||
('pk_tip_call', 'DE', 'Mitgehen (Call): Du zahlst genau die fehlende Differenz zum aktuellen Höchsteinsatz in den Pot, um in der Runde zu bleiben.'),
|
||||
('pk_tip_raise', 'DE', 'Erhöhen (Raise): Du gleichst einen eventuellen Einsatz aus und legst zusätzlich den gewählten Betrag oben drauf, um Gegner unter Druck zu setzen.'),
|
||||
('pk_tip_allin', 'DE', 'ALL-IN: Du setzt deinen kompletten restlichen Tisch-Stack auf einmal in den Pot. Du kannst in dieser Hand nicht mehr herausgedrängt werden (Side-Pots greifen automatisch).'),
|
||||
('pk_tip_fold', 'DE', 'Passen (Fold): Du wirfst deine Karten für diese Runde ab. Bereits gesetztes Gold im Pot geht verloren, aber du musst keine weiteren Erhöhungen mehr bezahlen.'),
|
||||
|
||||
-- EN: Neutral player info & Help Header
|
||||
('pk_player_bet_only', 'EN', 'Position:{0} | Street: {1}g | Total in Pot: {2}g{3}'),
|
||||
('pk_role_player', 'EN', ' Seat'),
|
||||
('pk_help_header', 'EN', 'Poker Hands (1 = Best)'),
|
||||
('pk_help_general_info', 'EN', 'Out of your 2 hole cards and the 5 community cards, your best 5-card combination counts automatically at Showdown (1 = highest to 10 = lowest).'),
|
||||
|
||||
-- EN: Hand Rank Explanations
|
||||
('pk_help_hand_9', 'EN', 'Royal Flush: 10, Jack, Queen, King, and Ace of the exact same suit. The unbeatable best hand in Poker!'),
|
||||
('pk_help_hand_8', 'EN', 'Straight Flush: Five consecutive cards of the exact same suit (e.g. 7-8-9-10-J of Spades).'),
|
||||
('pk_help_hand_7', 'EN', 'Four of a Kind: Four cards of the same rank (e.g. four Kings) plus one kicker card.'),
|
||||
('pk_help_hand_6', 'EN', 'Full House: Three of a Kind combined with One Pair (e.g. three Aces and two Nines).'),
|
||||
('pk_help_hand_5', 'EN', 'Flush: Any five cards of the same suit (e.g. five Spades), not in sequential order.'),
|
||||
('pk_help_hand_4', 'EN', 'Straight: Five sequential cards of mixed suits (Ace can play high above King or low as A-2-3-4-5).'),
|
||||
('pk_help_hand_3', 'EN', 'Three of a Kind: Three cards of the same rank (e.g. three Kings) plus two kickers.'),
|
||||
('pk_help_hand_2', 'EN', 'Two Pair: Two different pairs of the same rank (e.g. two Aces and two Nines) plus one kicker.'),
|
||||
('pk_help_hand_1', 'EN', 'One Pair: Two cards of the same rank (e.g. two Kings) plus three kickers.'),
|
||||
('pk_help_hand_0', 'EN', 'High Card: If no combination is made, the highest single card decides (Ace is highest).'),
|
||||
|
||||
-- EN: Action Button Explanations
|
||||
('pk_tip_check', 'EN', 'Check (Hold): Stay in the hand without betting additional Gold and pass action to the next player. Only available when no bet is facing you.'),
|
||||
('pk_tip_call', 'EN', 'Call: Match the current highest street bet to stay active in the pot.'),
|
||||
('pk_tip_raise', 'EN', 'Raise: Match any current bet and add the chosen chip amount on top, forcing opponents to pay more or fold.'),
|
||||
('pk_tip_allin', 'EN', 'ALL-IN: Push your entire remaining table stack into the pot. You cannot be forced out of the hand (Side Pots are calculated automatically).'),
|
||||
('pk_tip_fold', 'EN', 'Fold: Discard your hand for this round. Any Gold already committed stays in the pot, but you pay nothing further.');
|
||||
|
||||
COMMIT;
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 264 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.0 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.5 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.0 MiB |
BIN
user_data.db
BIN
user_data.db
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,4 +1,5 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# view/assets_manager.py
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageTk
|
||||
from models.resource_manager import ResourceManager
|
||||
|
|
@ -50,6 +51,14 @@ class AssetManager:
|
|||
self._tk_cache[key] = ImageTk.PhotoImage(pil_img.resize(size, Image.Resampling.LANCZOS))
|
||||
return self._tk_cache[key]
|
||||
|
||||
def get_proportional_photo(self, name: str, pil_img, target_width: int) -> ImageTk.PhotoImage | None:
|
||||
"""Skaliert ein Banner (z.B. title.jpg) exakt im Original-Seitenverhältnis auf target_width."""
|
||||
if not pil_img or target_width <= 10:
|
||||
return None
|
||||
src_w, src_h = pil_img.size
|
||||
target_height = max(1, int(round(target_width * (src_h / src_w))))
|
||||
return self.get_scaled_photo(name, pil_img, (target_width, target_height))
|
||||
|
||||
def get_gif_frames(self, key_or_filename: str, size=OUTCOME_GIF_SIZE) -> list[ImageTk.PhotoImage]:
|
||||
cache_key = ("gif", key_or_filename, size)
|
||||
if cache_key not in self._tk_cache:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,186 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# view/font_loader.py
|
||||
import ctypes
|
||||
import shutil
|
||||
import sys
|
||||
import tkinter as tk
|
||||
import tkinter.font as tkfont
|
||||
from pathlib import Path
|
||||
|
||||
from resources.code_res.game_constants import (
|
||||
CUSTOM_FONT_FILES, FONT_GOTH_ALT, FONT_GOTH_TITLE, FONTS_REL_DIR
|
||||
)
|
||||
|
||||
|
||||
class FontLoader:
|
||||
"""
|
||||
Lädt resources/fonts/OldLondon.ttf & OldLondonAlternate.ttf zur Laufzeit auf
|
||||
Windows, Linux, ChromeOS (Crostini) und macOS ohne System-Installation.
|
||||
"""
|
||||
_active_title_family: str = "Georgia"
|
||||
_active_alt_family: str = "Georgia"
|
||||
_hook_installed: bool = False
|
||||
|
||||
@classmethod
|
||||
def register_fonts(cls, root_dir: Path) -> None:
|
||||
fonts_dir = root_dir / FONTS_REL_DIR
|
||||
if not fonts_dir.is_dir():
|
||||
return
|
||||
|
||||
ttf_paths = [fonts_dir / fname for fname in CUSTOM_FONT_FILES if (fonts_dir / fname).is_file()]
|
||||
if not ttf_paths:
|
||||
return
|
||||
|
||||
if sys.platform.startswith("win"):
|
||||
cls._register_windows(ttf_paths)
|
||||
elif sys.platform == "darwin":
|
||||
cls._register_macos(ttf_paths)
|
||||
elif sys.platform.startswith("linux"):
|
||||
cls._register_linux_and_chromeos(ttf_paths)
|
||||
|
||||
@staticmethod
|
||||
def _register_windows(ttf_paths: list[Path]) -> None:
|
||||
"""Win32 AddFontResourceExW mit FR_PRIVATE (0x10): nur für diesen Prozess sichtbar."""
|
||||
FR_PRIVATE = 0x10
|
||||
try:
|
||||
gdi32 = ctypes.windll.gdi32
|
||||
for p in ttf_paths:
|
||||
gdi32.AddFontResourceExW(ctypes.c_wchar_p(str(p)), FR_PRIVATE, 0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _register_linux_and_chromeos(ttf_paths: list[Path]) -> None:
|
||||
"""
|
||||
1. Sofortige Prozess-Registrierung über libfontconfig (FcConfigAppFontAddFile).
|
||||
2. Sicherheits-Kopie nach ~/.local/share/fonts/goth_cardgames für X11/Crostini-Builds.
|
||||
"""
|
||||
try:
|
||||
fc = ctypes.CDLL("libfontconfig.so.1")
|
||||
fc.FcConfigGetCurrent.restype = ctypes.c_void_p
|
||||
fc.FcConfigAppFontAddFile.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
|
||||
fc.FcConfigAppFontAddFile.restype = ctypes.c_int
|
||||
cfg = fc.FcConfigGetCurrent()
|
||||
if cfg:
|
||||
for p in ttf_paths:
|
||||
fc.FcConfigAppFontAddFile(cfg, str(p).encode("utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
user_font_dir = Path.home() / ".local" / "share" / "fonts" / "goth_cardgames"
|
||||
user_font_dir.mkdir(parents=True, exist_ok=True)
|
||||
for p in ttf_paths:
|
||||
dst = user_font_dir / p.name
|
||||
if not dst.is_file():
|
||||
shutil.copy2(p, dst)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _register_macos(ttf_paths: list[Path]) -> None:
|
||||
"""macOS CoreText CTFontManagerRegisterFontsForURL (kCTFontManagerScopeProcess = 1)."""
|
||||
try:
|
||||
ct = ctypes.CDLL("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices")
|
||||
cf = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
|
||||
|
||||
cf.CFURLCreateFromFileSystemRepresentation.argtypes = [
|
||||
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_long, ctypes.c_bool
|
||||
]
|
||||
cf.CFURLCreateFromFileSystemRepresentation.restype = ctypes.c_void_p
|
||||
cf.CFRelease.argtypes = [ctypes.c_void_p]
|
||||
ct.CTFontManagerRegisterFontsForURL.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p]
|
||||
ct.CTFontManagerRegisterFontsForURL.restype = ctypes.c_bool
|
||||
|
||||
kCTFontManagerScopeProcess = 1
|
||||
for p in ttf_paths:
|
||||
raw = str(p).encode("utf-8")
|
||||
url = cf.CFURLCreateFromFileSystemRepresentation(None, raw, len(raw), False)
|
||||
if url:
|
||||
ct.CTFontManagerRegisterFontsForURL(url, kCTFontManagerScopeProcess, None)
|
||||
cf.CFRelease(url)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def bind_to_tk_root(cls, root: tk.Tk) -> None:
|
||||
"""
|
||||
Prüft nach Erstellung des Tk-Fensters, ob 'Old London' erkannt wurde,
|
||||
setzt Standard-Schriften und aktiviert das automatische Titel-Font-Mapping.
|
||||
"""
|
||||
available = {f.lower(): f for f in tkfont.families(root)}
|
||||
|
||||
if FONT_GOTH_TITLE.lower() in available:
|
||||
cls._active_title_family = available[FONT_GOTH_TITLE.lower()]
|
||||
elif "oldlondon" in available:
|
||||
cls._active_title_family = available["oldlondon"]
|
||||
|
||||
if FONT_GOTH_ALT.lower() in available:
|
||||
cls._active_alt_family = available[FONT_GOTH_ALT.lower()]
|
||||
else:
|
||||
cls._active_alt_family = cls._active_title_family
|
||||
|
||||
# Falls Old London erfolgreich geladen wurde, alle ("Georgia", ...) Überschriften
|
||||
# im gesamten Spiel automatisch und gut lesbar (+3pt) auf Old London heben!
|
||||
if cls._active_title_family != "Georgia" and not cls._hook_installed:
|
||||
cls._install_georgia_to_old_london_bridge()
|
||||
cls._hook_installed = True
|
||||
|
||||
@classmethod
|
||||
def title_font(cls, size: int = 16, weight: str = "normal") -> tuple:
|
||||
boost = 3 if cls._active_title_family != "Georgia" else 0
|
||||
return (cls._active_title_family, size + boost, weight)
|
||||
|
||||
@classmethod
|
||||
def alt_font(cls, size: int = 16, weight: str = "normal") -> tuple:
|
||||
boost = 3 if cls._active_alt_family != "Georgia" else 0
|
||||
return (cls._active_alt_family, size + boost, weight)
|
||||
|
||||
@classmethod
|
||||
def _remap_font_arg(cls, font_val):
|
||||
if isinstance(font_val, tuple) and len(font_val) >= 2:
|
||||
fam = str(font_val[0])
|
||||
if fam.lower() == "georgia":
|
||||
base_sz = int(font_val[1])
|
||||
# Frakturschrift braucht ~2-3pt mehr Höhe für dieselbe optische Größe wie Georgia;
|
||||
# "normal" statt "bold" verhindert bei Old London das Zulaufen feiner Linien!
|
||||
new_sz = base_sz + (3 if base_sz >= 12 else 2)
|
||||
return (cls._active_title_family, new_sz)
|
||||
return font_val
|
||||
|
||||
@classmethod
|
||||
def _install_georgia_to_old_london_bridge(cls) -> None:
|
||||
"""
|
||||
Transparentes Upgrade für bestehende Tk-Widgets (Label, Canvas.create_text, Button):
|
||||
Wandelt ("Georgia", X, "bold") automatisch in scharfes ("Old London", X+3) um.
|
||||
"""
|
||||
orig_widget_init = tk.Widget.__init__
|
||||
orig_configure = tk.Misc._configure
|
||||
orig_canvas_text = tk.Canvas.create_text
|
||||
|
||||
def _patched_init(self, master, widgetName, cnf={}, kw={}, extra=()):
|
||||
if "font" in kw:
|
||||
kw = dict(kw)
|
||||
kw["font"] = cls._remap_font_arg(kw["font"])
|
||||
elif isinstance(cnf, dict) and "font" in cnf:
|
||||
cnf = dict(cnf)
|
||||
cnf["font"] = cls._remap_font_arg(cnf["font"])
|
||||
return orig_widget_init(self, master, widgetName, cnf, kw, extra)
|
||||
|
||||
def _patched_configure(self, cmd, cnf, kw):
|
||||
if isinstance(kw, dict) and "font" in kw:
|
||||
kw = dict(kw)
|
||||
kw["font"] = cls._remap_font_arg(kw["font"])
|
||||
if isinstance(cnf, dict) and "font" in cnf:
|
||||
cnf = dict(cnf)
|
||||
cnf["font"] = cls._remap_font_arg(cnf["font"])
|
||||
return orig_configure(self, cmd, cnf, kw)
|
||||
|
||||
def _patched_canvas_text(self, *args, **kw):
|
||||
if "font" in kw:
|
||||
kw["font"] = cls._remap_font_arg(kw["font"])
|
||||
return orig_canvas_text(self, *args, **kw)
|
||||
|
||||
tk.Widget.__init__ = _patched_init
|
||||
tk.Misc._configure = _patched_configure
|
||||
tk.Canvas.create_text = _patched_canvas_text
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -1,8 +1,9 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# view/menus/login_view.py
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, FG_COLOR, INPUT_BG, MUTED_FG, SUBTLE_BORDER
|
||||
ACCENT_GOTH, BG_COLOR, BORDER_COLOR, FG_COLOR, INPUT_BG, MUTED_FG, SUBTLE_BORDER
|
||||
)
|
||||
from resources.code_res.i18n import t
|
||||
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
|
||||
|
|
@ -37,39 +38,40 @@ class LoginView:
|
|||
).pack(side="left")
|
||||
|
||||
main_frame = tk.Frame(
|
||||
self.root, bg=BG_COLOR, padx=40, pady=32,
|
||||
self.root, bg=BG_COLOR, padx=36, pady=28,
|
||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
main_frame.place(relx=0.5, rely=0.5, anchor="center")
|
||||
|
||||
# Titeltext direkt AUF die violette title1.png Plakette setzen
|
||||
title_photo = self.assets.get_scaled_photo("title_login", self.assets.raw_title, (420, 96))
|
||||
# Breites Panorama-Banner title.jpg proportional (560px breit -> ~140px hoch) ohne Text-Overlay
|
||||
title_photo = self.assets.get_proportional_photo("title_login_banner", self.assets.raw_title, 560)
|
||||
if title_photo:
|
||||
title_lbl = tk.Label(
|
||||
main_frame,
|
||||
image=title_photo,
|
||||
text="GOTH CARD\nCOLLECTION",
|
||||
compound="center",
|
||||
font=("Georgia", 18, "bold"),
|
||||
fg=ACCENT_GOLD,
|
||||
bg=BG_COLOR,
|
||||
bd=0,
|
||||
highlightthickness=1,
|
||||
highlightbackground=BORDER_COLOR,
|
||||
)
|
||||
title_lbl.image = title_photo
|
||||
title_lbl.pack(pady=(0, 20))
|
||||
title_lbl.pack(pady=(0, 22))
|
||||
else:
|
||||
tk.Label(
|
||||
main_frame, text=t("app_title").upper(),
|
||||
font=("Georgia", 22, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR
|
||||
main_frame, text=t("app_title"),
|
||||
font=("Georgia", 26, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR
|
||||
).pack(pady=(0, 20))
|
||||
|
||||
form_box = tk.Frame(main_frame, bg=BG_COLOR)
|
||||
form_box.pack()
|
||||
|
||||
if profiles:
|
||||
tk.Label(
|
||||
main_frame, text=t("login_select_lbl"),
|
||||
form_box, text=t("login_select_lbl"),
|
||||
font=("Helvetica", 10), fg=MUTED_FG, bg=BG_COLOR
|
||||
).pack(anchor="w", padx=10)
|
||||
).pack(anchor="w", padx=4)
|
||||
|
||||
frame = tk.Frame(main_frame, bg=BG_COLOR)
|
||||
frame = tk.Frame(form_box, bg=BG_COLOR)
|
||||
frame.pack(pady=(4, 12))
|
||||
initial_prof = preselect_name if preselect_name in profiles else profiles[0]
|
||||
self.profile_var = tk.StringVar(value=initial_prof)
|
||||
|
|
@ -83,14 +85,14 @@ class LoginView:
|
|||
lambda: self.ctrl.do_login(self.profile_var.get()), sound_mgr=self.sounds, width=155, height=40
|
||||
).grid(row=0, column=1)
|
||||
|
||||
tk.Frame(main_frame, bg=SUBTLE_BORDER, height=1).pack(fill="x", padx=10, pady=14)
|
||||
tk.Frame(form_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", padx=4, pady=14)
|
||||
|
||||
tk.Label(
|
||||
main_frame, text=t("login_create_lbl"),
|
||||
form_box, text=t("login_create_lbl"),
|
||||
font=("Helvetica", 10), fg=MUTED_FG, bg=BG_COLOR
|
||||
).pack(anchor="w", padx=10)
|
||||
).pack(anchor="w", padx=4)
|
||||
|
||||
new_frame = tk.Frame(main_frame, bg=BG_COLOR)
|
||||
new_frame = tk.Frame(form_box, bg=BG_COLOR)
|
||||
new_frame.pack(pady=(4, 4))
|
||||
self.new_name_var = tk.StringVar()
|
||||
entry = tk.Entry(
|
||||
|
|
|
|||
|
|
@ -39,17 +39,17 @@ class MainMenuView:
|
|||
self.selected_category = saved_cat if saved_cat in valid_cats else CAT_LUCK
|
||||
|
||||
container = tk.Frame(
|
||||
self.root, bg=BG_COLOR, padx=26, pady=16,
|
||||
self.root, bg=BG_COLOR, padx=26, pady=14,
|
||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
container.place(relx=0.5, rely=0.52, anchor="center", relwidth=0.90, relheight=0.86)
|
||||
container.place(relx=0.5, rely=0.52, anchor="center", relwidth=0.92, relheight=0.88)
|
||||
|
||||
# Symmetrische 3-Spalten-Topbar
|
||||
# 3-Spalten-Topbar mit zentriertem title.jpg Banner in Spalte 1
|
||||
top_bar = tk.Frame(container, bg=BG_COLOR)
|
||||
top_bar.pack(fill="x", pady=(0, 12))
|
||||
top_bar.columnconfigure(0, weight=1, uniform="hdr")
|
||||
top_bar.columnconfigure(1, weight=1, uniform="hdr")
|
||||
top_bar.columnconfigure(2, weight=1, uniform="hdr")
|
||||
top_bar.pack(fill="x", pady=(0, 10))
|
||||
top_bar.columnconfigure(0, weight=1)
|
||||
top_bar.columnconfigure(1, weight=1)
|
||||
top_bar.columnconfigure(2, weight=1)
|
||||
|
||||
left_btns = tk.Frame(top_bar, bg=BG_COLOR)
|
||||
left_btns.grid(row=0, column=0, sticky="w")
|
||||
|
|
@ -76,10 +76,20 @@ class MainMenuView:
|
|||
sound_mgr=self.sounds, width=85, height=36, font=("Helvetica", 9, "bold")
|
||||
).pack(side="left")
|
||||
|
||||
# Mitte: Proportionales Titel-Banner (320px breit -> ~80px hoch)
|
||||
header_banner = self.assets.get_proportional_photo("title_main_header", self.assets.raw_title, 320)
|
||||
if header_banner:
|
||||
hdr_lbl = tk.Label(
|
||||
top_bar, image=header_banner, bg=BG_COLOR, bd=0,
|
||||
highlightthickness=1, highlightbackground=SUBTLE_BORDER
|
||||
)
|
||||
hdr_lbl.image = header_banner
|
||||
hdr_lbl.grid(row=0, column=1, padx=12)
|
||||
else:
|
||||
tk.Label(
|
||||
top_bar, text=t("header_title"),
|
||||
font=("Georgia", 18, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR
|
||||
).grid(row=0, column=1)
|
||||
font=("Georgia", 20, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR
|
||||
).grid(row=0, column=1, padx=12)
|
||||
|
||||
acc_box = tk.Frame(top_bar, bg=PANEL_BG, padx=16, pady=7, highlightthickness=1, highlightbackground=BORDER_COLOR)
|
||||
acc_box.grid(row=0, column=2, sticky="e")
|
||||
|
|
@ -89,7 +99,7 @@ class MainMenuView:
|
|||
font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG
|
||||
).pack()
|
||||
|
||||
tk.Frame(container, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(0, 12))
|
||||
tk.Frame(container, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(0, 10))
|
||||
|
||||
cards_section = tk.Frame(container, bg=BG_COLOR)
|
||||
cards_section.pack(fill="both", expand=True)
|
||||
|
|
@ -117,12 +127,12 @@ class MainMenuView:
|
|||
resume_card.pack()
|
||||
return
|
||||
|
||||
# --- FLACHE 4-KATEGORIEN-LEISTE (keine Unterkategorien!) ---
|
||||
# --- FLACHE 4-KATEGORIEN-LEISTE ---
|
||||
cat_bar = tk.Frame(
|
||||
cards_section, bg=PANEL_BG, padx=16, pady=10,
|
||||
highlightthickness=1, highlightbackground=BORDER_COLOR
|
||||
)
|
||||
cat_bar.pack(fill="x", pady=(0, 14))
|
||||
cat_bar.pack(fill="x", pady=(0, 12))
|
||||
|
||||
tabs_wrap = tk.Frame(cat_bar, bg=PANEL_BG)
|
||||
tabs_wrap.pack()
|
||||
|
|
@ -185,7 +195,7 @@ class MainMenuView:
|
|||
lambda g=game: self.ctrl.launch_game(g),
|
||||
is_online=is_online_tab,
|
||||
)
|
||||
card_widget.grid(row=idx // 4, column=idx % 4, padx=18, pady=12)
|
||||
card_widget.grid(row=idx // 4, column=idx % 4, padx=18, pady=10)
|
||||
|
||||
def _create_game_card(
|
||||
self, parent, game_title: str, rank_subtitle: str, on_click, bg_col: str = BG_COLOR, is_online: bool = False
|
||||
|
|
@ -204,11 +214,12 @@ class MainMenuView:
|
|||
12, 12, card_w - 12, card_h - 12,
|
||||
fill="#16131c", outline=SUBTLE_BORDER, width=1
|
||||
)
|
||||
top_gem = cv.create_text(card_w // 2, 28, text="†" if is_online else "❖", font=("Georgia", 11, "bold"), fill=gem_color)
|
||||
bot_gem = cv.create_text(card_w // 2, card_h - 28, text="†" if is_online else "❖", font=("Georgia", 11, "bold"), fill=gem_color)
|
||||
# "Helvetica" für Unicode-Ornamente (❖), damit OldLondon kein Kästchen zeichnet
|
||||
top_gem = cv.create_text(card_w // 2, 28, text="†" if is_online else "❖", font=("Helvetica", 11, "bold"), fill=gem_color)
|
||||
bot_gem = cv.create_text(card_w // 2, card_h - 28, text="†" if is_online else "❖", font=("Helvetica", 11, "bold"), fill=gem_color)
|
||||
|
||||
longest_word = max((len(w) for w in game_title.replace("\n", " ").split()), default=0)
|
||||
title_size = 13 if longest_word >= 11 else 15
|
||||
title_size = 15 if longest_word >= 11 else 17
|
||||
title_y = (card_h // 2 - 22) if rank_subtitle else (card_h // 2)
|
||||
|
||||
txt_id = cv.create_text(
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -0,0 +1,129 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# view/widgets/info_badge.py
|
||||
import tkinter as tk
|
||||
from resources.code_res.game_constants import (
|
||||
ACCENT_GOLD, ACCENT_GOTH, FG_COLOR, MODAL_BG, MUTED_FG
|
||||
)
|
||||
|
||||
|
||||
class InfoBadge(tk.Label):
|
||||
"""Kompaktes ⓘ (U+24D8) Info-Icon mit Hover- & Klick-Hilfepopup."""
|
||||
_active_tip: tk.Toplevel | None = None
|
||||
_active_owner = None
|
||||
|
||||
def __init__(self, parent, text_provider, bg: str, font_size: int = 10):
|
||||
super().__init__(
|
||||
parent,
|
||||
text="\u24d8",
|
||||
font=("Helvetica", font_size, "bold"),
|
||||
fg=MUTED_FG,
|
||||
bg=bg,
|
||||
cursor="hand2",
|
||||
padx=2,
|
||||
pady=0,
|
||||
)
|
||||
self._text_provider = text_provider
|
||||
self._pinned = False
|
||||
|
||||
self.bind("<Enter>", self._on_enter)
|
||||
self.bind("<Leave>", self._on_leave)
|
||||
self.bind("<Button-1>", self._on_click)
|
||||
self.bind("<Destroy>", self._on_destroy)
|
||||
|
||||
@classmethod
|
||||
def close_global_tip(cls):
|
||||
if cls._active_tip is not None:
|
||||
try:
|
||||
if cls._active_tip.winfo_exists():
|
||||
cls._active_tip.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
cls._active_tip = None
|
||||
if cls._active_owner is not None:
|
||||
cls._active_owner._pinned = False
|
||||
try:
|
||||
if cls._active_owner.winfo_exists():
|
||||
cls._active_owner.configure(fg=MUTED_FG)
|
||||
except Exception:
|
||||
pass
|
||||
cls._active_owner = None
|
||||
|
||||
def _get_text(self) -> str:
|
||||
return self._text_provider() if callable(self._text_provider) else str(self._text_provider)
|
||||
|
||||
def _show_popup(self):
|
||||
msg = self._get_text().strip()
|
||||
if not msg:
|
||||
return
|
||||
|
||||
if InfoBadge._active_owner is not self:
|
||||
InfoBadge.close_global_tip()
|
||||
elif InfoBadge._active_tip is not None and InfoBadge._active_tip.winfo_exists():
|
||||
return
|
||||
|
||||
tip = tk.Toplevel(self)
|
||||
tip.wm_overrideredirect(True)
|
||||
try:
|
||||
tip.wm_attributes("-topmost", True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
outer = tk.Frame(tip, bg=ACCENT_GOTH, padx=1, pady=1)
|
||||
outer.pack(fill="both", expand=True)
|
||||
|
||||
lbl = tk.Label(
|
||||
outer,
|
||||
text=msg,
|
||||
font=("Helvetica", 9),
|
||||
fg=FG_COLOR,
|
||||
bg=MODAL_BG,
|
||||
justify="left",
|
||||
wraplength=290,
|
||||
padx=12,
|
||||
pady=8,
|
||||
)
|
||||
lbl.pack()
|
||||
|
||||
tip.update_idletasks()
|
||||
tw = tip.winfo_reqwidth()
|
||||
th = tip.winfo_reqheight()
|
||||
sw = self.winfo_screenwidth()
|
||||
sh = self.winfo_screenheight()
|
||||
|
||||
rx = self.winfo_rootx() + self.winfo_width() + 8
|
||||
ry = self.winfo_rooty() - th // 2 + 8
|
||||
|
||||
if rx + tw > sw - 16:
|
||||
rx = max(12, self.winfo_rootx() - tw - 8)
|
||||
if ry + th > sh - 24:
|
||||
ry = sh - th - 24
|
||||
if ry < 12:
|
||||
ry = 12
|
||||
|
||||
tip.wm_geometry(f"+{rx}+{ry}")
|
||||
tip.bind("<Button-1>", lambda _e: InfoBadge.close_global_tip())
|
||||
|
||||
InfoBadge._active_tip = tip
|
||||
InfoBadge._active_owner = self
|
||||
|
||||
def _on_enter(self, _event):
|
||||
self.configure(fg=ACCENT_GOLD)
|
||||
self._show_popup()
|
||||
|
||||
def _on_leave(self, _event):
|
||||
if not self._pinned:
|
||||
self.configure(fg=MUTED_FG)
|
||||
if InfoBadge._active_owner is self:
|
||||
InfoBadge.close_global_tip()
|
||||
|
||||
def _on_click(self, _event):
|
||||
if self._pinned and InfoBadge._active_owner is self:
|
||||
InfoBadge.close_global_tip()
|
||||
else:
|
||||
self._pinned = True
|
||||
self.configure(fg=ACCENT_GOLD)
|
||||
self._show_popup()
|
||||
|
||||
def _on_destroy(self, _event):
|
||||
if InfoBadge._active_owner is self:
|
||||
InfoBadge.close_global_tip()
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# view/window_state.py
|
||||
import re
|
||||
from models.database import Database
|
||||
|
||||
GEOM_RE = re.compile(r"^(\d+)x(\d+)\+(-?\d+)\+(-?\d+)$")
|
||||
|
||||
|
||||
class WindowStatePersistence:
|
||||
"""Merkt sich Fenstergröße, Position (x/y) sowie Maximiert-/Fullscreen-Zustand über Neustarts hinweg."""
|
||||
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
self._save_job = None
|
||||
self._last_normal_geom: str = Database.load_setting("window_geometry", "")
|
||||
|
||||
self._restore()
|
||||
self.root.bind("<Configure>", self._on_configure, add="+")
|
||||
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
|
||||
|
||||
def _restore(self):
|
||||
saved_geom = self._last_normal_geom
|
||||
was_zoomed = Database.load_setting("window_zoomed", "0") == "1"
|
||||
was_fullscreen = Database.load_setting("window_fullscreen", "0") == "1"
|
||||
|
||||
if saved_geom and self._is_visible_on_screen(saved_geom):
|
||||
try:
|
||||
self.root.geometry(saved_geom)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if was_fullscreen:
|
||||
try:
|
||||
self.root.attributes("-fullscreen", True)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if was_zoomed:
|
||||
try:
|
||||
self.root.state("zoomed")
|
||||
except Exception:
|
||||
try:
|
||||
self.root.attributes("-zoomed", True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _is_visible_on_screen(self, geom: str) -> bool:
|
||||
m = GEOM_RE.match(geom)
|
||||
if not m:
|
||||
return False
|
||||
w, h, x, y = map(int, m.groups())
|
||||
if w < 600 or h < 450:
|
||||
return False
|
||||
sw = self.root.winfo_screenwidth()
|
||||
sh = self.root.winfo_screenheight()
|
||||
return (-w + 120 < x < sw - 80) and (-20 <= y < sh - 80)
|
||||
|
||||
def _is_currently_zoomed(self) -> bool:
|
||||
try:
|
||||
if self.root.state() == "zoomed":
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
return bool(self.root.attributes("-zoomed"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _is_currently_fullscreen(self) -> bool:
|
||||
try:
|
||||
return bool(self.root.attributes("-fullscreen"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _on_configure(self, event):
|
||||
if event.widget is not self.root:
|
||||
return
|
||||
if self._save_job is not None:
|
||||
try:
|
||||
self.root.after_cancel(self._save_job)
|
||||
except Exception:
|
||||
pass
|
||||
self._save_job = self.root.after(350, self.persist_now)
|
||||
|
||||
def persist_now(self):
|
||||
self._save_job = None
|
||||
if not self.root.winfo_exists():
|
||||
return
|
||||
try:
|
||||
st = self.root.state()
|
||||
except Exception:
|
||||
st = "normal"
|
||||
|
||||
if st == "iconic":
|
||||
return
|
||||
|
||||
is_fs = self._is_currently_fullscreen()
|
||||
is_zm = self._is_currently_zoomed()
|
||||
|
||||
if not is_fs and not is_zm and st == "normal":
|
||||
cur_geom = self.root.geometry()
|
||||
if GEOM_RE.match(cur_geom):
|
||||
self._last_normal_geom = cur_geom
|
||||
Database.save_setting("window_geometry", cur_geom)
|
||||
|
||||
Database.save_setting("window_zoomed", "1" if is_zm else "0")
|
||||
Database.save_setting("window_fullscreen", "1" if is_fs else "0")
|
||||
|
||||
def _on_close(self):
|
||||
self.persist_now()
|
||||
self.root.destroy()
|
||||
Loading…
Reference in New Issue