关于python:如何使用PyGame计时器事件?如何使用计时器将时钟添加到pygame屏幕?

How do I use a PyGame timer event? How to add a clock to a pygame screen using a timer?

我是python的新手,因此决定尝试在pygame中制作一个简单的游戏。我想添加一个计时器/时钟,以显示"您玩过/还活着"多长时间,因此基本上可以创建一个时钟。

但是,我进行了搜索并得到了time.sleep(1)函数,它确实可以像时钟一样工作,但是它会将游戏的其他所有内容减慢到几乎无法移动的地步。

有没有简单的方法可以向游戏屏幕添加时钟?


pygame.time.get_ticks()可以检索自pygame.init()以来的毫秒数。请参见pygame.time模块。

此外,在pygame中还存在一个计时器事件。使用pygame.time.set_timer()重复创建USEREVENT。例如:

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必须以pygame.USEREVENT开头。在这种情况下,pygame.USEREVENT+1是计时器事件的事件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参数来停止计时器事件。

请参见示例:

> </p>
<div class=

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()