2017-06-28 46 views
1

マウスを上に移動するとこの矩形を強調表示し、クリックするとその色を変更します。私は強調表示されたままにすることができましたが、クリック後の色の変化はちょうど瞬間です。どうやってこのままにするのですか?すべてのヘルプは大歓迎ですPyGameクリックして矩形の色を変更します

import pygame, sys 
from pygame.locals import * 

FPS = 30 
BGCOLOR = (3, 115, 46) 
BEFORECLICK = (22, 22, 106) 
AFTERCLICK = (200, 200, 200) 

boardWidth = 500 
boardHeight = 500 
rectX = 150 
rectY = 150 
rectWidth = 200 
rectHeight = 200 
myRectangle = pygame.Rect(rectX, rectY, rectWidth, rectHeight) 

def main(): 
    global FPSCLOCK, DISPLAYSURF 
    pygame.init() 
    FPSCLOCK = pygame.time.Clock() 
    DISPLAYSURF = pygame.display.set_mode((boardWidth, boardHeight)) 
    pygame.display.set_caption("Klikni, kar klikni.") 

    mousex = 0 
    mousey = 0 

    while True: 
     mouseClicked = False 
     DISPLAYSURF.fill(BGCOLOR) 
     pygame.draw.rect(DISPLAYSURF, BEFORECLICK, myRectangle) 

     for event in pygame.event.get(): 
      if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): 
       pygame.quit() 
       sys.exit() 
      elif event.type == MOUSEMOTION: 
       mousex, mousey = event.pos 
      elif event.type == MOUSEBUTTONUP: 
       mousex, mousey = event.pos 
       mouseClicked = True 

     mouseOver = determine_mouseOver(mousex, mousey) 
     if mouseOver == True and mouseClicked == True: 
      pygame.draw.rect(DISPLAYSURF, AFTERCLICK, myRectangle) 
     elif mouseOver == True and mouseClicked == False: 
      pygame.draw.rect(DISPLAYSURF, AFTERCLICK, myRectangle, 3) 

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

def determine_mouseOver(valx, valy): 
    if myRectangle.collidepoint(valx, valy): 
     return True 
    else: 
     return False 

main() 

は、ここに私のコードです。ありがとう!

答えて

0

私は、現在選択しているボタンの色(たとえばbutton_color = BEFORECLICK)を参照する変数を定義し、ユーザーがボタンを押した場合はAFTERCLICKに変更します。その後、rectを描画して、メインループpygame.draw.rect(DISPLAYSURF, button_color, myRectangle)に現在の色を渡すことができます。

# Current color of the button. 
button_color = BEFORECLICK 
mouseOver = False 

while True: 
    for event in pygame.event.get(): 
     if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): 
      pygame.quit() 
      sys.exit() 
     elif event.type == MOUSEMOTION: 
      mousex, mousey = event.pos 
     elif event.type == MOUSEBUTTONUP: 
      if mouseOver: 
       # Change the current color if button was clicked. 
       button_color = AFTERCLICK 

    mouseOver = determine_mouseOver(mousex, mousey) 

    DISPLAYSURF.fill(BGCOLOR) 
    # Just draw the rect with the current button color. 
    pygame.draw.rect(DISPLAYSURF, button_color, myRectangle) 

    if mouseOver: 
     pygame.draw.rect(DISPLAYSURF, AFTERCLICK, myRectangle, 3) 

    pygame.display.update() 
    FPSCLOCK.tick(30) 
関連する問題