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

Python实现21点游戏时无法判断触发21分的回合归属问题求助

解决21点游戏的回合胜负检测问题

嘿,我懂你的困扰——当前代码是在玩家和电脑都完成操作后才检查总分,但这样根本没法区分是谁把总分推到21或以上的对吧?咱们来一步步修复这个问题:

先说说原代码里的几个小问题

  • carryOn == False这里是比较运算符,不是赋值,应该写成carryOn = False才能终止循环
  • user == 0这行完全没用,直接删掉就行
  • 最核心的问题:胜负检查的时机不对,应该在每一方操作完成后立刻检查,而不是等双方都操作完

修改后的完整代码

import random
import time

carryOn = True
counter = 0
print("First to 21 or above LOSES\n \n")

while carryOn:
    # 玩家回合
    user_input = input("Please enter any number from 1 – 4: ")
    # 可选:添加输入验证,防止玩家输入无效数字
    while not user_input.isdigit() or not (1 <= int(user_input) <=4):
        user_input = input("Invalid input! Please enter a number between 1 and 4: ")
    
    user_choice = int(user_input)
    print(f"You Chose {user_choice}")
    counter += user_choice
    print(f"The new Total is {counter}\n")

    # 玩家操作后立刻检查是否触发失败条件
    if counter >= 21:
        print("Oh no! You pushed the total to 21 or above. You lose!")
        carryOn = False
        break  # 直接跳出循环,不用再执行电脑回合

    # 电脑回合(仅玩家未输时执行)
    time.sleep(3)
    computer_choice = random.randint(1,4)
    print(f"The Computer Rolled a {computer_choice}")
    counter += computer_choice
    print(f"The new Total is {counter}\n")

    # 电脑操作后检查是否触发失败条件
    if counter >= 21:
        print("Computer pushed the total to 21 or above! You win!")
        carryOn = False

关键修改点说明

  1. 拆分胜负检查时机:玩家操作完立刻判断,如果总分≥21,直接判定玩家输并终止游戏;若玩家没问题,再执行电脑回合,电脑操作后同样立刻判断胜负。
  2. 输入验证(可选但实用):新增逻辑确保玩家只能输入1-4的有效数字,避免无效输入导致程序报错。
  3. 修正赋值错误:把carryOn == False改成carryOn = False,正确终止循环。
  4. 用f-string优化输出:比传统字符串拼接更简洁易读,代码维护起来更方便。

这样就能精准检测到是哪一方的回合导致总分达标,从而正确判定胜负啦!

内容的提问来源于stack exchange,提问作者Don't Sue Me

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:49:07