键盘按下顺序完成后鼠标单击(pygame)

时间:2015-07-19 04:32:27

标签: python python-2.7 pygame

我希望与鼠标单击(pygame.MOUSEBUTTONUP)绑定的代码仅在与空格键按下的代码(pygame.KEYDOWNpygame.K_SPACE)完成后执行。之前的任何鼠标点击都应该被忽略。

我知道第二个if声明不会起作用,因为它与for event in pygame.event.get():的关系或缺乏关系。我只是不知道如何写得正确...

import pygame

screen = pygame.display.set_mode((600, 400))

def task():

taskExit = False

while not taskExit:

     for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                print "Drawing..."
                screen.fill(gray)  
                    #<<<code to create pretty pictures>>>

                if event.type == pygame.MOUSEBUTTONUP:
                    print "mouse at (%d, %d)" % event.pos  # where they clicked.
                        #<<<more code to interact with said pretty pictures>>>

task()
pygame.quit()
quit()

2 个答案:

答案 0 :(得分:2)

通过一点重新组织,这将按预期工作。将要在这些事件之后执行的代码导出为两个函数:

    def space_bar():
            print "Drawing..."
            screen.fill(gray)  
                #<<<code to create pretty pictures>>>

    def mouse_event():
            print "mouse at (%d, %d)" % event.pos  # where they clicked.
                #<<<more code to interact with said pretty pictures>>>

允许您在鼠标事件之后调用它们,并让您控制代码执行的顺序。

    elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        space_bar()

    elif event.type == pygame.MOUSEBUTTONUP:
        space_bar()
        mouse_event()

答案 1 :(得分:1)

所以,对于后代来说,在pygame中有一种非常简单的方法(哦,实际阅读文档的价值......)

即,使用pygame.event.set_blocked(pygame.MOUSEBUTTONUP)pygame.event.set_allowed(pygame.MOUSEBUTTONUP),只需阻止鼠标左键单击即可。非常便利。

例如,

import pygame

screen = pygame.display.set_mode((600, 400))

def task():

    space_bar_pressed = 0

    taskExit = False

    while not taskExit:

         for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

                elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    pygame.event.set_blocked(pygame.MOUSEBUTTONUP)  #blocking
                    print "Drawing..."
                    screen.fill(gray)
                    #<<<code to create pretty pictures>>>
                    pygame.display.update()
                    pygame.event.set_allowed(pygame.MOUSEBUTTONUP)  #allowing
                    space_bar_pressed = 1

                elif event.type == pygame.MOUSEBUTTONUP and space_bar_pressed == 1:
                    print "mouse at (%d, %d)" % event.pos  # where they clicked.
                    #<<<more code to interact with said pretty pictures>>>
                    pygame.display.update()

task()
pygame.quit()
quit()