How do you delay specific events in a while loop?

前端 未结 3 1189
一个人的身影
一个人的身影 2020-12-22 09:41

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

相关标签:
3条回答
  • 2020-12-22 10:28

    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.

    0 讨论(0)
  • 2020-12-22 10:30

    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

    0 讨论(0)
  • 2020-12-22 10:32

    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 + 1
    STAR_ANIMATION_START = pygame.USEREVENT + 2
    
    # ... Your code ...
    
    for event in pygame.event.get():
    
        if event.key == pygame.K_SPACE and buttonHighlight == 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.
    
        elif event.code == FIRE_ANIMATION_START:
            pygame.time.set_timer(FIRE_ANIMATION_START, 0)     # Don't post the event anymore.
            FireAnimation() #displays a fire image
            if player[6] == 'Magic': #you deal damage to the enemy
                enemy[0] = enemy[0]-(((player[1])+((player[1])*1)-enemy[4]))
            else:
                enemy[0] = enemy[0]-(((player[1])+((player[1])*1)-enemy[3]))
    
        elif event.code == STAR_ANIMATION_START:
            pygame.time.set_timer(STAR_ANIMATION_START, 0)     # Don't post the event anymore.
            StarAnimation() #displays a star image
            if enemy[6] == 'Magic': #enemy deals damage to you
                 player[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.

    0 讨论(0)
提交回复
热议问题