线程计时器未按预期更改

时间:2019-01-28 19:49:01

标签: python multithreading

我试图编写一个程序/游戏,在其中您必须化解炸弹。它有一个计时器,它同时检查您是否切断了正确的电线以使其解散。但是,当我运行它时,它在输入的同一行上打印两次时间,如下所示:

enter image description here

仅第一个计时器更改。然后,光标跳至新行,如果我键入内容,则该行将出现在该行中(我希望它位于同一行)。计时器结束后,代码也不会exit

如何解决此问题,使计时器仅在第一行,第二行要求输入,并且在计时器结束时应显示“炸弹已熄灭”?

#import time library for the timer
import time
#import thread library to run timer and wire function at the same time
from threading import Thread

def splitTime(sec):
    #splits seconds in minutes and seconds
    seconds = sec % 60 
    minutes = int((sec - seconds) / 60)
    if minutes == 0 and seconds == 0:
        print("00:00")
    else:
        if minutes < 10 and seconds < 10:
            print("0" + str(minutes) + ":" + "0" + str(seconds), end="\r")
        elif minutes < 10:
            print("0" + str(minutes) + ":" + str(seconds), end="\r")
        elif seconds < 10:
            print(str(minutes) + ":" + "0" + str(seconds), end="\r")
        else:
            print(str(minutes) + ":" + str(seconds), end="\r")

def timer():
    #the timer
    timeToSet = 10 
    while timeToSet >= 0:
        splitTime(timeToSet)
        time.sleep(1)
        timeToSet -= 1
    if timeToSet == 0:
        print("The bomb went off!")
        exit()

def wireFunction():
    color = input("which wire to cut?: ")
    if color == "red":
        print("The bomb has been defused!")
        exit()
    else: 
        print("The bomb went off!")
        exit()

wire = "red"
print("There are these wires: blue, red, green, black")

if __name__ == "__main__":
    Thread(target = wireFunction).start()
    Thread(target = timer).start()

1 个答案:

答案 0 :(得分:0)

关于计时器未在0结束的问题的第二部分是因为您说while timeToSet >= 0:反对while timeToSet > 0:。当前,当它达到零时,它不会退出while循环。