Python简易BlackJack游戏代码偶发停滞问题排查求助
问题诊断与修复
核心错误:无限循环导致程序停滞
你的代码在打印"Now dealer moves"后停滞,根源是庄家回合的循环进入了无限循环,问题出在更新庄家总分的代码行:
在庄家回合的循环里,你错误地用玩家手牌的总和来更新庄家的总分:
dealer_sum = sum(player_hand)
这会导致两种问题:
- 如果玩家的总分小于17,庄家会持续加牌,永远满足
dealer_sum < 17的条件,循环无法终止,程序直接卡住。 - 即使玩家总分≥17,也会导致庄家的总分计算完全错误,游戏逻辑混乱。
修复代码
把庄家回合里的sum(player_hand)改成sum(dealer_hand),让庄家的总分基于自己的手牌计算:
print('\nNow dealer moves.') dealer_end = False while not dealer_end: if dealer_sum < 17: dealer_hand.append(choice(cards)) dealer_sum = sum(dealer_hand) # 修正为庄家自己的手牌求和 else: dealer_end = True print(f"The dealer's final hand is {dealer_hand} with a score of {dealer_sum}.")
可选优化建议
- 补充A牌的逻辑:BlackJack里A牌可以当11也可以当1,当手牌总和超过21时,应该把11转为1避免爆牌。可以写一个工具函数处理:
之后用这个函数替代直接def get_hand_score(hand): score = sum(hand) # 循环检查并转换A牌 while score > 21 and 11 in hand: hand.remove(11) hand.append(1) score = sum(hand) return scoresum()计算总分,游戏规则会更准确。 - 删除冗余导入:你导入了
inquirer但全程没用到,建议删除这行代码减少冗余。
内容的提问来源于stack exchange,提问作者Lori C
相关产品推荐
相关产品推荐

