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

如何为Python随机数学问答游戏添加20秒答题倒计时功能

修改说明
  • 核心问题:Python原生input()为阻塞方法,会一直等待用户输入,无法直接实现超时判断,本次修改使用inputimeout第三方库实现20秒超时逻辑,无需大幅改动原有代码结构
  • 修复原有代码中未定义elapsed变量的错误逻辑
  • 超时规则设置:20秒未作答视为本题作答失败,扣除1点生命值,进入下一题(可根据需求自行调整规则)
  • 补充除法题的异常处理,避免除数为0导致程序崩溃,同时增加浮点精度兼容逻辑,避免因为精度问题误判正确答案
  • 简化了原代码中重复的运算符判断逻辑,可读性更高
安装依赖

执行以下命令安装超时输入工具库:

pip install inputimeout
修改后完整代码
import random
from inputimeout import inputimeout, TimeoutOccurred

def startgame():
    answer = input("Would you like to play a game? Y/N")  
    if answer == "Y":
        game()
    elif answer == "N":
        print("Goodbye")

def game():
    life_counter = 3
    point_counter = 0
    end_number1 = 25
    end_number2 = 25  
    start_number1 = 0
    start_number2 = 0
    point_add = 1
    while life_counter != 0:
        # 分数里程碑提示
        if point_counter == 10:
            print("Great job, you have reached 10 points!")
        if point_counter == 30:
            print("Awesome! You have reached 30 points!")
        if point_counter == 50:
            print("Legendary! You have reached 50 points")
        
        # 生成题目
        a = random.randint(start_number1, end_number1)
        b = random.randint(start_number2, end_number2)
        operator = ["+", "-", "/", "*"]
        chosen_operator = random.choice(operator)
        # 除法题确保除数不为0
        if chosen_operator == "/" and b == 0:
            continue
        
        print("what is", a, chosen_operator, b)
        # 带20秒超时的输入逻辑
        try:
            c = float(inputimeout(prompt="What is your answer?\n", timeout=20))
        except TimeoutOccurred:
            print("答题超时,本题自动结束")
            life_counter -= 1
            print(f"You have {point_counter} points and {life_counter} lives left")
            if life_counter == 0:
                break
            continue
        
        # 答案判断逻辑
        correct = False
        if chosen_operator == "+":
            correct = c == (a + b)
        elif chosen_operator == "-":
            correct = c == (a - b)
        elif chosen_operator == "/":
            # 浮点精度兼容,允许极小误差
            correct = abs(c - (a / b)) < 1e-6
        elif chosen_operator == "*":
            correct = c == (a * b)
        
        if correct:
            print("That is correct")
            start_number1 += 25
            end_number1 += 25
            start_number2 += 25
            end_number2 += 25
            point_counter += point_add
            point_add += 1
            print(f"You have {point_counter} points")
        else:
            print("Incorrect, try again")
            life_counter -= 1
            print(f"You have {point_counter} points and {life_counter} lives left")
            if life_counter != 0: 
                yn = input("Would you like to try again?")
                if yn == "no":
                    print("GAME_OVER")
                    break
                     
    print(f"GAME_OVER, you ended with {point_counter} points")

startgame()
可选无依赖方案

如果不想安装第三方库,可以用多线程实现超时逻辑:单独开子线程等待用户输入,主线程计时,20秒未收到输入就直接终止输入流程,逻辑相对复杂,可根据需求调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:27:02