1
import pygame, sys, os.path

pygame.init()

# set up the colours
#         R    G    B
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = ( 50, 130, 255)

screen_surf = pygame.display.set_mode((500,500), 0, 24)
pygame.display.set_caption("Lewis' Menu")

screen_surf.fill((100,0,0))

class Button():
    def create(self,w,h,colour):
        self.button_surf = pygame.Surface((w,h), 0, 24)
        self.button = pygame.draw.rect(self.button_surf, colour, (0, 0, w, h))
    def view(self,text,x,y):
        width  = self.button_surf.get_width()
        height = self.button_surf.get_height()
        sys_font = pygame.font.SysFont(("None"), 25)
        rendered = sys_font.render(text,0,(255,255,255))
        self.button_surf.blit(rendered, ((width - 140),((height / 2) - 10)))
        screen_surf.blit(self.button_surf, (x,y))

start_button = Button()
start_button.create(300,100,BLUE), start_button.view("Clicky Button!",10,10)
exit_button = Button()
exit_button.create(300,50,GREEN), exit_button.view("Exit!",10,200)
while True:
    pos = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP:
            if start_button.button.collidepoint(pos):
                print("You opened a chest!")
            if exit_button.button.collidepoint(pos):
                pygame.quit()
                sys.exit()

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        pygame.display.update()

The 'button click' functionality works by checking to see if the mouse position overlaps the button rect. I can reposition the blitted view of the rectangle in the Button.view() method, but the actual rectangle doesn't move with it, which makes the clicking functionality trigger in the wrong location in the window. Is there any way to move the actual button rectangle collision along with the blitted view of it?

Thanks in advance.

1 Answer 1

2

I'd replace the create method with an __init__ method in which the background surface, the text surface and their corresponding rects are created. That allows you to pass all the needed parameters during the instantiation:

start_button = Button(10, 10, 300, 100, "Clicky Button!", BLUE)

Use the parameters to place the self.button rect at the desired coordinates:

self.button = pygame.Rect(x, y, w, h)

You can also use the get_rect method of the button surface to create the rect (see the text_rect creation).

The only purpose of the view method is to blit the surfaces at their rects.

import sys
import pygame


pygame.init()

RED   = (255,   0,   0)
GREEN = (  0, 255,   0)
BLUE  = ( 50, 130, 255)

screen_surf = pygame.display.set_mode((500,500), 0, 24)
screen_surf.fill((100,0,0))
clock = pygame.time.Clock()
# No need to recreate the font object all the time.
SYS_FONT = pygame.font.SysFont(None, 25)


class Button():

    def __init__(self, x, y, w, h, text, colour):
        self.button_surf = pygame.Surface((w,h), 0, 24)
        self.button_surf.fill(colour)
        self.button = pygame.Rect(x, y, w, h)
        self.text_surf = SYS_FONT.render(text, False, (255,255,255))
        # Pass the center coords of the button rect to the newly
        # created text_rect for the purpose of centering the text.
        self.text_rect = self.text_surf.get_rect(center=self.button.center)

    def view(self, screen_surf):
        screen_surf.blit(self.button_surf, self.button)
        screen_surf.blit(self.text_surf, self.text_rect)


# Button() calls the __init__ method.
start_button = Button(10, 10, 300, 100, "Clicky Button!", BLUE)
start_button.view(screen_surf)  # Call `view` in a separate line.
exit_button = Button(10, 200, 300, 50, "Exit!", GREEN)
exit_button.view(screen_surf)

while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP:
            if start_button.button.collidepoint(event.pos):
                print("You opened a chest!")
            elif exit_button.button.collidepoint(event.pos):
                pygame.quit()
                sys.exit()
        elif event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        pygame.display.update()

    clock.tick(60)  # Limit the frame rate to 60 FPS.
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.