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

添加超时功能后Python答题游戏失效:无法显示对错提示仅触发超时提示

添加超时功能后Python答题游戏失效:无法显示对错提示仅触发超时提示

Hey AJ8,我瞅了下你的代码,问题根源出在那个计时器函数的实现上!你写的wait_timer_for_stress()是个完全阻塞的循环——一旦调用它,程序就会一头扎进倒计时里,根本没给用户留出输入答案的时间!等计时器走完,直接就触发“Times Up!”了,自然轮不到显示对错提示。

要解决这个问题,我们得让计时器和用户输入同时运行,这里用多线程就能搞定。一个线程负责倒计时检测超时,另一个线程负责等待用户输入,互不干扰。

给你改好的可运行代码示例:

import random
import time
import threading
from colorama import init, Fore

# 初始化colorama,自动重置颜色
init(autoreset=True)

timer = 5
answered = False  # 标记用户是否已经提交答案

color_dict = {
    "1": "Red",
    "2": "Blue",
    "3": "Light Blue",
    "4": "Green",
    "5": "Cyan",
    "6": "Yellow",
    "7": "Magenta",
}

def wait_timer_for_stress():
    global timer, answered
    timer = 5
    # 倒计时同时检查用户是否已经答题
    while timer > 0 and not answered:
        timer -= 1
        time.sleep(1)
    # 只有用户没答题时才提示超时
    if not answered:
        print("\nTimes Up!")

def start_quiz():
    global answered
    answered = False
    # 随机抽取颜色对应的数字和名称
    color_num, color_name = random.choice(list(color_dict.items()))
    # 匹配对应的颜色样式
    color_code = [Fore.RED, Fore.GREEN, Fore.BLUE, Fore.YELLOW, Fore.MAGENTA, Fore.CYAN, Fore.LIGHTBLUE_EX][int(color_num)-1]
    
    print(f"{color_code}Type the number, not the color!\nCurrent color: {color_name}\n")
    
    # 启动计时器线程
    timer_thread = threading.Thread(target=wait_timer_for_stress)
    timer_thread.start()
    
    # 等待用户输入
    try:
        user_input = input("Your answer: ")
        answered = True
        timer_thread.join()  # 等待计时器线程结束
        
        if user_input == color_num:
            print("Correct!")
        else:
            print("Incorrect!")
    except:
        pass

# 主游戏循环
while True:
    start_quiz()
    # 给用户退出选项
    if input("\nPress Enter to continue, type 'q' to quit: ").lower() == 'q':
        break

我给你梳理下关键改动点:

  • 引入threading模块,用线程分离计时器和输入逻辑,两者并行运行
  • 新增answered变量,用来避免超时提示和对错提示同时触发
  • 把原来在循环里重复定义的函数提到外面,更规范高效
  • 初始化colorama时开启自动重置,不用手动写Fore.RESET
  • 补充了完整的出题逻辑,给用户加了退出选项,体验更友好

备注:内容来源于stack exchange,提问作者AJ8

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 09:34:43