gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:34:51 27 4
gpt4 key购买 nike

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()

关于python - 我正在测试 threading.Time 在我制作的这个小游戏中,但它一直重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48176160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com