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

Python猜数字加法游戏开发问题:关卡失效与需求实现求助

问题修复方案

问题1:关卡选择不生效的原因及修复

  • 原代码中level变量未被赋值,程序默认level值不为1/2,因此始终进入else分支生成三位数题目。
  • 修复:添加用户输入关卡的逻辑,确保level被正确赋值为整数类型。

问题2:题目数量与答错次数逻辑错误的原因及修复

  • 原代码用全局的fals变量同时控制总题数和单题错误次数,逻辑混乱:既限制了总错误次数为10次,又用它判断单题是否答错3次,无法实现“10道题+每题最多错3次”的需求。
  • 修复:
    1. 使用独立循环控制总题数(循环10次生成10道题);
    2. 每道题单独初始化错误次数计数器,避免跨题累计。
  • 额外隐藏问题:用户输入的guess是字符串类型,而answer是整数类型,两者永远不相等,导致即使答对也会被判定错误,需将guess转换为整数类型。

修正后的完整代码

import random

# 获取用户选择的关卡
level = int(input("请选择难度关卡(1/2/3):"))

total_questions = 10  # 总题数

for _ in range(total_questions):
    # 根据关卡生成对应范围的数字
    if level == 1:
        x = random.randint(0, 9)
        y = random.randint(0, 9)
    elif level == 2:
        x = random.randint(10, 99)
        y = random.randint(10, 99)
    else:
        x = random.randint(100, 999)
        y = random.randint(100, 999)
    
    answer = x + y
    wrong_attempts = 0  # 单题错误次数计数器
    
    while True:
        try:
            guess = int(input(f"{x} + {y} = "))
            if guess == answer:
                print("答对了!")
                break
            else:
                wrong_attempts += 1
                if wrong_attempts == 3:
                    print(f"答错3次,正确答案是:{x} + {y} = {answer}")
                    break
                else:
                    print(f"答错了,还有{3 - wrong_attempts}次机会")
        except ValueError:
            print("请输入有效的数字!")

代码说明

  • 导入random模块:确保能生成随机数;
  • 关卡输入:让用户选择关卡并转换为整数;
  • 总题数控制:用for循环生成10道题;
  • 单题错误计数:每道题开始时重置wrong_attempts,单独统计当前题的错误次数;
  • 类型转换与异常处理:将用户输入转为整数,同时处理非数字输入的情况,提升程序健壮性;
  • 答题逻辑:答对则进入下一题,答错累计次数,满3次显示正确答案后进入下一题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:36:21