как остановить увеличение переменной, когда щелчок мышью удерживается в pygame - PullRequest
2 голосов
/ 31 марта 2019

У меня есть переменная clickCounter, которая увеличивается при нажатии и удержании кнопки мыши (при нажатии на кнопку). Как остановить увеличение значения при удержании кнопки и только при нажатии?

Функция кнопки (было бы легче преобразовать ее в класс?):


def button(message, x, y, w, h, activeRGB, inactiveRGB, action=None): #example of color param for line 61/63 
    mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
    click = pygame.mouse.get_pressed()
    global clickCounter



    if x+w > mouse[0] > x and y+h > mouse[1] > y: 
        pygame.draw.rect(gameDisplay, activeRGB, (x, y, w, h))
        if click[0] ==1 and action != None:
            if action == "countUP": 
                clickCounter+= 1
                print(str(clickCounter)) 
                pygame.display.update()



    else: 
        pygame.draw.rect(gameDisplay, inactiveRGB, (x, y, w, h))



    smallText = pygame.font.Font("freesansbold.ttf", 20) # constant has been declared, try deleting line when done w/ proj 
    textSurf, textRect = textBox(message, smallText) 
    textRect.center = (  (x + (w/2)), y+(h/2))
    gameDisplay.blit(textSurf, textRect)


основной цикл


closeGame = False   

while not closeGame: # this keeps the window from shutting down 
    for thing in pygame.event.get(): 
        if thing.type == pygame.QUIT: 
            closeGame = True 

        print(thing)






    gameDisplay.fill(white)
    button("Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")
    textObject(str(clickCounter), black, mediumText, 200, 200) 
    pygame.display.update()
    clock.tick(20)  


Весь код:

import pygame 

pygame.init() 


displayWidth = 700 
displayHeight = displayWidth 

gameDisplay = pygame.display.set_mode((700,700))

clock = pygame.time.Clock()

black = (0, 0, 0) 
brightBlue = (0, 0, 225) 
blue = (0, 0, 255) 

white = (255, 255, 255) #predef colors to make temp rgb value coding easier 

closeGame = False 

mediumText = pygame.font.Font("freesansbold.ttf", 70) #initalize font 
clickCounter = 0 

#def fontSize (pxsize):

    #pygame.font.Font("freesandsbold.ttf", pxsize)

def textObject (text, color, font, x, y):
    storedGenerate = font.render(text, 1, ((color))) 
    gameDisplay.blit(storedGenerate, (x,y)) 


def textBox(text, font): #purely for redturning rectangle around font// used for btn function only, tObject for displaying text  

    textSurface = font.render(text, True, black) #swap black for rgb later
    return textSurface, textSurface.get_rect()

def button(message, x, y, w, h, activeRGB, inactiveRGB, action=None): #example of color param for line 61/63 
    mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
    click = pygame.mouse.get_pressed()
    global clickCounter

    if x+w > mouse[0] > x and y+h > mouse[1] > y: 
        pygame.draw.rect(gameDisplay, activeRGB, (x, y, w, h))
        if click[0] ==1 and action != None:
            if action == "countUP": 
                clickCounter+= 1
                print(str(clickCounter)) 
                pygame.display.update()
    else: 
        pygame.draw.rect(gameDisplay, inactiveRGB, (x, y, w, h))

    smallText = pygame.font.Font("freesansbold.ttf", 20) # constant has been declared, try deleting line when done w/ proj 
    textSurf, textRect = textBox(message, smallText) 
    textRect.center = (  (x + (w/2)), y+(h/2))
    gameDisplay.blit(textSurf, textRect)

closeGame = False   

while not closeGame: # this keeps the window from shutting down 
    for thing in pygame.event.get(): 
        if thing.type == pygame.QUIT: 
            closeGame = True 

        print(thing)

    gameDisplay.fill(white)
    button("Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")
    textObject(str(clickCounter), black, mediumText, 200, 200) 
    pygame.display.update()
    clock.tick(20)  

gameDisplay.fill(white)
pygame.display.update()
#logicloop()

pygame.quit()
quit()

Моя первоначальная мысль заключалась в том, чтобы не использовать pygame.mouse.get_pressed(), а вместо этого использовать кнопку мыши, но не смог заставить ее работать должным образом. Любая помощь приветствуется.

1 Ответ

1 голос
/ 31 марта 2019

Оцените событие MOUSEBUTTONDOWN вместо pygame.mouse.get_pressed. Событие происходит один раз, когда нажата кнопка мыши.

Сохранить кнопку мыши, которая была нажата для переменной mousebutton:

while not closeGame: # this keeps the window from shutting down 

    mousebutton = 0
    for thing in pygame.event.get(): 
        if thing.type == pygame.QUIT: 
            closeGame = True
        elif thing.type == pygame.MOUSEBUTTONDOWN:   
            mousebutton = thing.button

Передать переменную в функцию button:

button(mousebutton, "Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")

Оценить, была ли нажата левая кнопка в функции:

def button(mousebutton, message, x, y, w, h, activeRGB, inactiveRGB, action=None):  
    mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
    global clickCounter

    if x+w > mouse[0] > x and y+h > mouse[1] > y: 
        pygame.draw.rect(gameDisplay, activeRGB, (x, y, w, h))
        if mousebutton == 1 and action != None:
            if action == "countUP": 
                clickCounter+= 1
                print(str(clickCounter)) 
                pygame.display.update()
    else: 
        pygame.draw.rect(gameDisplay, inactiveRGB, (x, y, w, h))

    # [...]

Атрибут .button события MOUSEBUTTONDOWN возвращает 1 для левой кнопки, 2 для средней кнопки, 3 для правой кнопки соответственно 4 при вращении колесика мыши и 5 при вращении колесика мыши вниз.

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