Python猜数字AI游戏故障:AI重复猜同一数字的解决方法咨询
Python猜数字游戏AI重复猜数问题修复
问题根源分析
你的代码存在以下核心问题,导致AI始终重复猜测同一个数字:
- 变量初始化错误:
newag被固定初始为1,完全丢弃了一开始随机生成的aig值,导致AI从1开始猜,而非第一次的随机数。 - 函数未正确修改变量:
newter()和fewter()仅做了newag - 1/newag + 1的计算,但没有赋值操作,也未声明newag为全局变量,外部的newag值始终不变。 - 条件判断逻辑混乱:多个独立的
if语句导致输入"c"时,会触发后续的else分支输出错误提示;且猜对后未终止循环。 - 猜数逻辑低效:仅通过±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")
关键修改说明
- 维护猜数区间:新增
low和high变量记录当前可能的数字范围,每次根据用户反馈调整区间,确保猜测始终在有效范围内。 - 正确更新猜测值:移除无效的函数,直接在条件分支中根据调整后的区间生成新的随机猜测数。
- 优化条件判断:使用
elif替代独立if,避免逻辑冲突;猜对后用break终止循环。 - 提升容错性:将用户输入转为小写,支持大写输入(如"H""L""C")。
内容的提问来源于stack exchange,提问作者Chaitanya pawar
相关产品推荐
相关产品推荐

