Python:控制一个"for loop"的执行速度

Python: Controlling a "for loop" speed of execution

由于我对编程还是个新手,我正在尝试编写一些基本程序来帮助我理解编码和学习。

我正在尝试创建一个使用 pygame 向上发射小颗粒的对象。一切正常,但我找不到控制对象创建这些粒子的速率的方法。我有一个发射器和粒子 class,以及一个发射器和粒子列表。您需要程序的所有行吗?这是基本设置:

particles = []
launchers = []

class Particle:

    def __init__(self, x, y):

        self.pos = np.array([x, y])
        self.vel = np.array([0.0, -15])
        self.acc = np.array([0.0, -0.5])
        self.colors = white
        self.size = 1

    def renderParticle(self):

        self.pos += self.vel
        self.vel += self.acc
        pygame.draw.circle(mainscreen, self.colors, [int(particles[i].pos[0]), int(particles[i].pos[1])], self.size, 0)

class Launcher:

    def __init__(self, x):
        self.width = 10
        self.height = 23
        self.ypos = winHeight - self.height
        self.xpos = x

    def drawLauncher(self):
        pygame.draw.rect(mainscreen, white, (self.xpos, self.ypos, self.width, self.height))

    def addParticle(self):
        particles.append(Particle(self.xpos + self.width/2, self.ypos))

while True :
    for i in range(0, len(launchers)):
       launchers[i].drawLauncher()
       launchers[i].addParticle()
         # threading.Timer(1, launchers[i].addparticle()).start()
         # I tried that thinking it could work to at least slow down the rate of fire, it didn't

    for i in range(0, len(particles)):
        particles[i].renderParticle()

我使用鼠标将新的启动器添加到数组中,然后使用 while 循环渲染所有内容。就像我说的,我想找到一种方法来控制我的启动器吐出那些粒子的速率,而程序仍然是 运行(所以 sleep() 无法工作)

PyGame time module contains what you'll need. get_ticks() 会告诉你你的代码有多少毫秒。通过跟踪上次生成粒子时的值,您可以控制释放频率。类似于:

particle_release_milliseconds = 20 #50 times a second
last_release_time = pygame.time.get_ticks()
...
current_time = pygame.time.get_ticks()
if current_time - last_release_time > particle_release_milliseconds:
    release_particles()
    last_release_time = current_time