【问题标题】:Pygame Mouse Clicked Does Not UpdatePygame 鼠标点击不更新
【发布时间】:2018-07-30 01:12:38
【问题描述】:

函数 start_menu() 在按下按钮后会导致 run_instructions()。在 run_instructions() 中,一旦用户再次单击鼠标,它应该转到另一个函数,但是我认为前一个函数的单击会继续并自动触发 click[0] 到 = 1,尽管事实上没有人单击任何东西。

def run_instructions():
    clicked = False
    while clicked == False:
        click = pygame.mouse.get_pressed()
        board.blit(instructions,[0,0])
        pygame.display.update() 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        if click[0] == 1:
             create_environment()
             clicked = True

def start_menu():
    global menu
    while menu == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()
        if 125 + 172 > mouse[0] > 150 and 448 + 69 > mouse[1] > 448 and click[0] == 1:
            menu = False
            run_instructions()
            break

在进入run_instructions()时,是否有办法让click[0]更新或重置为0。我试过使用 pygame.MOUSEBUTTONDOWN 但它给出了同样的问题。

谢谢。

【问题讨论】:

    标签: python python-3.x pygame python-3.5


    【解决方案1】:

    在事件循环中检查pygame.MOUSEBUTTONDOWN 事件是正确的解决方案。 pygame.mouse.get_pressed 在这里有问题,因为它只告诉您当前是否按住鼠标按钮,而不告诉您是否单击了一次按钮。

    这是一个工作示例。我在第一个场景中使用pygame.Rect 作为一个非常简单的按钮,您必须单击它才能访问run_instructions 功能。在下一个场景中(使用不同的背景颜色)再次按下鼠标按钮,它将打印“create_environment”。

    import sys
    import pygame
    
    
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    BG_COLOR = pygame.Color('gray12')
    BG_COLOR2 = pygame.Color(50, 90, 120)
    
    
    def run_instructions():
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    print('create_environment')
    
            screen.fill(BG_COLOR2)
            pygame.display.flip()
            clock.tick(30)
    
    
    def start_menu():
        button_rect = pygame.Rect(40, 100, 80, 50)
    
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    # If the button collides with the mouse position.
                    if button_rect.collidepoint(event.pos):
                        run_instructions()
    
            screen.fill(BG_COLOR)
            pygame.draw.rect(screen, (90, 200, 50), button_rect)
            pygame.display.flip()
            clock.tick(30)
    
    start_menu()
    

    【讨论】:

    猜你喜欢
    • 2021-09-06
    相关资源
    最近更新 更多