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

Python猜数字AI游戏故障:AI重复猜同一数字的解决方法咨询

Python猜数字游戏AI重复猜数问题修复

问题根源分析

你的代码存在以下核心问题,导致AI始终重复猜测同一个数字:

  1. 变量初始化错误:newag被固定初始为1,完全丢弃了一开始随机生成的aig值,导致AI从1开始猜,而非第一次的随机数。
  2. 函数未正确修改变量:newter()和fewter()仅做了newag - 1/newag + 1的计算,但没有赋值操作,也未声明newag为全局变量,外部的newag值始终不变。
  3. 条件判断逻辑混乱:多个独立的if语句导致输入"c"时,会触发后续的else分支输出错误提示;且猜对后未终止循环。
  4. 猜数逻辑低效:仅通过±1调整猜测数,未利用用户反馈缩小范围,既低效也不符合猜数字游戏的合理逻辑。

修正后的代码

import random

print("""
      Hello there my friend
      I am an AI
      I have been made for a very Specific game
      and i would like you to play
      It is an number guesser
      You will think of a number
      and I will try to guess it
      and you would say higher or lower
      Lets Start
      """)
print("Okk so what is the range?:")
rang = int(input())
print("Lets Start. Say (h) for higher and (l) for Lower and (c) for Correct!")

# 初始化猜数的上下限
low = 1
high = rang
# 第一次随机猜测
current_guess = random.randint(low, high)
print(f"Is {current_guess} the number?")

while True:
    letter = input().lower()  # 统一转为小写,提升容错性
    if letter == "h":
        # 用户说更高,调整下限为当前猜测+1
        low = current_guess + 1
        current_guess = random.randint(low, high)
        print(f"Is {current_guess} the number?")
    elif letter == "l":
        # 用户说更低,调整上限为当前猜测-1
        high = current_guess - 1
        current_guess = random.randint(low, high)
        print(f"Is {current_guess} the number?")
    elif letter == "c":
        print("Finally i got that Right")
        break  # 猜对后终止循环
    else:
        print("Sorry but i cant understand")

关键修改说明

  1. 维护猜数区间:新增low和high变量记录当前可能的数字范围,每次根据用户反馈调整区间,确保猜测始终在有效范围内。
  2. 正确更新猜测值:移除无效的函数,直接在条件分支中根据调整后的区间生成新的随机猜测数。
  3. 优化条件判断:使用elif替代独立if,避免逻辑冲突;猜对后用break终止循环。
  4. 提升容错性:将用户输入转为小写,支持大写输入(如"H""L""C")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:30:47