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()