国外名校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()

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
21是一种非常流行的纸牌游戏,也称为“黑杰克”。在这个游戏中,玩家要比庄家更接近21分,但不能超过21分。如果玩家的数比庄家高且不超过21分,则玩家获胜。如果庄家的数比玩家高或者玩家超过了21分,则庄家获胜。 蒙特卡洛方法是一种基于随机抽样的统计方法,可以用来解决21问题。具体步骤如下: 1. 初始化一个空数组,用于存储每一局游戏的结果(胜利或失败)。 2. 对于每一局游戏,随机生成一个初始的玩家数(可以在1-21之间随机选择),并循环进行以下步骤: a. 判断当前玩家数是否超过21分,如果是,则当前局游戏结束,记录为失败。 b. 如果当前玩家数已经达到21分,则当前局游戏结束,记录为胜利。 c. 如果当前玩家数小于21分,则随机选择要不要再抽一张牌,如果选择抽牌,则将新抽到的牌的数加到当前玩家数上,否则当前局游戏结束,记录为胜利。 3. 计算所有游戏结果的胜利概率。 下面是用Python实现蒙特卡洛方法解决21问题的代码: ```python import random def play_game(): player_score = random.randint(1, 21) while player_score < 21: draw_card = input("Do you want to draw a card? (y/n)") if draw_card == "y": player_score += random.randint(1, 11) if player_score > 21: print("You lose!") return False else: print("You win!") return True print("You win!") return True def simulate(n): wins = 0 for i in range(n): if play_game(): wins += 1 win_probability = wins / n print("Win probability:", win_probability) simulate(10000) ``` 在这个代码中,`play_game`函数用于模拟一局游戏,返回值为True表示获胜,False表示失败。`simulate`函数用于模拟多次游戏,并计算胜利概率。在这里,我们模拟了10000次游戏,输出了最终的胜利概率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

数智侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值