python代码实现79523扑克牌游戏

import random

# 定义扑克牌的点数和花色
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 11}

# 创建扑克牌类
class Card:
    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank
        self.value = values[rank]

    def __repr__(self):
        return f"{self.rank} of {self.suit}"

# 创建扑克牌堆类
class Deck:
    def __init__(self):
        self.cards = [Card(suit, rank) for suit in suits for rank in ranks]
        random.shuffle(self.cards)
    
    def deal(self):
        return self.cards.pop()

# 计算手牌点数
def calculate_hand_value(hand):
    value = sum(card.value for card in hand)
    # 处理A的情况
    num_aces = sum(1 for card in hand if card.rank == 'A')
    while value > 21 and num_aces:
        value -= 10
        num_aces -= 1
    return value

# 游戏主函数
def play_game():
    deck = Deck()
    player_hand = [deck.deal(), deck.deal()]
    dealer_hand = [deck.deal(), deck.deal()]
    
    print("Welcome to 21 Points!")
    
    # 玩家回合
    while True:
        print(f"Your hand: {player_hand} | Total value: {calculate_hand_value(player_hand)}")
        print(f"Dealer's hand: {dealer_hand[0]} and hidden card")
        action = input("Do you want to 'hit' or 'stand'? ").strip().lower()
        
        if action == 'hit':
            player_hand.append(deck.deal())
            if calculate_hand_value(player_hand) > 21:
                print(f"Busted! Your final hand: {player_hand} | Total value: {calculate_hand_value(player_hand)}")
                return
        elif action == 'stand':
            break
    
    # 庄家回合
    print(f"Dealer's hand: {dealer_hand} | Total value: {calculate_hand_value(dealer_hand)}")
    while calculate_hand_value(dealer_hand) < 17:
        dealer_hand.append(deck.deal())
        print(f"Dealer hits: {dealer_hand} | Total value: {calculate_hand_value(dealer_hand)}")
    
    # 决定胜负
    player_total = calculate_hand_value(player_hand)
    dealer_total = calculate_hand_value(dealer_hand)
    
    if dealer_total > 21 or player_total > dealer_total:
        print("You win!")
    elif player_total < dealer_total:
        print("Dealer wins!")
    else:
        print("It's a tie!")

if __name__ == "__main__":
    play_game()
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值