2017-02-21 100 views
0

由於我還是新手,我試圖想出一些基本的程序,只是爲了幫助我理解編碼和學習。Python:控制一個「for循環」的執行速度

我想創建一個對象,使用pygame向上拍攝小顆粒。它一切正常,但我找不到控制對象創建這些粒子的速度的方法。我有一個Launcher和Particle類,以及一個發射器和粒子列表。你需要程序的所有行嗎?這裏是基本設置:

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循環來呈現一切。就像我說的,我想找到一種方法來控制我的啓動程序吐出這些粒子的速度,而程序仍在運行(所以睡眠()不能工作)

回答

1

PyGame time模塊包含什麼你需要。 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 
+0

一些進一步的閱讀,如果你有興趣在實現你的遊戲循環的更復雜的方式:www.koonsolo.com/news/dewitters-gameloop/ – Matt

+0

奇妙的作品!每個粒子都可以擁有自己的「last_released_time」,非常感謝,非常完美! –