我如何添加一个倒计时的计时器,当它用完时重新启动我的程序

2024-09-27 00:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个非常新的初学者编码,我不知道很多。我正在尝试创建一个猜谜游戏,我想在程序中添加一个计时器。 计时器的工作方式是,我设置一个设定的时间量,即60秒,一旦时间用完,程序就会停止,基本上就像“对不起,时间用完了。你想再试一次吗?”

我已经在YouTube和Stackoverflow上搜索了一些视频,但我要么不懂,要么就是做不到

https://www.youtube.com/watch?v=Mp6YMt8MSAU

这段视频我已经看了4遍了,但仍然不知道该怎么做。因此,如果有人愿意向我解释/告诉我如何增加时间,我将不胜感激

def main():
    import random
    n = random.randint(1, 99)
    chances = 5
    guess = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: " ))
    while n != "guess":
        chances -=1
        if chances ==0:
            print("out of chances, it is now player 2's turn to play. The number was", n)
            break
        if guess < n:
            print("guess is low you have",chances,"chances left")
            guess = int(input("Enter an integer from 1 to 99: "))
        elif guess > n:
            print ("guess is high you have",chances, "chances left")
            guess = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it and have", chances, "chances left")
            break
            
        import random
    n1 = random.randint(1, 99)
    chances1 = 0
    guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
    while n1 != "guess":
        chances1 +=1
        if chances1 ==5:
            print("out of chances, the number was", n1)
            break
        if guess1 < n1:
            print("guess is low you have",chances1,"chances left")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        elif guess > n1:
            print ("guess is high you have",chances1, "chances left")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it and have", chances1, "chances left")
            break
    retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
    if retry == "yes":
        main()
    elif retry == "no":
        print("Okay. have a nice day! :D ")
    else:
        print("Invalid input")
main()

这是我的密码。如有任何反馈,将不胜感激


Tags: tofromyouaninputifishave
2条回答

(我不知道您对python和编程了解多少,所以我将使用一种非常简单的语言)

好吧,如果你的游戏不需要在计时器处于活动状态时运行,你可以使用时间库的睡眠功能,并写下如下内容:

import time

time.sleep("time amount")
print("I'me sorry but you run out of time!")
print("Do you wanna retry ?")

使用“command”time.sleep,python将在您选择的时间内停止整个程序

(因此,如果必须在计时器运行时玩游戏,请不要使用time.sleep方法)

相反,如果在玩游戏时计时器必须处于活动状态,则应使用“线程”。 线程是一个库,它允许您执行非常简单的计时器,但不仅仅是。 用线程制作计时器对你来说可能更复杂,但不是真的

您必须编写一个函数,以便在计时器结束时调用,如下所示:

def time_over():
    print("I'm sorry but the time is over !")
    print("Do you want to play again ? ")

之后,您必须创建计时器:

timer_name = threading.timer("time amount", function) 

最后,您必须开始计时器写入:

timer_name.start()

这样,python将: 1-导入线程库 2-创建您想要的时间量的计时器 3-启动计时器 4-在时间用完时激活您编写的功能

如果你需要关于其中一种方法的更多信息,请写一条评论,我会尽快回答你的问题

祝您愉快:)

要解决您的问题,您必须使用Thread。我拿了你的代码,我在开头添加了线程,试着看一看

线程是可以在主程序旁边执行函数(其run函数)的对象。这就是所谓的并行编程
这里您需要它,因为您想要:

  1. 检查播放器的输入
  2. 倒计时

我没有修改你的代码或重写它,我只是添加了线程并使其工作。这很简单:

  1. 我在给定的时间内调用sleep_TIME_LIMIT]
  2. 计时器结束时发出一点声音
  3. 我将一个变量设置为True,这意味着计时器结束

只要稍加重写,当线程更改变量时,您就可以中断主循环。但这超出了最初问题的范围,请随意改进您的游戏。
目前,您需要输入一个数字来知道时间是否结束。这就是为什么我添加了小噪音(如果没有,您将没有提示)

请随时提问。
希望这对你有帮助


from threading import Thread
from time import sleep

import random


_TIME_OUT = [False, False]

_TIME_LIMIT = 1

class MyThread(Thread):
    def __init__(self, time_out, player):
        Thread.__init__(self)
        self.time_out = time_out
        self.player = player

    def run(self):
        sleep(self.time_out)
        _TIME_OUT[self.player - 1] = True
        print('\a', end="") # Make a noise

def main():
    _TIME_OUT[0] = False
    _TIME_OUT[1] = False

    tread_1 = MyThread(_TIME_LIMIT, 1)

    n = random.randint(1, 99)
    chances = 5

    
    tread_1.start()
    print(f"You have {_TIME_LIMIT} sec")

    guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: " ))
    while n != "guess" and not _TIME_OUT[0]:
        print(not _TIME_OUT, _TIME_OUT)
        chances -=1
        if chances == 0:
            print("out of chances, it is now player 2's turn to play. The number was", n)
            break
        if guess < n:
            print("guess is low you have",chances,"chances left")
            guess = int(input("Enter an integer from 1 to 99: "))
        elif guess > n:
            print ("guess is high you have",chances, "chances left")
            guess = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it and have", chances, "chances left")
            break
            
    if _TIME_OUT[0]:
        print("Sorry, out of time!")

    tread_2 = MyThread(_TIME_LIMIT, 2)

    n1 = random.randint(1, 99)
    chances1 = 0

    tread_2.start()
    print(f"You have {_TIME_LIMIT} sec")

    guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
    while n1 != "guess" and not _TIME_OUT[1]:
        chances1 +=1
        if chances1 ==5:
            print("out of chances, the number was", n1)
            break
        if guess1 < n1:
            print("guess is low you have",chances1,"chances left")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        elif guess > n1:
            print ("guess is high you have",chances1, "chances left")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it and have", chances1, "chances left")
            break

    if _TIME_OUT[1]:
        print("Sorry, out of time!")

    retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
    if retry == "yes":
        main()
    elif retry == "no":
        print("Okay. have a nice day! :D ")
    else:
        print("Invalid input")


if __name__ == "__main__":
    main()

相关问题 更多 >

    热门问题