multithreading - Python Game Timer (Threads?) -
i designing game in python , know how make efficient timer can run along side game.
note: using pygame.
i have timer so:
import time seconds = 60 def start_timer(): global seconds while seconds > 0: print seconds seconds -= 1 time.sleep(1)
however, when run in main game function game hangs because of timer.sleep
.
def main(self): timer.start_timer()
i'm pretty sure issue has not using threading, although i'm not 100% sure. can explain me proper solution is?
if you're using pygame, has own time functionality should using.
if you're using event-loop or hybrid design, loop on pygame.event.get()
or similar , call "event handlers" different events mouse-click or key-down, can use set_timer
create event fires every second. example:
timer1_event = pygame.userevent + 1 def start_timer1(): global seconds seconds = 60 pygame.time.set_timer(timer1_event, 1000) def on_timer1(): global seconds print seconds seconds -= 1 if seconds < 0: pygame.time.set_timer(timer1_event, 0) # elsewhere, inside main event loop elif event.type == timer1_event: on_timer1()
there simple example programs linked in docs each function; if @ examples set_timer
you'll see how easy use.
if you're using pure frame loop instead, you're presumably calling clock.tick
or similar, , you're going have use return value count down milliseconds since last time , decide whether you've passed integral number of seconds , when you're passed 0.
Comments
Post a Comment