pygame set_timer() 在类中不起作用



显然pygame.time.set_timer()在类中使用时不工作,我只能使它表现为计时器。在类内部,它将在每一帧

中被调用
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()

如果定时器类以外的工作原理,将调用一次每秒

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

谁能解释一下需要做什么才能使它在类中工作?谢谢你

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

最新更新