国外名校Python案例-实现21点游戏-黑杰克(Blackjack)

题目描述

代码实现

import random

def get_card():
    card_value = random.randint(1, 13)
    if card_value == 1:
        return 1, "ACE"
    elif card_value >= 11:
        return 10, ["JACK", "QUEEN", "KING"][card_value - 11]
    else:
        return card_value, str(card_value)

def get_hand_value(hand):
    hand_value = sum(card[0] for card in hand)
    for card in hand:
        if card[0] == 1 and hand_value <= 11:
            hand_value += 10
    return hand_value

def print_hand(hand, dealer=False):
    if dealer:
        print(f"Dealer's hand: {hand[1][1]}")
    else:
        cards = ", ".join([f"{card[1]} ({card[0]})" for card in hand])
        print(f"Your hand: {cards} ({get_hand_value(hand)})")


def print_stats(player_wins, dealer_wins, ties, game_number):
    pass


def play_game():
    game_number = 1
    player_wins = 0
    dealer_wins = 0
    ties = 0

    while True:
        print(f"\nSTART GAME #{game_number}")
        game_number += 1

        player_hand = [get_card()]
        print(f"Your card is a {player_hand[0][1]} ({player_hand[0][0]})")
        while get_hand_value(player_hand) < 21:
            print_hand(player_hand)
            print("\nWhat would you like to do?")
            print("1. Get another card")
            print("2. Hold hand")
            print("3. Print statistics")
            print("4. Exit")
            choice = int(input("Enter choice: "))

            if choice == 1:
                player_hand.append(get_card())
                if get_hand_value(player_hand) > 21:
                    print("You exceeded 21! You lose.")
                    dealer_wins += 1
                    break
                elif get_hand_value(player_hand) == 21:
                    print("BLACKJACK! You win!")
                    player_wins += 1
                    break
            elif choice == 2:
                break
            elif choice == 3:
                print_stats(player_wins, dealer_wins, ties, game_number)
            elif choice == 4:
                return
        dealer_hand = 0
        if get_hand_value(player_hand) <= 21:
            dealer_hand = get_hand_value([random.randint(1, 11) for i in range(2)])
            if dealer_hand > 21:
                print("Dealer exceeded 21! You win!")
                player_wins += 1
            elif dealer_hand == get_hand_value(player_hand):
                print("It's a tie! No one wins!")
                ties += 1
            else:
                print("Dealer wins!")
                dealer_wins += 1
        print_hand(player_hand)
        print_hand(dealer_hand)

if __name__ == '__main__':
    play_game()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源图客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值