443 lines
16 KiB
Python
443 lines
16 KiB
Python
# -*- coding: utf-8 -*-
|
|
# games/blackjack/models/blackjack_engine.py
|
|
from games.blackjack.models.bot_seat import BlackjackBotSeat
|
|
from games.blackjack.models.hand_evaluator import HandEvaluator
|
|
from games.blackjack.models.player_hand import PlayerHand
|
|
from models.card import Card
|
|
from models.deck import Deck
|
|
from resources.code_res.game_constants import BJ_DEALER_STAND, BJ_RESHUFFLE_RATIO, BJ_TARGET_SCORE
|
|
|
|
|
|
class BlackjackEngine:
|
|
def __init__(self, num_decks: int = 2):
|
|
self.num_decks = num_decks
|
|
self.deck = Deck(num_decks=num_decks, include_jokers=False)
|
|
|
|
self.player_hands: list[PlayerHand] = []
|
|
self.dealer_hand: list[Card] = []
|
|
|
|
self.pot: int = 0
|
|
self.highest_bet: int = 0
|
|
self.raises_in_round: int = 0
|
|
self.cycle_card_drawn: bool = False
|
|
self.state: str = "PRE_DEAL"
|
|
|
|
@property
|
|
def total_player_bet(self) -> int:
|
|
return sum(h.bet_in_pot for h in self.player_hands)
|
|
|
|
@property
|
|
def any_player_hand_active(self) -> bool:
|
|
return any(h.is_active_in_pot for h in self.player_hands)
|
|
|
|
# --- JSON-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, bots: list[BlackjackBotSeat]) -> dict:
|
|
return {
|
|
"num_decks": self.num_decks,
|
|
"deck_cards": self._cards_to_list(self.deck.cards),
|
|
"dealer_hand": self._cards_to_list(self.dealer_hand),
|
|
"pot": self.pot,
|
|
"highest_bet": self.highest_bet,
|
|
"raises_in_round": self.raises_in_round,
|
|
"cycle_card_drawn": self.cycle_card_drawn,
|
|
"state": self.state,
|
|
"player_hands": [
|
|
{
|
|
"cards": self._cards_to_list(h.cards),
|
|
"bet_in_pot": h.bet_in_pot,
|
|
"cards_locked": h.cards_locked,
|
|
"busted": h.busted,
|
|
"folded": h.folded,
|
|
"doubled": h.doubled,
|
|
"is_split_hand": h.is_split_hand,
|
|
"acted_once": h.acted_once,
|
|
}
|
|
for h in self.player_hands
|
|
],
|
|
"bots": [
|
|
{
|
|
"name": b.name,
|
|
"ai_level": b.ai_level,
|
|
"gold": b.gold,
|
|
"hand": self._cards_to_list(b.hand),
|
|
"bet_in_pot": b.bet_in_pot,
|
|
"cards_locked": b.cards_locked,
|
|
"busted": b.busted,
|
|
"folded": b.folded,
|
|
"doubled": b.doubled,
|
|
"acted_once": b.acted_once,
|
|
"status_text": b.status_text,
|
|
"rebought": b.rebought,
|
|
}
|
|
for b in bots
|
|
],
|
|
}
|
|
|
|
def load_from_dict(self, data: dict) -> list[BlackjackBotSeat]:
|
|
self.num_decks = data["num_decks"]
|
|
self.deck.num_decks = self.num_decks
|
|
self.deck.cards = self._list_to_cards(data["deck_cards"])
|
|
self.dealer_hand = self._list_to_cards(data["dealer_hand"])
|
|
self.pot = data["pot"]
|
|
self.highest_bet = data["highest_bet"]
|
|
self.raises_in_round = data.get("raises_in_round", 0)
|
|
self.cycle_card_drawn = bool(data.get("cycle_card_drawn", False))
|
|
self.state = data["state"]
|
|
|
|
self.player_hands = [
|
|
PlayerHand(
|
|
cards=self._list_to_cards(hd["cards"]),
|
|
bet_in_pot=hd["bet_in_pot"],
|
|
cards_locked=hd["cards_locked"],
|
|
busted=hd["busted"],
|
|
folded=hd["folded"],
|
|
doubled=hd.get("doubled", False),
|
|
is_split_hand=hd.get("is_split_hand", False),
|
|
acted_once=hd.get("acted_once", False),
|
|
)
|
|
for hd in data["player_hands"]
|
|
]
|
|
|
|
restored_bots = []
|
|
for bd in data.get("bots", []):
|
|
restored_bots.append(
|
|
BlackjackBotSeat(
|
|
name=bd["name"],
|
|
ai_level=bd["ai_level"],
|
|
gold=bd["gold"],
|
|
hand=self._list_to_cards(bd["hand"]),
|
|
bet_in_pot=bd["bet_in_pot"],
|
|
cards_locked=bd.get("cards_locked", False),
|
|
busted=bd["busted"],
|
|
folded=bd["folded"],
|
|
doubled=bd.get("doubled", False),
|
|
acted_once=bd.get("acted_once", False),
|
|
status_text=bd["status_text"],
|
|
rebought=bd["rebought"],
|
|
)
|
|
)
|
|
return restored_bots
|
|
|
|
def check_reshuffle(self, min_needed: int = 28) -> bool:
|
|
threshold = max(min_needed, int(52 * self.num_decks * BJ_RESHUFFLE_RATIO))
|
|
if self.deck.remaining() < threshold:
|
|
self.deck.reset(shuffle=True)
|
|
return True
|
|
return False
|
|
|
|
def deal_initial_round(self, ante: int, player_avail_gold: int, bots: list[BlackjackBotSeat]) -> int:
|
|
ante = int(ante)
|
|
p_ante = min(ante, player_avail_gold)
|
|
|
|
self.pot = p_ante
|
|
self.highest_bet = p_ante
|
|
self.raises_in_round = 0
|
|
self.cycle_card_drawn = False
|
|
|
|
p_cards = [self.deck.draw(), self.deck.draw()]
|
|
p_val, _ = HandEvaluator.evaluate(p_cards)
|
|
self.player_hands = [
|
|
PlayerHand(
|
|
cards=p_cards,
|
|
bet_in_pot=p_ante,
|
|
cards_locked=(p_val == BJ_TARGET_SCORE),
|
|
acted_once=False,
|
|
)
|
|
]
|
|
self.dealer_hand = [self.deck.draw(), self.deck.draw()]
|
|
|
|
for bot in bots:
|
|
b_ante = min(ante, bot.gold)
|
|
bot.gold -= b_ante
|
|
bot.bet_in_pot = b_ante
|
|
self.pot += b_ante
|
|
self.highest_bet = max(self.highest_bet, b_ante)
|
|
|
|
b_cards = [self.deck.draw(), self.deck.draw()]
|
|
b_val, _ = HandEvaluator.evaluate(b_cards)
|
|
bot.hand = b_cards
|
|
bot.cards_locked = (b_val == BJ_TARGET_SCORE)
|
|
bot.busted = False
|
|
bot.folded = False
|
|
bot.doubled = False
|
|
bot.acted_once = False
|
|
bot.status_text = ""
|
|
|
|
self.state = "ACTION_LOOP"
|
|
return p_ante
|
|
|
|
# --- Karten- & Einsatz-Operationen (Spieler) ---
|
|
def can_split_hand(self, hand_idx: int, wallet_gold: int) -> bool:
|
|
if len(self.player_hands) != 1 or hand_idx != 0:
|
|
return False
|
|
h = self.player_hands[0]
|
|
if not h.is_active_in_pot or h.cards_locked or len(h.cards) != 2:
|
|
return False
|
|
if h.cards[0].blackjack_value != h.cards[1].blackjack_value:
|
|
return False
|
|
return wallet_gold >= self.highest_bet
|
|
|
|
def split_player_hand(self) -> int:
|
|
orig = self.player_hands[0]
|
|
second_bet = self.highest_bet
|
|
c1, c2 = orig.cards[0], orig.cards[1]
|
|
|
|
h1_cards = [c1, self.deck.draw()]
|
|
h2_cards = [c2, self.deck.draw()]
|
|
v1, _ = HandEvaluator.evaluate(h1_cards)
|
|
v2, _ = HandEvaluator.evaluate(h2_cards)
|
|
|
|
h1 = PlayerHand(
|
|
cards=h1_cards,
|
|
bet_in_pot=orig.bet_in_pot,
|
|
cards_locked=(v1 == BJ_TARGET_SCORE),
|
|
is_split_hand=True,
|
|
acted_once=False,
|
|
)
|
|
h2 = PlayerHand(
|
|
cards=h2_cards,
|
|
bet_in_pot=second_bet,
|
|
cards_locked=(v2 == BJ_TARGET_SCORE),
|
|
is_split_hand=True,
|
|
acted_once=False,
|
|
)
|
|
self.player_hands = [h1, h2]
|
|
self.pot += second_bet
|
|
self.cycle_card_drawn = True
|
|
return second_bet
|
|
|
|
def get_double_down_cost(self, hand_idx: int) -> int:
|
|
h = self.player_hands[hand_idx]
|
|
target_bet = max(self.highest_bet, h.bet_in_pot) * 2
|
|
return max(0, target_bet - h.bet_in_pot)
|
|
|
|
def can_double_down(self, hand_idx: int, wallet_gold: int, already_drew_this_turn: bool = False) -> bool:
|
|
h = self.player_hands[hand_idx]
|
|
if not h.is_active_in_pot or h.cards_locked or h.doubled or already_drew_this_turn or len(h.cards) != 2:
|
|
return False
|
|
val, _ = HandEvaluator.evaluate(h.cards)
|
|
if val >= BJ_TARGET_SCORE:
|
|
return False
|
|
cost = self.get_double_down_cost(hand_idx)
|
|
return cost > 0 and wallet_gold >= cost
|
|
|
|
def double_down_player_hand(self, hand_idx: int) -> tuple[int, Card]:
|
|
cost = self.get_double_down_cost(hand_idx)
|
|
paid = self.player_add_gold_to_pot(hand_idx, cost)
|
|
h = self.player_hands[hand_idx]
|
|
card = self.player_draw_card(hand_idx)
|
|
h.doubled = True
|
|
h.cards_locked = True
|
|
return paid, card
|
|
|
|
def player_add_gold_to_pot(self, hand_idx: int, amount: int) -> int:
|
|
amt = max(0, int(amount))
|
|
if amt == 0:
|
|
return 0
|
|
h = self.player_hands[hand_idx]
|
|
h.bet_in_pot += amt
|
|
self.pot += amt
|
|
if h.bet_in_pot > self.highest_bet:
|
|
self.highest_bet = h.bet_in_pot
|
|
self.raises_in_round += 1
|
|
return amt
|
|
|
|
def player_draw_card(self, hand_idx: int) -> Card:
|
|
h = self.player_hands[hand_idx]
|
|
card = self.deck.draw()
|
|
h.cards.append(card)
|
|
self.cycle_card_drawn = True
|
|
val, _ = HandEvaluator.evaluate(h.cards)
|
|
if val > BJ_TARGET_SCORE:
|
|
h.busted = True
|
|
h.cards_locked = True
|
|
elif val == BJ_TARGET_SCORE:
|
|
h.cards_locked = True
|
|
return card
|
|
|
|
# --- Karten- & Einsatz-Operationen (Bots) ---
|
|
def bot_add_gold_to_pot(self, bot: BlackjackBotSeat, amount: int) -> int:
|
|
amt = max(0, min(int(amount), bot.gold))
|
|
if amt == 0:
|
|
return 0
|
|
bot.gold -= amt
|
|
bot.bet_in_pot += amt
|
|
self.pot += amt
|
|
if bot.bet_in_pot > self.highest_bet:
|
|
self.highest_bet = bot.bet_in_pot
|
|
self.raises_in_round += 1
|
|
return amt
|
|
|
|
def bot_draw_card(self, bot: BlackjackBotSeat) -> Card:
|
|
card = self.deck.draw()
|
|
bot.hand.append(card)
|
|
self.cycle_card_drawn = True
|
|
val, _ = HandEvaluator.evaluate(bot.hand)
|
|
if val > BJ_TARGET_SCORE:
|
|
bot.busted = True
|
|
bot.cards_locked = True
|
|
elif val == BJ_TARGET_SCORE:
|
|
bot.cards_locked = True
|
|
return card
|
|
|
|
# --- Umlauf- & Ausgleichs-Prüfungen ---
|
|
def has_unsettled_bets(self, bots: list[BlackjackBotSeat], player_wallet_gold: int) -> bool:
|
|
if player_wallet_gold > 0:
|
|
for h in self.player_hands:
|
|
if h.is_active_in_pot and h.bet_in_pot < self.highest_bet:
|
|
return True
|
|
for b in bots:
|
|
if b.is_active_in_pot and b.gold > 0 and b.bet_in_pot < self.highest_bet:
|
|
return True
|
|
return False
|
|
|
|
def any_contender_alive(self, bots: list[BlackjackBotSeat]) -> bool:
|
|
return self.any_player_hand_active or any(b.is_active_in_pot for b in bots)
|
|
|
|
# --- Dealer Regeln: Zieht bei <= 16, hält ab 17 ---
|
|
def dealer_should_hit(self) -> bool:
|
|
val, _ = HandEvaluator.evaluate(self.dealer_hand)
|
|
return val < BJ_DEALER_STAND
|
|
|
|
def dealer_hit(self) -> Card:
|
|
card = self.deck.draw()
|
|
self.dealer_hand.append(card)
|
|
return card
|
|
|
|
# --- Showdown & Pot-Abrechnung ---
|
|
@staticmethod
|
|
def _hand_rank(cards: list[Card], is_split: bool = False) -> tuple[int, int]:
|
|
rank = HandEvaluator.showdown_rank(cards)
|
|
if is_split and rank == (2, 21):
|
|
return (1, 21)
|
|
return rank
|
|
|
|
def resolve_showdown(self, bots: list[BlackjackBotSeat]) -> dict:
|
|
self.state = "SHOWDOWN"
|
|
total_p_bet = self.total_player_bet
|
|
|
|
if not bots:
|
|
active_p_hands = [h for h in self.player_hands if h.is_active_in_pot]
|
|
if not active_p_hands:
|
|
return {
|
|
"winner_type": "BANK",
|
|
"winner_names": [],
|
|
"player_payout": 0,
|
|
"player_net": -total_p_bet,
|
|
"bank_gain": self.pot,
|
|
"bot_gains": [],
|
|
}
|
|
d_rank = self._hand_rank(self.dealer_hand)
|
|
payout = 0
|
|
for h in active_p_hands:
|
|
hr = self._hand_rank(h.cards, is_split=h.is_split_hand)
|
|
if hr > d_rank:
|
|
payout += h.bet_in_pot * 2
|
|
elif hr == d_rank:
|
|
payout += h.bet_in_pot
|
|
net = payout - total_p_bet
|
|
w_type = "PLAYER" if net > 0 else ("TIE" if net == 0 else "BANK")
|
|
return {
|
|
"winner_type": w_type,
|
|
"winner_names": [],
|
|
"player_payout": payout,
|
|
"player_net": net,
|
|
"bank_gain": max(0, -net),
|
|
"bot_gains": [],
|
|
}
|
|
|
|
contenders: list[tuple[str, object, tuple[int, int]]] = []
|
|
for h in self.player_hands:
|
|
if h.is_active_in_pot:
|
|
contenders.append(("PLAYER", h, self._hand_rank(h.cards, is_split=h.is_split_hand)))
|
|
for b in bots:
|
|
if b.is_active_in_pot:
|
|
contenders.append(("BOT", b, self._hand_rank(b.hand)))
|
|
|
|
if not contenders:
|
|
return {
|
|
"winner_type": "BANK",
|
|
"winner_names": [],
|
|
"player_payout": 0,
|
|
"player_net": -total_p_bet,
|
|
"bank_gain": self.pot,
|
|
"bot_gains": [],
|
|
}
|
|
|
|
dealer_rank = self._hand_rank(self.dealer_hand)
|
|
best_contender_rank = max(c[2] for c in contenders)
|
|
|
|
if dealer_rank > best_contender_rank:
|
|
return {
|
|
"winner_type": "BANK",
|
|
"winner_names": [],
|
|
"player_payout": 0,
|
|
"player_net": -total_p_bet,
|
|
"bank_gain": self.pot,
|
|
"bot_gains": [],
|
|
}
|
|
|
|
if dealer_rank == best_contender_rank:
|
|
returned_total = 0
|
|
player_payout = 0
|
|
for kind, obj, rnk in contenders:
|
|
if rnk == best_contender_rank:
|
|
if kind == "PLAYER":
|
|
player_payout += obj.bet_in_pot
|
|
else:
|
|
obj.gold += obj.bet_in_pot
|
|
returned_total += obj.bet_in_pot
|
|
|
|
bank_leftover = max(0, self.pot - returned_total)
|
|
net = player_payout - total_p_bet
|
|
return {
|
|
"winner_type": "TIE" if player_payout > 0 and net == 0 else ("BANK" if net < 0 else "TIE"),
|
|
"winner_names": [],
|
|
"player_payout": player_payout,
|
|
"player_net": net,
|
|
"bank_gain": bank_leftover,
|
|
"bot_gains": [],
|
|
}
|
|
|
|
winners = [c for c in contenders if c[2] == best_contender_rank]
|
|
share = self.pot // len(winners)
|
|
remainder = self.pot % len(winners)
|
|
|
|
player_won_any = False
|
|
player_payout = 0
|
|
bot_win_totals: dict[int, tuple[BlackjackBotSeat, int]] = {}
|
|
|
|
for idx, (kind, obj, _rnk) in enumerate(winners):
|
|
win_amt = share + (remainder if idx == 0 else 0)
|
|
if kind == "PLAYER":
|
|
player_won_any = True
|
|
player_payout += win_amt
|
|
else:
|
|
obj.gold += win_amt
|
|
prev_amt = bot_win_totals.get(id(obj), (obj, 0))[1]
|
|
bot_win_totals[id(obj)] = (obj, prev_amt + win_amt)
|
|
|
|
winning_bot_names = [b.name for b, _ in bot_win_totals.values()]
|
|
bot_gains = [
|
|
(b.name, tot - b.bet_in_pot)
|
|
for b, tot in bot_win_totals.values()
|
|
if (tot - b.bet_in_pot) > 0
|
|
]
|
|
|
|
net = player_payout - total_p_bet
|
|
return {
|
|
"winner_type": "PLAYER" if player_won_any else "BOT",
|
|
"winner_names": winning_bot_names,
|
|
"player_payout": player_payout,
|
|
"player_net": net,
|
|
"bank_gain": 0,
|
|
"bot_gains": bot_gains,
|
|
} |