pygame set_timer() 在 class 中不起作用

pygame set_timer() doesn't work inside a class

所以显然 pygame.time.set_timer() 在 class 中使用时不起作用,我只能让它充当计时器。在 class 中它会在每一帧被调用

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 go(self):
        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.go()

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

pygame.quit()

如果计时器在 class 之外,它将按预期工作,每秒调用一次

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

count = 1
count_timer = pygame.USEREVENT + 1
pygame.time.set_timer(count_timer, 1000)
   
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
        if event.type == count_timer:
            print(count)
            count += 1

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

pygame.quit()

任何人都可以解释需要做些什么才能让它在 class 中工作吗?谢谢

这与set_timer无关。但是,您必须在事件循环中为每个事件调用 go 方法:

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        b.go()               # <--- INSTERT

    # b.go()                   <--- DELETE

我建议将 event 对象作为参数传递给方法:

class Bird():
    # [...]
    
    def go(self, e):
        if e.type == self.count_timer:
            print(self.count)
            self.count += 1
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        b.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 go(self, event_list):
        if self.count_timer in [e.type for e in event_list]:
            print(self.count)
            self.count += 1

b = Bird()
   
running = True
while running:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            running = False#
        
    b.go(event_list)

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

pygame.quit()