课堂内的Pygame事件无法识别

约旦

我已经使用pygame完成了游戏,没有任何问题。现在,我正在尝试组织代码并添加类。但是,我在使用事件命令时遇到了问题。

我尝试使用pygame.event.poll()pygame.event.get(),但均无济于事。

class MainRun():
    run = True
    def Main(self):
        #some code
        while MainRun.run:
            pygame.time.delay(35)
             for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    MainRun.run = False
            a.activate_skills()

class Player():
     #code
     def activate_skills(self):
        if event.type == pygame.MOUSEBUTTONDOWN:
            #some code

a = Player
main = MainRun().Main()

如果event.type == pygame.MOUSEBUTTONDOWN:NameError:名称'event'未定义

那么如何定义事件?请查看我已经尝试过的内容。

泰德·克莱恩·伯格曼

您仅应调用pygame.event.get()一次,因为它将获取所有发生的事件。例如:

a = pygame.event.get()  # Contains the events that has happen.
for event in a:
    if event.type == pygame.QUIT:
        quit()

b = pygame.event.get()  # Will probably contain nothing, as the code above took the events from the event queue. 
for event in b:
    if event.type == pygame.MOUSEBUTTONDOWN:
        do_something()

do_some_calculation()
c = pygame.event.get()  # Might contain something, if the user did something during the time it took to do the calculation.
for event in c:
    if event.type == pygame.MOUSEBUTTONDOWN:
        do_other_thing()

在上面的示例中,do_something()由于事件队列刚刚被清除,因此很可能永远不会调用do_other_thing()可能会被调用,但这在用户在执行过程中按下按钮时才发生do_some_calculations()如果用户在此之前或之后按下,则单击事件将被清除并丢失。

因此,根据您的情况,您可以执行以下操作:

class MainRun():
    run = True
    def Main(self):
        #some code
        while MainRun.run:
            pygame.time.delay(35)
             for event in pygame.event.get():  # ONLY CALLED HERE IN THE ENTIRE PROGRAM.
                if event.type == pygame.QUIT:
                    MainRun.run = False
                a.activate_skills(event)  # MOVED THIS INTO THE FOR LOOP!

class Player():
     #code
     def activate_skills(self, event):  # TAKING THE EVENT AS PARAMETER.
        if event.type == pygame.MOUSEBUTTONDOWN:
            #some code

a = Player
main = MainRun().Main()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章