首页 > 解决方案 > 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()

谁能解释需要做些什么才能使其在课堂上工作?谢谢

标签: pythonpygame

解决方案


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

推荐阅读