gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
Write in Python game where user plays vs computer in blackjack.
- User
Write in Python game where user plays vs computer in blackjack.
- Assistant
Write in Python game where user plays vs computer in blackjack.
Sure! Here's a simple Blackjack game in Python where the user plays against the computer (dealer). The dealer will follow standard Blackjack rules: hit until the score is 17 or more.
import random
def create_deck():
"""Creates a standard deck of 52 cards."""
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
deck = [(rank, suit) for suit in suits for rank in ranks]
random.shuffle(deck)
return deck
def card_value(card):
"""Returns the blackjack value of a card."""
rank, _ = card
if rank in ['J', 'Q', 'K']:
return 10
elif rank == 'A':
return 11
else:
return int(rank)
def hand_value(hand):
"""Calculate the value of the hand. Handle aces as 1 or 11."""
value = sum(card_value(card) for card in hand)
# Adjust for aces
aces = sum(1 for card in hand if card[0] == 'A')
while value > 21 and aces:
value -= 10
aces -= 1
return value
def display_hand(hand, name, hide_first_card=False):
"""Display the cards in hand."""
if hide_first_card:
print(f"{name}'s hand: [Hidden card], {hand[1][0]} of {hand[1][1]}")
else:
cards = ', '.join(f"{rank} of {suit}" for rank, suit in hand)
print(f"{name}'s hand: {cards}")
def blackjack_game():
print("Welcome to Blackjack!")
deck = create_deck()
# Initial deal
player_hand = [deck.pop(), deck.pop()]
dealer_hand = [deck.pop(), deck.pop()]
# Show hands
display_hand(player_hand, "Player")
display_hand(dealer_hand, "Dealer", hide_first_card=True)
# Player's turn
while True:
player_value = hand_value(player_hand)
if player_value > 21:
print(f"Player busts with {player_value}! Dealer wins.")
return
choice = input("Do you want to hit or stand? (h/s): ").lower()
if choice == 'h':
player_hand.append(deck.pop())
display_hand(player_hand, "Player")
elif choice == 's':
break
else:
print("Invalid input. Please enter 'h' or 's'.")
# Dealer's turn
print("\nDealer's turn:")
display_hand(dealer_hand, "Dealer")
dealer_value = hand_value(dealer_hand)
while dealer_value < 17:
dealer_hand.append(deck.pop())
display_hand(dealer_hand, "Dealer")
dealer_value = hand_value(dealer_hand)
# Determine winner
print(f"\nPlayer's hand value: {player_value}")
print(f"Dealer's hand value: {dealer_value}")
if dealer_value > 21:
print("Dealer busts! Player wins.")
elif dealer_value == player_value:
print("It's a tie!")
elif player_value > dealer_value:
print("Player wins!")
else:
print("Dealer wins!")
if __name__ == "__main__":
blackjack_game()
You can run this code in your Python environment and play a simple blackjack game against the computer dealer. Let me know if you'd like any enhancements or additional features!
Not yet included in a published release.