How do I use a PyGame timer event? How to add a clock to a pygame screen using a timer?
我是python的新手,因此决定尝试在
但是,我进行了搜索并得到了
有没有简单的方法可以向游戏屏幕添加时钟?
此外,在pygame中还存在一个计时器事件。使用
1 2 3 | time_delay = 500 # 0.5 seconds timer_event = pygame.USEREVENT + 1 pygame.time.set_timer(timer_event , time_delay ) |
注意,在pygame中可以定义客户事件。每个事件都需要一个唯一的ID。用户事件的ID必须以
在事件循环中接收事件:
1 2 3 4 5 6 7 8 9 | running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == timer_event: # [...] |
可以通过将0传递给time参数来停止计时器事件。
请参见示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import pygame pygame.init() window = pygame.display.set_mode((200, 200)) clock = pygame.time.Clock() font = pygame.font.SysFont(None, 100) counter = 0 text = font.render(str(counter), True, (0, 128, 0)) time_delay = 1000 timer_event = pygame.USEREVENT+1 pygame.time.set_timer(timer_event, time_delay) # main application loop run = True while run: clock.tick(60) # event loop for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == timer_event: # recreate text counter += 1 text = font.render(str(counter), True, (0, 128, 0)) # clear the display window.fill((255, 255, 255)) # draw the scene text_rect = text.get_rect(center = window.get_rect().center) window.blit(text, text_rect) # update the display pygame.display.flip() |