简体   繁体   English

Python:睡眠方法

[英]Python: Sleep methods

I know this is already technically "asked" on this forums but this question is based around a different concept that I couldn't find. 我知道这个论坛在技术上已经“提出了”,但是这个问题是基于一个我找不到的不同概念。

While using time.sleep(whatever) it obviously sleeps, I get that but while using Pygame it will lock up the program. 在使用time.sleep(无论如何)时,它显然会休眠,我明白了,但是在使用Pygame时,它将锁定程序。 Is there any real method of using a sleep or a pause in the code other than an input that doesn't lock up pygame? 除了不锁定pygame的输入外,是否有任何真正的方法在代码中使用睡眠或暂停? I've tried; 我试过了;

time.sleep
pygame.wait and
pygame.delay

these all do the exact same thing. 这些都做完全相同的事情。 I'm working on a game for a Computer Science class that involves a small animation of 13 photos I have that are slightly different, but when played 0.12seconds apart, it makes it look good, sadly the whole freezing up of the window from wait statements makes it skip and look very bad. 我正在为计算机科学课开发一款游戏,该游戏涉及一张由我拥有的13张照片组成的小动画,但是略有不同,但是当间隔播放0.12秒时,它看起来就不错了,可惜整个窗口被冻结了语句使它跳过并看起来非常糟糕。

Thanks to whoever can figure out this mystery. 多亏有谁能弄清楚这个谜。

I think you may want to try using the method that is shown here . 我认为您可能想尝试使用此处显示的方法。

an example of what I mean is this: 我的意思是一个例子:

class Unit():
    def __init__(self):
        self.last = pygame.time.get_ticks()
        self.cooldown = 300    

    def fire(self):
        # fire gun, only if cooldown has been 0.3 seconds since last
        now = pygame.time.get_ticks()
        if now - self.last >= self.cooldown:
            self.last = now
            spawn_bullet()

notice he uses pygame.time.get_ticks() to check if a variable is less than that and if it is, he passes in the if statement and spawns the bullet. 注意,他使用pygame.time.get_ticks()检查变量是否小于该变量,如果小于,则传递if语句并生成项目符号。

a simpler way to view this concept is the following 下面是查看此概念的一种更简单的方法

curtime = pygame.time.get_ticks() + 10  # the 10 is what we add to make it sleep

while True:  # Create a loop that checks its value each step
    if curtime < pygame.time.get_ticks():  # check if curtime is less than get_ticks()
        print("Sleep is over now!")
        break  # exit the loop

I hope that helps you in any way, it seems like it might be a viable option since it keeps freezing when you use normal functions. 我希望它能以任何方式对您有所帮助,这似乎是一个可行的选择,因为当您使用常规功能时,它会一直冻结。

ONE MORE THING 还有一件事

do note that pygame.time.get_ticks() will give you the current time in milliseconds, for full documentation on this go here . 请注意pygame.time.get_ticks()会以毫秒为单位提供当前时间,有关完整文档,请访问此处

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

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