python - 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()
推荐阅读
- mysql - 每个用户的 AWS RDS 数据库连接数
- python - 如何使用 python 替换丢失的布尔值?
- asp.net-mvc - 如何将模型绑定到 dxList 并允许多选?ASP.NET MVC
- google-apps-script - 我的自我调用解决方法有效还是巧合?
- c++ - pointer_traits typedefs 可以未定义吗?
- c++ - unique_ptr 作为通用处置对象
- aggregate - 拆分不连贯的聚集体
- php - 是否可以使用 php 从 parseplaform 从 GeoPoint 获取纬度和经度
- php - 将网站页面从域重定向到子域
- c++ - GNU MPFR 在精度高于 64 时给我完全相同的结果