You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pygame.time.set_timer()在类内使用失效每帧触发问题求解

问题根因
  • pygame.time.set_timer()的工作逻辑是每隔指定间隔往Pygame的事件队列中投放一个自定义类型事件,必须在遍历事件队列时逐个检查每个事件的类型才能正确捕获。
  • 你的错误代码将计时器事件的判断放在了for event in pygame.event.get()循环外部:遍历事件队列时只处理了退出事件,其余所有事件直接被丢弃;go()方法中使用的event是循环最后一次迭代的遗留值,当事件队列无新事件时该变量会保留上一次的计时器事件值,导致判断每帧都命中。
修复方案

将事件作为参数传入类的处理方法,并且在事件遍历循环内部调用该方法,逐个校验每个事件的类型:

import pygame
pygame.init()
screen = pygame.display.set_mode((100, 100))
FPS = 60
clock = pygame.time.Clock()

class Bird():
    def __init__(self):
        self.count = 1
        self.count_timer = pygame.USEREVENT + 1
        pygame.time.set_timer(self.count_timer, 1000)
    
    def handle_event(self, event):
        if event.type == self.count_timer:
            print(self.count)
            self.count += 1

b = Bird()
   
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # 每个事件都传入类的事件处理方法校验
        b.handle_event(event)

    pygame.display.update()
    clock.tick(FPS)

pygame.quit()

修改后运行即可实现1秒触发一次计时器的预期效果。

内容的提问来源于stack exchange,提问作者Ivan Yosifov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:12:04