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

Python游戏代码获取用户输入后随机停止的问题求助

问答游戏代码执行停滞问题解决

问题场景

这段代码用于读取文本文件中的问答对(示例格式:name : jd、country : finland),实现问答游戏功能,但在获取用户是否准备开始的输入后,程序停滞,未执行后续的问答逻辑。

原代码

def playSaved(choiceSaved):

    y =  open(choiceSaved,'r')

    for line in y.readlines():
        qna = line.split(" : ")
        randQues.append(qna[0])
        randAns.append(qna[1])

    print("Processing game.....")
    time.sleep(2)
    savedChoice = input("\nOk! Are you ready to play? (Y/N) ")

    # the code stops here, after getting the input

    if savedChoice.lower() == 'y':
        for num in range(len(y.readlines())):
            count = 1
            if "?" in randQues[num]:
                ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
            else:
                ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")

            if ansForSaved == randAns[num]:
                print("Correct!")
            else:
                print("Wrong!")

问题原因

第一次调用y.readlines()遍历文件后,文件的读取指针已经移动到了文件末尾,后续再调用y.readlines()只能得到空列表,导致for num in range(len(y.readlines()))的循环根本不会执行,看起来就像程序停滞了。

另外还有几个隐性问题:

  • 未导入time模块,运行会报错
  • 读取的答案中带有换行符,导致用户输入的答案无法匹配
  • count变量在循环内初始化,所有问题都会显示为「Question 1」

修复方案

最优方案:利用已存储的列表循环(无需重复读文件)

既然已经把所有问答对存入randQues和randAns列表,直接基于这两个列表的长度循环即可,同时修复上述隐性问题:

def playSaved(choiceSaved):
    global randQues, randAns
    randQues = []
    randAns = []
    
    # 使用with语句自动关闭文件,避免资源泄漏
    with open(choiceSaved, 'r') as y:
        for line in y.readlines():
            # 去除每行首尾的空白字符,避免拆分出错
            line_clean = line.strip()
            qna = line_clean.split(" : ")
            randQues.append(qna[0])
            # 去除答案中的换行符和空白字符
            randAns.append(qna[1].strip())

    import time
    print("Processing game.....")
    time.sleep(2)
    savedChoice = input("\nOk! Are you ready to play? (Y/N) ")

    if savedChoice.lower() == 'y':
        count = 1  # 将count初始化放在循环外
        for num in range(len(randQues)):
            # 简化问题提示逻辑
            prompt = f"Question {count}:\n{randQues[num]}\n> "
            ansForSaved = input(prompt)

            if ansForSaved == randAns[num]:
                print("Correct!")
            else:
                print("Wrong!")
            count += 1  # 每次循环后count自增

备选方案:重置文件指针(不推荐)

如果一定要重复读取文件,可在进入循环前调用y.seek(0)将文件指针移回开头,但这种方法会重复读取文件,浪费资源:

if savedChoice.lower() == 'y':
    y.seek(0)  # 将文件指针移回文件开头
    count = 1
    for num in range(len(y.readlines())):
        # 后续逻辑同原代码,同时记得修复count和换行符问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:01:07