单击Pygame鼠标不会更新

时间:2018-02-19 18:39:18

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

按下按钮后,函数start_menu()会导致run_instructions()。在run_instructions()中,一旦用户再次单击鼠标,它应该转到另一个函数但是我认为来自前一个函数的点击继续并自动触发click [0] to = 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()时,单击[0]更新或将其重置为0。我已经尝试过使用pygame.MOUSEBUTTONDOWN但它也会出现同样的问题。

感谢。

1 个答案:

答案 0 :(得分:0)

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

这是一个有效的例子。我在第一个场景中使用pygame.Rect作为一个非常简单的按钮,您必须单击该按钮才能转到run_instructions函数。在下一个场景中(使用不同的背景颜色)再次按下鼠标按钮,它将打印'创建环境'。

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()
相关问题