Countdown timer in Pygame

后端 未结 7 1055
眼角桃花
眼角桃花 2020-11-22 03:31

I started using pygame and I want to do simple game. One of the elements which I need is countdown timer. How can I do the countdown time (eg 10 seconds) in PyGame?

7条回答
  •  遥遥无期
    2020-11-22 04:02

    In pygame exists a timer event. Use pygame.time.set_timer() to repeatedly create an USEREVENT. e.g.:

    timer_interval = 500 # 0.5 seconds
    timer_event = pygame.USEREVENT + 1
    pygame.time.set_timer(timer_event , timer_interval)
    

    Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.
    To disable the timer for an event, set the milliseconds argument to 0.

    Receive the event in the event loop:

    running = True
    while running:
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
             elif event.type == timer_event:
                 # [...]
    

    The timer event can be stopped by passing 0 to the time parameter.


    See the example:

    import pygame
    
    pygame.init()
    window = pygame.display.set_mode((200, 200))
    clock = pygame.time.Clock()
    font = pygame.font.SysFont(None, 100)
    counter = 10
    text = font.render(str(counter), True, (0, 128, 0))
    
    timer_event = pygame.USEREVENT+1
    pygame.time.set_timer(timer_event, 1000)
    
    run = True
    while run:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == timer_event:
                counter -= 1
                text = font.render(str(counter), True, (0, 128, 0))
                if counter == 0:
                    pygame.time.set_timer(timer_event, 0)                
    
        window.fill((255, 255, 255))
        text_rect = text.get_rect(center = window.get_rect().center)
        window.blit(text, text_rect)
        pygame.display.flip()
    

提交回复
热议问题