如何使“pygame.event.get()”在 pygame 中的所有模块中可用

问题描述 投票:0回答:3

所以我正在制作一个

pygame
程序,为此我编写了一个
GUI.py
模块。其中一个类是 Button,单击该按钮的方法之一,它基本上检查按钮是否被按下。最初我使用
pygame.mouse.get_pressed()
来检查鼠标按下情况,但我遇到的问题是它在一个帧内注册了多次按下,这不是我想要的。

def clicked(self):
        mouse_pos = pygame.mouse.get_pos()# Gets the position of the mouse 
        mouse_pressed = pygame.mouse.get_pressed()# Checks if the mouse is being pressed
        # checking if the mouse is already inside the button
        if self.mouseover():
            # mouse_pressed[0] returns true if the left mouse button is being pressed
            if mouse_pressed[0]:
                return True
        return False

所以我需要使用事件来检查鼠标按下。但是,我将

GUI.py
导入到其他模块,然后将其导入到
main.py
。因此,我无法将
main.py
导入到
GUI.py
。但是
main.py
是在主循环中调用
pygame.event.get()
的地方。我可以在其他模块中调用该方法并将事件作为参数传递,但我想每次创建按钮时都这样做。 抱歉,如果我试图解释的内容不清楚,但这就是问题的根源。有没有办法让
pygame.event.get()
可供我的程序中的所有模块独立使用?

python events module pygame
3个回答
0
投票

我在我的pygame UI模块中解决这个问题的方法是存储前一帧的单击状态,因此如果鼠标单击了这一帧而不是最后一帧,则它是一个单击,否则它会被按住并且什么也不会发生。 (我的模块有点复杂,因为它确保您点击它,然后放开它算作一次点击)

if click and not previous_frame_click:
    #clicked

如果您只是使用函数而不是类来执行此操作,那么也许创建一个全局变量

last_frame_click = False

def clicked(self):
    global last_frame_click

    mouse_pos = pygame.mouse.get_pos()# Gets the position of the mouse 
    mouse_pressed = pygame.mouse.get_pressed()# Checks if the mouse is being pressed
    # checking if the mouse is already inside the button
    if self.mouseover():
        # mouse_pressed[0] returns true if the left mouse button is being pressed
        if mouse_pressed[0] and not last_frame_click[0]:
            last_frame_click = mouse_pressed
            return True
    last_frame_click = mouse_pressed
    return False

编辑:刚刚注意到你说的是其中一个类,不用担心上面的代码,只需使用

self.last_frame_click


0
投票

当我遇到类似的问题时,我为其创建了一个事件管理器模块。任何想要收到事件通知的东西都会向事件管理器注册一个事件处理程序,提供处理程序感兴趣的事件和事件处理程序回调。

事件管理器从事件循环中获取事件,它将根据注册的事件检查事件。如果存在匹配,则事件管理器将调用关联的事件处理程序回调,并将事件作为参数传递给回调。

听起来比实际情况更复杂。


0
投票

迟到总比不到好?我也遇到了同样的问题,对我有用的方法非常简单。创建一个新模块并将此代码放入其中:

import pygame

pygame.init()

def event_handler():
    events = []
    for event in pygame.event.get():
        events.append(event)

    return events

然后你的主游戏循环可能看起来像这样:

import pygame
from sys import exit
from Code.globals import screen
from Code.Level import Level
from Code.EventHandler import event_handler



pygame.init()


Level = Level()
clock = pygame.time.Clock()
Level.startup()


running = True
while running:
    for event in event_handler():
        if event.type == pygame.QUIT:
            running = False
            exit()
            pygame.quit()
        else:
            pass

    screen.fill((30, 30, 30))
    Level.update()

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

一切对我来说都很好,尽管就这条线索而言我来自未来。

© www.soinside.com 2019 - 2024. All rights reserved.