Blackjack(21点)游戏A牌11转1功能实现技术求助
解决Blackjack中A牌自动转换规则的实现方案
原代码的核心问题是只记录了手牌总和,没有保存具体的手牌列表,导致无法追踪A(值为11)的数量,也就没法在总和超21时自动将11转为1。下面是修改后的完整实现,完全符合需求:
修改后的完整代码
import random def calculate_hand_total(hand): """计算手牌的有效总和,自动处理A的转换""" total = sum(hand) # 统计手牌中A(11)的数量 aces_count = hand.count(11) # 当总和超过21且还有可转换的A时,逐个将11转为1(即总和减10) while total > 21 and aces_count > 0: total -= 10 aces_count -= 1 return total while True: cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] # 用列表保存玩家和庄家的手牌,而不是单独的卡片变量 player_hand = [random.choice(cards), random.choice(cards)] dealer_hand = [random.choice(cards), random.choice(cards)] player_total = calculate_hand_total(player_hand) dealer_total = calculate_hand_total(dealer_hand) print(f"Your cards: {player_hand}\nTotal: {player_total}") print(f"Dealer's cards: [{dealer_hand[0]}] [?]") # 玩家拿到黑杰克的情况 if player_total == 21: print("$$$Winner Winner Chicken Dinner$$$") # 重新开始/退出逻辑 while True: answer = input('Run again? (y/n): ').lower() if answer in ('y', 'n'): break print("Invalid input. Please enter 'y' or 'n'.") if answer == 'y': continue else: print("Goodbye") break # 玩家选择Hit/Stay的循环 while player_total < 21: hit_stay = input("Hit[1] or Stay[2]? ") if hit_stay == "1": # 新增一张牌到手牌列表 new_card = random.choice(cards) player_hand.append(new_card) player_total = calculate_hand_total(player_hand) print(f"Your cards: {player_hand}\nTotal: {player_total}") # 检查是否爆牌(转换A后仍超21) if player_total > 21: print("Dealer Wins") break elif hit_stay == "2": break else: print("Invalid input. Please enter '1' or '2'.") # 玩家爆牌后的重新开始/退出逻辑 if player_total > 21: while True: answer = input('Run again? (y/n): ').lower() if answer in ('y', 'n'): break print("Invalid input. Please enter 'y' or 'n'.") if answer == 'y': continue else: print("Goodbye") break # 庄家回合 print(f"Dealer's cards: {dealer_hand}\nTotal: {dealer_total}") while dealer_total <= 16: new_card = random.choice(cards) dealer_hand.append(new_card) dealer_total = calculate_hand_total(dealer_hand) print(f"Dealer draws {new_card}. New total: {dealer_total}") # 判断胜负 if dealer_total > 21: print("Player Wins") elif dealer_total > player_total: print("Dealer Wins") elif dealer_total < player_total: print("Player Wins") else: print("Draw") # 重新开始/退出逻辑 while True: answer = input('Run again? (y/n): ').lower() if answer in ('y', 'n'): break print("Invalid input. Please enter 'y' or 'n'.") if answer == 'y': continue else: print("Goodbye") break
关键修改说明
- 新增
calculate_hand_total函数:这是处理A转换的核心,它会先计算手牌总和,然后统计A的数量,当总和超21时,逐个将A从11转为1(总和减10),直到总和≤21或没有A可转换。 - 改用列表存储手牌:玩家和庄家的手牌都用列表保存,这样能追踪每一张牌的具体值,尤其是A的数量,为转换提供依据。
- 更新Hit逻辑:玩家Hit时,新牌会添加到手牌列表,然后重新计算有效总和,自动处理A的转换。
- 统一胜负判断逻辑:确保所有情况下的总和都是经过A转换后的有效数值,避免错误判断。
内容的提问来源于stack exchange,提问作者MR.J
相关产品推荐
相关产品推荐

