Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
7.2 kB
3
Indexable
Never
import tkinter as tk
from tkinter import messagebox
import random
import os

# Definizione delle carte e dei valori
suits = ['Cuori', 'Quadri', 'Fiori', 'Picche']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 11}
saldo_file = "saldo.txt"

# Funzione per creare un mazzo di carte
def create_deck():
    deck = []
    for suit in suits:
        for rank in ranks:
            deck.append((rank, suit))
    random.shuffle(deck)
    return deck

# Funzione per calcolare il punteggio della mano
def calculate_score(hand):
    score = 0
    aces = 0

    for card in hand:
        rank = card[0]
        score += values[rank]
        if rank == 'A':
            aces += 1

    # Gestione degli assi (A può valere 1 o 11)
    while score > 21 and aces:
        score -= 10
        aces -= 1

    return score

# Funzione per controllare se è un Blackjack
def is_blackjack(hand):
    return len(hand) == 2 and calculate_score(hand) == 21

# Funzione per caricare il saldo dal file
def load_saldo():
    if os.path.exists(saldo_file):
        with open(saldo_file, "r") as file:
            return int(file.read())
    return 500  # Saldo iniziale

# Funzione per salvare il saldo su file
def save_saldo(saldo):
    with open(saldo_file, "w") as file:
        file.write(str(saldo))

class BlackjackGame(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title("Blackjack")
        self.geometry("600x400")

        self.saldo = load_saldo()
        self.deck = create_deck()
        self.player_hand = []
        self.dealer_hand = []
        self.bet = 0
        self.split_hand = []
        self.double_down = False

        # Interfaccia grafica
        self.create_widgets()
        self.update_saldo_label()

    def create_widgets(self):
        # Mostra il saldo del giocatore
        self.saldo_label = tk.Label(self, text=f"Saldo: {self.saldo}")
        self.saldo_label.pack()

        # Campo di inserimento della scommessa
        self.bet_entry = tk.Entry(self)
        self.bet_entry.pack()
        self.bet_button = tk.Button(self, text="Scommetti", command=self.place_bet)
        self.bet_button.pack()

        # Area di visualizzazione delle carte
        self.player_frame = tk.Frame(self)
        self.player_frame.pack(pady=10)
        self.dealer_frame = tk.Frame(self)
        self.dealer_frame.pack(pady=10)

        # Pulsanti di controllo del gioco
        self.hit_button = tk.Button(self, text="Hit", command=self.hit, state=tk.DISABLED)
        self.hit_button.pack(side=tk.LEFT, padx=5)
        self.stand_button = tk.Button(self, text="Stand", command=self.stand, state=tk.DISABLED)
        self.stand_button.pack(side=tk.LEFT, padx=5)
        self.double_button = tk.Button(self, text="Double Down", command=self.double_down_option, state=tk.DISABLED)
        self.double_button.pack(side=tk.LEFT, padx=5)
        self.split_button = tk.Button(self, text="Split", command=self.split, state=tk.DISABLED)
        self.split_button.pack(side=tk.LEFT, padx=5)

    def update_saldo_label(self):
        self.saldo_label.config(text=f"Saldo: {self.saldo}")

    def place_bet(self):
        try:
            self.bet = int(self.bet_entry.get())
            if self.bet > self.saldo or self.bet <= 0:
                messagebox.showerror("Errore", "Scommessa non valida!")
                return

            self.saldo -= self.bet
            self.update_saldo_label()
            self.start_game()
        except ValueError:
            messagebox.showerror("Errore", "Per favore inserisci un numero valido.")

    def start_game(self):
        self.deck = create_deck()
        self.player_hand = [self.deck.pop(), self.deck.pop()]
        self.dealer_hand = [self.deck.pop(), self.deck.pop()]
        self.display_hands()

        if is_blackjack(self.player_hand) or is_blackjack(self.dealer_hand):
            self.handle_initial_blackjack()
        else:
            self.enable_buttons()

    def display_hands(self):
        # Cancella le mani precedenti
        for widget in self.player_frame.winfo_children():
            widget.destroy()
        for widget in self.dealer_frame.winfo_children():
            widget.destroy()

        # Mostra le carte del giocatore
        tk.Label(self.player_frame, text="Giocatore:").pack()
        for card in self.player_hand:
            tk.Label(self.player_frame, text=f"{card[0]} di {card[1]}").pack()

        # Mostra le carte del dealer
        tk.Label(self.dealer_frame, text="Dealer:").pack()
        tk.Label(self.dealer_frame, text=f"Carte nascoste").pack()
        tk.Label(self.dealer_frame, text=f"{self.dealer_hand[1][0]} di {self.dealer_hand[1][1]}").pack()

    def handle_initial_blackjack(self):
        if is_blackjack(self.player_hand) and is_blackjack(self.dealer_hand):
            messagebox.showinfo("Risultato", "Entrambi avete Blackjack! È un pareggio.")
        elif is_blackjack(self.player_hand):
            messagebox.showinfo("Risultato", "Blackjack! Hai vinto 3 a 2!")
            self.saldo += int(self.bet * 2.5)
        elif is_blackjack(self.dealer_hand):
            messagebox.showinfo("Risultato", "Il dealer ha Blackjack! Il dealer vince.")
        self.end_round()

    def hit(self):
        self.player_hand.append(self.deck.pop())
        self.display_hands()
        if calculate_score(self.player_hand) > 21:
            messagebox.showinfo("Risultato", "Hai sballato! Il dealer vince.")
            self.end_round()

    def stand(self):
        self.dealer_turn()

    def double_down_option(self):
        if self.saldo >= self.bet:
            self.saldo -= self.bet
            self.bet *= 2
            self.update_saldo_label()
            self.hit()
            self.stand()
        else:
            messagebox.showinfo("Errore", "Saldo insufficiente per raddoppiare.")

    def split(self):
        if values[self.player_hand[0][0]] == values[self.player_hand[1][0]]:
            self.split_hand = [self.player_hand.pop()]
            self.split_hand.append(self.deck.pop())
            self.player_hand.append(self.deck.pop())
            messagebox.showinfo("Split", "Hai diviso le carte in due mani.")
            self.display_hands()
        else:
            messagebox.showinfo("Errore", "Le carte non sono adatte per lo split.")

    def dealer_turn(self):
        while calculate_score(self.dealer_hand) < 17:
            self.dealer_hand.append(self.deck.pop())
        self.display_hands()
        self.check_winner()

    def check_winner(self):
        player_score = calculate_score(self.player_hand)
        dealer_score = calculate_score(self.dealer_hand)

        if dealer_score > 21 or dealer_score < player_score:
            messagebox.showinfo("Risultato", "Hai vinto!")
            self.saldo += self.bet * 2
        elif dealer_score > player_score:
            messagebox.showinfo("Risultato", "Il dealer vince!")
        else:
            messagebox.showinfo("Risultato", "È un pareggio!")
            self.saldo += self.bet

        self.end_round()

    def end_round(self):
        self.update_saldo_label()
Leave a Comment