Python 如何在pygame中等待一段时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18839039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:01:54  来源:igfitidea点击:

How to wait some time in pygame?

pythontimepygamewait

提问by bzzr

While I've been using time.waitin my code since I began learning Python and Pygame, I've been wondering if there are any other ways to do it and what are the advantages and disadvantages of each approach. For example, Pygame also has a pygame.time.wait. What's the difference between python's wait and pygame's wait functions? Which one is better? And are there other ways to wait some time besides using these two functions?

自从我开始学习 Python 和 Pygame 以来,我一直在我的代码中使用time.wait,我一直想知道是否还有其他方法可以做到这一点,以及每种方法的优缺点是什么。例如,Pygame 还有一个pygame.time.wait。python的wait和pygame的wait函数有什么区别?哪一个更好?除了使用这两个功能之外,还有其他方法可以等待一段时间吗?

采纳答案by ninMonkey

For animation / cooldowns, etc: If you want to 'wait', but still have code running you use: pygame.time.get_ticks

对于动画/冷却等:如果您想“等待”,但仍有代码在运行,请使用:pygame.time.get_ticks

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

回答by ljs.dev

For Python in general, you will want to look at the sleeplibrary.

一般来说,对于 Python,您需要查看sleep库。

For Pygame, however, using pygame.time.delay()will pause for a given number of milliseconds based on the CPU clock for more accuracy (as opposed to pygame.time.wait).

然而,对于 Pygame,使用pygame.time.delay()将根据 CPU 时钟暂停给定的毫秒数以获得更高的准确性(与 pygame.time.wait 相反)。