Skip to content Skip to sidebar Skip to footer

How Do You Delay Specific Events In A While Loop?

Recently I've been working with a simple and straightforward RPG in python with pygame, but I'm having some problems delaying specific events. Running the code below, everything ha

Solution 1:

You can create two new events (FIRE_ANIMATION_START, STAR_ANIMATION_START) which you post to the event queue with a delay (with pygame.time.set_timer(eventid, milliseconds)). Then in your event loop you just check for it.

FIRE_ANIMATION_START=pygame.USEREVENT+1STAR_ANIMATION_START=pygame.USEREVENT+2# ... Your code ...foreventinpygame.event.get():ifevent.key==pygame.K_SPACEandbuttonHighlight==0:pygame.time.set_timer(FIRE_ANIMATION_START,10)# Post the event every 10 ms.pygame.time.set_timer(STAR_ANIMATION_START,1000)# Post the event every 1000 ms.elifevent.code==FIRE_ANIMATION_START:pygame.time.set_timer(FIRE_ANIMATION_START,0)# Don't post the event anymore.FireAnimation()#displays a fire imageifplayer[6]=='Magic':#you deal damage to the enemyenemy[0]=enemy[0]-(((player[1])+((player[1])*1)-enemy[4]))else:enemy[0]=enemy[0]-(((player[1])+((player[1])*1)-enemy[3]))elifevent.code==STAR_ANIMATION_START:pygame.time.set_timer(STAR_ANIMATION_START,0)# Don't post the event anymore.StarAnimation()#displays a star imageifenemy[6]=='Magic':#enemy deals damage to youplayer[0]=player[0]-(((enemy[1])+((enemy[1])*1)-player[4]))else:player[0]=player[0]-(((enemy[1])+((enemy[1])*1)-player[3]))

Documentation for pygame.time.set_timer(eventid, milliseconds). Also, as the code is right now it has bugs in it. The attributes for the events differs between different event types, so always make sure to check whether an event is KEYDOWN or USEREVENT before accessing the attributes event.key or event.code. The different types and attributes can be found here.

Solution 2:

If you know how much time you need, you can simply add:

from time import sleep
...
sleep(0.1)

This will add a 100 milliseconds delay

Solution 3:

You can use

pygame.time.delay(n)

or

pygame.time.wait(n)

to pause the program for n milliseconds. delay is a little more accurate but wait frees the processor for other programs to use while pygame is waiting. More details in pygame docs.

Post a Comment for "How Do You Delay Specific Events In A While Loop?"