Code me blakcjack in python
- User
Code me blakcjack in python
- Assistant
Code me blakcjack in python
Sure! Below is a simple implementation of a Blackjack game in Python that you can run in your console. This version allows one player to play against the dealer.
import random
# Define card suits, ranks, and values
suits = ('Hearts', 'Diamonds', 'Clubs', 'Spades')
ranks = (
'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten',
'Jack', 'Queen', 'King', 'Ace'
)
values = {
'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7,
'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10,
'Queen': 10, 'King': 10, 'Ace': 11
}
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.rank} of {self.suit}"
class Deck:
def __init__(self):
self.all_cards = [Card(suit, rank) for suit in suits for rank in ranks]
def shuffle(self):
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop()
class Hand:
def __init__(self):
self.cards = [] # Cards in the hand
self.value = 0 # Total value of the hand
self.aces = 0 # Number of aces
def add_card(self, card):
self.cards.append(card)
self.value += values[card.rank]
if card.rank == 'Ace':
self.aces += 1
self.adjust_for_ace()
def adjust_for_ace(self):
# If total value > 21 and there is an ace, adjust its value from 11 to 1
while self.value > 21 and self.aces:
self.value -= 10
self.aces -= 1
def take_bet():
while True:
try:
bet = int(input("Enter your bet: "))
if bet > 0:
return bet
else:
print("Bet must be a positive integer.")
except ValueError:
print("Please enter a valid integer.")
def hit(deck, hand):
card = deck.deal_one()
hand.add_card(card)
print(f"Hit: {card}")
def hit_or_stand(deck, hand):
while True:
choice = input("Would you like to Hit or Stand? (h/s): ").lower()
if choice == 'h':
hit(deck, hand)
return True
elif choice == 's':
print("Player stands. Dealer's turn.")
return False
else:
print("Invalid input. Please enter 'h' or 's'.")
def show_some(player, dealer):
print("\nDealer's Hand:")
print(" <Hidden card>")
print(f" {dealer.cards[1]}")
print("\nPlayer's Hand:", *player.cards, sep='\n ')
def show_all(player, dealer):
print("\nDealer's Hand:", *dealer.cards, sep='\n ')
print(f"Dealer's Hand = {dealer.value}")
print("\nPlayer's Hand:", *player.cards, sep='\n ')
print(f"Player's Hand = {player.value}")
def player_busts():
print("Player busts! Dealer wins.")
def player_wins():
print("Player wins!")
def dealer_busts():
print("Dealer busts! Player wins!")
def dealer_wins():
print("Dealer wins!")
def push():
print("It's a tie! Push.")
def play_game():
print("Welcome to Blackjack!")
# Create and shuffle deck
deck = Deck()
deck.shuffle()
# Create player and dealer hands
player_hand = Hand()
dealer_hand = Hand()
# Deal two cards to player and dealer
for _ in range(2):
player_hand.add_card(deck.deal_one())
dealer_hand.add_card(deck.deal_one())
# Show initial hands
show_some(player_hand, dealer_hand)
# Player's turn
while True:
if hit_or_stand(deck, player_hand):
show_some(player_hand, dealer_hand)
if player_hand.value > 21:
show_all(player_hand, dealer_hand)
player_busts()
return
else:
break
# Dealer's turn
show_all(player_hand, dealer_hand)
while dealer_hand.value < 17:
print("Dealer hits.")
hit(deck, dealer_hand)
show_all(player_hand, dealer_hand)
if dealer_hand.value > 21:
dealer_busts()
return
# Compare hands
if dealer_hand.value > player_hand.value:
dealer_wins()
elif dealer_hand.value < player_hand.value:
player_wins()
else:
push()
if __name__ == "__main__":
while True:
play_game()
new_game = input("\nWould you like to play another hand? (y/n): ").lower()
if new_game != 'y':
print("Thanks for playing!")
break
Save the Code: Copy the above code into a file named, for example, blackjack.py.
Run the Script:
Open your terminal or command prompt.
Navigate to the directory where blackjack.py is saved.
Run the script using Python:
python blackjack.py
If you have multiple versions of Python installed, you might need to use python3 instead:
python3 blackjack.py
Play the Game: Follow the on-screen prompts to place your bet, choose to hit or stand, and see the outcome of each round.
This basic version covers the fundamental gameplay mechanics. Here are some ways you could enhance it:
Feel free to modify and expand the code to add more features and make the game more robust!
Not yet included in a published release.