简体   繁体   English

如何在不导入时间的情况下在 Python 中制作倒数计时器?

[英]How do I make a countdown timer in Python without importing time?

I'm creating a countdown timer for a game in Python.我正在为 Python 中的游戏创建倒数计时器。 My problem is I could only find code that uses time.sleep() , which pauses the entire code.我的问题是我只能找到使用time.sleep()的代码,这会暂停整个代码。 Is there a way to make a countdown timer, for example, from 60 seconds.有没有办法让倒数计时器,例如,从 60 秒。 Is it possible to use millis()?是否可以使用millis()?

time.sleep() makes your program wait some time and not do anything. time.sleep()让你的程序等待一段时间而不做任何事情。 The way it's usually done is to use something like time.time() to get the current time and as your title says: 'count down' from there using your loop and getting the difference between the start value and the current value of time.time() .通常的做法是使用time.time()类的东西来获取当前时间,正如您的标题所说:使用循环从那里“倒计时”并获取时间的起始值和当前值之间的差异time.time() If it's greater than your desired value, then just simply break out of the loop.如果它大于您想要的值,那么只需跳出循环即可。

Assuming you have a game loop that runs every tick of your program, you could have a Countdown class whose countdownElapsed function gets called every tick of your game loop and that checks when your countdown is at zero假设您有一个运行程序的每个滴答声的游戏循环,您可以拥有一个 Countdown 类,它的countdownElapsed函数在游戏循环的每个滴答声中都会被调用,并检查您的倒计时何时为零

// Pseudo-code
func countdownElapsed(countdown):
    return (countdown.lastTime - time.currentTime()) < 0

You could also create a Scheduler class that stores a bunch of function pointers, their arguments and the time you want to call said function pointers inside a vector of some sort and does the check above for every function inside the vector every tick.您还可以创建一个 Scheduler 类,该类存储一堆函数指针、它们的参数以及您想在某种向量中调用所述函数指针的时间,并在每个滴答声中对向量中的每个函数进行上述检查。

Finally, you can also just have a separate thread where you sleep and time-sensitive tasks.最后,您还可以拥有一个单独的线程,用于睡眠和时间敏感的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM