파이 게임에서 마우스 클릭을 멈출 때 변수 증가를 막는 방법

페키 와프

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()않고 대신 마우스 버튼을 사용하는 것이었지만 제대로 작동하지 못했습니다. 도움을 주시면 감사하겠습니다.

Rabbid76

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, 마우스 휠이 롤업되면 각각 4, 마우스 휠이 롤 다운되면 5를 반환합니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

마우스 버튼을 클릭했을 때 깜박임을 멈추도록 Unity의 텍스트 알파 깜박임 스크립트를 수정하는 방법

componentResized 메서드를 한 번만 호출하는 방법 (사용자가 마우스 버튼을 멈출 때)?

ajax 호출을 통해 jstree 마지막 노드를 클릭 할 때 데이터를 채우는 방법

마우스가 jQuery의 요소에서 이동을 멈출 때

마우스 버튼을 클릭했을 때 파이 게임에 이미지를 넣을 수 있습니까?

Java에서 마우스를 클릭했을 때 색상을 변경하는 방법은 무엇입니까?

파이 게임에서 버튼을 클릭할 때 변수가 하나씩만 올라가도록 만드는 방법과 텍스트가 업데이트되도록 만드는 방법

Python3-파이 게임에서 마우스 클릭 여부를 감지하는 방법

마우스 아웃시 또는 마우스 오버가 멈출 때 이미지 전환을 중지하는 방법

이미지 맵-마우스 오버시 및 마우스가 멈출 때만 도구 설명을 표시하는 방법

마우스 포인터가 파일을 클릭 할 때 python3.6을 사용하여 노틸러스 GUI에서 파일 이름을 추출하는 방법은 무엇입니까?

PyQt5에서 마우스를 클릭하는 동안 아이콘을 변경하는 방법

파이 게임의 중첩 된 버튼 내부에서 마우스 클릭을 감지하는 방법

사용자가 스크롤을 멈출 때 Android의 ListView 항목에서 이미지를 바꾸는 방법

C #에서 공을 클릭 할 때마다 점수가 1 씩 증가하는이 프로그램에 마우스 클릭을 추가하려면 어떻게해야합니까?

파이 게임에서 왼쪽 클릭, 오른쪽 클릭 마우스 클릭을 구별하는 방법은 무엇입니까?

파이 게임을 사용하여 클래스에서 변수를 얻는 방법

마우스를 가리키고 클릭 할 때 OpenLayers 5에서 기능 팝업을 구현하는 방법

WinForms PictureBox에서 마우스를 클릭 할 때마다 작은 점을 그리는 방법

TableView JavaFX에서 마우스 클릭 이벤트를 수행하는 방법

함수 이름이 변수에 저장되어 있을 때 클래스의 함수를 호출하는 방법

파이썬을 사용하여 마우스 더블 클릭에서 텍스트를 검색하는 방법

마우스 클릭을 계속 수신하고 차단하면서 파이 게임 창을 투명하게 만드는 방법은 무엇입니까?

파이 게임에서 키를 클릭하여 공 방향을 변경하는 방법은 무엇입니까?

react-router에서 자식 경로를 올바르게 처리하는 방법 (라우팅은 작동하지만 클릭 할 때마다 URL이 증가 함)

Mockito, 마지막으로 호출되었을 때 ther 메서드의 매개 변수를 확인하는 방법

막대 위에 마우스를 놓을 때 레이블을 표시하는 방법

개체가 파이 게임에서 마우스를 감지하는 방법

jQuery에서 마우스 오버 및 마우스가 떠날 때 토글 스타일 변경을 얻는 방법

TOP 리스트

  1. 1

    PrematureCloseException : 연결이 너무 일찍 닫혔습니다.

  2. 2

    MDRotatingPieChart를 회전하면 각도 대신 x / y 위치가 변경됩니다.

  3. 3

    c # 웹 사이트에서 텍스트를 복사하는 방법 (소스 코드 아님)

  4. 4

    jfreecharts에서 x 및 y 축 선을 조정하는 방법

  5. 5

    ArrayBufferLike의 typescript 정의의 깊은 의미

  6. 6

    Ionic 2 로더가 적시에 표시되지 않음

  7. 7

    복사 / 붙여 넣기 비활성화

  8. 8

    Google Play Console에서 '예기치 않은 오류가 발생했습니다. 나중에 다시 시도해주세요. (7100000)'오류를 수정하는 방법은 무엇입니까?

  9. 9

    정점 셰이더에서 카메라에서 개체까지의 XY 거리

  10. 10

    QT Designer를 사용하여 GUI에 이미지 삽입

  11. 11

    java Apache POI Word 기존 테이블 셀 스타일 및 서식이있는 행 삽입

  12. 12

    Kubernetes Horizontal Pod Autoscaler (HPA) 테스트

  13. 13

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

  14. 14

    C # HttpWebRequest 기본 연결이 닫혔습니다. 전송시 예기치 않은 오류가 발생했습니다.

  15. 15

    어떻게 같은 CustomInfoWindow 다른 이벤트를 할 수 있습니다

  16. 16

    rclone으로 원격 디렉토리의 모든 파일을 삭제하는 방법은 무엇입니까?

  17. 17

    dataSnapShot.getValue () 반환 데이터베이스에 그겁니다 데이터 종료 널 (null)

  18. 18

    ORA-12557 TNS : 프로토콜 어댑터를로드 할 수 없습니다

  19. 19

    JNDI를 사용하여 Spring Boot에서 다중 데이터 소스 구성

  20. 20

    다음 컨트롤이 추가되었지만 사용할 수 없습니다.

  21. 21

    C # Asp.net 웹 API-JSON / XML 변환기 API 만들기

뜨겁다태그

보관