|
| 1 | +import random |
| 2 | + |
| 3 | +# Define the deck of cards |
| 4 | +suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] |
| 5 | +ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace'] |
| 6 | + |
| 7 | +def create_deck(): |
| 8 | + deck = [{'rank': rank, 'suit': suit} for rank in ranks for suit in suits] |
| 9 | + random.shuffle(deck) |
| 10 | + return deck |
| 11 | + |
| 12 | +def calculate_hand_value(hand): |
| 13 | + values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, |
| 14 | + 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} |
| 15 | + |
| 16 | + value = sum(values[card['rank']] for card in hand) |
| 17 | + |
| 18 | + # Handle Aces |
| 19 | + aces = [card for card in hand if card['rank'] == 'Ace'] |
| 20 | + for _ in range(len(aces)): |
| 21 | + if value > 21: |
| 22 | + value -= 10 # Change an Ace's value from 11 to 1 if it prevents busting |
| 23 | + |
| 24 | + return value |
| 25 | + |
| 26 | +def blackjack(): |
| 27 | + deck = create_deck() |
| 28 | + player_hand = [deck.pop(), deck.pop()] |
| 29 | + dealer_hand = [deck.pop(), deck.pop()] |
| 30 | + |
| 31 | + print("Welcome to Blackjack!") |
| 32 | + |
| 33 | + while True: |
| 34 | + print("\nYour hand:", [card['rank'] + ' of ' + card['suit'] for card in player_hand]) |
| 35 | + print("Dealer's hand:", dealer_hand[0]['rank'] + ' of ' + dealer_hand[0]['suit'], "and an unknown card") |
| 36 | + |
| 37 | + player_value = calculate_hand_value(player_hand) |
| 38 | + if player_value == 21: |
| 39 | + print("Congratulations! You got a Blackjack!") |
| 40 | + break |
| 41 | + elif player_value > 21: |
| 42 | + print("Bust! You went over 21. You lose.") |
| 43 | + break |
| 44 | + |
| 45 | + action = input("Do you want to 'hit' or 'stand'? ").strip().lower() |
| 46 | + |
| 47 | + if action == 'hit': |
| 48 | + player_hand.append(deck.pop()) |
| 49 | + elif action == 'stand': |
| 50 | + while calculate_hand_value(dealer_hand) < 17: |
| 51 | + dealer_hand.append(deck.pop()) |
| 52 | + |
| 53 | + dealer_value = calculate_hand_value(dealer_hand) |
| 54 | + print("\nDealer's hand:", [card['rank'] + ' of ' + card['suit'] for card in dealer_hand]) |
| 55 | + |
| 56 | + if dealer_value > 21: |
| 57 | + print("Dealer busts! You win.") |
| 58 | + elif dealer_value >= player_value: |
| 59 | + print("Dealer wins.") |
| 60 | + else: |
| 61 | + print("You win!") |
| 62 | + |
| 63 | + break |
| 64 | + else: |
| 65 | + print("Invalid input. Please enter 'hit' or 'stand'.") |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + blackjack() |
0 commit comments