Certainly! Below is a Python implementation of a simple Blackjack game where the user plays against the computer (dealer). Each card in the deck has an additional description that is displayed when the card is shown. The descriptions provide fun or thematic details beyond just the rank and suit.
Here is the code:
import random
# Define cards with descriptions
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
# Descriptions by rank (these are example descriptions; you can customize)
descriptions = {
'2': "Deuces are wild in some games.",
'3': "A tricky three — watch your hand!",
'4': "Four-leaf clover good luck card.",
'5': "Five fingers on a hand.",
'6': "Six shooter, ready to play.",
'7': "Lucky seven, often wins.",
'8': "Eight is great — eight ball!",
'9': "Nine lives of a cat.",
'10': "Perfect 10!",
'J': "Jack of all trades.",
'Q': "Queen reigns supreme.",
'K': "King of the deck.",
'A': "Ace can be one or eleven."
}
# Card class with description
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.description = descriptions[rank]
def __str__(self):
return f"{self.rank} of {self.suit} - {self.description}"
def value(self):
"""Return the blackjack value of the card."""
if self.rank in ['J', 'Q', 'K']:
return 10
elif self.rank == 'A':
return 11 # value of Ace handled later for soft/hard totals
else:
return int(self.rank)
# Deck class
class Deck:
def __init__(self):
self.cards = [Card(s, r) for s in suits for r in ranks]
random.shuffle(self.cards)
def deal(self):
return self.cards.pop()
# Hand class to represent player or dealer hand
class Hand:
def __init__(self):
self.cards = []
def add_card(self, card):
self.cards.append(card)
def get_values(self):
"""Calculate all possible values for a hand (accounting for Aces)"""
total = 0
num_aces = 0
for card in self.cards:
val = card.value()
total += val
if card.rank == 'A':
num_aces += 1
# Adjust for aces: reduce value by 10 if total > 21 and have Aces
values = [total]
for _ in range(num_aces):
# Each ace can count as 1 instead of 11
total -= 10
values.append(total)
# Return unique sorted values that are > 0
valid_values = sorted({v for v in values if v <= 21}, reverse=True)
if not valid_values:
# All values bust, return minimum (even if > 21)
return [min(values)]
return valid_values
def best_value(self):
"""Return the best (highest <=21) value, or lowest if bust."""
return self.get_values()[0]
def is_blackjack(self):
return len(self.cards) == 2 and self.best_value() == 21
def is_bust(self):
return self.best_value() > 21
def __str__(self):
return ', '.join(str(card) for card in self.cards)
def show_hands(player_hand, dealer_hand, show_all_dealer_cards=False):
print("\nYour hand:")
for card in player_hand.cards:
print(f" {card}")
print(f"Total value: {player_hand.best_value()}")
print("\nDealer's hand:")
if show_all_dealer_cards:
for card in dealer_hand.cards:
print(f" {card}")
print(f"Total value: {dealer_hand.best_value()}")
else:
print(f" {dealer_hand.cards[0]}") # Show only one dealer card
print(" <hidden card>")
def player_turn(deck, player_hand, dealer_hand):
while True:
show_hands(player_hand, dealer_hand, show_all_dealer_cards=False)
if player_hand.is_blackjack():
print("You got a Blackjack!")
break
if player_hand.is_bust():
print("You busted!")
break
choice = input("Do you want to (H)it or (S)tand? ").strip().lower()
if choice == 'h' or choice == 'hit':
card = deck.deal()
print(f"You drew: {card}")
player_hand.add_card(card)
elif choice == 's' or choice == 'stand':
print("You stand.")
break
else:
print("Invalid input. Please enter H or S.")
def dealer_turn(deck, dealer_hand):
print("\nDealer's turn...")
while dealer_hand.best_value() < 17:
card = deck.deal()
dealer_hand.add_card(card)
print(f"Dealer draws: {card}")
if dealer_hand.is_bust():
print("Dealer busted!")
else:
print(f"Dealer stands with value {dealer_hand.best_value()}.")
def compare_hands(player_hand, dealer_hand):
player_val = player_hand.best_value()
dealer_val = dealer_hand.best_value()
if player_hand.is_bust():
return "You lose. You busted."
elif dealer_hand.is_bust():
return "You win! Dealer busted."
elif player_hand.is_blackjack() and not dealer_hand.is_blackjack():
return "You win with a Blackjack!"
elif dealer_hand.is_blackjack() and not player_hand.is_blackjack():
return "Dealer has Blackjack. You lose."
elif player_val > dealer_val:
return "You win!"
elif player_val < dealer_val:
return "You lose."
else:
return "It's a tie (push)."
def play_blackjack():
print("Welcome to Blackjack!")
deck = Deck()
player_hand = Hand()
dealer_hand = Hand()
# Initial deal
player_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
player_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
# Player turn
player_turn(deck, player_hand, dealer_hand)
# Dealer turn if player not bust
if not player_hand.is_bust():
dealer_turn(deck, dealer_hand)
# Show final hands
show_hands(player_hand, dealer_hand, show_all_dealer_cards=True)
# Determine winner
result = compare_hands(player_hand, dealer_hand)
print("\n" + result)
if __name__ == "__main__":
play_blackjack()
How the code works:
- Card: Each card has a suit, rank, and a description string.
- Deck: The deck contains 52 Cards, shuffled.
- Hand: Represent player or dealer hand, with logic to evaluate Blackjack values considering Aces (which can be 1 or 11).
- Gameplay:
- Both player and dealer get two cards.
- Player can hit or stand.
- Dealer plays according to Blackjack rules — hits until 17 or more.
- Show cards with descriptions.
- Determine and announce winner.
Example output:
Welcome to Blackjack!
Your hand:
9 of Hearts - Nine lives of a cat.
A of Diamonds - Ace can be one or eleven.
Total value: 20
Dealer's hand:
5 of Spades - Five fingers on a hand.
<hidden card>
Do you want to (H)it or (S)tand? s
You stand.
Dealer's turn...
Dealer draws: 6 of Clubs - Six shooter, ready to play.
Dealer stands with value 21.
Your hand:
9 of Hearts - Nine lives of a cat.
A of Diamonds - Ace can be one or eleven.
Dealer's hand:
5 of Spades - Five fingers on a hand.
J of Hearts - Jack of all trades.
6 of Clubs - Six shooter, ready to play.
You lose.
You can copy and run the code as is in Python 3. Enjoy your Blackjack game with descriptive cards!