You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在二十一点(Blackjack)游戏的while循环中延续try/catch逻辑以处理非法投注输入

解决二十一点游戏投注金额验证的循环终止问题

嘿,你遇到的问题其实很常见——你的代码触发了自定义异常但没捕获它,导致程序直接崩溃退出,而不是回到循环让用户重新输入。咱们一步步来修复它:

问题根源

你在判断投注金额小于1或超过现有筹码时手动raise了异常,但except块只处理了ValueError,这些自定义异常没有被捕获,所以程序会直接终止,无法回到while True循环。

解决方案1:捕获自定义异常

只需要在except块里新增对自定义Exception的捕获,处理完错误后让循环继续即可:

print("\n==== BLACKJACK GAME ====")
chip_amount = 5  # 初始筹码示例值
player_hand = ["Ace", "10"]  # 示例玩家手牌
player_total = 21
dealer_hand = ["Queen", "5"]
dealer_total_sliced = 10

print(f'\nYou have currently have {chip_amount} chips available.')
while True:
    try:
        chips_input = int(input("How many chips do you want to bet? "))
        if chips_input < 1:
            raise Exception("Sorry, you have to enter a number bigger than 0.")  # 修正提示,1个筹码是合法投注
        if chips_input > chip_amount:
            raise Exception(f'Sorry, you have to enter a number less than or equal to {chip_amount}.')
    except ValueError:
        print("\nYou have to enter a number!")
        continue
    except Exception as e:
        print(f"\n{e}")  # 打印自定义错误信息
        continue  # 回到循环,让用户重新输入
    else:
        print(f'\nYou bet {chips_input} chips out of your total of {chip_amount} chips.')
        print(f'\nThe cards have been dealt. You have a {" and a ".join(player_hand)}, with a total value of {player_total}.')
        print(f'The dealers visible card is a {dealer_hand[0]}, with a value of {dealer_total_sliced}.')
        break  # 验证通过后退出循环,进入游戏环节

解决方案2:不用自定义异常,直接判断后延续循环

其实不需要手动raise异常,直接在try块外做金额验证,不符合条件时打印错误并continue回到循环,代码会更简洁直观:

print("\n==== BLACKJACK GAME ====")
chip_amount = 5
player_hand = ["Ace", "10"]
player_total = 21
dealer_hand = ["Queen", "5"]
dealer_total_sliced = 10

print(f'\nYou have currently have {chip_amount} chips available.')
while True:
    try:
        chips_input = int(input("How many chips do you want to bet? "))
    except ValueError:
        print("\nYou have to enter a number!")
        continue
    
    # 在这里做金额合法性验证
    if chips_input < 1:
        print("\nSorry, you have to enter a number bigger than 0.")
        continue
    if chips_input > chip_amount:
        print(f"\nSorry, you have to enter a number less than or equal to {chip_amount}.")
        continue
    
    # 验证通过后执行游戏后续逻辑
    print(f'\nYou bet {chips_input} chips out of your total of {chip_amount} chips.')
    print(f'\nThe cards have been dealt. You have a {" and a ".join(player_hand)}, with a total value of {player_total}.')
    print(f'The dealers visible card is a {dealer_hand[0]}, with a value of {dealer_total_sliced}.')
    break

小细节优化

我把错误提示里的“bigger than 1”改成了“bigger than 0”,因为投注1个筹码是完全合法的,这样更符合二十一点的实际规则~

内容的提问来源于stack exchange,提问作者Suzdar Ibrahim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:12:50