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

Python实现答题游戏与倒计时器并发运行问题求助

问题描述

我首次在Stackoverflow发帖,正在学习Python,尝试制作一个简单游戏:系统随机生成一个两位小数的数字,玩家需输入另一个数字使两者之和为10,游戏限时30秒,因此添加了倒计时函数。但无法让游戏与倒计时器同时运行,尝试使用threading模块但未成功,希望得到帮助!

原代码:

import random
import time
import threading

number = 10.0
print("Sum up to 10!")


def game():
    global score
    score = 0
    while True:
        question = round(random.uniform(0.01, 9.99), 2)
        while True:
            print("\nYour number is: " + str(question))
            try:
                answer = float(input("\nAnswer: "))
                if question + answer != number:
                    print("\nWrong answer! Try again!")

                elif answer + question == number:
                    score += 1
                    print("\nCorrect!")
                    break
            except ValueError:
                print("Please key in a number(2 decimals)!")


def clock(countdown=0):
    while countdown > 0:
        time.sleep(1)
        countdown -= 1
        print("\rTime Left: " + str(countdown), end="")
        if countdown == 0:
            print("Final score: " + str(score))
            quit()


clock_thread = threading.Thread(target=clock(31))
game_thread = threading.Thread(target=game())
clock_thread.start()
game_thread.start()
修复方案

核心问题修正

  • 线程创建错误:创建线程时,target参数需传入函数对象,而非函数调用结果。原代码中clock(31)和game()会直接执行函数,导致线程无法正确启动,需改为通过args传递参数。
  • 浮点数精度问题:直接用==判断浮点数之和是否为10会因精度误差出错,应判断差值的绝对值小于极小值(如1e-9)。
  • 优雅终止线程:用全局标志位替代quit(),让游戏线程主动检测并退出,避免强制终止程序。

修改后的完整代码

import random
import time
import threading

number = 10.0
game_running = True  # 全局标志位,控制游戏线程运行
score = 0
print("Sum up to 10!")


def game():
    global score, game_running
    while game_running:
        question = round(random.uniform(0.01, 9.99), 2)
        while game_running:
            print("\nYour number is: " + str(question))
            try:
                answer = float(input("\nAnswer: "))
                # 用差值绝对值判断浮点数是否相等
                if abs((question + answer) - number) > 1e-9:
                    print("\nWrong answer! Try again!")
                else:
                    score += 1
                    print("\nCorrect!")
                    break
            except ValueError:
                print("Please key in a number(2 decimals)!")


def clock(countdown=30):
    global game_running
    while countdown > 0:
        time.sleep(1)
        countdown -= 1
        print("\rTime Left: " + str(countdown), end="")
    print("\nFinal score: " + str(score))
    game_running = False  # 设置标志位终止游戏线程


# 正确创建线程:target传函数,args传参数元组
clock_thread = threading.Thread(target=clock, args=(30,))
game_thread = threading.Thread(target=game)
clock_thread.start()
game_thread.start()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:00:16