0% found this document useful (0 votes)
26 views

Import Random

Uploaded by

vasylosypiv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Import Random

Uploaded by

vasylosypiv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import random

class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value

def __repr__(self):
return f"{self.value} of {self.suit}"

class Deck:
def __init__(self):
self.cards = [Card(s, v) for s in ["Spades", "Hearts", "Diamonds", "Clubs"]
for v in range(1, 14)]

def shuffle(self):
if len(self.cards) > 1:
random.shuffle(self.cards)

def deal(self):
if len(self.cards) > 1:
return self.cards.pop(0)

class Hand:
def __init__(self):
self.cards = []

def add_card(self, card):


self.cards.append(card)

def calculate_value(self):
value = 0
has_ace = False
for card in self.cards:
if card.value == 1:
has_ace = True
value += min(card.value, 10)
if has_ace and value + 10 <= 21:
return value + 10
return value

class Blackjack:
def __init__(self):
self.deck = Deck()
self.deck.shuffle()
self.player_hand = Hand()
self.dealer_hand = Hand()
for _ in range(2):
self.player_hand.add_card(self.deck.deal())
self.dealer_hand.add_card(self.deck.deal())

def play(self):
print("Welcome to Blackjack!")
print("Player's Hand:", self.player_hand.cards)
print("Dealer's Hand:", [self.dealer_hand.cards[0], "Unknown"])
while True:
player_score = self.player_hand.calculate_value()
if player_score == 21:
print("Blackjack! Player wins!")
break
elif player_score > 21:
print("Player busts! Dealer wins!")
break
else:
action = input("Do you want to hit or stand? (h/s): ").lower()
if action == "h":
self.player_hand.add_card(self.deck.deal())
print("Player's Hand:", self.player_hand.cards)
elif action == "s":
break
dealer_score = self.dealer_hand.calculate_value()
while dealer_score < 17:
self.dealer_hand.add_card(self.deck.deal())
dealer_score = self.dealer_hand.calculate_value()
print("Dealer's Hand:", self.dealer_hand.cards)
if dealer_score > 21:
print("Dealer busts! Player wins!")
elif dealer_score == 21 or dealer_score > player_score:
print("Dealer wins!")
elif dealer_score < player_score:
print("Player wins!")
else:
print("It's a tie!")

if __name__ == "__main__":
game = Blackjack()
game.play()

You might also like