Search code examples
pythonmouseeventpygamerect

Pygame action when mouse 'click' on .rect?


I have been writing a test function to learn how a mouse 'click' action on a pygame.rect will result in a reponse.

So far:

def test():
    pygame.init()
    screen = pygame.display.set_mode((770,430))
    pygame.mouse.set_visible(1)
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((250,250,250))
    screen.blit(background, (0,0))
    pygame.display.flip()

    ## set-up screen in these lines above ##

    button = pygame.image.load('Pictures/cards/stand.png').convert_alpha()
    screen.blit(button,(300,200))
    pygame.display.flip()

    ## does button need to be 'pygame.sprite.Sprite for this? ##
    ## I use 'get_rect() ##
    button = button.get_rect()

    ## loop to check for mouse action and its position ##
    while True:
        for event in pygame.event.get():
            if event.type == pygame.mouse.get_pressed():
                ## if mouse is pressed get position of cursor ##
                pos = pygame.mouse.get_pos()
                ## check if cursor is on button ##
                if button.collidepoint(pos):
                    ## exit ##
                    return

I have come across pages on google where people are using or are recommended to use a pygame.sprite.Sprite class for the images and I'm thinking that this is where my problem is from. I have checked the pygames docs and there isn't much cohesion between methods, imho. I am obviously missing something simple but, I thought get_rect would make an image in pygames be able to check if the mouse position is over it when pressed?

Edit: I'm thinking I need to call the pygame.sprite.Sprite method to make the images/rects interactive?


Solution

  • Well, if anyone is interested or is having a similar issue, this is what I needed to change.

    First off, remove:

    button = button.get_rect()
    

    Then:

    screen.blit(button, (300, 200))
    

    Should be:

    b = screen.blit(button, (300, 200))
    

    This to create a Rect of the area of where the button is located on the screen.

    From:

    if event.type == pygame.mouse.get_pressed()
    

    To:

    if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
    

    The pygame.mouse.get_pressed() gets the state of all three mouse buttons (MOUSEBUTTONDOWN, MOUSEBUTTONUP, or MOUSEMOTION). I also needed to add in event.button == 1 to specify that this was the 'left-mouse' button being pressed.

    Finally:

    `if button.collidepoint(pos):` 
    

    To:

    `if b.collidepoint(pos):`
    

    Using Rect b's collidepoint method.