首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用PyGame计时器事件?如何使用计时器将时钟添加到游戏屏幕?

如何使用PyGame计时器事件?如何使用计时器将时钟添加到游戏屏幕?
EN

Stack Overflow用户
提问于 2020-01-28 08:34:14
回答 1查看 2.1K关注 0票数 4

我对python很陌生,因此决定尝试在pygame中做一个简单的游戏。我想添加一个计时器/时钟来显示“你玩了/活了多久”,这样基本上就可以创建一个时钟了。

然而,我已经搜索并获得了time.sleep(1)函数,它确实可以作为一个时钟工作,但它减缓了游戏的其他一切,以至于它几乎没有移动。

有没有一种简单的方法可以在游戏屏幕上添加一个时钟?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-28 08:39:10

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

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

代码语言:javascript
复制
time_delay = 500 # 0.5 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event , time_delay )

注意,在游戏中可以定义客户事件。每个事件都需要一个唯一的id。用户事件的ids必须从pygame.USEREVENT开始。在本例中,pygame.USEREVENT+1是计时器事件的事件id。

在事件循环中接收事件:

代码语言:javascript
复制
running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

         elif event.type == timer_event:
             # [...]

可以通过将0传递给time参数来停止计时器事件。

参见示例:

代码语言:javascript
复制
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()
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59944795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档