Pygame.mouse.get_pressed () не обнаружит большинство моих кликов - PullRequest
2 голосов
/ 13 февраля 2020

Так вот мой код:

import pygame
import pygame as pg

pygame.init()

displayWidth = 800
displayHeight = 600

### colour codes ###
bgColour = (245, 230, 255)
grey = (150, 150, 150)
darkGrey = (100, 100, 100)
darkBlack = (0,0,0)

clock = pygame.time.Clock()

mouse_clicked = False

display = pygame.display.set_mode((displayWidth, displayHeight))#sets height and width of screen
pygame.display.set_caption('Fashion!')

def screenDisplay():                                                #subroutine to display screens
    display = pygame.display.set_mode((displayWidth, displayHeight))#sets height and width of screen
    pygame.display.set_caption('Fashion!')                          #sets screen title
    display.fill(bgColour)

def text_objects(text, font):                       #font colour
    textSurface = font.render(text, True, darkBlack)
    return textSurface, textSurface.get_rect()

def textDisplay(s,t,x,y):                           #subroutine for displaying text on screen
    smallText = pygame.font.SysFont("",s)           #creates front and font size
    textSurf, textRect = text_objects(t, smallText) #inputs text
    textRect.center = (x,y)                         #centres text
    display.blit(textSurf, textRect)                #displays test


def button(msg,s,x,y,w,h,ic,ac,action=None):    #format for button
    mouse = pygame.mouse.get_pos()                  #gets mouse position (tracks cursor)
    click = pygame.mouse.get_pressed()              #gets status of mouse (tracks click)
    print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:   #draws rectangle for button
        pygame.draw.rect(display, ac,(x,y,w,h))     #draws rectangle after colour if mouse is on area

        if click[0] == 1 and action != None:        #performs function on click
            action()      
    else:
        pygame.draw.rect(display,ic,(x,y,w,h))      #draws rectangle initial colour if mouse isnt on area

    smallText = pygame.font.SysFont("",s)           #adds text to button
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    display.blit(textSurf, textRect)


    smallText = pygame.font.SysFont("",s)           #adds text to button
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    display.blit(textSurf, textRect)

def menuDisplay():
    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        screenDisplay()

        button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
        button("OUTFIT",  60,200,250,400,100,grey,darkGrey,page)
        button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
        button("QUIT",    40,300,530,200,50,grey,darkGrey,page) 

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

def page():
        intro = True

        while intro:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
            screenDisplay() 

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


menuDisplay()

Он печатает нажатие, но возвращает только [0,0,0] до случайного времени (иногда сразу, иногда после 10 нажатий, иногда после 50 щелчки) он регистрируется [1,0,0]. он никогда не работал даже на других компьютерах. Это не сработало, когда у меня тоже не было часов, поэтому ничего не изменилось.

Я так грустный и подчеркнул пожалуйста, помогите 101

Ответы [ 2 ]

1 голос
/ 13 февраля 2020

Проблема заключается в вызове pygame.display.set_mode в screenDisplay. Обратите внимание, pygame.display.set_mode вызывает повторную инициализацию окна и приводит к потере всех состояний событий мыши.
screenDisplay вызывается в главном приложении l oop. Инициализация дисплея в каждом кадре - это потеря производительности и плохого стиля.

Не вызывайте screenDisplay в главном приложении l oop, просто очистите дисплей с помощью display.fill(bgColour), чтобы решить проблему :

def menuDisplay():
    intro = True

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

        # screenDisplay() <-- DELETE
        display.fill(bgColour)

        button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
        button("OUTFIT",  60,200,250,400,100,grey,darkGrey,page)
        button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
        button("QUIT",    40,300,530,200,50,grey,darkGrey,page) 

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

Сделайте то же самое в page()

def page():
        intro = True

        while intro:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
            # screenDisplay() <-- DELETE
            display.fill(bgColour)

            pygame.display.update()
            clock.tick(30)
0 голосов
/ 13 февраля 2020

Я изменил некоторые вещи, и это работает:

import pygame

pygame.init()

displayWidth = 800
displayHeight = 600

### colour codes ###
bgColour = (245, 230, 255)
grey = (150, 150, 150)
darkGrey = (100, 100, 100)
darkBlack = (0,0,0)

smallText = pygame.font.SysFont("",32)

display = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Fashion!')

def text_objects(text, font):                       #font colour
    textSurface = font.render(text, True, darkBlack)
    return textSurface, textSurface.get_rect()

def button(msg,s,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    print(click)

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(display, ac,(x,y,w,h)) 
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(display, ic,(x,y,w,h))

    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    display.blit(textSurf, textRect)

def menuDisplay():
    display.fill(bgColour)
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
        button("OUTFIT",  60,200,250,400,100,grey,darkGrey,page)
        button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
        button("QUIT",    40,300,530,200,50,grey,darkGrey,page) 

        pygame.display.update()

def page():
    display.fill(bgColour)
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        pygame.draw.rect(display,grey,(50,50,50,50) )   
        pygame.display.update()



menuDisplay()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...