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

Blackjack项目:如何实现玩家选择stand时退出while循环

解决Blackjack游戏中选择stand无法退出循环的问题

方案一:提前初始化变量,调整循环条件

提前给Pchoice赋一个非"stand"的初始值,就能把它加入循环判断条件中。当用户选择stand时,下一次循环的条件会不满足,自动退出循环。

示例代码:

# 初始化变量,确保首次循环正常执行
Pchoice = ""
Phand = 0  # 替换成你实际的玩家手牌点数变量

while Phand != 21 and Pchoice != "stand":
    Pchoice = input("Would you like to hit, stand or fold? ").lower()
    if Pchoice == "hit":
        # 执行抽牌逻辑,更新Phand的值
        print("抽牌中...")
        # 示例:Phand += random.randint(1,11)
    elif Pchoice == "fold":
        # 执行弃牌逻辑
        print("你选择了弃牌,游戏结束")
        break  # 弃牌直接终止循环

方案二:循环内判断stand后使用break

保持原循环结构,在用户输入后单独判断是否选择了stand,仅在该情况下执行break,既能正常处理多次抽牌,又能在选择stand时退出循环。

示例代码:

Phand = 0  # 替换成你实际的玩家手牌点数变量

while Phand != 21:
    Pchoice = input("Would you like to hit, stand or fold? ").lower()
    if Pchoice == "hit":
        # 执行抽牌逻辑,更新Phand的值
        print("抽牌中...")
        # 示例:Phand += random.randint(1,11)
    elif Pchoice == "fold":
        # 执行弃牌逻辑
        print("你选择了弃牌,游戏结束")
        break
    elif Pchoice == "stand":
        print("你选择了停止抽牌")
        break  # 仅在选择stand时退出循环
    else:
        print("无效输入,请输入hit、stand或fold")

关键说明

  • 加入.lower()是为了兼容用户输入不同大小写的情况(比如Stand、STAND),避免判断失效。
  • 方案一优势是逻辑更连贯,循环结束条件统一在while语句中;方案二更灵活,适合不想调整初始变量的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:45:12