Skip to main content
 首页 » 编程设计

python之我正在测试 threading.Time 在我制作的这个小游戏中,但它一直重叠

2024年09月07日46Leo_wl

import time 
from threading import Timer 
from random import randint 
print("Every wrong answer is a 3s delay; you have 30s") 
end = False 
def lose(): 
    print(end) 
    print("Time up!") 
    time.sleep(1) 
    print("Score is",pts,", with",wrong,"wrong answers.") 
    time.sleep(1) 
    input("enter to quit") 
    quit() 
timer = Timer(10,lose) 
timer.start() 
pts = 0 
wrong = 0 
while end == False: 
    a = randint(5,50) 
    b = randint(5,50) 
    print(a,"+",b) 
    ans = input() 
    if ans.isnumeric(): 
        ans = int(ans) 
    if ans == a+b: 
        print("correct") 
        pts = pts+1 
    else: 
        print("wrong,",a+b) 
        wrong = wrong+1 
        print("delay") 
        time.sleep(3) 
        print("delay end") 
    print("") 

当计时器结束时,循环与'lose'函数重叠,并且它像这样在行上搞砸了:

Time up! 
 
45 + 10 
55 
Score iscorrect  
3  
, with29  0+  wrong answers.37 
 
 
enter to quitwrong,p 
 66 
delay 

我该如何解决这个问题?
抱歉,如果这个问题已经得到回答,但我想知道。

请您参考如下方法:

理想情况下,您应该完全避免使用线程,如评论中所述。

但是,如果您要使用线程,请考虑使用 mutex以确保多个线程不会同时尝试写入标准输出。

例如:

# setup at the beginning: 
from threading import Thread, Lock 
mutex = Lock() 
 
# surrounding each print statement: 
mutex.acquire() 
try: 
    print('text') 
finally: 
    mutex.release()